Monday, February 12, 2018

how to write a game in c++ from scratch

Disclaimer: I am in no way a game developer, this is the story of my tries and errors.

So, we decided to create a project to exercise c++17. Let it be a game. It has been decided to use cmake and gtest and tdd. Perfect. And then we realized we have no idea how to build an architecture for a game. Googled it. Found this outdated tutorial:

http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-2.aspx

Well, at least the author provided some basic architecture we can use. So, let's write a ping-pong game!

The tutorial is easy and I thought I could have it running in a day. But alas! 3 days in we are stuck with environment configuration.

This is how it goes: we use sfml as our graphics lib. At first I wanted to use cmake to fetch the master from github, build and link it, just as it is done in the gtest how-to. But, it has around 10 dependecies. We cannot rely on the developer to install all of them by hand, right? Right? So, it has been decided to pre-build sfml statically. Does it mean that I will have to build all 10 deps statically too? And what if each of them has 10 dependencies? omg.

Monday, December 4, 2017

haskell, yesod and Kabbalah

That moment when you try to google haskell-yesod for more tutorials, stumble upon a something called Kabbalah, thinking "wow, that's such a good naming, the words fit really good together, with their Hebrew origin" and then realize it's not some piece of software, it's actual Kabbalah.


Tuesday, November 28, 2017

Yesod tutorial for beginners, haskell web programming

Well hello

So, I started to learn web programming with haskell and yesod. Yesod book was too hard for me to grasp and I couldn't find a plausible entry-level tutorial, that would not be written 5 years ago and could compile. So I took an article by  yannesposito and fixed it.

I saw some effort to fix the tutorial on the school of haskell here, but its formatting gave me an impression, that it is not maintained anymore.

Prerequisites: a basic understanding of haskell. If you lack it, I recommend you to read this.

1. Work environment setup


I use stack instead of cabal. I, together with yesod manual, really recommend you to use it. Not to mention, that using yesod you don't really have a choice. The only way to create a new project is to use stack  ¯\_(ツ)_/¯.

1.1 So, let's get us some stack!


It's as easy as running either one of the two.
curl -sSL https://get.haskellstack.org/ | sh
or
wget -qO- https://get.haskellstack.org/ | sh

I strongly recommend using the latest version of stack instead of just apt-getting it. Ubuntu repos often contain older and buggier versions of our favorite software.

[optional] Check what templates are available
$ stack templates

1.2 Generate a template project.


You can generate a yesod project only using stack. The init command has been removed from yesod.  Use yesod-sqlite template to store you blog entries (see "Blog" chapter). Of course, if you don't intend to go that far with this tutorial, you can use yesod-simple. So, let's create a new project called "yolo" with type yesod-sqlite.
stack new yolo yesod-sqlite

1.3 Install yesod

You should be able to run your  project, for this you have to install yesod. This takes about 20 min.
stack install yesod-bin --install-ghc

1.4 Build and launch

Warning, first build will take a looong time
stack build && stack exec -- yesod devel

And check your new website at http://localhost:3000/
(3000 is the default port for yesod).
For more detailed reference about setting up yesod look here.

My versions of stuff:
stack:  Version 1.5.1, Git revision 600c1f01435a10d127938709556c1682ecfd694e
yesod-bin version: 1.5.2.6
The Glorious Glasgow Haskell Compilation System, version 8.0.2


2. Git setup

You know it's easier to live with a version control system.
git init .
git add .
git commit -m 'Initial commit'

3. Echo

Goal: going to localhost:3000/echo/word should generate a page with the same word.

Don't add the handler with `yesod add-handler`, instead, do it manually.

Add this to config/routes, thus adding a new page to the website.
/echo/#String EchoR GET
#String is the type of the input after slash and haskell's strict types prevent us from getting SQL injections, for example.
EchoR is the name of the GET request handler, GET is the type of supported requests.

