Thursday 27 April 2017

Design Patterns in Java

A design patterns are well-proved solution for solving the specific problem/task.
Now, a question will be arising in your mind what kind of specific problem? Let me explain by taking an example.
Problem Given:
Suppose you want to create a class for which only a single instance (or object) should be created and that single object can be used by all other classes.
Solution:
Singleton design pattern is the best solution of above specific problem. So, every design pattern has some specification or set of rules for solving the problems. What are those specifications, you will see later in the types of design patterns.

But remember one-thing, design patterns are programming language independent strategies for solving the common object-oriented design problems. That means, a design pattern represents an idea, not a particular implementation.
By using the design patterns you can make your code more flexible, reusable and maintainable. It is the most important part because java internally follows design patterns.
To become a professional software developer, you must know at least some popular solutions (i.e. design patterns) to the coding problems.

Advantage of design pattern:

  1. They are reusable in multiple projects.
  2. They provide the solutions that help to define the system architecture.
  3. They capture the software engineering experiences.
  4. They provide transparency to the design of an application.
  5. They are well-proved and testified solutions since they have been built upon the knowledge and experience of expert software developers.
  6. Design patterns don?t guarantee an absolute solution to a problem. They provide clarity to the system architecture and the possibility of building a better system.

When should we use the design patterns?

We must use the design patterns during the analysis and requirement phase of SDLC(Software Development Life Cycle).
Design patterns ease the analysis and requirement phase of SDLC by providing information based on prior hands-on experiences.

Categorization of design patterns:

Basically, design patterns are categorized into two parts:
  1. Core java (or JSE) Design Patterns.
  2. JEE Design Patterns.

Core Java Design Patterns

In core java, there are mainly three types of design patterns, which are further divided into their sub-parts:

1.Creational Design Pattern

  1. Factory Pattern
  2. Abstract Factory Pattern
  3. Singleton Pattern
  4. Prototype Pattern
  5. Builder Pattern.

2. Structural Design Pattern

  1. Adapter Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

3. Behavioral Design Pattern

  1. Chain Of Responsibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Memento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern

Creational design patterns

Creational design patterns are concerned with the way of creating objects. These design patterns are used when a decision must be made at the time of instantiation of a class (i.e. creating an object of a class).
But everyone knows an object is created by using new keyword in java. For example:
  1. StudentRecord s1=new StudentRecord();  
Hard-Coded code is not the good programming approach. Here, we are creating the instance by using the new keyword. Sometimes, the nature of the object must be changed according to the nature of the program. In such cases, we must get the help of creational design patterns to provide more general and flexible approach.

Types of creational design patterns

There are following 6 types of creational design patterns.
  1. Factory Method Pattern
  2. Abstract Factory Pattern
  3. Singleton Pattern
  4. Prototype Pattern
  5. Builder Pattern
  6. Object Pool Pattern

Factory Method Pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.
The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern

  • Factory Method Pattern allows the sub-classes to choose the type of objects to create.
  • It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.

Usage of Factory Design Pattern

  • When a class doesn't know what sub-classes will be required to create
  • When a class wants that its sub-classes specify the objects to be created.
  • When the parent classes choose the creation of objects to its sub-classes.

UML for Factory Method Pattern

  • We are going to create a Plan abstract class and concrete classes that extends the Plan abstract class. A factory class GetPlanFactory is defined as a next step.
  • GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get the type of object it needs.
factory pattern

Calculate Electricity Bill : A Real World Example of Factory Method

Step 1: Create a Plan abstract class.
import java.io.*;      
abstract class Plan{  
         protected double rate;  
         abstract void getRate();  
   
         public void calculateBill(int units){  
              System.out.println(units*rate);  
          }  
}//end of Plan class.  
Step 2: Create the concrete classes that extends Plan abstract class.

class  DomesticPlan extends Plan{  
        //@override  
         public void getRate(){  
             rate=3.50;              
        }  
   }//end of DomesticPlan class.  
 
