Viber Contacts Filter App

This is an step by step process of using the Viber Contacts Filter App. Please follow the steps as mentioned at the right side Notepad window.


Youtube link for step-by-step video : https://www.youtube.com/watch?v=ut8o0pAno_M


For reference, the text shown in this video is mentioned below:

Hi,

This is the demo of how Viber filter app works.

Please follow the steps in sequence.
  • 1. Open genymotion. Make sure you already have installed the Viber app in genymotion device. I have already added a device in genymotion. The device is now started.
  • 2. Open Viber in genymotion. If it is a first time installation of Viber in Genymotion, then you need to register with your mobile number first.
  • 3. Now, install Viber for desktop. After installation, open the Viber for desktop app and register with the same mobile number as done for genymotion app.
  • 4. It will now ask for QR code to scan from mobile. The problem is we dont have it installed in our mobile, so how can we scan that QR code. See now how it can be done. As you can see there is one camera option at the right side of the genymotion app. You have to turn this ON. Configure both front and back camera as your PC laptop/desktop camera. It will look similar to this image. Now click the pic of this from your mobile an open that image in you mobile.
  • 5. Go to genymotion app and click on QR code. It will open the camera to scan. The only thing is you have to show the picture clicked in previous step to your laptop/desktop camera. Now, once you have your image scanned by genemotion viber, your desktop viber will be activated.
  • 6. Now, open Viber Contact Filter app. The screen will look like as shown.
  • 7. First you need to register a mobile number to create a communication channel. Just type your number and click on Register.
  • 8. It will show your current contacts of Viber app.
  • 9. Now click on Browse to browse a bulk contact file. (Note that you should first select the delimiter from the dropdown above)
  • 10. In this contact file I have one number which is a Valid viber contact. The highlighted one is a valid viber contact.
  • 11. Now, all contacts have been imported in the app.
  • 12. Now, click on "Generate Viber Contact File". A vcf file has been saved to MyDocuments folder. Let's grab that.
  • 13. I have copy-pasted this file from my documents to some other folder. Now drag and drop this file to genymotion. Now open the file. This is downloaded in "Download" folder. Double click this file and open in Contacs.
  • 14. It is showing that contacts will be imported shortly. Now, go to contacts.
  • 15. Now, open Viber, you can see all the contacts here including the one which is a valid Viber contact. Now, going back to our Viber filter app.
  • 16. Unregister and Re-enter the mobile number.
  • 17. Now, all contacts have been here.
  • 18. Now, Click on Start Filtering Contacts.
  • 19. You can see that one valid Viber contact is here. This was the one which was in bulk contact file.
  • 20. You can now click on Export to export the list of these valid viber contacts.

Click here to download the executables. (zip password - 123)

Concatenate two integer variables in C



#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int concatenateInt(int firstNumber, int secondNumber)
{
 int count = 0;
 int temp = secondNumber;
 while (secondNumber)
 {
  secondNumber = secondNumber / 10;
  count++;
 }
 if (count == 0)
  count = 1;
 return (firstNumber * pow(10, count) + temp);
}

Angular 2 : Services and Dependency Injection

Let's look some definitions to understand the subject.

A Service is a functionality that can be shared with different Components. Whenever we find some common aspects in our components, we usually separate it out as a Service.

Dependency Injection is a coding pattern in which a class takes the instances of objects it needs which is called dependencies from an external source rather than creating them itself.

In Angular 2, services are Singleton. It internally implements the Service Locator Pattern. This means each service register itself under one container as a single instance. Angular provides a built in Injector which acts as a container to hold the single instances of all registered services. Angular takes care of creation of Service instance and registering it to the Service container.

The @Injectable() decorator

To inject the service into component, Angular 2 provides an Injector decorator : @Injectable().

We broadly have the following steps to create a Service:

1) Create the service class
2) Define the metadata with a decorator
3) Import what we need.


To understand the Service more, let's built a service in Angular 2 for getting the user profile details in the User component. Let's create some classes:

1. IProfile interface

export interface IProfile{
  Name: string;
  Age: number;
}

2. Profile Class

import {Component, Injectable} from '@angular/core'
import {IProfile} from './iprofile'

@Component({
  selector: 'profile',
  template: `
    <div>
      <h2>Name : {{MyProfile.Name}}</h2>
      <h2>Age : {{MyProfile.Age}}</h2>
    </div>
  `
})
export class Profile{
  MyProfile : IProfile;
  constructor(){
  }
}

