## Problem Statement

Given an array of integers, every element appears twice except for one. Find that single one.

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example :

Input : [1 2 2 3 1]
Output : 3

## Solution

Logic:

The basic logic that A XOR A = 0 means that means all the doubles will be XOR’ed out to 0 and the remaining number will be the result of the XOR.

## Problem Statement

Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical. Sherlock’s companion, Dr. Watson, suggests Moriarty may be responsible for MI6’s recent issues with their supercomputer, The Beast.

Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beastwith a virus; however, he also gives him a clue—a number, NN. Sherlock determines the key to removing the virus is to find the largest Decent Number having NN digits.

A Decent Number has the following properties:

1. Its digits can only be 3‘s and/or 5‘s.
2. The number of 3‘s it contains is divisible by 5.
3. The number of 5‘s it contains is divisible by 3.
4. If there are more than one such number, we pick the largest one.

Moriarty’s virus shows a clock counting down to The Beast‘s destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed!

Constraints
1T201≤T≤20
1N1000001≤N≤100000

Input Format

The first line is an integer, TT, denoting the number of test cases.

The TT subsequent lines each contain an integer, NN, detailing the number of digits in the number.

Output Format

Print the largest Decent Number having NN digits; if no such number exists, tell Sherlock by printing -1.

Sample Input

4
1
3
5
11


Sample Output

-1
555
33333
55555533333


Explanation

For N=1, there is no decent number having 1 digit (so we print 1−1).
For N=3, 555 is the only possible number. The number 5 appears three times in this number, so our count of 5‘s is evenly divisible by 3 (Decent Number Property 3).
For N=5, 33333 is the only possible number. The number 3 appears five times in this number, so our count of 3‘s is evenly divisible by 5 (Decent Number Property 2).
For N=11, 55555533333 and all permutations of these digits are valid numbers; among them, the given number is the largest one.

## Easy Rules: Java™ rules engine

Easy Rules is a Java rules engine inspired by an article called Should I use a Rules Engine? by Martin Fowler in which he says:

You can build a simple rules engine yourself. All you need is to create a bunch of objects with conditions and actions, store them in a collection, and run through them to evaluate the conditions and execute the actions.

## Core features

• Lightweight library and easy to learn API
• POJO based development with annotation programming model
• Useful abstractions to define business rules and apply them easily with Java
• The ability to create composite rules from primitive ones
• Dynamic rule configuration at runtime using JMX

# Hello World tutorial

This tutorial shows how to use Easy Rules in a very simple application. The goal is to ask the user if he is a friend of duke and says ‘Hello duke’s friend!’ only if he replies ‘yes’.

Based on this requirement, the rule is pretty straightforward :

• The condition is that the user input must be equal to ‘yes’
• The action is to say ‘Hello duke’s friend!’ to the user

First, let’s create a rule class:

@Rule(name = "Hello World rule",
description = "Say Hello to duke's friends only")
public class HelloWorldRule {

/**
* The user input which represents the data
* that the rule will operate on.
*/
private String input;

@Condition
public boolean checkInput() {
//The rule should be applied only if
//the user's response is yes (duke friend)
return input.equalsIgnoreCase("yes");
}

@Action
public void sayHelloToDukeFriend() throws Exception {
//When rule conditions are satisfied,
//prints 'Hello duke's friend!' to the console
System.out.println("Hello duke's friend!");
}

public void setInput(String input) {
this.input = input;
}

}


Then, we have to register an instance of this rule in a Easy Rules engine and launch the tutorial with the following class:

public class Launcher {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
System.out.println("Are you a friend of duke?[yes/no]:");
String input = scanner.nextLine();

/**
* Declare the rule
*/
HelloWorldRule helloWorldRule = new HelloWorldRule();

/**
* Set business data to operate on
*/
helloWorldRule.setInput(input.trim());

/**
* Create a rules engine and register the business rule
*/
RulesEngine rulesEngine = aNewRulesEngine().build();

rulesEngine.registerRule(helloWorldRule);

/**
* Fire rules
*/
rulesEngine.fireRules();

}
}