And this is the handler, add it to src/Handler/Home.hs.
getEchoR :: String -> Handler Html
getEchoR theText = do
    defaultLayout $ do
        setTitle "My brilliant echo page!"
        $(widgetFile "echo")

This tiny piece of code accomplishes a very simple task:
  • theText is the argument, that we passed through /echo/<theText is here>
  • for it we return a defaultLayout (that is specified in templates/defaultLayout.hamlet and is just a standart blank html page)
  • set page's title "My brilliant echo page!"
  • set main widget according to templates/echo.hamlet
 Also, remember that RepHtml is deprecated.

So, let's add this echo.hamlet to the <projectroot>/templates! As you can see it's just a header with the text that we passed after slash of echo/<word here>.
<h1> #{theText}

Now run and check localhost:3000/ :)

If you're getting an error like this
 Illegal view pattern:  fromPathPiece -> Just dyn_apb9
    Use ViewPatterns to enable view patterns
or
 Illegal view pattern:  fromPathPiece -> Just dyn_aFon 

then just open your package.yaml file, that stack has automatically created for you and add the following lines just after `dependencies:` section:
default-extensions: ViewPatterns

Else if you're getting something like this
yesod: devel port unavailable
CallStack (from HasCallStack):
  error, called at ./Devel.hs:270:44 in main:Devel
that most probably you have another instance of site running and thus port 3000 is unavailable.

If you see this warning
Warning: Instead of 'ghc-options: -XViewPatterns -XViewPatterns' use
'extensions: ViewPatterns ViewPatterns'

It's okay, so far stack does not support 'extensions' section in .cabal file. Catch up with this topic in this thread.

If you see this warning
Foundation.hs:150:5: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘isAuthorized’:
        Patterns not matched: (EchoR _) _

That means, that you need to add this line to Foundation.hs
isAuthorized (EchoR _) _ = return Authorized 
All it does is grants permissions to access localhost/echo to everybody.

 4. Mirror

Goal: create a page /mirror with an input field, which will post the actual word and its palindrome glued together, as in book -> bookkoob or bo -> boob.

Add the following to config/routes to create a new route (i. e. a page in our case).
/mirror MirrorR GET POST


Now we just need to add a handler to src/Handler/Mirror.hs
    import Import
    import qualified Data.Text as T

    getMirrorR :: Handler RepHtml
    getMirrorR = do
        defaultLayout $ do
            setTitle "You kek"
            $(widgetFile "mirror")

    postMirrorR :: Handler RepHtml
    postMirrorR = do
        postedText <- runInputPost $ ireq textField "content"
        defaultLayout $ ($(widgetFile "posted"))

 Don't be overwhelmed! It's quite easy to understand.

And add the handler import to src/Application.hs, you will see a section, where all other handlers are imported

import Handler.Mirror

Mirror.hs mentions two widget files: 'mirror' and 'posted', here's their contents

templates/mirror.hamlet

<h1> Enter your text
<form method=post action=@{MirrorR}>
    <input type=text name=content>
    <input type=submit>

templates/posted.hamlet
<h1>You've just posted
<p>#{postedText}#{T.reverse postedText}
<hr>
<p><a href=@{MirrorR}>Get back

There is no need to add anything to .cabal or .yaml files, because stack magically deducts everything on its own :)

Don't forget to add the new route to isAuthorized like in the previous example!

Now build, launch and check out your localhost:3000, you must see something similar to my pics

stack build && stack exec -- yesod devel

And after you entered some text in the form, you should get something like this

5. Blog

Again, add Handler.Article and Handler.Blog to Application.hs imports.
This is contents of Blog.hs

{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}

module Handler.Blog
    ( getBlogR
    , postBlogR
    , YesodNic
    , nicHtmlField
    )
where

import Import
import Data.Monoid

import Yesod.Form.Nic (YesodNic, nicHtmlField)
instance YesodNic App

entryForm :: Form Article
entryForm = renderDivs $ Article
    <$> areq textField "Title" Nothing
    <*> areq nicHtmlField "Content" Nothing