3. ProfileService class

import {Injectable} from '@angular/core'
import {IProfile} from './iprofile'

@Injectable()
export class ProfileService{
  getProfiles(): IProfile[]{
    return [{
      Name:'Bob',
      Age: 25
    },
    {
      Name:'Alice',
      Age: 23
    }];
  }
}

Registering a Service:

A Service can be registered in any component. However, it should be registered at root level component only. This is because it we register at two different nested level component, then the service will have two entire different instances in both components. However, we can register at any nested level component just in case if we require to use the service in that component or it's child components only.


In above figure,
1. The "Service 1" is registered at app level, so it is available to all the nested components.
2. The "Service 2" is registered at "Parent 1" component, so it is available to Parent 1, Child1, Child2 and Child 3 components.
3. The "Service 3" is registered at "Child 1" component, so it is available to "Child 1" only, as no other component comes under its hierarchy.
4. The "Service 4" is registered at "Parent 2" component, so it is available to Parent 2 and Child 4 only.

Now, if we try to register "Service 1" both in root component and "Parent 1" component, then it's two instances will be created. That is why, we should register the service at an appropriate component level as per it's usage.

Continuing with our example, Import ProfileService and change the @NgModule() decorator of root level component as:

import {ProfileService} from './profile.service';

.
.
.

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  providers:[ProfileService],
  bootstrap: [ App ]
})


Injecting a Service in component:

We can inject our service as a parameter to our constructor class.

constructor(private _profileService: ProfileService){
   
}

Now, we can execute the methods of our service to get the data. We can call the service method inside our constructor, but what if the service wants to pull to data from backend. We don't want the construction of our class halted till the time we pull the data.
A better solution would be to implement the OnInit interface hook provided by Angular 2 and call the service method inside ngOnInit() function. (Know more about Angular hooks here.)

Modify the Profile class as below:

import {Component, Injectable} from '@angular/core'

import {ProfileService} from './profile.service';
import {IProfile} from './iprofile'


@Component({
  selector: 'profile',
  template: `
    <div>
      <h2>Name : {{MyProfile.Name}}</h2>
      <h4>Age : {{MyProfile.Age}}</h4>
    </div>
  `,
})
export class Profile implements OnInit{
  ProfileList : IProfile[];
  MyProfile : IProfile;
  constructor(private _profileService: ProfileService){
   
  }
  
  ngOnInit(){
    this.ProfileList = this._profileService.getProfiles();
    this.MyProfile = this.ProfileList[0];
  }
}

To summarize:

* Create a Service class
* Use @Injectable() decorator to the service.
* Register the service at the root component.
* Inject the service as a constructor parameter of the dependent class.

Live Code:

Plunker here: https://embed.plnkr.co/SbgOOoUtJIeaQBY2FizW?show=app,preview

Angular 2 : Working with Nested Components

What are Nested/Child components?

A Component in Angular 2 can have child components. Also, those child components can have their own further child components. Angular 2 seamlessly supports nested components.

As an example, consider a calculator as a top level component. It is built with several other child components like screen component, button component, body component, battery component etc. These screen, button, body and battery components are nested components of Calculator component.

The nested component have all the functionalities just as any other Angular 2 component.

Now several question arises in our mind:


  1. How we are going to use our nested components in its parent component?
  2. How we can pass data from parent component into its child component?
  3. How can we get the data back from child component to parent component?
  4. How does the child component can respond to the parent events?
  5. How does the parent component can respond to the child events?

To answer all these questions, lets us built a step-by-step example where we have a profile page of a person. It will also have a friend's list.

1) Building Parent and Child components.

Let's first built our Child component in our example app which is Friend list component.

import { Component } from '@angular/core';
 
@Component({
    selector: 'my-friends',
    template: `<div>
                <table>
                  <tr *ngFor='let friend of friends'>
                    <td>{{friend}}</td>
                    <td>
                       <img 
                          src="http://witspry.in/ContentServer/Images/User/user.png" 
                          width="20" />
                    </td>
                  </tr>
                </table>
              </div>`
})
export class MyFriendsComponent{
    friends: Array<string> = [
      'Friend 1',
      'Friend 2',
      'Friend 3',
      'Friend 4',
      'Friend 5',
    ];
}