class  CommercialPlan extends Plan{  
   //@override   
    public void getRate(){   
        rate=7.50;  
   }   
//end of CommercialPlan class.  
  1. class  InstitutionalPlan extends Plan{  
  2.    //@override  
  3.     public void getRate(){   
  4.         rate=5.50;  
  5.    }   
  6. /end of InstitutionalPlan class.  
Step 3: Create a GetPlanFactory to generate object of concrete classes based on given information.


class GetPlanFactory{  
      
   //use getPlan method to get object of type Plan   
       public Plan getPlan(String planType){  
            if(planType == null){  
             return null;  
            }  
          if(planType.equalsIgnoreCase("DOMESTICPLAN")) {  
                 return new DomesticPlan();  
               }   
           else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){  
                return new CommercialPlan();  
            }   
          else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {  
                return new InstitutionalPlan();  
          }  
      return null;  
   }  
}//end of GetPlanFactory class.  
 
 
Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete classes by passing an information such as type of plan DOMESTICPLAN or COMMERCIALPLAN or INSTITUTIONALPLAN.

import java.io.*;    
class GenerateBill{  
    public static void main(String args[])throws IOException{  
      GetPlanFactory planFactory = new GetPlanFactory();  
        
      System.out.print("Enter the name of plan for which the bill will be generated: ");  
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  
      String planName=br.readLine();  
      System.out.print("Enter the number of units for bill will be calculated: ");  
      int units=Integer.parseInt(br.readLine());  
  
      Plan p = planFactory.getPlan(planName);  
      //call getRate() method and calculateBill()method of DomesticPaln.  
  
       System.out.print("Bill amount for "+planName+" of  "+units+" units is: ");  
           p.getRate();  
           p.calculateBill(units);  
            }  
    }//end of GenerateBill class. 


Preprocessor instruction in C # pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.
Syntax:

#pragma token  
 
Different compilers can provide different usage of #pragma directive.
The turbo C++ compiler supports following #pragma directives.

#pragma argsused  
#pragma exit  
#pragma hdrfile  
#pragma hdrstop  
#pragma inline  
#pragma option  
#pragma saveregs  
#pragma startup  
#pragma warn  
 
Let's see a simple example to use #pragma preprocessor directive.

#include<stdio.h>  
#include<conio.h>  
  
void func() ;  
  
#pragma startup func  
#pragma exit func  
  
void main(){  
printf("\nI am in main");  
getch();  
}  
  
void func(){  
printf("\nI am in func");  
getch();  
}  
Output:
I am in func
I am in main
I am in func

Wednesday 26 April 2017

Future of Digital Marketing in India

The advent of the digital marketing has opened up a novel landscape of doing business i.e. online business.
According to a survey- by 2017, India will have around 600 million internet users that ultimately create a fascinating business opportunity to sell services and products to a growing population of tech-savvy internet users. Recently, booming prevalence of digital India campaign is also adding lots of new flavors and fervors to the future of digital marketing in India. Growing startup trend is another reason that plays significant role in creating a great scope of digital marketing in India. The most common problem that startups face is lack of funds and digital marketing can rescue them as the most cost-effective blessing in disguise. It is highly economical and equally powerful way of conversion-oriented marketing. All the digital marketing maneuvers can also be quantified through powerful digital marketing tools like Kissmetrics, Google Analytics, Google Website Optimizer, etc. that make it one of the most result-oriented modes of marketing.
       There are more than 900 private TV channels and 250+ radio stations in India, which make traditional marketing quite expensive and highly confusing with lots of in-built vacillations. However, in today’s world of internet, Digital Marketing is the only one and most guaranteed way of marketing, which is popularly being the most preferred space of marketing communications and related interactions.
Changing statistical dynamics of future of Digital Marketing in India are-statistics-about-future-of-digital-marketing-in-india
The future of marketing is way beyond the traditional marketing or outbound marketing methodologies that have been using TV and radio ads, print ads, hoardings, banners, magazines, etc. Now, marketing is majorly based on online marketing (inbound marketing) — Marketing in the Digital Sphere. Scope of Digital Marketing provides some of the most powerful techniques of marketing where traditional modes of marketing fail.
Digital Marketing has great panjandrum over entrepreneurs as it not only rescues but also empowers them to optimize their startups in the most cost-effective and quickest possible fashion. Future of digital marketing is going to be more encompassing in 2017, thanks to its ability to offer wide range of economical, powerful and contemporary mechanisms and mediums of marketing.
Digital marketing takes things into consideration like –
  • Page rankings in search engine results
  • Advertising on search engine platforms
  • Conversion through SMO & SEO campaigns
  • Optimization of internet marketing & associated ROI
  • Banner ads on other websites & Marketing on Digital World
Key findings of some of the Recent Digital Marketing Surveys are –
  1. 34% of the companies already had an integrated digital marketing strategy in 2016
  2. 72% marketers believe that traditional model of marketing is no longer sufficient
  3. Company revenue driven by internet marketing will get increased by 30%
  4. In 2017, 80% businesses will increase their digital marketing budget
  5. Digital Marketing budget may surpass the IT budget in 2017

Future Trends of Digital Marketing in India

Digital Marketing will remain as the most powerful and result-oriented way of marketing in 2017 too, and some of my observations on current and future outlook of 5 key channels that will pay key role in deciding future of digital marketing in India are

1. Mobile Marketing

To devise result-oriented marketing plans and campaigns, mobile marketing is going to play one of the most significant roles in 2017. Understanding customers’ changing needs and characteristics lets marketers plan in a result-oriented fashion. As per stats-
  • Current Outlook of Mobile Marketing in Driving Customer-Engagement- 40% (approx)
  • Future Outlook of Mobile Marketing in Driving Customer-Engagement- 75% (approx)
From consumers’ device usage perspective, Smartphone adoption and prevalence of mobile apps and messaging are going to be the topmost trends of digital marketing in 2017. From Facebook’s Mobile Messenger, to Whatsapp and WeChat, we have been witnessing the growing wish of consumers to communicate directly through mobiles compared to public social network pages. 2017 will come with some of the new options for paid media on mobile messaging apps that will further be boosted by artificial intelligence, which is another trend that will go hand in hand with mobile marketing. Brands are developing bots to engage customers, and Facebook’s Bot Engine for Messenger and Google’s new assistance service introduced in Google I/O 2016 indicated towards the rise of Artificial Intelligence to provide more personalized and interactive assistance to consumers through mobile marketing.
  • More than 52% of searches are done through mobile.
  • 89% of Facebook Daily Active users come through mobile.
  • 83% of Facebook advertising revenue comes through Smartphones.
  • 92% of mobile media time is spent in Smartphone apps by consumers.mobile-marketing-is-going-to-be-a-top-future-trend-of-digital-marketing

2. Video Marketing

Modern customers prefer to view a video content on company promos. Growing need for the visual content has turned video marketing be one of the most appealing trends of digital marketing in 2017. When a visual content is well produced to communicate the message in an interactive and engaging way, conversions are always guaranteed.
  • Current Outlook of Video Marketing in driving Customer Engagement- 37%
  • Future Outlook of Video Marketing in driving Customer Engagement- 69%
Video content is swallowing up the content marketing and online marketers take advantage of its power to tempt more customers in quickest possible time. With booming mobile marketing, videos are now offered on mobile phones that fuel up the whole process. Video marketing is the most powerful way that companies use for –
  • Introducing themselves
  • Spreading their messages
  • Promoting their products/services
  • Increasing their reach and optimizing search ranking
  • Boosting customer engagement and enhancing returns on investments
 Different kinds of Trending Video Content are-
  • Social Media Videos like Facebook Videos, Facebook 360 Videos, YouTube Videos, Snapchat Videos, etc.
  • Use of GIF videos on different social media channels like Twitter & Facebook
  • Product Description/Demo Videos and Landing Page Videos
  • Storytelling with the help of live streaming videos
  • Use of Videos in Email Marketing

3. Email Marketing

Email marketing is so effective in nurturing leads and ensuring conversions. Email marketers of some of the most successful marketing agencies claim a return of $40 for every dollar they invested. Well-targeted email marketing will be one of the most effective ways of ensuring conversions in 2017. 
  • Current Outlook of Email Marketing in Driving Customer Engagement- 45%
  • Future Outlook of Email Marketing in Driving Customer Engagement- 57%
Email marketing is the most important part of your business branding and you need to choose those trends that befit with your customer profile and business objective.  Your emails should reflect your quality and using professional email templates should be the base of your e-mail marketing campaign in 2017. Some of the top trends of email marketing in 2017 are-
  • Use of Email automation tools for sending and tracking of targeted and personalized emails that will let you understand more and more about your customer base like their demographics, tendencies, age, loyalty, etc.
  • Integration of social media content in email marketing strategy is another trend that will see great rise in 2017. Marketers will preferably provide references to their social content within their emails.
  • 2017 will see a decrease in email blast, as this year would be of customized mails. Mobile-friendly email marketing is another trend that will be quite popular within the domains of digital marketing.
  • Aesthetically appealing animated emails are also going to be a popular trend of digital marketing as such fun new mails entice visitors and hold their attention that ultimately aids in conversions. 

4. Social Media Marketing

Social media changes quickly as there are dozens of new platforms arrive each year. The year 2017 will also be a host for the variety of new social media trends, and social media marketing will for sure be one of the most popular digital marketing channels for branding, optimization, lead generations and conversions.
  • Current Outlook of Social Media Marketing in Driving Customer Engagement- 36%
  • Future Outlook of Social Media Marketing in Driving Customer Engagement- 55%
As social media keeps evolving, it has a massive power to channelize marketing campaigns in innovative and effective ways. Social media is a medium that adeptly responds to new tech innovations, but at the same time, it also exceeds customer’s expectations. Knowing future trends of social media and planning strategy as per that will ensure success for companies. Some of the key social media trends in 2017 are –
  • Enormous evolution of Snapchat is going to be one of the most interesting, powerful and creative trends of social media marketing in 2017.
  • Live video streaming is slowly changing the scenario of social media campaigns, and the trend will see great rise in next year too. Different platforms like Facebook live, SnapChat, Twitter, and Instagram all are blending live streaming videos that will let them be a top pick for marketers.
  • Live videos also ensure 10 times more comments than pre-recorded videos, and such qualities will let them dominate social media marketing more efficaciously
  • Instagram stories, social slideshow ads, social chats, etc. would be the top components of social media marketing in 2017.

5. Search & SEO Marketing

Search engines evolve constantly, and their changes prompt shift in marketers’ ways of targeting audiences. To succeed, it is important for you to know latest changes of SEO marketing and employing effective search engine strategies accordingly. Mobile marketing and social media optimization has enhanced the frequencies of searches all across the globe, and as per statistics, 14 billion web searches are conducted each month through different search engines.
  • Current Outlook of SEO Marketing in driving Customer Engagement- 21%
  • Future Outlook of SEO Marketing in driving Customer Engagement- 40%
  Some of the SEO trends that will turn out to be major hits in 2017 are-
  • Link building will stay as a powerful SEO technique, mobile marketing will rock the house, and along with Google, other search engines will also play significant roles in ensuring great search results.
  • Use of keyword search tools like Google’s Keyword Planner, Moz’s keyword Planner are going to be the most effective trends to know right keywords that your audiences search.
  • Quality content marketing with perfect blending of video content would be another prudent practice that experts think as the most dominant future trend of digital marketing in 2017.
  • Personalizing SEO campaigns as per target audiences, being creative, use of natural links and moving site to HTTPS will be the SEO trend that will decide future of internet marketing campaigns in 2017.moving-site-to-https-is-smoothing-that-google-will-love
Conclusion 
To survive in today’s competitive and frenzied market scenario; it is must for Indian businesses to have a well-integrated internet marketing strategy. Without Digital Marketing, businesses may fall short of creating contemporary marketing strategies and hence, they may turn directionless. Digital Marketing is the present and the future of marketing that will not only let businesses survive but also thrive in the most result-oriented fashion. Including new techniques, following latest updates of Google and incorporating future trends of digital marketing will let your inbound marketing reap great benefits for you in 2017.
In the year 2016, most of the industries were kind of struggling with a growth rate around 6 to 11%; only digital industry saw a growth rate of 41%, which is not going to be stagnant in 2017 as well. Digital Marketing will for sure remain as the most effective way of marketing in the future too, and it will be worthwhile for you to climb on to the digital bandwagon when the time is right, either career-wise or business-wise.

Monday 24 April 2017

Friday 21 April 2017

What is the difference between double DES and 3-DES?

Double-DES is two successive DES instances, while Triple-DES is three successive DES instances.
Use 3DES and not 2DES because 2DES does not yield the security increase that you would believe. Namely, 2DES uses 112 key bits (two 56-bit DES keys) but offers a security level of about 257, not 2112, because of a "meet-in-the middle attack" which is well explained there (not to be confused with "man-in-the-middle", a completely different concept). Similarly, 3DES uses 168 key bits, but offers "only" 2112 security (which is quite sufficient in practice). This also explains why 3DES is sometimes used with a 112-bit key (the third DES key is a copy of the first): going to 168 bits does not actually make things more secure.
This can be summarized as: we use n-DES because a simple DES is too weak (a 56-bit key can be brute-forced by a determined attacker), but in order to really improve security, we must go to n ≥ 3. Of course, every additional DES implies some computational overhead (simple DES is already quite slow in software, 3DES thrice as much).

Current Issues with Cloud Computing

Cloud computing is steadily becoming a popular and cheaper option for most IT-reliant companies for various integral services to their operations. What used to be investments for servers, hardware and storage devices are now monthly service fees for virtual storage and applications that a network of computers can access anytime and anywhere with the right IT infrastructure.
Cloud computing
Although the emergence of great cloud-based computing companies like RingCentral and Dropbox that provide awesome services is such a treat for SMEs and startups, the way the technology is structures presents various issues that need to be addressed.

These issues include but are not limited to the following:

Security
Since the data isn’t protected by security measures you employed yourself, how sure can you be that the cloud computing company you contracted is taking every measure to keep it safe? And who are they keeping it safe from? The data itself is stored on the service provider’s own infrastructure. You pay them to store it and manage it, along with giving you a way to access and change the data. But how about the people who access it illegally? How does your service provider prevent this? Since the service provider hosts the data, is it allowed access to it, or must it simply facilitate your usage? Before you ump headfirst into the trend, make sure you ask your service provider what it does to secure the data you upload.

Tampering
In relation to data security, your data may be tampered while it is under the purview of  your service provider’s infrastructure. While the data may not be taken or deleted, it can be changed or modified.

Data ownership
The transference of data to servers that aren’t physically-owned by the authors or uploaders of the data themselves begs the question of whom does the data belong to? Lawmakers continue to debate and try to define the parameters of the data stored in the cloud as to whose the pieces are, or if it’s actually owned by no one.

Impact on other industries
VoIP phone services are basically telephony solutions that work through software phones and access to cloud-based computing services and applications. The great price difference from a landline phone system may impact the PSTN-based companies greatly when users switch to digitized and cheaper systems, creating more jobs but turning others almost obsolete. Although this move into the future may be favorable, old systems become outdated. New courses in education may emerge from the shift while others that involve older technology may not be taught anymore.
So if you’re planning to switch to internet-based services for storing your files, making phone calls or collaborating on a project, consider the risks and issues that face this exciting new tech first before you decide it’s time for you to enter the future.

Criteria for Selecting the Right Cloud Platform

Not all cloud platforms are the same. Application developers have become increasingly savvy about the cloud and the options now available to them. But most of today’s cloud solutions are essentially “one-size-fits-all,” requiring developers to sacrifice one, or more, aspects of their cloud computing requirements – whether it's cost, preferred provider or availability of certain services to meet their unique needs.
While practically everything is being offered “as-a-service” now, vendors’ offerings can vary wildly as they try to adapt to the evolving needs of applications. Some apps are simple, others have complex platform requirements. Most apps need to scale, but some have limited life spans. How exactly can developers find a cloud platform that is a good fit for their needs today, but will adapt to meet changing needs?
Answering that question may seem daunting at first, but if you consider the following five criteria when evaluating cloud providers, you’ll be more confident that you’re selecting the right cloud platform.

Polytech – Can the Platform Support Multiple Languages, Databases and Middleware?
You may need to use multiple languages or databases as you create your applications. Each application will have different needs as it is developed, and those needs also may change over time. By finding a cloud provider that can support multiple languages and databases, you’ll avoid having to select a different cloud for each type of application. It’s important not just to look at the service a cloud provider is offering, but whether that platform provides the depth and breadth you need.
For example, a SaaS company that helps developers build visual prototypes in the cloud leverages several PHP frameworks, as well as a variety of databases and queueing technologies to meet its clients’ varying needs. And a sport merchandise company uses multiple languages and related frameworks and middleware to power its site to ensure customers can shop anytime.

Polycloud – Can the Provider Run on Multiple Infrastructures and Support Hybrid Options?
As demand increases for your applications, you’ll need a provider that can grow with you. The key to ensuring compatibility with these changing requirements is not getting locked in. Therefore you should look for a PaaS solution that supports multiple infrastructures and offers the combination of both private and public resources in hybrid cloud configurations.
For example, by deploying high availability and disaster recovery (HA/DR) across public clouds, one e-commerce company ensures its independent artists and designers can showcase their work without interruption. A gamification company separates its data and application infrastructures by deploying them on different public clouds with a low latency secure gateway for inter-cloud connectivity.

Complete Application Lifecycle Support – Can the Platform Deliver a Balance of Automation and Granular Control?
Your company’s current IT processes and the size of your DevOps team will likely guide the level of automation or extent of control you want. As you’re considering your cloud platform, you will want to make sure that it can provide, both, a high level of automation and granular control, so you are not locked in to your initial choice.
For example, a start-up may have a great idea for an app, but few employees in DevOps. In this scenario, automation is necessary to enable the small staff to write the code and easily deploy the app. But over time, as the company grows and scales, their applications may become more complex and require greater control. On the flipside, there are large enterprises that have historically managed in-house infrastructure, but now want the benefits of moving to the cloud. They often want a platform that provides the same level of control they are accustomed to, with more automation.

Proven – Does the Cloud Provider Have a Strong Track Record?
Because the cloud market is relatively new with strong growth potential, there are a myriad of young platform providers that are trying to get in on the opportunity. When considering cloud platform providers, it’s critical to choose a stable company that can provide the service level you need, whether you’re a small start-up, a development agency supporting many customers or running large enterprise applications. You should look for case studies and references that prove the provider’s capabilities, and strongly consider selecting a provider with a history of delivering a commercial-grade platform that is reliable, secure and flexible.
Questions you should ask include: how long has the company been in business, how many apps they have in production, what’s the expertise of both the management and development team, and are they comfortable with both legacy and new apps. With these answers, you won’t risk your business-critical applications to an inexperienced provider that has service interruptions, poor support, and could unexpectedly go out of business.

Customer Support - How Involved Does Your Provider Get?
Many cloud platform providers offer basic help through a knowledge base or other online resources. That is often where the support ends, but it doesn’t have to. Some providers are investing heavily in enhanced customer support. They employ experts who can help you speed your time to market and focus on developing and troubleshooting apps without having to hire more Ops staff. They provide advice on deployment, high availability strategies, scaling, code and security audits, application analysis and best practices. They will stay with you even after your app launches, not just reacting to problems, but providing proactive monitoring and support that keeps your apps running smoothly 24x7.
One financial services organization, for example, relies on its cloud provider’s expertise and dedicated support team for round-the-clock availability and scaling. With this assistance, its developers can focus on their core strengths while the cloud provider takes care of all DevOps responsibilities.
Cloud platforms are dramatically changing the ways that apps are developed and deployed. So that you can focus on what you do best – developing apps – you need a platform provider who will not lock you into decisions that may hamper your innovation and growth over the long term. Clearly, the underlying platform is critical, but equally important is the flexibility and level of support that a cloud provider can deliver. By considering these five criteria, you can find a provider that will enable you to leverage its platform to plan, build, deploy and manage your applications throughout the entire lifecycle of your business and effectively innovate for the future. Are these the criteria your company has used when selecting a cloud platform? What other factors have you considered in your decision-making process?

Path to cloud migrations

Many organizations embark on cloud migrations to achieve scalability, cost-efficiency and higher application performance. But migrating apps to the cloud is a complex process that requires careful planning and deliberation.
It's essential that organizations consider all possibilities -- both good and bad. Cloud migration issues, such as unexpected costs, interoperability, security gaps and unanticipated application rework, can create significant obstacles. To help smooth a frequently bumpy path, organizations need to craft a well-thought-out migration strategy.
Whether your organization is migrating to the cloud from an in-house environment or from one cloud to another, it's important to understand the process and temper any exorbitant expectations. And, since not every application will benefit from the cloud, make sure a migration is right for your organization before diving in.

1.Planning for a cloud migration

Prepare to take the cloud plunge with a migration strategy

Cloud migrations can be fraught with risks and unknowns, so don't go into them unprepared. To avoid potential disaster, map out your strategy and plan for the unexpected. A solid migration strategy acts as a guide or checklist to ensure a successful journey to the cloud. Enterprises need to plan for expenses -- especially the unexpected ones -- as well as the migration's effect on an organization, its systems and users.

2. Performing a cloud migration

Technical considerations for migrating to the cloud

Cloud migrations can be laborious, requiring many steps and manual adjustments. While a solid cloud migration strategy can simplify the process, enterprises still need to consider a number of factors, including tools, governance, performance, application design and more. With a plethora of third-party tools available, it's important to identify those that best meet your migration needs. Additionally, enterprises must consider scary, what-if scenarios, such as a migration driving up, rather than reducing, application costs.

3.Avoiding cloud migration risks

Mitigating migration challenges for cloud success

The path to cloud computing can be a long and arduous one for organizations considering migration. Whether an enterprise is migrating from an on-premises environment or from one cloud to another, it's a risky proposition. Enterprises often contend with regulatory and compliance issues, unexpected budget busters, poor performance, security concerns and more. But for many organizations, improved scalability, agility and other cloud benefits make the risk worth the reward.

Thursday 20 April 2017

List of Program for programming in C,Java, C#, Python based on mathematics

Some C program for practice

Predict the output or error(s) for the following:


C aptitude 1.1







void main()
{
            int  const * p=5;
            printf("%d",++(*p));

}


Explanation: p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".

C aptitude 1.2








main()
{
            char s[ ]="man";
            int i;
            for(i=0;s[ i ];i++)
            printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}


Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].

