Author Archives: toni

Webpack – Getting Started

How to use this tutorial ?

The table of contents of this tutorial is located on the right side

There are two projects that we need:
– the front-end website that we are going to build in this tutorial,
GraphQL server which we are going to use later in “Adding Apollo provider and introduction to making queries to GraphQL“.

There are two GitHub repositories with the complete projects located here:
GitHub:WebpackReactReduxApolloTutorial

And the GraphQL server located here
GitHub:graphql-boilerplate

Instructions of how to set up GraphQL server could be found HERE.

When you go through each chapter you could check out the appropriate branch which contains the chapter specific code, instead of looking at the complete project.
This way will be easier to follow the developing process. Each branch name could be found at the beginning and the end of the tutorial. Look for branch-name: XXXXX

In general it would be better if you follow the tutorial and build the website yourself but if you get stuck somewhere feel free to clone the repository and check out the appropriate branch.

Setting up the project

branch-name:  
Click To Copy

 

mkdir babel-webpack-boilerplate
cd babel-webpack-boilerplate
yarn init -y
yarn add webpack webpack-cli --dev

What we just did:
– line 1: created project’s folder
– line 2: navigate to project’s folder root
– line 3: executing yarn init -y initialized our new project. – y simply means ‘answer yes and use the default init settings’. A package.json is created, which is used to describe the npm project dependencies and executable scripts.
– line 4: we added Webpack as a dev dependency (–save-dev) in our project.

Creating project’s files

Using your favorite text editor create index.html in the root folder of the project, with plain html, and a script tag to include our bundled Java Script code (Line 9).

./index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Babel Webpack Boilerplate</title>
    </head>
    <body>
        <h1>Babel Webpack React Boilerplate</h1>
        <script type="text/javascript" src="dist/main-bundle.js"></script>
    </body>
</html>

Create folder to store the actual bundle files:

mkdir ./src

Create the actual bundle files:

src/app.js

import test from './test';
test('Babel is running!');

src/test.js

const test = (msg) => {
  console.log(msg);
}
export default test;

and dist folder to store compiled bundle:

mkdir ./dist

The project’s layout should look like this:

babel-webpack-react-boilerplate
├── dist
├── index.html
├── node_modules
├── package.json
├── src
|        ├── app.js
|       └── test.js
└─ package.lock

* package.lock is used to describe which versions of node modules are installed, and is create automatically after executing npm install, so don’t worry if it’s not there yet.

Running Webpack and creating Java Script bundle.

Now we have laid out a simple project, let’s create a bundle and run it.
In the terminal in the project’s root folder execute

./node_modules/webpack/bin/webpack.js ./src/app.js -o ./dist/main-bundle.js

What we just did:
– we called Webpack from the command line.
– passed the entry point ./src/app.js to create the bundle.
– and the output file -o ./dist/main-bundle.js

Now if we look at the ./dist folder, we will see that the bundle.js is created.

Testing the project

Open your browser and navigate to the the project’s root.

Look at the console and you will see ‘Babel is running!’.

Congratulations, you just created your first bundle!

branch-name:  
Click To Copy

 

 

where to go from here ?

Add Two Numbers

Task

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Examples :

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

This problem was taken from Leetcode

Solution

The solution:

Java Script

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */



function ListNode(val, next) {
  this.val = (val===undefined ? 0 : val)
  this.next = (next===undefined ? null : next)
}


/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
  
  function doSum(a,b, carry) {
    var result = {
      val: 0,
      carry: 0
    }
    var sum = a + b + carry;
    if(sum > 9) {
      result.val = sum - 10;
      result.carry = 1;
    }
    else {
      result.val = sum;
      result.carry = 0;
    }
    return result;
  }

  var nodeA = l1;
  var nodeB = l2;
  var end = false;
  var carry = 0;
  var result = new ListNode(0, null);
  var resultPointer = result;
  var tmp = null;

  while(nodeA != null || nodeB != null) {
    var valA = nodeA == null ? 0 : nodeA.val;
    var valB = nodeB == null ? 0 : nodeB.val;
    var sumResult = doSum(valA, valB, carry);
    carry = sumResult.carry;
    
    resultPointer.val = sumResult.val;
    resultPointer.next = new ListNode(0, null);
    tmp = resultPointer;
    resultPointer = resultPointer.next;

    nodeA = nodeA ? nodeA.next : null;
    nodeB = nodeB ? nodeB.next : null;
  }

  if(carry != 0) {
    tmp.next.val = carry; // add carry to the val of the last node
  }
  else 
    tmp.next = null; // remove the last empty node.
  return result;
};