getBlogR :: Handler RepHtml
getBlogR = do
    articles <- runDB $ selectList [] [Desc ArticleTitle]
    (articleWidget, enctype) <- generateFormPost entryForm
    defaultLayout $ do
        setTitle "kek"
        $(widgetFile "articles")

postBlogR :: Handler Html
postBlogR = do
    ((res, articleWidget), enctype) <- runFormPost entryForm
    case res of
        FormSuccess article -> do
            articleId <- runDB $ insert article
            setMessage $ toHtml $ (articleTitle article) Import.<> " created"
            redirect $ ArticleR articleId
        _ -> defaultLayout $ do
                setTitle "You loose, sucker!"
                $(widgetFile "articleAddError")


Article.hs contents

{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}

module Handler.Article
(
    getArticleR
)
where

import Import

getArticleR :: ArticleId -> Handler Html
getArticleR articleId = do
    article <- runDB $ get404 articleId
    defaultLayout $ do
        setTitle $ toHtml $ articleTitle article
        $(widgetFile "article")

Add this to conf/models

Article
    title   Text
    content Html
    deriving

This to conf/routes

/blog               BlogR       GET POST
/blog/#ArticleId    ArticleR    GET


And add these lines to src/Foundation.hs. This is a hack, but you cannot view the contents unauthorized, right? :) Drawback: all users on the internets will be able to see your post.

    isAuthorized BlogR _ = return Authorized
    isAuthorized (ArticleR _) _ = return Authorized

All done! What will you see:

Wednesday, November 22, 2017

haskell first steps

Well hello

So I started to learn haskell.
And I know it's old news, but still, look how short haskell's quick sort implementation is!

qsort :: (Ord a) => [a] -> [a]
qsort [] = []
qsort (x:xs) =
    let smaller = qsort (filter (<= x) xs)
        bigger = qsort (filter (> x) xs)
    in smaller ++ [x] ++ bigger

And my first steps with haskell are:
  1. learnyouahaskell
  2. exercism/haskell
  3. https://www.haskell.org/documentation
  4. Real World Haskell, but I must say, that this book is incredibly vague, obfuscated and is the opposite of clear. It is the most hard to get book that I've read so far, and it's not that haskell is complicated, no. It's the book.
  5.  Web services for haskell -- yesod (how-to).

Wednesday, November 15, 2017

Best free courses from coursera: 2017 reality check

Well hello

Coursera was the sublimation of the ultimate good on the Internet: free courses on programming, machine learning, probabilistic graphical models and so much more! But alas, all good has to come to an end. As of Dec 2017 Daphne Koller and Andrew Ng has made quite a few steps towards monetizing the platform (and who can blame them? they are a startup after all). All the legendary courses, whose names were well known among my fellow programmers were either deleted (Standford Compilers) or turned into paid specializations (Stanford Algorithms and even the Probabilistic Graphical Models by the previously mentioned founder of the Coursera Daphne Koller!).


Compilers course logo / openclassroom.stanford.edu

 But, there's still some fun to explore for me and my fellow penniless adventurers! And here is the top of best free courses on coursera, 2017 reality check:

1. Algorithms I and Algorithms II by R. Sedgewick of Princeton.


/ coursera.org

The top of the top in my personal courses list of all time. Sedgewick, who actually invented the red-black tree with his colleague in Stanford, in addition to being a real life grandpa from Up! is a brilliant teacher, it is quite impossible not to understand what he wants you to understand :) He goes sometimes into so much details, that I had to listed at speed 1.5x, but for some people it could be quite a good pace. Also, you get to solve 5 puzzles in each course for free! And they are really cool. Highly recommended, 100/100.

2. Machine learning by Andrew Ng of Stanford.


 / coursera.org

The legendary founding father of coursera keeps his first course free of charge, and I'm quite happy with that! Extremely engaging lecture and even more so programming assignments keep you busy for the whole of 11 weeks! Loving it!