C aptitude 1.3










main()
{
            float me = 1.1;
            double you = 1.1;
            if(me>=you)
              printf("I love U");
             else
                        printf("I hate U");
}

Wednesday 19 April 2017

Deploying Django, Python 3 and PostgreSQL to AWS Elastic Beanstalk

Tools/technologies used:
  1. Python v3.4.3
  2. Django v1.9
  3. Amazon Elastic Beanstalk, EC2, S3, and RDS
  4. EB CLI 3.x
  5. PostgreSQL

Elastic Beanstalk vs EC2

Elastic Beanstalk is a Platform As A Service (PaaS) that streamlines the setup, deployment, and maintenance of your app on Amazon AWS. It’s a managed service, coupling the server (EC2), database (RDS), and your static files (S3). You can quickly deploy and manage your application, which automatically scales as your site grows. Check out the official documentation for more information.
elastic beanstalk architecture

Getting Started

We’ll be using a simple “Image of the Day” app, which you can grab from this repository:
$ git clone https://github.com/realpython/image-of-the-day.git
$ cd image-of-the-day/
$ git checkout tags/start_here_py3
After you download the code, create a virtualenv and install the requirements via pip:
$ pip install -r requirements.txt
Next, with PostgreSQL running locally, set up a new database named iotd. Also, depending upon your local Postgres configuration, you may need to update the DATABASES configuration in settings.py. For example, I updated the config to:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'iotd',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
Now you can set up the database schema, create a superuser, and run the app:
$ python manage.py migrate
$ python manage.py createsuperuser
$ python manage.py runserver
Navigate to the admin page in your browser at http://localhost:8000/admin and add a new image, which will then be displayed on the main page.
The application isn’t meant to be very exciting; we’re just using it for demo purposes. All it does is let you upload an image via the admin interface and display that image full screen on the main page. That said, although this is a relatively basic app, it will still allow us to explore a number of “gotchas” that exist when deploying to Amazon Beanstalk and RDS.
Now that we have the site up and running on our local machine, let’s start the Amazon deployment process.