var l1 = new ListNode(9, 
          new ListNode(9,
          new ListNode(9,
          new ListNode(9, null)
      ))
);

var l2 = new ListNode(9, 
          new ListNode(9,
          new ListNode(9,
          new ListNode(9,
          new ListNode(9,
          new ListNode(9,                    
          new ListNode(9, null)
      )))))
)

// [9,9,9] , [9,9,9,9,9]
// result: [8,9,9,0,0,1]

var result = addTwoNumbers(l1, l2);

console.log(result);

Understanding Java Script Map, Filter and Reduce

 

The array

// The array
var people = [
  { name: 'john', age: 24, weight: 84 },
  { name: 'tim', age: 34, weight: 76 },
  { name: 'Jack', age: 26, weight: 65 },
];

 

MAP

// map - use it if I want to do the same operation for each element in the array
// and return the same amount of items in the array.
// array.map(
// current item of the array,
// curent index,
// the entire array
// );
var result = people.map((person, index, persons) => {
  return `${person.name}: ${person.age}`;
});
console.log('map', result);

 

FILTER

// filter - return only items that match certain criteria.
// array.filter(
// current item of the array,
// curent index,
// the entire array
// )

var result = people.filter((person, index, persons) => {
  return person.age < 30;
});
console.log('filter', result);

 

REDUCE

// reduce - return something completely new after iteration through each element
// in the array
// array.reduce(
// current value of the end value,
// current item,
// curent index,
// the entire array
// )
var initialValue = 10;
var combined_weight = people.reduce((weight, person, index, persons) => {
  return weight += person.weight;
}, initialValue);
console.log('reduce', combined_weight);

Another example of reduce, that will convert the array of objects, to object of objects, where person.name is going to be the key

var reducer = (accumolator, person) => {
  accumolator[person.name] = person;
  return accumolator;
}

var initialValue = {};

// reduce takes reducer function as first parameter, and initial value
var result = people.reduce(reducer, initialValue);

console.log('reduce', result);

 

Two way communication between parent document and iFrame

This page is a simple demonstration of two way communication between iFrame and parent document even if they are hosted in different domains.

index.html

<html>
  <head>
    <style>
      iframe {
      width:50%;
      height:50%;
      }
    </style>

    <script>
      // Listen for iframe loaded event
      window.addEventListener("message", receiveMessage, false);
      function receiveMessage(event)
      {
        if(event.origin !== "http://sandbox.toni-develops.com")
        return
        console.log('[parent]' + event.data);
      }

      function postTheMessage() {
        document.querySelector('#my_iframe').contentWindow.postMessage("Parent doc messaged the iframe", "*");
      }
    </script>
  </head>

  <body>
    <div id="wrapper">
    <iframe id="my_iframe" src="./iframe.html"></iframe>
    <br>
    <button onclick="postTheMessage()">send message to the iframe</button>
    </div>
  </body>
</html>

Two very important notes:
– When we add an event listener, we have to explicitly specify that we are going to listen to a “message” (line 12) and not passing the actual message there.
– we have to declare the event listeners before loading the actual <iframe ..> tag.

 

iframe.html

<html>

<head></head>

<body>
  <script>
    window.addEventListener("message", receiveMessage, false);
    function receiveMessage(event) {
      if (event.origin !== "http://mydev.com")
        return
      console.log('[iframe]' + event.data);
    }
    function postTheMessage() {
      window.parent.postMessage("iFrame sent a message", "http://mydev.com/sandbox/*");
    }
    postTheMessage();
  </script>
  <p>I am an iFrame!</p>
  <br>
  <button onclick="postTheMessage()">click to post message to the parent document</button>