Now, let's built our Parent component which is User's profile page.

import { Component } from '@angular/core';

import {MyFriendsComponent} from './myFriends';

@Component({
    selector: 'my-profile',
    template:`<img [src]="imgURL" width="50"/>
              <h3>My Friends</h3>
              <my-friends></my-friends>`
})
export class MyProfileComponent{
  constructor(){
    this.imgURL = 'http://witspry.in/ContentServer/Images/User/user_circle.png';  
  }
}

* See the above example as how the <my-friends> is used as a directive to the Profile component.

Now, in main app import both component and add them in the "declarations" array.

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, MyProfileComponent, MyFriendsComponent ],
  bootstrap: [ App ]
})
export class AppModule {}


Next, we are going to see how parent component provides input to child component and how child component emit events to send the payloads to parent component. Here is a diagram to get a gist of it.



2) Passing data using @Input() decorator.

@Input() decorator to the rescue

Add a variable name as a following line with @Input() decorator.

export class MyFriendComponent{
  @Input() name : string;   
}

Change our User's profile page as:

@Component({
    selector: 'my-profile',
    template:`
              <img [src]="imgURL" width="50"/>
              <h3>My Friends</h3>
              <div *ngFor="let friend of friends">
                <my-friend [name]='friend'></my-friend>
              </div>
    `
})
export class MyProfileComponent{
  constructor(){
    this.imgURL = 'http://witspry.in/ContentServer/Images/User/user_circle.png';  
    this.friends = [
      'Friend 1',
      'Friend 2',
      'Friend 3',
      'Friend 4',
      'Friend 5'
    ];
  }
}

See the line - <my-friend [name]='friend'></my-friend>
Here we are passing a friend name to the "name" property of the child component.

3) Raising an event using @Output() decorator

The @Output directive enables a child component to use its properties in the parent component.

Lets modify our MyFriend component as:


import { Component, Input, Output, EventEmitter } from '@angular/core';
 
@Component({
    selector: 'my-friend',
    template: `<div>
                <table>
                  <tr>
                    <td>{{name}}</td>
                    <td>
                        <img src="http://putiw.xyz/clashroyaleunlimitedgems/img/user.png"
                            width="20" />
                    </td>
                    <td><button (click)='OnClick()'>Ping</button></td>
                    <td> {{timesPinged}} </td>
                  </tr>
                </table>
              </div>`
})
export class MyFriendComponent{
  @Input() name : string;
  timesPinged: number = 0;
  @Output() pingClicked: EventEmitter<string> = new EventEmitter<string>();
  
  OnClick(){
    this.timesPinged++;
    this.pingClicked.emit('You pinged ' + this.name + ' ' + 
          this.timesPinged + (this.timesPinged == 1? ' time' : ' times'));
  }
}

Here, we have imported Output and EventEmitter from Angular core library. Also, we have defined an event using @Output() decorator. The OnClick is a local function which is invoked from button's click event. Since the "pingClicked" is decorated with @Output(), it's emit function is able to notify the parent component.

Now, change the parent component to capture the raised event from it's child component as below:

import { Component } from '@angular/core';

@Component({
    selector: 'my-profile',
    template: `
              <img [src]="imgURL" width="50"/>
              <br />
              {{pingMessage}}
              <br />
              Total Pings today : {{totalPings}}
              <h3>My Friends</h3>
              <div *ngFor="let friend of friends">
                <my-friend [name]='friend'
                          (pingClicked)='onFriendPingClicked($event)'>
                </my-friend>
              </div>
    `
})
export class MyProfileComponent{
  constructor(){
    this.imgURL = 
 'http://witspry.in/ContentServer/Images/User/user_circle.png';  
    this.friends = [
      'Friend A',
      'Friend B',
      'Friend C',
      'Friend D',
      'Friend E'
    ];
    this.totalPings = 0;
    this.pingMessage = '';
  }
  
  onFriendPingClicked(pingMessage: string): void{
    this.totalPings++;
    this.pingMessage = pingMessage;
  }
}

Finally, we have added an Event binding (please check our previous article in Angular 2 : Event bindings) which is "pingClicked". Have you remember, this was decorated with @Output in our child component. Yes, this is how was are able to use it here. Also, it is assigned to a function "onFriendPingClicked($event)". The $event contains the data that the child component emits on the occurrence of it's event.

To Summarize:

* Use @Input() decorator to pass data to child component.
* Use @Output() decorator to raise an event to parent component. Note : The @Output() decorator property can be only of EventEmitter type.

Live Code

Angular 2 : Pipes

In simple words, In Angular 2, a pipe takes in data as input and transforms it to a desired output. It is corresponding to what filters are in Angular 1.

A quick example :

<p>{{date | date:'shortDate'}}</p> <p>{{date | date:'longDate'}}</p>

It transforms a date string to short date and long date format.

There are three type of Pipes Angular 2 provides:

1) Builtin Pipes:


There are several inbuilt pipes provided by Angular 2 framework. Following is the list of some of the Builtin Pipes:

a) DatePipe:

date_expression | date[:format]

where expression is a date object or a number and format indicates which date/time components to include. The format can be predifined as shown below or custom as shown in the table.

Format Description
medium equivalent to 'yMMMdjms' (e.g. Sep 3, 2010, 12:05:08 PM for en-US)
short equivalent to 'yMdjm' (e.g. 9/3/2010, 12:05 PM for en-US)
fullDate equivalent to 'yMMMMEEEEd' (e.g. Friday, September 3, 2010 for en-US)
longDate equivalent to 'yMMMMd' (e.g. September 3, 2010 for en-US)
mediumDate equivalent to 'yMMMd' (e.g. Sep 3, 2010 for en-US)
shortDate equivalent to 'yMd' (e.g. 9/3/2010 for en-US)
mediumTime equivalent to 'jms' (e.g. 12:05:08 PM for en-US)
shortTime equivalent to 'jm' (e.g. 12:05 PM for en-US)

Example :
{{ dateObj | date }} // output is 'Jan 10, 2016'

{{ dateObj | date:'medium' }} // output is 'Jan 10, 2016, 2:10:15 PM'

{{ dateObj | date:'shortTime' }} // output is '2:10 PM'

{{ dateObj | date:'mmss' }} // output is '10:15'


b) UpperCasePipe,

expression | uppercase

It converts value into an uppercase string using String.prototype.toUpperCase().

Example:
<p>In uppercase: <pre>'{{value | uppercase}}'</pre>

c) LowerCasePipe:

expression | lowercase

It converts value into a lowercase string using String.prototype.toLowerCase().

Example:
<p>In lowercase: <pre>'{{value | lowercase}}'</pre>

d) CurrencyPipe:

number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]

where
currencyCode - the ISO 4217 currency code, such as USD for the US dollar and EUR for the euro.

symbolDisplay - a boolean indicating whether to use the currency symbol or code.
true - use symbol (e.g. $).
false(default): use code (e.g. USD).

digitInfo -
digitInfo is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

e) PercentPipe:

number_expression | percent[:digitInfo]
where digitInfo is same as mentioned above.

Note : Pipes can be chained as:{{ birthday | date | uppercase}}

2. Async Pipes:

observable_or_promise_expression | async

An async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes.

3. Custom Pipes:

We can create very own custom pipes by using the @Pipe decorator and implementing the PipeTransform interface:

Example:

import { Pipe, PipeTransform } from 'angular2/core'; 

@Pipe({ name: 'HtoS' }) 
export class HoursToSeconds implements PipeTransform { 
  transform(value: string, args: any[]){
  return parseFloat(value)*3600; 
  } 
}


Live Code:

Angular 2 : Data Bindings

Angular provides many kinds of data binding

We can group all bindings into three categories by the direction in which data flows. Each category has its distinctive syntax:

Interpolation

Any property in Component class can be shown as text through Interpolation written as {{}}

Property Binding

It is similar to Interpolation but it is a preferable way of doing one way binding, especially in case of styles and attribute bindings. It has a syntax []

Event Binding

It binds and event to a Component function. The events are standard browser events such as Click, DoubleClick etc.

Two-way binding

It binds a Component property to an input element. The changes gets reflected in the property at the same time. This is actually a combination of One-way binding and Event-binding. It is written as Banana-in-a-box syntax [(..)]. The outer braces shows One-way binding and the inner brace shows Event binding.


To Visualize

DOM


Interpolation : {{someText}}
Property Binding :
<img [src]='prop.URL'>
Event Binding :
<button (click)='showImage()'>
Two way Binding :
<input [(ngModel)]='Name'>

Component


Example

