Script with hash tables on windows and Linux

How to declare and write a script with hash tables on windows and linux

  • Hash tables with powershell on windows

    Declaration:
    $states=@{“Alberta” = “Calgary”; “British Columbia” = “Vancouver”; “Ontario” = “Toronto” ; “Quebec” = “Montreal”}

    Name
    _____
    Value
    _______
    Alberta Calgary
    British Columbia Vancouver
    Ontario Toronto
    Quebec Montreal

    Add new key-value in hashtable:
    $states.Add(“Manitoba”,”Winnipeg”)

    Remove key-value in hashtable:
    $states.Remove(“Manitoba”,”Winnipeg”)
    Change value in hashtable:
    $states.Set_Item(“Ontario”,”Ottawa”)
    Retrieve value in hashtable:
    $states.Get_Item(“Alberta”)
    Find key in hashtable:
    $states.ContainsKey(“Alberta”)
    Find Value in hashtable:
    $states.ContainsValue(“Calgary”)
    Count items in hashtable:
    $states.Count
    Sort items by Name in hashtable:
    $states.GetEnumerator() | Sort-Object Name -descending
    Sort items by Value in hashtable:
    $states.GetEnumerator() | Sort-Object Value -descending

  • Hash tables with perl on linux or windows

     
    Declaration:
    my %hash = (); #Initialize a hash
    my $hash_ref = {}; # Initialize a hash reference. ref will return HASH
    Clear (or empty) a hash
    for (keys %hash)
    {
    delete $hash{$_};
    }
    Clear (or empty) a hash reference
    for (keys %$href)
    {
    delete $href->{$_};
    }
    Add a key/value pair to a hash
    $hash{ ‘key’ } = ‘value’; # hash
    $hash{ $key } = $value; # hash, using variables
    Using Hash Reference
    $href->{ ‘key’ } = ‘value’; # hash ref
    $href->{ $key } = $value; # hash ref, using variables
    Add several key/value pairs to a hash
    %hash = ( ‘key1’, ‘value1’, ‘key2’, ‘value2’, ‘key3’, ‘value3’ );
    %hash = (
    key1 => ‘value1’,
    key2 => ‘value2’,
    key3 => ‘value3’,
    );

    Copy a hash
    my %hash_copy = %hash; # copy a hash
    my $href_copy = $href; # copy a hash ref
    Delete a single key/value pair
    delete $hash{$key};
    delete $hash_ref->{$key};

  • Hash tables with python on linux or windows

    Hash tables are called dictionary in python.
    Declaration:
    dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
    Accessing Values
    print “dict[‘Name’]: “, dict[‘Name’]
    print “dict[‘Age’]: “, dict[‘Age’]
    Output:
    dict[‘Name’]: Zara
    dict[‘Age’]: 7
    Updating Dictionary
    dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

    dict[‘Age’] = 8; # update existing entry
    dict[‘School’] = “DPS School”; # Add new entry
    Delete Dictionary Elements
    #!/usr/bin/python

    dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

    del dict[‘Name’]; # remove entry with key ‘Name’
    dict.clear(); # remove all entries in dict
    del dict ; # delete entire dictionary

Source:

  1. https://technet.microsoft.com/en-us/library/ee692803.aspx
  2. http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash/
  3. http://www.tutorialspoint.com/python/python_dictionary.htm

How to pipe grep on command line on windows and Linux

Let’s find how to pipe grep or find a specific string after running a command using shell, batch and powershell (windows and Linux)

  • On Linux via shell

    ls -al | grep filename

  • On Windows via powershell

    GetChildItem | Select-Object “filename”
    or
    GetChildItem | where-Object {$_ -match “filename”}

  • On Windows via batch

    Dir | findstr “filename”

Which one is better to live in, Calgary or Edmonton? Why?

Calgary and Edmonton are the 2 biggest cities in Alberta, Canada. The question is which one is better to live in, Calgary or Edmonton? Why?

What are the pros and cons of Calgary vs Edmonton.