CLI for AWS Elastic Beanstalk

To work with a Amazon Elastic Beanstalk, we can use a package called awsebcli. As of this writing the latest version of is 3.7.4 and the recommended way to install it is with pip:
$ pip install awsebcli
Now test the installation to make sure it’s working:
$ eb --version
This should give you a nice 3.x version number:
EB CLI 3.7.4 (Python 3.4.3)
To actually start using Elastic Beanstalk you will need an account with AWS (surprise!). Sign up (or log in).

login screen for aws

Configure EB – initialize your app

With the AWS Elastic Beanstalk CLI working, the first thing we want to do is create a Beanstalk environment to host the application on. Run this from the project directory (“image-of-the-day”):
$ eb init
This will prompt you with a number of questions to help you configure your environment.
Default region
Choosing the region closest to your end users will generally provide the best performance. 
Credentials
Next, it’s going to ask for your AWS credentials.
Here, you will most likely want to set up an IAM User. See this guide for how to set one up. If you do set up a new user you will need to ensure the user has the appropriate permissions. The simplest way to do this is to just add “Administrator Access” to the User. (This is probably not a great choice for security reasons, though.) For the specific policies/roles that a user needs in order to create/manage an Elastic Beanstalk application, see the link here.
Application name
This will default to the directory name. Just go with that.
Python version
Next, the CLI should automagically detect that you are using Python and just ask for confirmation. Say yes. Then you need to select a platform version. You have 2 different options here for Python 3:
  • Python 3.4
  • Python 3.4 (Preconfigured – Docker)