<input type="text" [value]="myName">
<button (click)="colorChange(textColor)" [style.color]="textColor">Change My Color</button>
<input type="text" [(ngModel)]="textColor">

<table border=2>
    <!--  expression calculates colspan=2 -->
    <tr>
        <td [attr.colspan]="1 + 1 + 1">Left - Center - Right</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>

Live Code 

Plunker here: https://embed.plnkr.co/plunk/BT8gj5?show=app,preview

Genetic Algorithms - An Introduction

Genetic algorithms are one of the best ways to solve a problem for which little is known. They are a very general algorithm and so will work well in any search space. All you need to know is what you need the solution to be able to do well, and a genetic algorithm will be able to create a high quality solution. Genetic algorithms use the principles of selection and evolution to produce several solutions to a given problem.

When are Genetic Algorithms Useful?

There are at least three situations where genetic algorithms are useful:

The objective function is not smooth (i.e., not differentiable).
There are multiple local optima.
There is a large number of parameters (the meaning of "large" keeps changing).

A typical genetic algorithm requires:

1) A genetic representation (e.g. Array of Bits) of the solution domain,
2) A fitness function to evaluate the solution domain. A fitness function is a particular type of objective function that is used to summarize, as a single figure of merit, how close a given design solution is to achieving the set aims.

Once the genetic representation and the fitness function are defined, a GA proceeds to initialize a population of solutions and then to improve it through repetitive application of the mutation, crossover, inversion and selection operators.

Simple Genetic Algorithm Pseudo-code
function SimpleGeneticAlgorithm ()
{
 Initialize population;
 Calculate fitness function;
 While (fitness value != termination criteria)
 {
  Selection;
  Crossover;
  Mutation;
  Calculate fitness function;
 }
}

Genetic Algorithms steps:

1. Initialization 

The population size depends on the nature of the problem, but typically contains several hundreds or thousands of possible solutions. Often, the initial population is generated randomly, allowing the entire range of possible solutions (the search space). Occasionally, the solutions may be "seeded" in areas where optimal solutions are likely to be found.

2. Selection

During each successive generation, a portion of the existing population is selected to breed a new generation. Individual solutions are selected through a fitness-based process, where fitter solutions (as measured by a fitness function) are typically more likely to be selected. The fitness function is defined over the genetic representation and measures the quality of the represented solution. The fitness function is always problem dependent.

3. Genetic operators

The next step is to generate a second generation population of solutions from those selected through a combination of genetic operators: crossover (also called recombination), and mutation.

a) Crossover (also called as Recombination)

Crossover is a genetic operator used to vary the programming of a chromosome or chromosomes from one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic algorithms are based. Cross over is a process of taking more than one parent solutions and producing a child solution from them.



Single-point crossover

Two-point crossover

Cut and splice


b) Mutation

Mutation alters one or more gene values in a chromosome from its initial state. In mutation, the solution may change entirely from the previous solution. Hence GA can come to a better solution by using mutation. Mutation should allow the algorithm to avoid local minima by preventing the population of chromosomes from becoming too similar to each other, thus slowing or even stopping evolution.
The mutation of bit strings ensue through bit flips at random positions.
Example:
1 0 1 0 0 1 0
1 0 1 0 1 1 0

4. Termination

This generational process is repeated until a termination condition has been reached. Common terminating conditions are:
  • A solution is found that satisfies minimum criteria
  • Fixed number of generations reached
  • Allocated budget (computation time/money) reached
  • The highest ranking solution's fitness is reaching or has reached a plateau such that successive iterations no longer produce better results
  • Manual inspection
  • Combinations of the above

Case Study : Roulette Wheel Selection

Parents are selected according to their fitness. The better the chromosomes are, the more chances to be selected they have. Imagine a roulette wheel where all the chromosomes in the population are placed. The size of the section in the roulette wheel is proportional to the value of the fitness function of every chromosome - the bigger the value is, the larger the section is. See the following picture for an example.



A marble is thrown in the roulette wheel and the chromosome where it stops is selected. Clearly, the chromosomes with bigger fitness value will be selected more times.

This process can be described by the following algorithm.

[Sum] Calculate the sum of all chromosome fitnesses in population - sum S.
[Select] Generate random number from the interval (0,S) - r.
[Loop] Go through the population and sum the fitnesses from 0 - sum s. When the sum s is greater then r, stop and return the chromosome where you are. Of course, the step 1 is performed only once for each population.