3. Cryptography I by D. Boneh of Standford.


/ coursera.org

In his work, Boneh goes through all the basics and details of -- you guessed it -- cryptography. I would say, the course contains enough material for the whole undergraduate course.

4. Introduction to Mathematical Thinking by K. Devlin of Stanford.


/ coursera.org

Haven't seen a lot of this course, but it was enough to decide to definitely return to it in the future.  Introduction to Mathematical Thinking will help you develop a creative way of thinking and solving all kinds of problems, for example, how to prove a theorem, that nobody was able to solve before.

5. Game Theory by   M. O. Jackson and K. Leyton-Brown of Stanford and British Columbia.


/ coursera.org

Never thought what to do if we play the game against another player, that knows that we play the game and also knows what is our best strategy, as do we know about his. Who will win in this situation? Game theory can answer that. It's not your usual application on game theory for competitive programming problems, neither is it a game development course, but it's quite interesting and kinda gets you on the other plane of thinking.


And down here, let me have a quick rant on coursera specializations. They ruin all the magic of free education, they really do! And the platform is constantly shoving them down my throat to that extent that it's impossible to search for courses only, one can only search for the keywords, like "machine learning", and then get 100000 "only $49 a month!" specializations, which is absolutely not what one was hoping for. 

So, coursera, please give us our free education back! I understand you need machine time to review the programming assignment, but come on! I can volunteer you some of mine, and I think many of us will! I will even pay for certificates, I promise :)

Sunday, November 12, 2017

Rich father poor father, magic of thinking big and other books of the year

Well hello


The year is getting to its end, who would not think it's the most suitable time to analyze the books I've read so far?

1. The magic of thinking big by D. J. Schwartz

 / penguin random house /

The most inspiring book so far.


2. Rich dad poor dad by R. T. Kiyosaki

/ wikipedia /
#1 personal finance book of all time? Looks more like garbage to me.


3. You are a badass at making money by J. Sincero
 / kobo.com /
To some point inspiring. Bullshit to a lot of other points.


4. #GIRLBOSS by S. Amoruso

 / goodreads /

Total bullshit, a poetic retelling of main character's bio.


5. Take your time by Easwaran
  / goodreads /

Total bullshit, the content of this small book can be expressed in one sentence: less bustle, more meditation.


6. Accelerated C++ by A. Koening and B. E. Moo


/slant/

As the authors state at the beginning of the book, it is a transcript of the course they used to teach to C programmers. Agonizingly obvious at times and mediocre at others.


Next year I'll try to read at least one book a month.

Saturday, March 25, 2017

Как я стала тем, кем я стала

... или как стать лучше меня.

На недавнем митапе в честь Outreachy вокруг меня собралось некоторое количество девушек, одна из которых задала мне вопрос, обозначенный в описании. Не знаю, что именно она имела в виду, но тем не менее, здесь я хочу грубо очертить мой путь начинающего разработчика ПО.

1) Линукс, у меня Дебиан.
2) ACM ICPC и codeforces.
3) Курсера.
4) Изучение разнообразных иностранных языков, в первую очередь английского.
5) Восприятия учебы как нечто, что продлится всю жизнь (life long learning), учеба вопреки университету.
6) Больше литературы по программированию и самого программирования.
7) Занятие пассивно проведенного времени, например в маршрутке, очереди или на скучной паре.
8) Общение с более опытными людьми в разных сферах человеческой жизнедеятельности. Некоторые из них могут оказаться полными говнюками, но не переживайте, их немного. Как выразился один мой знакомый: "Нет в здравом уме такого человека, который вместо помощи новичку посмеялся бы над ним".
9) Last, but not least, Google guide.

Надеюсь, дополнить этот список в будущем.

Saturday, March 11, 2017

Outreachy May-August 2017