You would get the following output:

Are you a friend of duke? [yes/no]:
yes
INFO: Rule 'Hello World rule' triggered.
Hello duke's friend!
INFO: Rule 'Hello World rule' performed successfully.


Source

## Local Mail Server With HMailServer

When we write code to push out emails to our customers or visitors, we want to be confident it’s going to arrive at the destination, looking the way we expect.

Most local windows server setups with XAMPP or WAMP won’t by default be setup with a mail server and setting one up can be a pain.

Luckily hMailServer is an option that you may want to try out

## hMailServer

This quick step-by-step guide should get you up and running with local mail functionality and a test script in under 20 minutes.

Start by going to www.hmailserver.com, click download in the menu and choose the latest build (hMailServer 5.6.4 – Build 2283).

For testing the Mail You can follow the following tutorial

# What is Gearman?

Gearman provides a generic application framework to farm out work to other machines or processes that are better suited to do the work. It allows you to do work in parallel, to load balance processing, and to call functions between languages. It can be used in a variety of applications, from high-availability web sites to the transport of database replication events. In other words, it is the nervous system for how distributed processing communicates. A few strong points about Gearman:

• Open Source It’s free! (in both meanings of the word) Gearman has an active open source community that is easy to get involved with if you need help or want to contribute. Worried about licensing? Gearman is BSD.
• Multi-language – There are interfaces for a number of languages, and this list is growing. You also have the option to write heterogeneous applications with clients submitting work in one language and workers performing that work in another.
• Flexible – You are not tied to any specific design pattern. You can quickly put together distributed applications using any model you choose, one of those options being Map/Reduce.
• Fast – Gearman has a simple protocol and interface with an optimized, and threaded, server written in C/C++ to minimize your application overhead.
• Embeddable – Since Gearman is fast and lightweight, it is great for applications of all sizes. It is also easy to introduce into existing applications with minimal overhead.
• No single point of failure – Gearman can not only help scale systems, but can do it in a fault tolerant way.
• No limits on message size – Gearman supports single messages up to 4gig in size. Need to do something bigger? No problem Gearman can chunk messages.
• Worried about scaling? – Don’t worry about it with Gearman. Craig’s List, Tumblr, Yelp, Etsy,… discover what others have known for years.

Content is being updated regularly, so please check back often. You may also want to check out other forms of communication if you would like to learn more or get involved!

# How Does Gearman Work?

A Gearman powered application consists of three parts: a client, a worker, and a job server. The client is responsible for creating a job to be run and sending it to a job server. The job server will find a suitable worker that can run the job and forwards the job on. The worker performs the work requested by the client and sends a response to the client through the job server. Gearman provides client and worker APIs that your applications call to talk with the Gearman job server (also known as gearmand) so you don’t need to deal with networking or mapping of jobs. Internally, the Gearman client and worker APIs communicate with the job server using TCP sockets. To explain how Gearman works in more detail, lets look at a simple application that will reverse the order of characters in a string. The example is given in PHP, although other APIs will look quite similar.

# How Is Gearman Useful?

You can use Gearman as an interface between a client and a worker written in different languages. If you want your PHP web application to call a function written in C, you could use the PHP client API with the C worker API, and stick a job server in the middle.

Gearman can also be useful when the worker code is put on a separate machine (or cluster of machines) that are better suited to do the work.
Say your PHP web application wants to do image conversion, but this is too much processing to run it on the web server machines.
You could instead ship the image off to a separate set of worker machines to do the conversion, this way the load does not impact the performance of your web server and other PHP scripts. By doing this, you also get a natural form of load balancing since the job server only sends new jobs to idle workers. If all the workers running on a given machine are busy, you don’t need to worry about new jobs being sent there. This makes scale-out with multi-core servers quite simple. You may have 16 cores on a worker machine. Start up 16 instances of your worker (or perhaps more if they are not CPU bound). It is also seamless to add new machines to expand your worker pool, just boot them up, install the worker code, and have them connect to the existing job server.

