Sunday, February 08, 2015

[UVa] 12024 - Hats

A good explaination on this problem can be found here [ https://gist.github.com/Tafhim/b5705901e33017205a3b ]
I used the formula for the DP implementation
D(n) = n D(n-1) + (-1)^n

Solution:
#include <bits/stdc++.h>
using namespace std;

map<int, pair<int, int> > precalc;
int main() {
 int kase, n, ai;
 int de[100], f[100];
 de[0] = 1;
 f[0] = 1;
 de[1] = 0;
 f[1] = 1;
 ai = -1;
 for (int i = 2 ; i<=12 ; i++) {
  ai *= (-1);
  de[i] = i * de[i-1] + ai;
  f[i] = f[i-1]*i;
 }

 cin >> kase;

 while (kase--) {
  cin >> n;
  cout << de[n] << "/" << f[n] << endl;
 }

 return 0;
}

Saturday, February 07, 2015

Mount non Linux drives automatically when they are not in /etc/fstab

So, I usually face this problem when I'm not using GUI based File Managers. They allow you to auto mount drives when you click on them but when you are using CLI based file managers or no file managers at all, the only way is to mount them through writing commands. I'm a lazy fad and I want this done automatically. So here's a script for that. [ https://gist.github.com/Tafhim/5d0839caca813ae82c97 ].
#!/usr/bin/zsh
if [[ "$1" == "" ]] then
  echo "Please specify a device name";
  exit;
fi;
deviceFile=$1
 
## Auto mount only ntfs, fat32, vfat
for i in $(ls $deviceFile* | grep '[0-9]$'); do
  blkid -s UUID -o value $i | read z;
  blkid -s TYPE -o value $i | read f;
  echo "$z is $f";
  if [[ "$z" !=  "" && ("$f" == "ntfs" || "$f" == "vfat" || "$f" == "fat32" ) ]] then
    /usr/bin/udisksctl mount -t $f -b $i # https://help.ubuntu.com/community/AutomaticallyMountPartitions
  fi;
done

Thursday, February 05, 2015

Documenting my first Arch build

I bought a new Laptop a few months ago and now I have the old one being thrown around and ready for some wild tests. So I decided instead of using prebuilt Arch Linux distros I'll make a proper one myself and see how things turn up. :)

1. First things first, I built the vanilla setup simply by following the "Beginners's guide in Arch Wiki" and the only 2 things I found of good notice is the "Partitioning part" and the "Get yourself wifi" part. Both of these have different scenarios but in my case things were a bit simplified since
a. I always use MBR
b. I always use WiFI
So to fix the partitioning issue I didn't do much. Used parted to get my disks ready, wrote the file systems using mkfs.ext4 and mkswap and set the bootflag on root.
To fix up with the WiFi, I first unblocked using
rfkill unblock all
Then used
wifi-menu
To connect to my system
This pretty much brought up my whole system using the guide I mentioned earlier which you can find here

2. Now for the post installation part. The very first thing that came in my way is that my fan was blasting away like crazy. I fixed this using 'laptop-mood-tools' and 'powertop'. So first I created a new user (I can't be root when installing packages from the AUR) then I installed
yaourt
Then I installed 'laptop-mode-tools' using 'yaourt'. After that I installed 'powertop' using 'pacman' and ran it
powertop
Then I used to TAB key to go to the Turntables column and made all the 'Bad' entries 'Good'. Then pressed 'Esc' to save the settings and rebooted.
UPDATE: Apparently this did not bring the crazy fan speeds down. After some browsing around, I hit a thread in the ArchBang forums where it became pretty apparent that recent Kernel changes in 3.18 have triggered the issue and still has not been resolved. So, I had to downgrade to 3.17.6 which I did by following a well written guide here. What I basically did was
a. Went to the Arch official package database
b. Located the Linux package
c. On the upper right Package Section of the page, click on View Changes. There I located an earlier version, in this case upgpkg: linux 3.17.6-1
d. Located the revision number from the line that is like "file:///srv/svn-packages@177020". That’s the revision number after the @, it might be anything. e. Then to compile 3.17.6, did the following in the terminal. CAUTION: This process might take several hours, took me around 4 hours to compile the kernel
cd ~/Downloads
mkdir linux-kernel && cd linux-kernel
svn checkout --depth=empty svn://svn.archlinux.org/packages
cd packages
svn update -r  linux
cd linux/trunk/
makepkg -g >> PKGBUILD
makepkg -s
sudo pacman -U *.pkg.tar.xz
This will install the new kernel. You might face some dependency issues where it might ask for 3.18. I removed those packages. Rebooted the PC and it was fixed.
3. Now for the GUI. I personally do not find full blown desktop environments much useful so I stick to Window Managers. I installed Xmonad. Then I configured Xorg for my user account using
Xorg -configure
Copied the barebones default xmonad configuration template from their configuration archives into ~/.xmonad/xmonad.hs
--
-- xmonad example config file for xmonad-0.9
--
-- A template showing all available configuration hooks,
-- and how to override the defaults in your own xmonad.hs conf file.
--
-- Normally, you'd only override those defaults you care about.
--
-- NOTE: Those updating from earlier xmonad versions, who use
-- EwmhDesktops, safeSpawn, WindowGo, or the simple-status-bar
-- setup functions (dzen, xmobar) probably need to change
-- xmonad.hs, please see the notes below, or the following
-- link for more details:
--
-- http://www.haskell.org/haskellwiki/Xmonad/Notable_changes_since_0.8
--
 
import XMonad
import Data.Monoid
import System.Exit
 
import qualified XMonad.StackSet as W
import qualified Data.Map        as M
 
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
--
myTerminal      = "xterm"
 
-- Whether focus follows the mouse pointer.
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
 
-- Width of the window border in pixels.
--
myBorderWidth   = 1
 
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt").  You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
--
myModMask       = mod1Mask
 
-- NOTE: from 0.9.1 on numlock mask is set automatically. The numlockMask
-- setting should be removed from configs.
--
-- You can safely remove this even on earlier xmonad versions unless you
-- need to set it to something other than the default mod2Mask, (e.g. OSX).
--
-- The mask for the numlock key. Numlock status is "masked" from the
-- current modifier status, so the keybindings will work with numlock on or
-- off. You may need to change this on some systems.
--
-- You can find the numlock modifier by running "xmodmap" and looking for a
-- modifier with Num_Lock bound to it:
--
-- > $ xmodmap | grep Num
-- > mod2        Num_Lock (0x4d)
--
-- Set numlockMask = 0 if you don't have a numlock key, or want to treat
-- numlock status separately.
--
-- myNumlockMask   = mod2Mask -- deprecated in xmonad-0.9.1
------------------------------------------------------------
 
 
-- The default number of workspaces (virtual screens) and their names.
-- By default we use numeric strings, but any string may be used as a
-- workspace name. The number of workspaces is determined by the length
-- of this list.
--
-- A tagging example:
--
-- > workspaces = ["web", "irc", "code" ] ++ map show [4..9]
--
myWorkspaces    = ["1","2","3","4","5","6","7","8","9"]
 
-- Border colors for unfocused and focused windows, respectively.
--
myNormalBorderColor  = "#dddddd"
myFocusedBorderColor = "#ff0000"
 
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
 
    -- launch a terminal
    [ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)
 
    -- launch dmenu
    , ((modm,               xK_p     ), spawn "exe=`dmenu_path | dmenu` && eval \"exec $exe\"")
 
    -- launch gmrun
    , ((modm .|. shiftMask, xK_p     ), spawn "gmrun")
 
    -- close focused window
    , ((modm .|. shiftMask, xK_c     ), kill)
 
     -- Rotate through the available layout algorithms
    , ((modm,               xK_space ), sendMessage NextLayout)
 
    --  Reset the layouts on the current workspace to default
    , ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)
 
    -- Resize viewed windows to the correct size
    , ((modm,               xK_n     ), refresh)
 
    -- Move focus to the next window
    , ((modm,               xK_Tab   ), windows W.focusDown)
 
    -- Move focus to the next window
    , ((modm,               xK_j     ), windows W.focusDown)
 
    -- Move focus to the previous window
    , ((modm,               xK_k     ), windows W.focusUp  )
 
    -- Move focus to the master window
    , ((modm,               xK_m     ), windows W.focusMaster  )
 
    -- Swap the focused window and the master window
    , ((modm,               xK_Return), windows W.swapMaster)
 
    -- Swap the focused window with the next window
    , ((modm .|. shiftMask, xK_j     ), windows W.swapDown  )
 
    -- Swap the focused window with the previous window
    , ((modm .|. shiftMask, xK_k     ), windows W.swapUp    )
 
    -- Shrink the master area
    , ((modm,               xK_h     ), sendMessage Shrink)
 
    -- Expand the master area
    , ((modm,               xK_l     ), sendMessage Expand)
 
    -- Push window back into tiling
    , ((modm,               xK_t     ), withFocused $ windows . W.sink)
 
    -- Increment the number of windows in the master area
    , ((modm              , xK_comma ), sendMessage (IncMasterN 1))
 
    -- Deincrement the number of windows in the master area
    , ((modm              , xK_period), sendMessage (IncMasterN (-1)))
 
    -- Toggle the status bar gap
    -- Use this binding with avoidStruts from Hooks.ManageDocks.
    -- See also the statusBar function from Hooks.DynamicLog.
    --
    -- , ((modm              , xK_b     ), sendMessage ToggleStruts)
 
    -- Quit xmonad
    , ((modm .|. shiftMask, xK_q     ), io (exitWith ExitSuccess))
 
    -- Restart xmonad
    , ((modm              , xK_q     ), spawn "xmonad --recompile; xmonad --restart")
    ]
    ++
 
    --
    -- mod-[1..9], Switch to workspace N
    --
    -- mod-[1..9], Switch to workspace N
    -- mod-shift-[1..9], Move client to workspace N
    --
    [((m .|. modm, k), windows $ f i)
        | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
        , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
    ++
 
    --
    -- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
    -- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
    --
    [((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
        | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
        , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
 
 
------------------------------------------------------------------------
-- Mouse bindings: default actions bound to mouse events
--
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
 
    -- mod-button1, Set the window to floating mode and move by dragging
    [ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
                                       >> windows W.shiftMaster))
 
    -- mod-button2, Raise the window to the top of the stack
    , ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
 
    -- mod-button3, Set the window to floating mode and resize by dragging
    , ((modm, button3), (\w -> focus w >> mouseResizeWindow w
                                       >> windows W.shiftMaster))
 
    -- you may also bind events to the mouse scroll wheel (button4 and button5)
    ]
 
------------------------------------------------------------------------
-- Layouts:
 
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- * NOTE: XMonad.Hooks.EwmhDesktops users must remove the obsolete
-- ewmhDesktopsLayout modifier from layoutHook. It no longer exists.
-- Instead use the 'ewmh' function from that module to modify your
-- defaultConfig as a whole. (See also logHook, handleEventHook, and
-- startupHook ewmh notes.)
--
-- The available layouts.  Note that each layout is separated by |||,
-- which denotes layout choice.
--
myLayout = tiled ||| Mirror tiled ||| Full
  where
    -- default tiling algorithm partitions the screen into two panes
    tiled   = Tall nmaster delta ratio
 
    -- The default number of windows in the master pane
    nmaster = 1
 
    -- Default proportion of screen occupied by master pane
    ratio   = 1/2
 
    -- Percent of screen to increment by when resizing panes
    delta   = 3/100
 
------------------------------------------------------------------------
-- Window rules:
 
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
--
myManageHook = composeAll
    [ className =? "MPlayer"        --> doFloat
    , className =? "Gimp"           --> doFloat
    , resource  =? "desktop_window" --> doIgnore
    , resource  =? "kdesktop"       --> doIgnore ]
 
------------------------------------------------------------------------
-- Event handling
 
-- Defines a custom handler function for X Events. The function should
-- return (All True) if the default handler is to be run afterwards. To
-- combine event hooks use mappend or mconcat from Data.Monoid.
--
-- * NOTE: EwmhDesktops users should use the 'ewmh' function from
-- XMonad.Hooks.EwmhDesktops to modify their defaultConfig as a whole.
-- It will add EWMH event handling to your custom event hooks by
-- combining them with ewmhDesktopsEventHook.
--
myEventHook = mempty
 
------------------------------------------------------------------------
-- Status bars and logging
 
-- Perform an arbitrary action on each internal state change or X event.
-- See the 'XMonad.Hooks.DynamicLog' extension for examples.
--
--
-- * NOTE: EwmhDesktops users should use the 'ewmh' function from
-- XMonad.Hooks.EwmhDesktops to modify their defaultConfig as a whole.
-- It will add EWMH logHook actions to your custom log hook by
-- combining it with ewmhDesktopsLogHook.
--
myLogHook = return ()
 
------------------------------------------------------------------------
-- Startup hook
 
-- Perform an arbitrary action each time xmonad starts or is restarted
-- with mod-q.  Used by, e.g., XMonad.Layout.PerWorkspace to initialize
-- per-workspace layout choices.
--
-- By default, do nothing.
--
-- * NOTE: EwmhDesktops users should use the 'ewmh' function from
-- XMonad.Hooks.EwmhDesktops to modify their defaultConfig as a whole.
-- It will add initialization of EWMH support to your custom startup
-- hook by combining it with ewmhDesktopsStartup.
--
myStartupHook = return ()
 
------------------------------------------------------------------------
-- Now run xmonad with all the defaults we set up.
 
-- Run xmonad with the settings you specify. No need to modify this.
--
main = xmonad defaults
 
-- A structure containing your configuration settings, overriding
-- fields in the default config. Any you don't override, will
-- use the defaults defined in xmonad/XMonad/Config.hs
--
-- No need to modify this.
--
defaults = defaultConfig {
      -- simple stuff
        terminal           = myTerminal,
        focusFollowsMouse  = myFocusFollowsMouse,
        borderWidth        = myBorderWidth,
        modMask            = myModMask,
        -- numlockMask deprecated in 0.9.1
        -- numlockMask        = myNumlockMask,
        workspaces         = myWorkspaces,
        normalBorderColor  = myNormalBorderColor,
        focusedBorderColor = myFocusedBorderColor,
 
      -- key bindings
        keys               = myKeys,
        mouseBindings      = myMouseBindings,
 
      -- hooks, layouts
        layoutHook         = myLayout,
        manageHook         = myManageHook,
        handleEventHook    = myEventHook,
        logHook            = myLogHook,
        startupHook        = myStartupHook
    }
Then I opened up ~/.xinitrc and added
exec xmonad
Installed a file manager called 'ranger' and then added it to the configuration to launch with mod + f key. Installed a terminal emulator called 'xfce4-terminal'. I might switch from it later but what the hell.
I will update this article as more changes are added to the system.

Fix fans running at full in Arch Linux vanilla (Kernel 3.18 and up)

So, the other day I was tinkering with a fresh Arch installation and the very first issue that I ran into was my fan was rotating at full blast even though there was now processor load at all. While looking for a solution I was surprised to find that there were no actual solutions on the internet to these. I followed the path of "Fan speed control" in Arch Linux wiki and but no luck. Then I installed 'powertop'
pacman -S powertop
Then I ran
powertop
Used Tab to navigate to the "Turntables" area. Then changed the states of all "Bad" to "Good" as many as possible. Saved using "Esc" and then reboot. It worked :)

UPDATE: Apparently this did not bring the crazy fan speeds down. After some browsing around, I hit a thread in the ArchBang forums where it became pretty apparent that recent Kernel changes in 3.18 have triggered the issue and still has not been resolved. So, I had to downgrade to 3.17.6 which I did by following a well written guide here. What I basically did was
a. Went to the Arch official package database
b. Located the Linux package
c. On the upper right Package Section of the page, click on View Changes. There I located an earlier version, in this case upgpkg: linux 3.17.6-1
d. Located the revision number from the line that is like "file:///srv/svn-packages@177020". That’s the revision number after the @, it might be anything. e. Then to compile 3.17.6, did the following in the terminal. CAUTION: This process might take several hours, took me around 4 hours to compile the kernel
cd ~/Downloads
mkdir linux-kernel && cd linux-kernel
svn checkout --depth=empty svn://svn.archlinux.org/packages
cd packages
svn update -r  linux
cd linux/trunk/
makepkg -g >> PKGBUILD
makepkg -s
sudo pacman -U *.pkg.tar.xz
This will install the new kernel. You might face some dependency issues where it might ask for 3.18. I removed those packages. Rebooted the PC and it was fixed.
Credits: https://ask.fedoraproject.org/en/question/31514/how-to-change-cpu-temperature-thresholds-and-control-fan-speed/
https://nims11.wordpress.com/2013/02/17/downgrading-packages-in-arch-linux-the-worst-case-scenario/

Connect Rapoo MT750S with Linux (Tested on Manjaro)

 I bought this obvious copy of MX Master 2S in hopes of having the device switching functionality along with a lightweight body because I ha...