Что такое Outreachy?
Это ежегодная программа, которая предоставляет возможность в течении 3 месяцев удаленно работать над open source проектом и получать за это денежное вознаграждение. Сумма может варьироваться, на 11-й раунд она составляет $5500. При чем, можно не только писать код, но и заниматься дизайном, документацией, маркетингом и другими видами деятельности, приносящими пользу open source сообществу. Изначально, целью стипендии было поддержка женщин, которые занимаются разработкой ПО (сейчас, как известно, большинство разработчиков являются мужчинами). С недавних пор, стипендия поддерживает больше underrepresented minorities. Спонсируется некоммерческой организацией GNOME.

Подхожу ли я для стипендии?
 Вам нужно
  • знать английский хотя бы на B1 (то, что как минимум дают в школе)
  • быть старше 18 лет
  • не быть резидентом Крыма, Кубы, Ирана, Северной Кореи, Сирии или Судана и идентифицировать себя как женщину, транс-мужчину или гендерквир (включая гендерфлюид или не идентифицировать себя ни с каким полом).
  • принимать участие в этой программе в первый раз, а также не принимать участие в Google Summer of Code до этого.
  • иметь возможность работать 40 часов в неделю в течении периода программы (30 мая -- 30 Августа 2017).
  • иметь право работать в стране нынешнего проживания.
  • не проживать в стране, на которую действую экспортные ограничения или санкции США.
Подробнее.

Как подать заявку?
Вкратце: с февраля по 30 марта 2017 длится отборочный тур, вам нужно
  • найти подходящий проект
  •  сделать для него небольшое пробное задание 
  • дожидаться результата, паралельно общаясь с обществом и пытаясь вникнуть в таску, которую вы хотите в этом раунде выполнять.
 Конечно, в идеале вы должны около года контрибьютить в проект, делая задания все сложнее и сложнее, и, когда вы окажетесь контрибтютором средней крупности, подавать на стипендию, но в первый раз можно попробовать и так. Подробнее, см. здесь.


Как получить стипендию?
Лучше сказать я не смогу (тыц).

Как обустроить workflow на эти 3 месяца?
Окей, если вы подали заявку и получили стипендию, сейчас начинается самое сложное. Если вы работали у себя дома, то вы знаете, как часто вашим близким нужна ваша помощь, когда у вас самый разгар рабочего процесса. Обустроить все за вас я не смогу, но у меня, после опыта с Outreachy, есть некоторые tips&tricks:
  1. Работайте за столом, диванчик/кровать не располагают к работе, вам дадут задание, которое у вас займет по 40 часов в течении 13 недель, как думаете, у вас будет время прокрастинировать? Вы или соберетесь или провалите все к чертям (и денег не дадут). Байдикування -- це іграшка диявола, еге ж!
  2. Контактируйте с ментором как можно чаще, если у вас (как и у меня) проблемы с самоорганизацией, или вы просто впервые работаете дома, попросите ментора контролировать вас каждый день. Каждый день вечером пишите ему отчет о проделанной работе и планы на следующий день. С улучшением самоконтроля, можно переходить на спринты длиной в полнедели, а в случае открытия третьего глаза, отчитываться можно и раз в неделю.
  3. Скорее всего, работать в проекте вы будете не одни, кроме вас будут еще участники Outreachy, а кроме этого еще милионная армия open source движения, которая делает такую же работу как вы, но каждый день в году и бесплатно. Не стесняйтесь говорить с опытными разрабами, с другими новичками, в open source нет никого, кто не захотел бы с вами обсудить новую фичу или посоветовать подход к решению того или иного бага. Обращаться, по традиции, можно на ты. Даже к Столлману =) Основные канала связи индивидуальны для каждго проекта, но обычно это irc и рассылки писем.
  4. Объясните домочадцам, что вы работаете, это не просто хобби, вам за эту работу платят деньги. Обозначте время, в течении которого вас нельзя тревожить, если только не горит квартира, например с 8 до 12 и с 2 до 6. И приучайте их к мысли, что вы будете в обозначенное время недоступны в течении 3х месяцев.