If you’re a hipster, choose the ‘Preconfigured – Docker’ choice, otherwise go with the normal ‘Python 3.4’. No, only teasing; the basic difference is this:

Python 3.4

This gives you an EC2 image running 64bit Amazon Linux with Python 3.4 pre-installed. The front end web server is apache, with mod_wsgi installed. This is the “standard” or “traditional” way that Beanstalk works. In other words, with this option Beanstalk will create EC2 images for you, and you can use the ebextension files we will talk about later to customize the EC2 image.

Python 3.4 (Preconfigured – Docker)

This gives you an EC2 image running Docker, with a Docker image already setup for you. The Docker image runs 64bit Debian Jessie with Python 3.4, nginx 1.8 and uWSGI 2.0.8. Because you’re basically interacting with the Docker image directly, if you choose this route you would use standard Docker configuration techniques (i.e., a ‘Dockerfile’), and then you don’t have to do much that is AWS Beanstalk specific, as Beanstalk knows how to manage the Docker image for you.
For this article we will focus on the “standard” or “traditional” way of using an EC2 image, so choose the ‘Python 3.4’ option and let’s move on.
SSH
Say yes to setting up SSH for your instances.
RSA Keypair
Next, you need to generate an RSA keypair, which will be added to your ~/.ssh folder. This keypair will also be uploaded to the EC2 public key for the region you specified in step one. This will allow you to SSH into your EC2 instance later in this tutorial.