As someone who has lived in both cities for more than 3 years and is still living in Calgary:

  1. Weather: you have more sunshine and less harsh winter in Calgary with occasional positive temperature in the middle of the winter because of the Chinook winds: Calgary wins
  2. Cost of life: Edmonton rent, home ownership, food, clothing is slightly cheaper than same items in Calgary: Edmonton wins
  3. Job Opportunities: more blue collar jobs in Edmonton, more white collar jobs in Calgary: tie
  4. Education: Edmonton has one of the top university in Canada called University of Alberta. University of Calgary has a first class business school called Hayskane school of business. Edmonton wins.
  5. City’s architecture: Calgary seems newer, nicely architected and just more beautiful to me by far: Calgary wins
  6. People: just the same to me, no difference: tie
  7. Size and population: Calgary (1.3 million people, 825 km2) is larger and have more people than Edmonton (1 million people, 684 km2): I won’t call this a win
  8. Mountains and lakes : Banff National Park, Lake Louise, Jasper National Park, Waterton Lakes National Park, are all closer to Calgary than Edmonton: Calgary Wins
  9. Summer festivities: Both cities have great and similar festivals, but Calgary hosts the greatest western festival on earth in July called the Stampede. Calgary wins.
  10. Sunshine: Calgary has way more sunshine that Edmonton. In fact, Calgary is amongst the top city with sunshine exposure in the entire country. Sunshine is happiness. Calgary wins.
  11. Politics: Both cities are economically conservative. Edmonton is a little bit more socially liberal than Calgary. Who cares? Tie.
  12. Sports: Flames(NHL)and Stampeders(CFL)in Calgary, Oiler(NHL) and Eskimos(CFL) in Edmonton. Several amateur leagues, indoor and outdoor facilities for soccer, hockey, basketball, football and baseball in both cities; ShowUpAndPlay in Calgary, ShowUpAndPlay in Edmonton : Tie
  13. Bars and Pubs: Cowboys in Calgary, Black dog free house in Edmonton are the most populars. Cowboy culture in both cities but not violent, no guns. Tie ( The 10 Best Nightclubs in Calgary , The Best Nightlife in Edmonton – TripAdvisor )
  14. Downton: See Calgary Downtown inRealTimeNow.com. See Edmonton inRealTimeNow.com They are both vibrant and Nice: Tie
  15. Cleanliness: Calgary is one of the cleanness cities in the world. I am in awe myself whenever I walk downtown and in my neighbourhood of Walden. Calgary wins by far.

 

With all that in mind, I’ll choose Calgary any day.

Resources:




Learn more about Calgary here.
Learn more about Edmonton here.

Are you planning to visit or move to Calgary or Edmonton?

Things to do to build more diverse technical teams?

What are specific Things to do to build more diverse technical teams?

  • 1. Start at the junior high school level in poor neighborhood by helping schools to teach minority kids how to code.
  • 2. Help set up computer labs in junior high school in poor neighborhoods so that kids who cannot afford the equipment can use the lab.
  • 3. Start coding challenges with prizes in those high school neighborhood and make the kids feel confident about their abilities.
  • 4. Get successful minorities entrepreneurs to host the kids and give them tours of their companies and offices and projects to inspire them.
  • 5. Give internships to minorities kids starting in high school.
  • 6. For the kids in senior high school who missed early adoption to coding, speed them up with after hours coding classes to prepare them for college.
  • 7. In college, make the minority kids feel welcome. Try to make them part of all activities ( computer related or not).
  • 8. For the kids in senior high school who missed early adoption to coding, speed them up with after hours coding classes to prepare them for college.
  • 9. In college, make the minority kids feel welcome. Try to make them part of all activities ( computer related or not). Help find internships from top IT firms (Google, Apple, IBM, etc.) for minorities.
  • 10. When minorities start working after college, welcome them in the team and trust them. Don’t just invite certain kids to dinner and golf. It makes minorities feel unappreciated and unwanted.
  • 11. Give minorities the same opportunity of advancement at work with other employees.
  • 12. Inclusion, inclusion, inclusion in every aspect of the company is the key.
  • Assess the progress of your efforts and adjust. Make sure that team leads or managers are open minded people and make it a priority for them to build diverse teams, because in the long run, it will be a win win for the company

Read more here on Quora.

How to stay healthy as a software engineer?

Tricks and Tips: How to stay healthy as a software engineer or IT professional?

I am a software engineer like you and by my second year I started feeling the unhealthy behavior of sitting down and coding for long hours.

How to stay healthy as a software engineer
How to stay healthy as a software engineer