Python code for Roulette wheel selection 

#!/usr/bin/env python

import sys, time, numpy, random

# Individual has a genome and fitness and knows how to print itself
class Individual:
    def __init__(self, genome):
        if genome is None:
            self.genome = numpy.array(numpy.random.random_integers(0, 1, LEN), dtype='bool')
        else:
            self.genome = genome
        self.fitness = FITNESS(self.genome)
    def __str__(self):
        return "".join(str(int(i)) for i in self.genome)
        
# Uniform crossover
def xover(a, b):
    g, h = a.genome.copy(), b.genome.copy()
    for pt in range(len(g)):
        if numpy.random.random() < 0.5:
            g[pt], h[pt] = h[pt], g[pt]
    return (Individual(g), Individual(h))

# Per-gene bit-flip mutation
def mutate(a):
    g = a.genome.copy()
    for pt in range(len(g)):
        if numpy.random.random() < PMUT:
            g[pt] = not g[pt]
    return Individual(g)

# Print statistics, and return True if we have succeeded already.
def stats(pop, gen):
    best = max(pop, key=lambda x: x.fitness)
    print("{0} {1:.2f} {2} {3}".format(gen, numpy.mean([i.fitness for i in pop]), best.fitness, str(best)))
    return (best.fitness >= SUCCESS_THRESHOLD)

# Roulette-wheel (fitness-proportionate) selection. Tricky but fast.
# http://stackoverflow.com/questions/2140787/select-random-k-elements-from-a-list-whose-elements-have-weights
def roulette(items, n):
    total = float(sum(w.fitness for w in items))
    i = 0
    w, v = items[0].fitness, items[0]
    while n:
        x = total * (1 - numpy.random.random() ** (1.0 / n))
        total -= x
        while x > w:
            x -= w
            i += 1
            w, v = items[i].fitness, items[i]
        w -= x
        yield v
        n -= 1

# Use many tournaments to get parents
def tournament(items, n, tsize=5):
    for i in range(n):
        candidates = random.sample(items, tsize)
        yield max(candidates, key=lambda x: x.fitness)

# Run one generation
def step(pop):
    newpop = []
    parents = SELECTION(pop, len(pop) + 1) # one extra for final xover    
    while len(newpop) < len(pop):
        if numpy.random.random() < CROSSOVER_PROB:
            # crossover and mutate to get two new individuals
            newpop.extend(map(mutate, xover(parents.next(), parents.next())))
        else:
            # clone and mutate to get one new individual
            newpop.append(mutate(parents.next()))
    return newpop
    
def main():
    if len(sys.argv) > 1:
        numpy.random.seed(int(sys.argv[1]))
    print("GENERATIONS {0}, POPSIZE {1}, LEN {2}, CROSSOVER_PROB {3}, PMUT {4}".format(GENERATIONS, POPSIZE, LEN, CROSSOVER_PROB, PMUT))
    pop = [Individual(None) for i in range(POPSIZE)]
    stats(pop, 0)
    for gen in range(1, GENERATIONS):
        pop = step(pop)
        if stats(pop, gen):
            print("Success")
            sys.exit()
    print("Failure")

# parameters
GENERATIONS, POPSIZE, LEN, CROSSOVER_PROB, PMUT = (100, 100, 100, 0.5, 0.1)
FITNESS, SUCCESS_THRESHOLD = (numpy.sum, LEN)
SELECTION = roulette # roulette sucks: tournament is better

main()

Print first repeating character of input string in C++ : Memory Optimized



#include <iostream>

#define CHAR_TO_INT(c) (c - 'a' + 1)
int main(int argc, char** argv)
{
    std::string strInput;
    std::cout << "Get any string:\t";
    std::cin >> strInput;
    int count = 0;

    for (int i = 0; i < strInput.length(); i++) {

        int val = CHAR_TO_INT(strInput[i]);
        if ((count & (1 << val)) > 0) {
            std::cout << "Input string has first non-uniques character \t" << strInput[i];
            break;
        }
        count |= (1 << val);
    }

    return 0;
}

Journey of AI in Robotics and Mobile Apps

In early age, use of AI was limited to the computers. Later on, robotics came into the picture.

In our day, it becomes an integral part of human life by expanding its technical proficiency for mobile platforms. Introducing highly intuitive apps, AI is changing the everyday lives of users profoundly.