What did we accomplish?

Once eb init is finished, you will see a new hidden folder called .elasticbeanstalk in your project directory:
├── .elasticbeanstalk
│   └── config.yml
├── .gitignore
├── README.md
├── iotd
│   ├── images
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   └── __init__.py
│   │   ├── models.py
│   │   ├── tests.py
│   │   └── views.py
│   ├── iotd
│   │   ├── __init__.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   ├── manage.py
│   ├── static
│   │   ├── css
│   │   │   └── bootstrap.min.css
│   │   └── js
│   │       ├── bootstrap.min.js
│   │       └── jquery-1.11.0.min.js
│   └── templates
│       ├── base.html
│       └── images
│           └── home.html
├── requirements.txt
└── www
    └── media
        └── sitelogo.png
Inside that directory is a config.yml file, which is a configuration file that is used to define certain parameters for your newly minted Beanstalk application.
At this point, if you type eb console it will open up your default browser and navigate to the Elastic Beanstalk console. On the page, you should see one application (called image-of-the-day if you’re following along exactly), but no environments.

elastic beanstalk console
An application represents your code application and is what eb init created for us. With Elastic Beanstalk, an application can have multiple environments (i.e., development, testing, staging, production). It is completely up to you how you want to configure/manage these environments. For simple Django applications I like to have the development environment on my laptop, then create a test and a production environment on Beanstalk.
Let’s get a test environment set up…

Configure EB – create an environment

Coming back to the terminal, in your project directory type:
$ eb create
Just like eb init, this command will prompt you with a series of questions.
Environment Name
You should use a similar naming convention to what Amazon suggests – e.g., application_name-env_name – especially when/if you start hosting multiple applications with AWS. I used – iod-test.
DNS CNAME prefix
When you deploy an app to Elastic Beanstalk you will automatically get a domain name like xxx.elasticbeanstalk.com. DNS CNAME prefix is what you want to be used in place of xxx. The default probably won’t work if you’re following along because somebody else has already used it (the names are global to AWS), so pick something unique and keep on going.

What happens now?