For more details on specific uses and installations, go to Gearman’s examples page.

## Color Thief

A script for grabbing the color palette from an image.
Uses JavaScript and the canvas tag to make it happen.

## How to use

### Get the dominant color from an image

var colorThief = new ColorThief();
colorThief.getColor(sourceImage);
getColor(sourceImage[, quality])
returns {r: num, g: num, b: num}

### Build a color palette from an image

In this example, we build an 8 color palette.

var colorThief = new ColorThief();
colorThief.getPalette(sourceImage, 8);
getPalette(sourceImage[, colorCount, quality])
returns [ [num, num, num], [num, num, num], ... ]

## How to Decompile Class/Jar Files

For Decompiling Java Classes or Complete Jar files, JD-GUI is very useful.

Since it is Open Source, no worries for Licencing fees as well

## OpenCart 1.5.X developer quick start guide for beginners

This guide is written for developers already familiar with PHP, OOP and the MVC architecture

In the following, you’ll see examples for the catalog side of the cart. The admin side is identical in function with the exception of the views which is noted in the relevant section

## Understanding Libraries

All of the library functionality is accessible through Controller, Model and Views using $this->library_name. All of these can be found in the /system/library/ folder. For example, to access the current shopping cart’s products, you’ll need to use the Cart class, which is in /system/library/cart.php and can be accessed using $this->cart->getProducts()

Commonly used items

• customer.php – Customer related functions
• user.php – Admin user related functions
• cart.php – Cart related functions
• config.php – All settings are loaded from this
• url.php – URL generation functions

## Understanding the route parameter

OpenCart’s framework relies on the route=aaa/bbb/ccc in the query string parameter to know what to load, and is the underpinning feature to finding the files you need to edit for each page. Most route’s actually only use the aaa/bbb which should be seen as two parts, however some contain three parts aaa/bbb/ccc The first part aaa generally related to the folder within a generic folder such as the controller or template folders. The second part usually relates to the file name, without the relevant .php or .tpl extension. The third part is explained in the understanding controllers below

## Understanding languages