Эта запись в блоге является выборочным переводом подробной инструкции, искренне вам советую прочитать ее полностью. Мне не остается ничего, кроме как пожелать вам удачи! Передавайте всем, кто по вашему мнению должен знать о программе.


Monday, February 6, 2017

Thursday, May 12, 2016

git diff with odt-files

A brilliant article.
https://www.thomas-krenn.com/de/wiki/Git_diff_mit_odt-Dateien

Wednesday, May 4, 2016

Internship Programme of German Business for Ukraine (Stipendienprogramm der Deutschen Wirtschaft für die Ukraine)

Hi, my name is Asalle and I participated in Internship Programme of German Business for Ukraine. First of all, I would like to answer some common questions, detailed answer for them you can find in the "Contacts" section below.


What is the Internship Programme of German Business for Ukraine?

In short, it's the joint effort of German government and Ukrainian non-profits to bring Ukraine and Germany together. They give you a scholarship and an opportunity to have an internship in one of the German well-known company and you share your Ukrainian culture in Germany and you positive experience in Ukraine. Why would they do that? Because, we are a huge market they would like to work closer with. You know Bosch, METRO, SAP, they have departments in Ukraine as well and they participate in this programme as host companies.

Who can participate?

Students, that have finished at least 2 years of their study and young graduates, all preferably under 30. Good command of English, German or both is required, but no language certificate is obligatory.

What is expecting me in Germany?

You will do a 3 to 5 month internship in one of the coolest German companies, of course in Germany. You will dive into German culture and everyday life and will have a unique opportunity to work together with a "global player", as I did, see below.

How did you apply?
Just go to the http://stipendienprogramm-ukraine.de/ and on the front page you will see a huge button "Please apply here" or "Hier geht es zur Bewerbung" depending on the language you're viewing the page in.


You can additionally check your area of study and industry with a table in the beginning. For example, I study software engineering, my area of study is IT and my industry is called "Informatics/Mathematics". Sometimes you can choose between several industries, but choose wisely, if you study insurance you don't want to go repair a plane.
Then create 2 pdf documents: one should contain your CV and motivational letter and the second one -- your transcript of records (required), its translation into English or German(required) and another certificates/awards/references/diplomas (optional)

Then choose the day and place for interview, go to the special recruiting website and upload your 2 files. Wait for the response.

How was the preparation period and applying for visa?
If you're cool, you're on the shortlist and some company picked you out, the program coordinators will contact you and tell you to prepare for visa application. The program takes care of everything and you will apply together with other participants and the coordinators in Kyiv. You won't need anything you don't have: just copies of your ids, your insurance and the contract that you will get from the company via mail. You will also need to fill out some fancy forms and sort the documents in a special order XD Oh this bureaucracy. All can I say, it was not stressful at all, on the contrary -- it was fun.

What did the University say about your absence?
It's a complicated question. In general, Universities are not happy that you break their old kinky workflow, and the first thing I heard from my faculty office is to take an academical vacation. You know, that one, for a year. I disagreed and asked people: it turned out that my internship is academical mobility and I can be absent for 3 months without a problem, but the biggest requirement was to take exams in time. I would come back after the exams had finished, so I decided to take them before semester. It worked, everybody's happy.

What can you say about your company?
I had an internship in Bosch Rexroth. It's a big company that does a lot of things, and developing industrial controllers is among them.

It's a part a bigger Bosch Group and it's motto is "The drive and control company".

How was your internship?
Well, it was a great chance. I met a lot of great people and professionals, made a few friends around the globe, increased my proficiency in German language rather drastically and got a recommendation letter with a Bosch logo on it. Not to mention all the traveling, having fun and a wonderful old town I lived in for the whole three months!


What can you say in the end?
If you hesitate -- don't, just try. I am an average student with a slight English proficiency and I did it. So can you, I am sure.

If you have any questions feel free to ask them in the comment section below, I will try to add new answers in the post. Good luck!