At this point eb will actually create your environment for you. Be patient as this can take some time.
If you do get an error creating the environment, like – aws.auth.client.error.ARCInstanceIdentityProfileNotFoundException– check that the credentials you are using have appropriate permissions to create the Beanstalk environment, as discussed earlier in this post.
Also, it may prompt you with a message about Platform requires a service role. If it does, just say yes and let it create the role for you.
Immediately after the environment is created, eb will attempt to deploy your application, by copying all the code in your project directory to the new EC2 instance, running pip install -r requirements.txt in the process.
You should see a bunch of information about the environment being set up displayed to your screen, as well as information about eb trying to deploy. You will also see some errors. In particular you should see these lines buried somewhere in the output:
ERROR: Your requirements.txt is invalid. Snapshot your logs for details.
Don’t worry – It’s not really invalid. Check the logs for details:
$ eb logs
This will grab all the recent log files from the EC2 instance and output them to your terminal. It’s a lot of information, so you may want to redirect the output to a file (eb logs -z). Looking through the logs, you’ll see one log file named eb-activity.log:
Error: pg_config executable not found.
The problem is that we tried to install psycopy2 (the Postgres Python bindings), but we need the Postgres client drivers to be installed as well. Since they are not installed by default, we need to install them first. Let’s fix that…

Customizing the Deployment Process

eb will read custom .config files from a folder called “.ebextensions” at the root level of your project (“image-of-the-day” directory). These .config files allow you to install packages, run arbitrary commands and/or set environment variables. Files in the “.ebextensions” directory should conform to either JSON or YAML syntax and are executed in alphabetical order.

Installing packages

The first thing we need to do is install some packages so that our pip install command will complete successfully. To do this, let’s first create a file called .ebextensions/01_packages.config:
packages:
  yum:
    git: []
    postgresql93-devel: []
    libjpeg-turbo-devel: []
EC2 instances run Amazon Linux, which is a Redhat flavor, so we can use yum to install the packages that we need. For now, we are just going to install three packages – git, the Postgres client, and libjpeg for Pillow.
After creating that file to redeploy the application, we need to do the following:
$ git add .ebextensions/
$ git commit -m "added eb package configuration"
We have to commit the changes because the deployment command eb deploy works off the latest commit, and will thus only be aware of our file changes after we commit them to git. (Do note though that we don’t have to push; we are working from our local copy…)
As you probably guessed, the next command is:
$ eb deploy
You should now see only one error:
INFO: Environment update is starting.
INFO: Deploying new version to instance(s).
ERROR: Your WSGIPath refers to a file that does not exist.
INFO: New application version was deployed to running EC2 instances.
INFO: Environment update completed successfully.
Let’s find out what’s happening…

Configuring our Python environment

EC2 instances in Beanstalk run Apache, and Apache will find our Python app according to the WSGIPATH that we have set. By default eb assumes our wsgi file is called application.py. There are two ways of correcting this-
Option 1: Using environment-specific configuration settings
$ eb config
This command will open your default editor, editing a configuration file called .elasticbeanstalk/iod-test.env.yml. This file doesn’t actually exist locally; eb pulled it down from the AWS servers and presented it to you so that you can change settings in it. If you make any changes to this pseudo-file and then save and exit, eb will update the corresponding settings in your Beanstalk environment.
If you search for the terms ‘WSGI’ in the file, and you should find a configuration section that looks like this:
aws:elasticbeanstalk:container:python:
  NumProcesses: '1'
  NumThreads: '15'
  StaticFiles: /static/=static/
  WSGIPath: application.py
Update the WSGIPath:
 aws:elasticbeanstalk:container:python:
   NumProcesses: '1'
   NumThreads: '15'
   StaticFiles: /static/=static/
   WSGIPath: iotd/iotd/wsgi.py
And then you will have you WSGIPath set up correctly. If you then save the file and exit, eb will update the environment configuration automatically:
Printing Status:
INFO: Environment update is starting.
INFO: Updating environment iod-test's configuration settings.
INFO: Successfully deployed new configuration to environment.
INFO: Environment update completed successfully.
The advantage to using the eb config method to change settings is that you can specify different settings per environment. But you can also update settings using the same .config files that we were using before. This will use the same settings for each environment, as the .config files will be applied on deployment (after the settings from eb config have been applied).
Option 2: Using global configuration settings
To use the .config file option, let’s create a new file called /.ebextensions/02_python.config:
option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "iotd.settings"
    "PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
    WSGIPath: iotd/iotd/wsgi.py
    NumProcesses: 3
    NumThreads: 20
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "www/static/"
What’s happening?
  • DJANGO_SETTINGS_MODULE: "iotd.settings" – adds the path to the settings module.
  • "PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH" – updates our PYTHONPATH so Python can find the modules in our application. This path may vary depending on your setup! 
  • WSGIPath: iotd/iotd/wsgi.py sets our WSGI Path.
  • NumProcesses: 3 and NumThreads: 20 – updates the number of processes and threads used to run our WSGI application.
  • "/static/": "www/static/" sets our static files path.
Again, we can do a git commit then an eb deploy to update these settings.
Next let’s add a database.

Configuring a Database

Try to view the deployed website:
$ eb open
This command will show the deployed application in your default browser. You should see a connection refused error:
OperationalError at /
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
This is because we haven’t set up a database yet. At this point eb will set up your Beanstalk environment, but it doesn’t set up RDS (the database tier). We have to set that up manually.

Database setup

Again, use eb console to open up the Beanstalk configuration page.

elastic beanstalk config page
From there, do the following:
  1. Click the “Configuration” link.
  2. Scroll all the way to the bottom of the page, and then under the “Data Tier” section, click the link “create a new RDS database”.
  3. On the RDS setup page change the “DB Engine” to “postgres”.
  4. Add a “Master Username” and “Master Password”.
  5. Save the changes.

create new rds database
Beanstalk will create the RDS for you. Now we need to get our Django app to connect to the RDS. Beanstalk will help us out here by exposing a number of environment variables on the EC2 instances for us that detail how to connect to the Postgres server. So all we need to do is update our settings.py file to take advantage of those environment variables. Confirm that the DATABASES configuration parameter reflects the following in settings.py:
if 'RDS_DB_NAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'iotd',
            'USER': 'iotd',
            'PASSWORD': 'iotd',
            'HOST': 'localhost',
            'PORT': '5432',
        }
    }