</body>

</html>

 

How this works:
– Parent document index.html is subscribing for events named “message” (line 12) and calls receiveMessage function (line 13) when the event occur.
– When document is loaded, and the iframe is ready, it emits message to index.html (line 19 in iframe.html)
– When parent document receives message, it makes sure that it comes from the domain that the parent document is interested in, so no other iframe could trigger this action (line 15 in index.html) If so, do something. In this case console.log the message.

 

Climbing stairs

Task

You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.


Example 1:

Input: 2
Output: 2

Explanation:

 There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps


Example 2:

Input: 3
Output: 3

Explanation:

 There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

 

This problem was taken from Leetcode

Solution

The solution:

Let’s look at the possible scenarios:

[table id=1 /]

If we look at the # of ways to climb, we clearly see that the ways to climb grows in Fibonacci sequence: 1, 2,  3,  5,  8,  13, 21

Then all we need to do is to iterate n times (where n  is the number of stairs) and to find the corresponding Fibonacci number.

Using while loop

  • basically we use temp to store previous Fibonacci number temp = a , initially 1
  • then we calculate the next number a = a + b , initially a = 0 + 1
  • then we set up b = temp which stores the last Fibonacci number in order to be ready for the next iteration. Initially 1.

Looking at the numbers from the first iteration, it is clear that on the second one we will have:
temp = a = 1
a = a + b = 1 + 1 = 2
b = temp = 1

third iteration will produce:
temp = a = 2
a = a + b = 2 + 1 = 3
b = temp = 2
forth iteration:
temp = a = 3
a = a + b = 3 + 2 = 5
b = temp = 3

and so on … a will always return the Fibonacci number for the current n position.

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n < 4) 
        return n;

    fibonacci = function(n) {

        var a = 1, b = 0, temp, num = 1;

        while(num <= n) {
            temp = a;
            a = a + b;
            b = temp;
            num ++;
        }
        return a;
    }

    return fibonacci(n);
};

Using For loop

This is the easiest to comprehend:

  • we create an array to store the Fibonacci numbers var fn = [1,1] with the first two numbers pre-set so the for loop could generate the next one.
  • created for loop that picks the fn[i - 1] and fn[i - 2] numbers and generate the next one.
  • pushed newly calculated Fibonacci number into an array so we could use to generate next one.
  • keep looping till we reached i < n + 1 which is the  answer.

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n  < 3)
    return n;
    
    var fn = [1,1];
    for(var i = 2; i < n + 1; i ++) {
        var nextNumber = fn[i - 1] + fn[i - 2]; 
        fn.push(nextNumber);
    }

    return fn[fn.length - 1];
};

 

Third solution: Using recursive function.

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n < 4) 
        return n;

    fibonacci = function(n) {
        if(n < 2) {
            return n;
        }
        var result = fibonacci(n - 1) + fibonacci(n - 2);        
        return result;
    }

    return fibonacci(n + 1);
};

The idea here is to call fibonacci(n) function to generate the next Fibonacci number.
For n < 2 the function will simply return n 0,1,2.
For n = 3 the function will call itself recursively asking for previous two Fibonacci numbers (2 and 1) and will calculate the next number which is the sum of the previous two, and so on.

Optimize the recursive function to use Memoization.

Memoization is simple technique where we are storing the value of already computed parameter into a HashMap function and quickly retrieve it when we need it.

In our current example since the keys are just a numbers we could store the Fibonacci numbers in a regular array (line 9). Then we simply check if the value already is set up into memo array and return it or call fibonacci function once again.
Then we set up memo array with the next solved Fibonacci number with index n

Java Script

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    if( n < 4) 
        return n;

    var memo = [];
    fibonacci = function(n) {
        if(n < 2) {
            return n;
        }
        var a = memo[n - 1] ? memo[n - 1] : fibonacci(n - 1);
        var b = memo[n - 2] ? memo[n - 2] : fibonacci(n - 2);

        return memo[n] = a + b;
    }

    return fibonacci(n + 1);
};

 