Contacts:
  1. http://stipendienprogramm-ukraine.de/
  2. www.ost-ausschuss.de/ua
  3. https://www.facebook.com/UAinternship
  4. https://vk.com/uainternship
  5. https://www.giz.de/en/worldwide/30663.html
  6. http://eo-ucci.org.ua/en/the-scholarship-program-of-the-german-economy/the-scholarship-program-of-the-german-economy

Monday, January 18, 2016

The Narnia cookbook

I dreamed about cooking the same meal, Mrs Beaver cooked and now my dreams come true.

Friday, December 25, 2015

How to save custom shortcuts or keybindings on debian GNOME

According to ubuntu reference dconf is the most appropriate tool to manage shortcuts. Custom keybindings are stored in /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/, so we do

dconf dump /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/ > bkp

and bkp contains something like this:
[custom1]
binding='<Primary><Alt>t'
command='gnome-terminal &'
name='console'

[custom2]
binding='<Shift>Print'
command='gnome-screenshot -a'
name='screenshot-to-/home/asalle/Pictures'

[custom3]
binding='<Primary><Alt>i'
command='iceweasel'
name='iceweasel'

After this, put the bkp file into the cloud or elsewhere, where it can be safe and restore keybindings, if necessary, with:

 dconf load /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/ < bkp

Sorry, guys, I haven't tried the last one, so I am not sure if it works.

Sunday, September 6, 2015

if the "compress" context menu of nautilus is missing

I had a freshly installed latest stable Debian (Jessie) and some files to archive. Those were photos, ant it was very convenient to pick some of them in visual mode and choose compress from the context menu of nautilus, but it was not there.

After some digging I found that file-roller package is missing, after installing it everything was okay, so

sudo apt-get install file-roller
killall nautilus
nautilus &

Thursday, July 23, 2015

Touchpad not working after suspend on Debian Jessie

You can try some tricks, like adding

quiet splash i8042.notimeout atkbd.reset

to /etc/default/grub (line GRUB_CMDLINE_LINUX_DEFAULT=)

and then run
sudo update-grup and reboot

Or run
gconftool-2 --set --type boolean /desktop/gnome/peripherals/touchpad/touchpad_enabled true
if your touchpad is simply hardware-disabled.

As for me, nothing mentioned above worked. I use a workaround, that unplugs and plugs in the touchpad again, here what it looks like

#!/bin/bash
rmmod psmouse
modprobe psmouse

I was forced to call this after every awakening, and this was very annoying. I thought about automating all this. Most articles I read tried to use pm-suspend and some custom hooks for it:

sudo vim /etc/pm/sleep.d/0000trackpad
  1 cat /etc/pm/sleep.d/0000trackpad
  2 #!/bin/sh
  3 case "$1" in
  4     suspend|hibernate)
  5          modprobe -r psmouse ;;
  6     resume|thaw)
  7         modprobe psmouse ;;
  8 esac