* Here we go with the AI and Robotics evolution timeline *



Isolated Storage in Windows Desktop Apps using .Net

As we are becoming more and more aware of, giving programs unfettered access to a computer is not a great idea. Unfortunately, many programs still need to save some sort of state data about themselves. To bridge the needs of applications to save data and the desire of administrators and users to use more limited security settings, the .NET Framework supports the concept of isolated storage.

What Is Isolated Storage?

Running code with limited privileges has many benefits given the presence of predators who are foisting viruses and spyware on your users. The .NET Framework has several mechanisms for dealing with running as least-privileged users. By using isolated storage to save your data, you will have access to a safe place to store information without needing to resort to having users grant access to specific files or folders in the file system. The main benefit of using isolated storage is that your application will run regardless of whether it is running under partial, limited, or full-trust.

The IsolatedStorageFile Class

The IsolatedStorageFile class provides the basic functionality to create files and folders in isolated storage.

IsolatedStorageFile Static/Shared Methods

Name Description
GetMachineStoreForApplication Retrieves a machine-level store for calling the Click-Once,application
GetMachineStoreForAssembly Retrieves a machine-level store for the assembly that called
GetMachineStoreForDomain Retrieves a machine-level store for the AppDomain within the current,assembly that called.
GetStore Retrieves stores based on the IsolatedStorage- Scope enumerator
GetUserStoreForApplication Retrieves a user-level store for the Click-Once application that,called
GetUserStoreForAssembly Retrieves a user-level store for the assembly that called
GetUserStoreForDomain Retrieves a user-level store for the AppDomain within the current,assembly that called

How to Create a Store

Before you can save data in isolated storage, you must determine how to scope the data you want in your store. For most applications, you will want to choose one of the following two methods:

Assembly/Machine 

This method creates a store to keep information that is specific to the calling assembly and the local machine. This method is useful for creating application-level data.

IsolatedStorageFile machineStorage = IsolatedStorageFile.GetMachineStoreForAssembly();

Assembly/User

This method creates a store to keep information that is specific to the calling assembly and the current user. This method is useful for creating user-level data. If you need to specify the user for the store, you will need to use impersonation.

IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly();


Example Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.IsolatedStorage;

namespace ConfigurationStorage
{
    public partial class ConfigurationStorage : Form
    {
        public ConfigurationStorage()
        {
            InitializeComponent();
        }

        private void ConfigurationStorage_Load(object sender, EventArgs e)
        {
            comboBox_Car.Items.AddRange(new object[] {
                                                        "BMW","Mercitez Benz", "Honda Civic",
                                                        "Mistibushi Lancer", "Toyota Supra",
                                                        "SUV"
                                                     });
            comboBox_Color.Items.AddRange(new object[] { "Red", "Green", "Blue" });
            comboBox_HolDest.Items.AddRange(new object[] { "Singapore", "Paris", "Las Vegas", "Perl Harbour" });
            comboBox_Singer.Items.AddRange(new object[] { "Shakira Mabarak", "Enriquae Iglesias", "Eminem", "Snoop Dogg", "Shina Twain" });
            comboBox_Sports.Items.AddRange(new object[] { "Cricket", "Football", "Tennis", "WWE", "Hockey" });

            comboBox_Car.SelectedIndex = 0;
            comboBox_Color.SelectedIndex = 0;
            comboBox_HolDest.SelectedIndex = 0;
            comboBox_Singer.SelectedIndex = 0;
            comboBox_Sports.SelectedIndex = 0;

            CheckAndLoadPrefs();
        }

        private void button_Save_Click(object sender, EventArgs e)
        {
            IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();
            IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("ConfigurationStorage_UserPreferences.settings", FileMode.Create, userStore);

            StreamWriter writer = new StreamWriter(userStream);
            writer.Write("Car:" + comboBox_Car.SelectedIndex.ToString() + "," +
                         "Color:" + comboBox_Color.SelectedIndex.ToString() + "," +
                         "HolidayDestination:" + comboBox_HolDest.SelectedIndex.ToString() + "," +
                         "Singer:" + comboBox_Singer.SelectedIndex.ToString() + "," +
                         "Sports:" + comboBox_Sports.SelectedIndex.ToString() + ",");
            writer.Close();
            userStream.Close();
            userStore.Close();
        }