Below are the steps that I took:

  1. Avoid sitting down for more than 1 hour without getting up for a walk.
  2. Stand up for 15 minutes every hour to code.
  3. Take multiple short walks outdoor during working hours.
  4. Avoid elevators unless you have no choice, use the stairs to go up and down if your office floor is lower than the 5th floor.
  5. Avoid drinking sweet drinks or too much coffee during work hours.
  6. Avoid eating chips or almost anything while working.
  7. Instead of spending long hours reading manuals and documents on your computer, print them out, then take a walk and read them somewhere quiet while standing.
  8. Stretch often while working (extend your legs, arms, rotate your neck).
  9. Take short breaks of 2 to 5 minutes every 2 hours to read something different from your main topic. It can be news, sports, entertainment, or anything else you like. I read or write on Quora during my breaks.
  10. Change your position frequently and don’t hesitate to stand up at your desk from time to time while working.
  11. Make sure that your chair is always comfortable. Don’t hesitate to upgrade or get a better chair if necessary.

Here are the steps that I took to stay active and healthy:

  1. I am committed, no matter what, to playing at least 2 competitive games of soccer or basketball a week, either in an amateur team league or at drop-in sports leagues. Check out one of my drop in league chapter in your city at ShowUpAndPlaySports chapters – Djamga – ShowUpAndPlaySports
  2. I volunteer to organize soccer and basketball games every week via Home – Djamga – ShowUpAndPlaySports
  3. I walk regularly at lunch time, and try to get as much sunshine as possible.
  4. I visit a chiropractor once a month to adjust my back and neck.
  5. I visit a certified massage therapist regularly to work on my neck, back, hamstrings, and feet.
  6. I visit a pedicure clinic once a month for a good pedicure and foot massage.
  7. I eat a healthy diet of mostly vegetables and fish (mostly salmon).
  8. I drastically reduced the carbs in my diet. Every morning, I take one cup of coffee or tea with no sugar or milk and a small cake. Then, I am covered until dinner time. In the evening, I have a large meal of vegetables and fish, usually salmon.
  9. I drink plenty of water.
  10. I don’t drink alcohol or smoke.
  11. It is very important to sleep well; sleep at least 6 hours per day.
    You spend about 25% of your life in your bed, there you need to invest on your mattresses, pillows, bed furnitures and upgrade them regularly.

After adopting these habits, my efficiency came back. I was able to work as hard as when I was a student . I even lost weight!

Now, I can go toe-to-toe with young players and students in their twenties on the soccer field. I easily work more than 60 hours per week and still have enough time to play with my kids and enjoy a fulfilling life with my family.

I highly recommend these life-changing habits to all IT professionals and engineers so they can remain healthy and effective as they get older and busier.

reverse a string on Linux and Windows

How to reverse a string on Linux and Windows

Via shell script on Linux

reverse a string on Linux and Windows

sh-3.2# vi reverse.sh
#### Start Script #####
#!/bin/bash
input_string=”$1″
reverse_string=””