You might also want to check Fibonacci sequence generator.

Multiple asynchronous http calls using curl

If you ever needed to fetch data from multiple sources on the backend, probably you already explored the benefits of using curl multi fetch.
In the examples below, I’m using curl to fetch data from two urls, which simply have

[php]
<?php
sleep(3);
echo “Content 1 …”;

[/php]

 intentionally to delay the content generation so we could see the difference between regular http call and asynchronous curl multi fetch.

http://toni-develops.com/sandbox/examples/php/curl-multi-fetch/fetched-content/fetch1.php
http://toni-develops.com/sandbox/examples/php/curl-multi-fetch/fetched-content/fetch2.php

[php]

<?php

$t1 = microtime(true);

function fetchContent($Url) {
// is cURL installed yet?
if (!function_exists(‘curl_init’)){
die(‘Sorry cURL is not installed!’);
}

// OK cool – then let’s create a new cURL resource handle
$ch = curl_init();

// Now set some options (most are optional)

// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);

// Set a referer
curl_setopt($ch, CURLOPT_REFERER, “http://www.example.org/yay.htm”);

// User agent
curl_setopt($ch, CURLOPT_USERAGENT, “MozillaXYZ/1.0”);

// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);

// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

//Proxy if needed
//curl_setopt($ch, CURLOPT_PROXY, “64.210.197.20:80”);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

// Download the given URL, and return output
$output = curl_exec($ch);

// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}

echo “<textarea style=’width:100%;height:40%’>”;
echo fetchContent(‘http://toni-develops.com/sandbox/examples/php/curl-multi-fetch/fetched-content/fetch1.php’);
echo “</textarea>”;

echo ‘<hr>’;

echo “<textarea style=’width:100%;height:40%’>”;
echo fetchContent(‘http://toni-develops.com/sandbox/examples/php/curl-multi-fetch/fetched-content/fetch2.php’);
echo “</textarea>”;

echo ‘fetched for: ‘ . (microtime(true) – $t1) . “\n”;
[/php]

 

[php]
<?php

// is cURL installed yet?
if (!function_exists(‘curl_init’)){
die(‘Sorry cURL is not installed!’);
}

$ch = array();
$mh = curl_multi_init();
$total = 100;

$t1 = microtime(true);

$URLs = array( “http://toni-develops.com/sandbox/examples/php/curl-multi-fetch/fetched-content/fetch2.php”,
“http://toni-develops.com/sandbox/examples/php/curl-multi-fetch/fetched-content/fetch2.php”);

$i = 0;
foreach($URLs as $url) {
$ch[$i] = curl_init();
curl_setopt($ch[$i], CURLOPT_URL, $url);
curl_setopt($ch[$i], CURLOPT_HEADER, 0);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);

curl_multi_add_handle($mh, $ch[$i]);
$i ++;
}

$active = null;
do {
$mrc = curl_multi_exec($mh, $active);
//usleep(100); // Maybe needed to limit CPU load (See P.S.)
} while ($active);

$content = array();

$i = 0;
foreach ($ch AS $i => $c) {
$content[$i] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}

curl_multi_close($mh);

echo “<textarea style=’width:100%;height:40%’>”;
echo $content[0];
echo “</textarea>”;

echo ‘<hr>’;

echo “<textarea style=’width:100%;height:40%’>”;
echo $content[1];
echo “</textarea>”;

echo ‘fetched for: ‘ . (microtime(true) – $t1) . “\n”;
[/php]

 

So this way we are reducing the amount of time to fetch data from multiple URLs to the amount needed to complete the longest transaction.

 

Synchronizing Filezilla site config between all devices.

If you use several computers at work and at home, sometimes becomes quite handy to be able to have all site configs synced automatically instead of importing and exporting it after each change. And this is quite simple to achieve.
Filezilla stores site config in sitemanager.xml file, so all that you need to do is to replace this file with a copy stored in Dropbox, Google Drive or any other file synchronizing service.

  1. Locate sitemanager.xml file on your machine.
    Windows 7/8 & Vista – C:\Users\YourUserName\AppData\Roaming\FileZilla\sitemanager.xml
    Mac OSX – /users/YourUserName/.config/filezilla/sitemanager.xml
    Linux – /home/YourUserName/.filezilla/sitemanager.xml
  2. Create copy of this file to your favorite synchronizing folder: i.e.:\Dropbox\Settings\sitemanager.xml
  3. Create “softlink” (symbolic link) to the new location.
    Windows(open command prompt and type):
    mklink “C:\Users\YourUserName\AppData\Roaming\FileZilla\sitemanager.xml” “C:\Users\YourUserName\Dropbox\Settings\sitemanager.xml”OS X (terminal):
    ln -s /users/YourUserName/Dropbox/Settings/sitemanager.xml /users/YourUserName/.config/filezilla/sitemanager.xml

    Linux (terminal):
    ln -s /home/YourUserName/Dropbox/Settings/sitemanager.xml /home/YourUserName/.filezilla/sitemanager.xml

Brief Introduction to SWIFT types

Playground located at:  https://github.com/ToniNichev/Swift-Data-Types

  • Arrays

Arrays store data of the same type in the same order (sorted)
– line 1 demonstrates creating an array syntax.
– line 7 shows the shorthand array creation syntax
– line 13 shows creating an array with Array literal (and default values)

[csharp highlight=”2,7,13″]
// create empty array
var myArrayOne = Array<String>()
myArrayOne.append(“Test Value”)
print(“Array one value: \(myArrayOne[0])”)

// or using shorter syntax
var myArrayTwo = [Int]()
myArrayTwo.append(1)
myArrayTwo.append(2)
print(“Array one value: \(myArrayTwo[1])”)

// or with default values using array literal
var myArrayThree = [“one”, “two”, “three”]
print(“Array one value: \(myArrayThree[1])”)

// or
var myArrayFour = Array(repeating: 5, count: 3)
print(“Array count: \(myArrayThree.count)”)

//iterating over an array
for item in myArrayTwo {
print(item)
}
[/csharp]

result:

Array one value: Test Value
Array one value: 2
Array one value: two
Array count: 3
1
2

Although arrays can only store elements of the same type, it is still possible to store elements from different types by creating array of Any type.
In the example below, an array of Any type is created, and populated with string, integer, double values and even another array. Then while iterating through the array elements we convert all values to string representation (line 9), and print them.

var mixedArray = Array&lt;Any&gt;()
mixedArray.append("This is string") // adding string
mixedArray.append(123) // adding integer
mixedArray.append(2.64) // double value
mixedArray.append(myArrayTwo) // adding another array

print("Printing values of mixed array, converted to strings")
for item in mixedArray {
let val: String = String(describing: item)
print("\(val)")
}

 

 

[csharp highlight=”9″]
var mixedArray = Array<Any>()
mixedArray.append(“This is string”) // adding string
mixedArray.append(123) // adding integer
mixedArray.append(2.64) // double value
mixedArray.append(myArrayTwo) // adding another array

print(“Printing values of mixed array, converted to strings”)
for item in mixedArray {
let val: String = String(describing: item)
print(“\(val)”)
}
[/csharp]

result:

Printing values of mixed array, converted to strings
This is string
123
2.64
[1, 2]
  • Sets

Sets unlike arrays could only store unique values in unsorted order

[csharp highlight=”2,7,13″]

// create empty set
var mySetOne = Set<String>()
mySetOne.insert(“one”)
mySetOne.insert(“two”)
mySetOne.insert(“three”)
print(“mySetOne does contain’two’ : \(mySetOne.contains(“two”)) “)

// iterating
for item in mySetOne {
print(“mySetOne: \(item)”)
}

// we could create sets using Array literal too
var mySetTwo: Set&amp;amp;amp;amp;amp;lt;String&amp;amp;amp;amp;amp;gt; = [“One”, “two”]
[/csharp]

result:

mySetOne does contain'two' : true 
mySetOne: one
mySetOne: three
mySetOne: two
  • Dictionaries

    Dictionaries are pretty much like arrays, but they store values against keys

[csharp]
// dictionary with integer values
var myDict = [String: Int]()
myDict[“one”] = 1
myDict[“two”] = 2
print(“myDict value at positon ‘one’: \(myDict[“one”]!)\n”)

// dictionary with different types of objects
var obj = [String: AnyObject]()
obj[“one”] = “12345” as AnyObject?

// velue two, contains second dictionary
obj[“two”] = [“user”: [“name”: “Jim”, “email”: “jim@yahoo.com”] ] as AnyObject?
obj[“three”] = “1221” as AnyObject?

// value ‘four’ is Integer
obj[“four”] = 25 as AnyObject

//getting second dictionary inside value ‘two’
var subDict = obj[“two”]! as! [String: AnyObject]
print(“\n’subDict’ value: \(subDict)”)

// retreiving specific value
var subDict_user_name = ((obj[“two”]! as! [String: AnyObject])[“user”] as! [String: AnyObject])[“email”] as! String
print(“\n’subDict_user_name’ value: \(subDict_user_name)”)

[/csharp]

result:

myDict value at positon 'one': 1


'subDict' value: ["user": {
 email = "jim@yahoo.com";
 name = Jim;
}]

'subDict_user_name' value: jim@yahoo.com
  • Enumerations

Swift enumerations are common set of related cases

[csharp]
enum Locations {
case Bulgaria, USA, Australia

var address: String {
switch self {
case .Bulgaria:
return “Ohrid 3 b”
case .USA:
return “5711 Jefferson st”
case .Australia:
return “New zeland drive”
default:
return “No selection!”
}
}

var city: String {
switch self {
case .Bulgaria:
return “Velico Tarnovo”
case .USA:
return “West New Tork”
case .Australia:
return “Sidney”
default:
return “No selection!”
}
}
}

let country = Locations.USA
print(“COUNTRY: \(country) \nAddress: \(country.address) \nCity:\(country.city)”)
[/csharp]

result:

COUNTRY: USA 
Address: 5711 Jefferson st 
City:West New Tork

 

  • Closures

[csharp]

let s = double(2, 2)

testFunc(ParamA: 2, closureA: { (paramB) in
print(“>>>\(paramB)”)
}) {
print(“Closure 2”)
}
}
// a closure that has no parameters and return a String
var hello: () -> (String) = {
return “Hello!”
}

// a closure that take two parameters and return an Int
var double: (Int, Int) -> (Int) = { x, y in
return y * x
}
func testFunc(ParamA:Int, closureA:(_ paramB:Int)->(), closureB:()->()) {
let result = 2 * ParamA
closureA(result)
closureB()
}

[/csharp]

 

 

Playground located at:  https://github.com/ToniNichev/Swift-Data-Types

GIT bash cheatsheet

  • Create repository from existing folder in github

    – open terminal and navigate to project’s folder
    – initialize repository with git init

[bash]git init[/bash]

– (optionally) create `.gitignore` file and add all files and folders that should not be a part of the repository commit like: log folders, cache folders, .project, and perhaps .gitignore itself.

add all files and folders

[bash]git add .[/bash]

commit all files

[bash]git commit -m”My first commit”[/bash]

create new repository by logging into your github account and visiting http://github.com/new

– copy remote repository url

link local repository to the remote one

[bash]git remote add origin remote repository URL[/bash]

push new repository to the server

git push -u <origin> <branch-name>

-u specifies upstream

  • Clone existing repository

git clone myGitName@http://my.repository.com

– or clone specific branch

git clone -b branchname myGitName@http://my.repository.com

  • Show

all branches and their origin upstreams

git branch -avv

– a shows all branches (current branch is marked with * in front of the name
– v verbose

remote repository path

git remote show <origin>

remote repositories list

git ls-remote

  • Branches and day to day workflow

– create new branch

git checkout -b <new_branch_name>

– delete branch

locally:

git branch -D <branch_name>

on the remote server

git push --delete <origin-server> <branch-name>

– push new branch to remote repository

git push -u origin new_branch_name

– u upstream

– reset local repository to be the same like remote repository

git reset --hard head