Languages are stored in /catalog/language/ folder in the your-language subfolder. Within this, general text values used across various pages are stored in the your-language.php file inside the folder, so for the English language on the catalog side, you’ll find the values in catalog/language/english/english.php. For specific page text, you’ll need the route for the page (This is generally the case, but not always as you can specify any language file you like). For example, the search page has the route product/search, and therefore the language specific text for that page can be found in catalog/language/english/product/search.php (Notice the file’s name and subfolder match the route followed by .php.

To load the language in a controller, you use

$this->language->load('product/search'); Then you can use the language library function get to retrieve specific language texts, such as $some_variable = $this->language->get('heading_title'); The language variables are assigned in the language file using a special variable $_ which is an array of keys and text values. In your /catalog/language/english/product/search.php you should find something similar to

$_['heading_title'] = 'Search'; The values in the global language file english/english.php are automatically loaded and available to use without the $this->language->load method

## Understanding controllers

Controllers are loaded based on the route and are fairly straight forward to understand. Controllers are located in the /catalog/controller/ folder. Continuing from the last example, the Controller for the Search page is in /product/search.php within this folder. Notice again that the route followed by .php is used.

Opening the controller file, you’ll see a Pascal Case classname extending the Controller class, called ControllerProductSearch. This again is specific to the route, with Controller followed by the subfolder name and file name without the extension capitalised. The capitalisation is not actually required, but it’s recommended for easy readability. It’s worth noting that classnames don’t take any values from the subfolder and file name other than letters and numbers. Underscores are removed.

Within the class are the methods. Methods in the class declared public are accessible to be run via the route – private are not. By default, with a standard two part route (aaa/bbb above), a default index() method is called. If the third part of a route (ccc above) is used, this method will be run instead. For example, account/return/insert will load the /catalog/controller/account/return.php file and class, and try to call the insert method

## Understanding Models

Model’s in OpenCart are found in the /catalog/model/ folder and are grouped based on function not the route, and therefore you will need to load them in your controller via

$this->load->model('xxx/yyy'); This will load the file in the subfolder xxx called yyy.php. It is then available to use via the object $this->model_xxx_yyy

and as with controllers you can only call it’s public methods. For instance, to resize an image, you would use the tool/image model and call it’s resize method as follows

$this->load->model('tool/image');$this->model_tool_image->resize('image.png', 300, 200);

## Understanding variable assignment in views from the controller

In order to pass values to the view from the controller, you simply need to assign your data to the $this->data variable, which is essentially an array of key => value pairs. As an example $this->data['example_var'] = 123;

Accessing this in a view is a little should be easy to understand if you’re familiar with the extract()method which converts each key into a variable. So the example_var key becomes $example_varand can be accessed as such in the view ## Understanding themes Themes are available to the catalog side only, and are basically a folder of templates, stylesheets and theme images. Theme folders are placed in the /catalog/view/theme/ folder followed by the theme name. The folder name isn’t of importance with exception to the default folder The admin side uses /admin/view/template/ (skipping the /theme/theme-name/ from the path as it doesn’t allow differing themes) Template files reside in a template folder within the theme folder. Should any template not be available for the currently selected theme, the default folder’s template is used instead as a fallback. This means themes can be created with very few files and still function fully. It also reduces code duplication and issues as upgrades are made ## Understanding views (templates) As with language and models, the view file’s are generally related to the route, though don’t have to be at all. Templates on the catalog side are usually found in /catalog/view/theme/your-theme/template/ unless it doesn’t exist, in which case the default theme’s templates will be used. For our search page example above, the file is product/search.tpl. For routes with three parts, it is generally in aaa/bbb_ccc.tpl though there’s no hard set rule. In the admin, most pages follow this, with the exception that pages listing items, like the product listing page are in catalog/product_list.tpl and the product editing form is in catalog/product_form.tpl. Again, these aren’t set, but a standard for the default cart It’s worth point out that the template file is in fact just another php file, but with a .tpl extension and is actually run in the controller file, therefore all of the things you can code in a controller can be run in a template file (though not recommended unless absolutely necessary) ## Understanding the database object Queries are run using $result = $this->db->query("SELECT * FROM " . DB_PREFIX . "table"); DB_PREFIX as the name suggests is a constant containing the database prefix if one exists $result will return an object for SELECT queries, containing a few properties

$result->row contains the first row’s data if one or more are returned as an associative array $result->rows contains an array of row results, ideal for looping over using foreach

$result->num_rows contains the number of results returned There are also a few extra methods the $this->db object has

$this->db->escape() uses mysql_real_escape_string() on the value passed $this->db->countAffected returns the number of rows affected by an UPDATE query and so on

$this->db->getLastId() returns the last auto increment id using mysql_insert_id() ## Understanding reserved variables OpenCart has predefined variables to use in place of the standard $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUEST AND $_SERVER

$_SESSION is edited using $this->session->data where data is an associative array mimicking the $_SESSION All of the others can be accessed using $this->request and have been “cleaned” to comply with magic quotes enabled/disabled, so

$_GET becomes $this->request->get

$_POST becomes $this->request->post

$_COOKIE becomes $this->request->cookie

$_FILES becomes $this->request->files

$_REQUEST becomes $this->request->request

$_SERVER becomes $this->request->server

## Summary

While the above isn’t a bulletproof guide for developers, hopefully it will serve as a good starting point for those getting started

Credit: Post

## How to create a custom admin page in OpenCart?

OpenCart uses the MVC pattern.

Recommended reading: How to be an OpenCart Guru?

1) Create a new file in admin/controller/custom/helloworld.php

Your filename and controller name should be the same in desc order:

helloworld.php

<?