        void CheckAndLoadPrefs()
        {
            IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();
            string[] files = userStore.GetFileNames("ConfigurationStorage_UserPreferences.settings");

            if(files.Length > 0)
            {
                IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("ConfigurationStorage_UserPreferences.settings", FileMode.Open, userStore);
                StreamReader reader = new StreamReader(userStream);

                string data = reader.ReadToEnd();

                int pos = 0;
                int colonpos = 0;
                int commapos = -1;
                string userObject = "";
                string indexStr = "";
                foreach (char c in data)
                {
                    if (c == ':')
                    {
                        colonpos = pos;
                        userObject = data.Substring(commapos + 1, colonpos - commapos - 1);                                               
                    }                    
                    if (c == ',')
                    {
                        commapos = pos;
                        indexStr = data.Substring(colonpos + 1, commapos - colonpos -1);
                        int index = Int32.Parse(indexStr);
                        if (userObject == "Car")
                        {
                            comboBox_Car.SelectedIndex = index;
                        }
                        else if (userObject == "Color")
                        {
                            comboBox_Color.SelectedIndex = index;
                        }
                        else if (userObject == "HolidayDestination")
                        {
                            comboBox_HolDest.SelectedIndex = index;
                        }
                        else if (userObject == "Singer")
                        {
                            comboBox_Singer.SelectedIndex = index;
                        }
                        else if (userObject == "Sports")
                        {
                            comboBox_Sports.SelectedIndex = index;
                        } 
                    }
                    pos++;
                }
                reader.Close();
                userStream.Close();
            }
            userStore.Close();
        }
    }
}

File compression using C#.Net

Follow 3 simple steps:

1. Add a new .cs file in your project and add the below namespaces.

using System.IO;
using System.IO.Compression;

2. Add the below code; use this function for compressing the file.

static void CompressFile(string inFileName, string outFileName)
{
     FileStream sourceFile = File.Open(inFileName, FileMode.Open);
     FileStream destFilename = File.Open(outFileName, FileMode.Create);

     GZipStream compStream = new GZipStream(destFilename, CompressionMode.Compress);
            
     Byte[] buffer = new Byte[1024*1024];
     int tempByte = sourceFile.Read(buffer,0,buffer.Length);
     while (tempByte > 0)
     {                
          compStream.Write(buffer, 0, buffer.Length);
          tempByte = sourceFile.Read(buffer, 0, buffer.Length);
     }
     compStream.Close();
     destFilename.Close();
     sourceFile.Close();
}


3. Add the below code; use this function for uncompressing the file.

static void UnCompressFile(string inFileName, string outFileName)
{
     FileStream sourceFile = File.Open(inFileName, FileMode.Open);
     FileStream destFilename = File.Open(outFileName, FileMode.Create);

     GZipStream compStream = new GZipStream(destFilename, CompressionMode.Decompress);
            
     int tempByte = compStream.ReadByte();
     while (tempByte != -1)
     {    destFilename.WriteByte((Byte)tempByte);
          tempByte = compStream.ReadByte();
     }
     compStream.Close();
     destFilename.Close();
     sourceFile.Close();
}

Programming Superstars

This blog is dedicated to our "Programming Heroes" who have lead the evolution of Information Technology, programming languages and libraries in such a way that these have become the real I.T. game changers.

While these technological evolution and revolutions are endless process, we must thank to those who always took initiatives to take the current development technologies to a next level.

Here is a list of some:

1. Anders Hejlsberg

Image Source : Wikipedia.com

Creator and Lead architect of C# language and core developer on TypeScript.



Top Video

2. James Arthur Gosling

Image Source : Wikipedia.com

Creator of Java programming language and best known as the father of the Java programming language.



Top Video

3. John Resig

Image Source : Wikipedia.com

Creator and Lead developer of JQuery.



Top Video

4. Ryan Dahl

Image Source : Google.com

Creator of NodeJs - An open-source, cross-platform JavaScript runtime environment for developing a diverse variety of tools and applications.



Top Video

5. Terence Parr

Image Source : Google.com

Creator of ANTLR (ANother Tool for Language Recognition).



Top Video

6. Jared Hanson

Image Source : Twitter.com

Creator of PassportJS - Passport is authentication middleware for Node.js.



Top Video

7. Guido van Rossum

Image Source : Wikipedia.com

Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, benevolent dictator for life (BDFL).



Top Video


We will be adding more stars to the sky...:)