This simply says, “use the environment variable settings if present, otherwise use our default development settings.” Simple.

Handling database migrations

With our database setup, we still need to make sure that migrations run so that the database table structure is correct. We can do that by modifying .ebextensions/02_python.config and adding the following lines at the top of the file:
container_commands:
  01_migrate:
    command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py migrate --noinput"
    leader_only: true
container_commands allow you to run arbitrary commands after the application has been deployed on the EC2 instance. Because the EC2 instance is set up using a virtual environment, we must first activate that virtual environment before running our migrate command. Also the leader_only: true setting means, “only run this command on the first instance when deploying to multiple instances.”
Don’t forget that our application makes use of Django’s admin, so we are going to need a superuser…

Create the Admin User

Unfortunately createsuperuser doesn’t allow you to specify a password when using the --noinput option, so we will have to write our own command. Fortunately, Django makes it very easy to create custom commands.
Create the file iotd/images/management/commands/createsu.py:
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User


class Command(BaseCommand):

    def handle(self, *args, **options):
        if not User.objects.filter(username="admin").exists():
            User.objects.create_superuser("admin", "admin@admin.com", "admin")
Make sure you add the appropriate __init__.py files as well:
└─ management
    ├── __init__.py
    └── commands
        ├── __init__.py
        └── createsu.py
This file will allow you to run python manage.py createsu, and it will create a superuser without prompting for a password. Feel free to expand the command to use environment variables or another means to allow you to change the password.
Once you have the command created, we can just add another command to our container_commands section in .ebextensions/02_python.config:
02_createsu:
  command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py createsu"
  leader_only: true
Before you test this out, let’s make sure our static files are all put in the correct place…

Static Files

Add one more command under container_commands:
03_collectstatic:
  command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py collectstatic --noinput"
So the entire file looks like this:
container_commands:
  01_migrate:
    command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py migrate --noinput"
    leader_only: true
  02_createsu:
    command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py createsu"
    leader_only: true
  03_collectstatic:
    command: "source /opt/python/run/venv/bin/activate && python iotd/manage.py collectstatic --noinput"

option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "iotd.settings"
    "PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH"
    "ALLOWED_HOSTS": ".elasticbeanstalk.com"
  "aws:elasticbeanstalk:container:python":
    WSGIPath: iotd/iotd/wsgi.py
    NumProcesses: 3
    NumThreads: 20
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "www/static/"
We now need to ensure that the STATIC_ROOT is set correctly in the settings.py file:
STATIC_ROOT = os.path.join(BASE_DIR, "..", "www", "static")
STATIC_URL = '/static/'
Make sure you commit the www directory to git so the static dir can be created. Then run eb deploy again, and you should now be in business:
INFO: Environment update is starting.
INFO: Deploying new version to instance(s).
INFO: New application version was deployed to running EC2 instances.
INFO: Environment update completed successfully.
At this point you should be able to go to http://your_app_url/admin, log in, add an image, and then see that image displayed on the main page of your application.
Success!

Using S3 for Media Storage

With this setup, each time we deploy again, we will lose all of our uploaded images. Why? Well, when you run eb deploy, a fresh instance is spun up for you. This is not what we want since we will then have entries in the database for the images, but no associated images. The solution is to store the media files in Amazon Simple Storage Service (Amazon S3) instead of on the EC2 instance itself.
You will need to:
  1. Create a bucket
  2. Grab your user’s ARN (Amazon Resource Name)
  3. Add bucket permissions
  4. Configure your Django app to use S3 to serve your static files
Since there are good write ups on this already, I’ll just point you to my favorite: Using Amazon S3 to store you Django Static and Media Files

Apache Config

Since we are using Apache with Beanstalk, we probably want to set up Apache to (among other things) enable gzip compression so files are downloaded faster by the clients. That can be done with container_commands. Create a new file .ebextensions/03_apache.config and add the following:
container_commands:
  01_setup_apache:
    command: "cp .ebextensions/enable_mod_deflate.conf /etc/httpd/conf.d/enable_mod_deflate.conf"
Then you need to create the file .ebextensions/enable_mod_deflate.conf:
# mod_deflate configuration
<IfModule mod_deflate.c>
  # Restrict compression to these MIME types
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE application/xml+rss
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/css
  # Level of compression (Highest 9 - Lowest 1)
  DeflateCompressionLevel 9
  # Netscape 4.x has some problems.
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  # Netscape 4.06-4.08 have some more problems
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  # MSIE masquerades as Netscape, but it is fine
  BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
<IfModule mod_headers.c>
  # Make sure proxies don't deliver the wrong content
  Header append Vary User-Agent env=!dont-vary
</IfModule>
</IfModule>
Doing this will enable gzip compression, which should help with the size of the files you’re downloading. You could also use the same strategy to automatically minify and combine your CSS/JS and do any other preprocessing you need to do.

Troubleshooting

Don’t forget the very helpful eb ssh command, which will get you into the EC2 instance so you can poke around and see what’s going on. When troubleshooting, there are a few directories you should be aware of:
  • /opt/python – Root of where you application will end up.
  • /opt/python/current/app – The current application that is hosted in the environment.
  • /opt/python/on-deck/app – The app is initially put in on-deck and then, after all the deployment is complete, it will be moved to current. If you are getting failures in your container_commands, check out out the on-deck folder and not the current folder.
  • /opt/python/current/env – All the env variables that eb will set up for you. If you are trying to reproduce an error, you may first need to source /opt/python/current/env to get things set up as they would be when eb deploy is running.
  • opt/python/run/venv – The virtual env used by your application; you will also need to run source /opt/python/run/venv/bin/activate if you are trying to reproduce an error.