class ControllerCustomHelloWorld extends Controller{
public function index(){
// VARS
$template="custom/hello.tpl"; // .tpl location and file$this->load->model('custom/hello');
$this->template = ''.$template.'';
$this->children = array( 'common/header', 'common/footer' );$this->response->setOutput($this->render()); } } ?> 2) Create a new file in admin/view/template/custom/hello.tpl Hello.tpl <?php echo$header; ?>
<div id="content">
<h1>HelloWorld</h1>
<?php
echo 'I can also run PHP too!';
?>
</div>
<?php echo $footer; ?> 3) Create a new file in admin/model/custom/hello.php <?php class ModelCustomHello extends Model { public function HellWorld() {$sql = "SELECT x FROM " . DB_PREFIX . "y)";
$implode = array();$query = $this->db->query($sql);
return $query->row['total']; } } ?> 4) You then need to enable the plugin to avoid permission denied errors: Opencart > Admin > Users > User Groups > Admin > Edit Select and Enable the Access Permission. To visit your page go to www.yoursite.com/opencart/admin/index.php?route=custom/helloworld Credits: Post ## Code maintenance for Open Source Projects: GIT Sub-modules and Composer ### Problem Statement: Lets say you have a working directory of GIT where all your project work is stored and checked in. Also you are using Open Source Solutions from 3-4 different repositories. You want the latest code to be available whenever it is uploaded. 1 way to do that is to download the zip/repository code each time to your project folder. Other sleek and effective ways are: • Git Sub modules: Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.Extract: ### Starting with Submodules We’ll walk through developing a simple project that has been split up into a main project and a few sub-projects. Let’s start by adding an existing Git repository as a submodule of the repository that we’re working on. To add a new submodule you use the git submodule add command with the URL of the project you would like to start tracking. In this example, we’ll add a library called “DbConnector”. $ git submodule add https://github.com/chaconinc/DbConnector
Cloning into 'DbConnector'...
remote: Counting objects: 11, done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 11 (delta 0), reused 11 (delta 0)
Unpacking objects: 100% (11/11), done.
Checking connectivity... done.

By default, submodules will add the subproject into a directory named the same as the repository, in this case “DbConnector”. You can add a different path at the end of the command if you want it to go elsewhere.

If you run git status at this point, you’ll notice a few things.

$ git status On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed:  (use "git reset HEAD <file>..." to unstage)  new file: .gitmodules  new file: DbConnector First you should notice the new .gitmodules file. This is a configuration file that stores the mapping between the project’s URL and the local subdirectory you’ve pulled it into: $ cat .gitmodules
[submodule "DbConnector"]
	path = DbConnector
	url = https://github.com/chaconinc/DbConnector

If you have multiple submodules, you’ll have multiple entries in this file. It’s important to note that this file is version-controlled with your other files, like your .gitignore file. It’s pushed and pulled with the rest of your project. This is how other people who clone this project know where to get the submodule projects from.

Since the URL in the .gitmodules file is what other people will first try to clone/fetch from, make sure to use a URL that they can access if possible. For example, if you use a different URL to push to than others would to pull from, use the one that others have access to. You can overwrite this value locally with git config submodule.DbConnector.url PRIVATE_URL for your own use.

The other listing in the git status output is the project folder entry. If you run git diff on that, you see something interesting:

$ git diff --cached DbConnector diff --git a/DbConnector b/DbConnector new file mode 160000 index 0000000..c3f01dc --- /dev/null +++ b/DbConnector @@ -0,0 +1 @@ +Subproject commit c3f01dc8862123d317dd46284b05b6892c7b29bc Although DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository. If you want a little nicer diff output, you can pass the --submodule option to git diff. $ git diff --cached --submodule
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..71fc376
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "DbConnector"]
+       path = DbConnector
+       url = https://github.com/chaconinc/DbConnector
Submodule DbConnector 0000000...c3f01dc (new submodule)

When you commit, you see something like this:

$ git commit -am 'added DbConnector module' [master fb9093c] added DbConnector module  2 files changed, 4 insertions(+)  create mode 100644 .gitmodules  create mode 160000 DbConnector Notice the 160000 mode for the DbConnector entry. That is a special mode in Git that basically means you’re recording a commit as a directory entry rather than a subdirectory or a file. ### Cloning a Project with Submodules Here we’ll clone a project with a submodule in it. When you clone such a project, by default you get the directories that contain submodules, but none of the files within them yet: $ git clone https://github.com/chaconinc/MainProject
Cloning into 'MainProject'...
remote: Counting objects: 14, done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 14 (delta 1), reused 13 (delta 0)
Unpacking objects: 100% (14/14), done.
Checking connectivity... done.
$ cd MainProject $ ls -la
total 16
drwxr-xr-x   9 schacon  staff  306 Sep 17 15:21 .
drwxr-xr-x   7 schacon  staff  238 Sep 17 15:21 ..
drwxr-xr-x  13 schacon  staff  442 Sep 17 15:21 .git
-rw-r--r--   1 schacon  staff   92 Sep 17 15:21 .gitmodules
drwxr-xr-x   2 schacon  staff   68 Sep 17 15:21 DbConnector
-rw-r--r--   1 schacon  staff  756 Sep 17 15:21 Makefile
drwxr-xr-x   3 schacon  staff  102 Sep 17 15:21 includes
drwxr-xr-x   4 schacon  staff  136 Sep 17 15:21 scripts
drwxr-xr-x   4 schacon  staff  136 Sep 17 15:21 src
$ cd DbConnector/ $ ls
$ The DbConnector directory is there, but empty. You must run two commands: git submodule init to initialize your local configuration file, and git submodule update to fetch all the data from that project and check out the appropriate commit listed in your superproject: $ git submodule init
Submodule 'DbConnector' (https://github.com/chaconinc/DbConnector) registered for path 'DbConnector'
$ git submodule update Cloning into 'DbConnector'... remote: Counting objects: 11, done. remote: Compressing objects: 100% (10/10), done. remote: Total 11 (delta 0), reused 11 (delta 0) Unpacking objects: 100% (11/11), done. Checking connectivity... done. Submodule path 'DbConnector': checked out 'c3f01dc8862123d317dd46284b05b6892c7b29bc' Now your DbConnector subdirectory is at the exact state it was in when you committed earlier. There is another way to do this which is a little simpler, however. If you pass --recursive to the git clone command, it will automatically initialize and update each submodule in the repository. $ git clone --recursive https://github.com/chaconinc/MainProject
Cloning into 'MainProject'...
remote: Counting objects: 14, done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 14 (delta 1), reused 13 (delta 0)
Unpacking objects: 100% (14/14), done.
Checking connectivity... done.
Submodule 'DbConnector' (https://github.com/chaconinc/DbConnector) registered for path 'DbConnector'
Cloning into 'DbConnector'...
remote: Counting objects: 11, done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 11 (delta 0), reused 11 (delta 0)
Unpacking objects: 100% (11/11), done.
Checking connectivity... done.
Submodule path 'DbConnector': checked out 'c3f01dc8862123d317dd46284b05b6892c7b29bc'

### Working on a Project with Submodules

Now we have a copy of a project with submodules in it and will collaborate with our teammates on both the main project and the submodule project.

#### Pulling in Upstream Changes

The simplest model of using submodules in a project would be if you were simply consuming a subproject and wanted to get updates from it from time to time but were not actually modifying anything in your checkout. Let’s walk through a simple example there.

If you want to check for new work in a submodule, you can go into the directory and run git fetchand git merge the upstream branch to update the local code.

$ git fetch From https://github.com/chaconinc/DbConnector  c3f01dc..d0354fc master -> origin/master $ git merge origin/master
Updating c3f01dc..d0354fc
Fast-forward
 scripts/connect.sh | 1 +
 src/db.c           | 1 +
 2 files changed, 2 insertions(+)

Now if you go back into the main project and run git diff --submodule you can see that the submodule was updated and get a list of commits that were added to it. If you don’t want to type --submodule every time you run git diff, you can set it as the default format by setting thediff.submodule config value to “log”.

$ git config --global diff.submodule log $ git diff
Submodule DbConnector c3f01dc..d0354fc:
  > more efficient db routine
  > better connection routine

If you commit at this point then you will lock the submodule into having the new code when other people update.

There is an easier way to do this as well, if you prefer to not manually fetch and merge in the subdirectory. If you run git submodule update --remote, Git will go into your submodules and fetch and update for you.

$ git submodule update --remote DbConnector remote: Counting objects: 4, done. remote: Compressing objects: 100% (2/2), done. remote: Total 4 (delta 2), reused 4 (delta 2) Unpacking objects: 100% (4/4), done. From https://github.com/chaconinc/DbConnector  3f19983..d0354fc master -> origin/master Submodule path 'DbConnector': checked out 'd0354fc054692d3906c85c3af05ddce39a1c0644' This command will by default assume that you want to update the checkout to the master branch of the submodule repository. You can, however, set this to something different if you want. For example, if you want to have the DbConnector submodule track that repository’s “stable” branch, you can set it in either your .gitmodules file (so everyone else also tracks it), or just in your local .git/config file. Let’s set it in the .gitmodules file: $ git config -f .gitmodules submodule.DbConnector.branch stable

$ git submodule update --remote remote: Counting objects: 4, done. remote: Compressing objects: 100% (2/2), done. remote: Total 4 (delta 2), reused 4 (delta 2) Unpacking objects: 100% (4/4), done. From https://github.com/chaconinc/DbConnector  27cf5d3..c87d55d stable -> origin/stable Submodule path 'DbConnector': checked out 'c87d55d4c6d4b05ee34fbc8cb6f7bf4585ae6687' If you leave off the -f .gitmodules it will only make the change for you, but it probably makes more sense to track that information with the repository so everyone else does as well. When we run git status at this point, Git will show us that we have “new commits” on the submodule. $ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

  modified:   .gitmodules
  modified:   DbConnector (new commits)

no changes added to commit (use "git add" and/or "git commit -a")

If you set the configuration setting status.submodulesummary, Git will also show you a short summary of changes to your submodules:

$ git config status.submodulesummary 1 $ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   .gitmodules
	modified:   DbConnector (new commits)

Submodules changed but not updated:

* DbConnector c3f01dc...c87d55d (4):
  > catch non-null terminated lines

At this point if you run git diff we can see both that we have modified our .gitmodules file and also that there are a number of commits that we’ve pulled down and are ready to commit to our submodule project.

$ git diff diff --git a/.gitmodules b/.gitmodules index 6fc0b3d..fd1cc29 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,4 @@  [submodule "DbConnector"]  path = DbConnector  url = https://github.com/chaconinc/DbConnector + branch = stable  Submodule DbConnector c3f01dc..c87d55d:  > catch non-null terminated lines  > more robust error handling  > more efficient db routine  > better connection routine This is pretty cool as we can actually see the log of commits that we’re about to commit to in our submodule. Once committed, you can see this information after the fact as well when you run git log -p. $ git log -p --submodule
commit 0a24cfc121a8a3c118e0105ae4ae4c00281cf7ae
Author: Scott Chacon <schacon@gmail.com>
Date:   Wed Sep 17 16:37:02 2014 +0200

    updating DbConnector for bug fixes

diff --git a/.gitmodules b/.gitmodules
index 6fc0b3d..fd1cc29 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,3 +1,4 @@
 [submodule "DbConnector"]
        path = DbConnector
        url = https://github.com/chaconinc/DbConnector
+       branch = stable
Submodule DbConnector c3f01dc..c87d55d:
  > catch non-null terminated lines
  > more robust error handling
  > more efficient db routine
  > better connection routine

Git will by default try to update all of your submodules when you run git submodule update --remote so if you have a lot of them, you may want to pass the name of just the submodule you want to try to update.

#### Working on a Submodule

It’s quite likely that if you’re using submodules, you’re doing so because you really want to work on the code in the submodule at the same time as you’re working on the code in the main project (or across several submodules). Otherwise you would probably instead be using a simpler dependency management system (such as Maven or Rubygems).

So now let’s go through an example of making changes to the submodule at the same time as the main project and committing and publishing those changes at the same time.

So far, when we’ve run the git submodule update command to fetch changes from the submodule repositories, Git would get the changes and update the files in the subdirectory but will leave the sub-repository in what’s called a “detached HEAD” state. This means that there is no local working branch (like “master”, for example) tracking changes. So any changes you make aren’t being tracked well.

In order to set up your submodule to be easier to go in and hack on, you need do two things. You need to go into each submodule and check out a branch to work on. Then you need to tell Git what to do if you have made changes and then git submodule update --remote pulls in new work from upstream. The options are that you can merge them into your local work, or you can try to rebase your local work on top of the new changes.

First of all, let’s go into our submodule directory and check out a branch.

$ git checkout stable Switched to branch 'stable' Let’s try it with the “merge” option. To specify it manually, we can just add the --merge option to ourupdate call. Here we’ll see that there was a change on the server for this submodule and it gets merged in. $ git submodule update --remote --merge
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2)
Unpacking objects: 100% (4/4), done.
From https://github.com/chaconinc/DbConnector
   c87d55d..92c7337  stable     -> origin/stable
Updating c87d55d..92c7337
Fast-forward
 src/main.c | 1 +
 1 file changed, 1 insertion(+)
Submodule path 'DbConnector': merged in '92c7337b30ef9e0893e758dac2459d07362ab5ea'

If we go into the DbConnector directory, we have the new changes already merged into our localstable branch. Now let’s see what happens when we make our own local change to the library and someone else pushes another change upstream at the same time.

$ cd DbConnector/ $ vim src/db.c
$ git commit -am 'unicode support' [stable f906e16] unicode support  1 file changed, 1 insertion(+) Now if we update our submodule we can see what happens when we have made a local change and upstream also has a change we need to incorporate. $ git submodule update --remote --rebase
First, rewinding head to replay your work on top of it...
Applying: unicode support
Submodule path 'DbConnector': rebased into '5d60ef9bbebf5a0c1c1050f242ceeb54ad58da94'

If you forget the --rebase or --merge, Git will just update the submodule to whatever is on the server and reset your project to a detached HEAD state.

$ git submodule update --remote Submodule path 'DbConnector': checked out '5d60ef9bbebf5a0c1c1050f242ceeb54ad58da94' If this happens, don’t worry, you can simply go back into the directory and check out your branch again (which will still contain your work) and merge or rebase origin/stable (or whatever remote branch you want) manually. If you haven’t committed your changes in your submodule and you run a submodule update that would cause issues, Git will fetch the changes but not overwrite unsaved work in your submodule directory. $ git submodule update --remote
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 4 (delta 0)
Unpacking objects: 100% (4/4), done.
From https://github.com/chaconinc/DbConnector
   5d60ef9..c75e92a  stable     -> origin/stable
error: Your local changes to the following files would be overwritten by checkout:
	scripts/setup.sh
Please, commit your changes or stash them before you can switch branches.
Aborting
Unable to checkout 'c75e92a2b3855c9e5b66f915308390d9db204aca' in submodule path 'DbConnector'

If you made changes that conflict with something changed upstream, Git will let you know when you run the update.

\$ git submodule update --remote --merge
Auto-merging scripts/setup.sh
CONFLICT (content): Merge conflict in scripts/setup.sh
Recorded preimage for 'scripts/setup.sh'
Automatic merge failed; fix conflicts and then commit the result.
Unable to merge 'c75e92a2b3855c9e5b66f915308390d9db204aca' in submodule path 'DbConnector'

You can go into the submodule directory and fix the conflict just as you normally would.

• Composer{PHP Only}:

Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

#### Dependency management

Composer is not a package manager. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

This idea is not new and Composer is strongly inspired by node’s npm and ruby’s bundler. But there has not been such a tool for PHP.

The problem that Composer solves is this:

a) You have a project that depends on a number of libraries.

b) Some of those libraries depend on other libraries.

c) You declare the things you depend on.

d) Composer finds out which versions of which packages need to be installed, and installs them (meaning it downloads them into your project).