input_string_length=${#input_string}
for (( i=$input_string_length-1; i>=0; i– ))
do
reverse_string=”$reverse_string${input_string:$i:1}”
done

echo “$reverse_string”
##### End Script #####

Let’s run it:

sh-3.2# chmod 775 reverse.sh
sh-3.2# ./reverse.sh Etienne
enneitE

Via powershell script on Windows

#Let’s use the script reverse.ps1 below.
######
$string=”Etienne”
$string_array=$string -split “”
[array]::Reverse($string_array)
$string_array -join ”

#####Output#####
PS C:\Users\etienne_noumen\Documents\Etienne\Scripting> .\reverse.ps1

E t i e n n e

enneitE

Via powershell script on Windows in one line

([regex]::Matches($String,’.’,’RightToLeft’) | ForEach {$_.value}) -join ”

Via batch script on Windows

::Note: ReverseStr also calls StrLen
::and string length is not greater than 80 chars
:: but can be changed.

@echo off
SetLocal EnableDelayedExpansion
cls
set Str=Etienne
call :StrLen %Str%
echo Length=%Len%
call :ReverseStr %Str%
echo String=%Str%
echo Reverse Str=%Reverse%
exit /b

::—————-
:: Calc Var Length
::—————-
:: %*=Str to Check
:: Returns %Len%
:: —————
:StrLen %*
set Data=%*
for /L %%a in (0,1,80) do (
set Char=!Data:~%%a,1!
if not “!Char!”==”” (
set /a Len=%%a+1
) else (exit /b)
)
exit /b

::—————
:: Reverse String
::—————
:: %* Str to Reverse
:: Returns %Reverse%
::——————
:ReverseStr %*
set Data=%*
call :StrLen %Data%
for /L %%a in (!Len!,-1,0) do (
set Char=!Data:~%%a,1!
set Reverse=!Reverse!!Char!
)
exit /b

Via perl script on Windows or Linux

Via python script on Windows or Linux

Source:

  1. http://www.computing.net/answers/programming/reverse-a-string-in-dos/26004.html

jQuery What is it?


Who hasn’t gotten this question yet: jQuery What is it?

Source: http://www.w3schools.com/jquery/jquery_intro.asp

Definition:
jQuery is a lightweight, “write less, do more”, JavaScript library.
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.

Purpose
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery’s syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

What is in it
The jQuery library contains the following features:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

Advantages:
The modular approach to the jQuery library allows the creation of powerful dynamic web pages and web applications.
jQuery has plugins for almost any task out there.

jQuery Syntax:
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() – hides the current element.

$(“p”).hide() – hides all

elements.

$(“.test”).hide() – hides all elements with class=”test”.

$(“#test”).hide() – hides the element with id=”test”.

Example of html page including jQuery code:
jQuery_Code_Example
Test it below:






If you click on me, I will disappear.

Click me away!

Click me too!




More on jQuery:
[jQuery Guide and Resources]

JSON : JavaScript Object Notation

What is JSON : JavaScript Object Notation?

Source: https://www.json.com/

What is JSON?

JSON is a lightweight text-based open standard designed for human-readable data. It is the most widely used format for exchanging data on the web. It originates from the JavaScript language and is represented with two primary data structures: ordered lists (recognized as ‘arrays’) and name/value pairs (recognized as ‘objects’).

Why JSON?

The JSON standard is language-independent and its data structures, arrays and objects, are universally recognized. These structures are supported in some way by nearly all modern programming languages and are familiar to nearly all programmers. These qualities make it an ideal format for data interchange on the web.

JSON vs XML

The XML specification does not match the data model for most programming languages which makes it slow and tedious for programmers to parse. Compared to JSON, XML has a low data-to-markup ratio which results in it being more difficult for humans to read and write.

JSON Data Types

  • Number{ “myNum”: 123.456 }
    A series of numbers; decimals ok; double-precision floating-point format.
  • String{ “myString”: “abcdef” }
    A series of characters (letters, numbers, or symbols); double-quoted UTF-8 with backslash escaping.
  • Boolean{ “myBool”: true }
    True or false.
  • Array{ “myArray”: [ “a”, “b”, “c”, “d” ] }
    Sequence of comma-separated values (any data type); enclosed in square brackets.
  • Object{ “myObject”: { “id”: 7 } };
    Unordered collection of comma-separated key/value pairs; enclosed in curly braces; properties (keys) are distinct strings.
  • Null{ “myNull”: null }
    Variable with null (empty) value.

Unsupported Data Types

  • Undefinedvar myUndefined;
    Variable with no value assigned.
  • Datevar myDate = new Date();
    Object used to work with dates and times.
  • Errorvar myError = new Error();
    Object containing information about errors.
  • Regular Expressionvar myRegEx = /json/i;
    Variable containing a sequence of characters that form a search pattern.
  • Functionvar myFunction = function(){};
    Variable containing a block of code designed to perform a particular task.

JSON cheat sheet

Example1: Mixed Data Types

var myObject = {
“myNumber”: 123.456,
“myString”: “abcdef”,
“myBool”: true,
“myArray”: [ “a”, “b”, “c”, “d” ],
“myObject”: { “id”: 7 },
“myNull”: null
};

Example2: Send HTTP POST request with JSON to a http://url with the following string fields: ‘first_name’, ‘last_name’, ’email’, ‘phone’,’urls’

curl -X POST -d ‘{“first_name”: “John”, “last_name”: “Doe”, “email”: “johndoe@email.com”, “phone”: “000-000-0000″,”urls”: [“https://djamga.com”,”http://enoumen.com”,”http://twitter.com/enoumen”]}’ http:/url -H ‘Content-Type: application/json’

Remove all empty lines in a file

How to Remove all empty lines in a file on Linux and Windows?

Remove empty lines from file.txt via Linux command line

  • Option 1: sed -i ‘/^$/d’ file.txt
  • Option 2: awk ‘NF > 0’ file.txt > output.txt
  • Option 3: perl -i.backup -n -e “print if /\S/” file.txt
  • Option 4: grep . file.txt > output.txt

Remove empty lines from file.txt using Powershell script on Windows

  • (gc file.txt) | ? {$_.trim() -ne “” } | set-content file.txt