This worked, but... It turned out that debian does not use pm-suspend when it suspends =(
To suspend and awake with touchpad working I had to sudo pm-suspend manually, so annoying. And again, when debian suspends from low battery or lid closed, it suspends without pm-suspend, so I had to run my annoying script.

Arghh!..

Debian uses systemd to manage power, so should I. By the way, when duckduckgoing word "systemd" a lot of controversial and critical posts come up about it being too complex and handling too much responsibility, try it!

systemd provides it's own environment to create hooks, so I created one that finally worked!

sudo vim /etc/systemd/system/touchpad_awakening.service 

[Unit]
Description=Reload mouse after suspend
After=suspend.target
After=hibernate.target
After=hybrid-sleep.target

[Service]
ExecStart=/home/asalle/bin/mouse

[Install]
WantedBy=suspend.target
WantedBy=hibernate.target
WantedBy=hybrid-sleep.target

(mouse is the script that modprobes the psmouse)

then, enable the service by
sudo systemctl enable touchpad_awakening.service 
and start manually to check it by
sudo systemctl start touchpad_awakening.service
check the result
sudo systemctl status touchpad_awakening.service

it reads:
● touchpad_awakening.service - Reload mouse after suspend
   Loaded: loaded (/etc/systemd/system/touchpad_awakening.service; enabled)
   Active: inactive (dead) since Thu 2015-07-23 16:08:20 EEST; 5s ago
  Process: 4285 ExecStart=/home/asalle/bin/mouse (code=exited, status=0/SUCCESS)
 Main PID: 4285 (code=exited, status=0/SUCCESS)

After suspend it worked okay. 
At last!

Monday, July 20, 2015

Debian Jessie on Fujitsu UH 552

So I had my Fujitsu UH 552 for a while now.
First, I had pre-installed Windows 8 there. First day I got it, I partitioned the hard disk for several parts:

Here is fdisk -l
Device         Start       End   Sectors   Size Type
/dev/sda1       2048    194559    192512    94M EFI System
/dev/sda2     194560  30914559  30720000  14.7G Linux filesystem
/dev/sda3  968669184 976771071   8101888   3.9G Linux swap
/dev/sda4   30914560  92354559  61440000  29.3G Microsoft basic data
/dev/sda5   92354560 153794013  61439454  29.3G Microsoft basic data
/dev/sda6  153794560 866269183 712474624 339.8G Microsoft basic data
/dev/sda7  866269184 968667135 102397952  48.8G Linux filesystem


sda1 is the boot partition, since I have UEFI, it is marked as EFI System. The grub and bootloader stuff is stored there.

sda2 is the /opt/ on his own partition (I have almost 5 GB of additional software, most of it are IDEs).

sda3 is a swap partition

sda4 is the C:/ drive of Windows 8

sda5 is the root directory (/). I'm wondering, why it is marked as Microsoft basic data by the fdisk.

sda6 is a ntfs data partition, where all the big data is stored, as archives of my university files and so on.

sda7 is /home on his own partition.

So, with this crazy-crazy situation I made up my mind to move from Ubuntu to Debian.
First, I made a live-usb. Just jigdo-ed the latest (Jessie) livecd distribution and tried to

dd if=debian-8.1-livecd.iso of=/dev/sdb1

and... nothing happened.
I guess there was some problem with bootloader, but I didn't want to dig deep this time, I wanted my Jessie to be right away! So I used the UNetBootin app. Great stuff, saved me a lot of times! So I flashed the liveusb with the jigdo-ed iso and UNetBootin and booted from the usb.

Installation process is rather ordinary, the only thing I changed is used sda7 as /home and didn't format it.

The several problems of fresh-installed Debian Jessie:
  1. no touchpad
  2. no wlan
  3. =(
 During the installation I missed that no Ethernet card was found on my laptop, so there was no driver installed for it. What a pity.
 Also, a classical problem of debian-like OS: Synaptic touchpad is not working. I must add, that even if you  fix it by adding

i8042.nomux

to /etc/default/grub, you will still face the problem after every single suspend. This is also fixable (but I'm telling it not now).

For wifi you need to install iwlwifi driver (I have Inter 3022 Ethernet card). You need to install firmware-iwlwifi_versionhere.deb or something like that. After installing the package, just do

modprobe iwlwifi

and reboot. Voila, after that I immediately had my wifi working, hooray.

Result: safe moving with several partitions and Windows8  from Ubuntu to Debian, no skill required. Thank you, great developers!

Wednesday, June 3, 2015

if you cannot view phpmyadmin's web interface


  1. check if you have Apache server running
  2. do the magic:
Open Apache config file:
Code:
sudo gedit /etc/apache2/apache2.conf
Add this line:
Code:
Include /etc/phpmyadmin/apache.conf
Restart Apache:
Code:
sudo /etc/init.d/apache2 restart
Type in your browser:
Code:
http://localhost/phpmyadmin


Tuesday, January 6, 2015

Happy New Year!

I got a few hours before work and I decided to codefore a bit.
Hope this was not a server failure :D