Thursday, August 18, 2016

JSON (JavaScript Object Notation) Tutorial with Examples!


In this tutorial I am going to give you some information on JSON and explain its use within various programming languages such as Python, Java, Javascript, etc.
  • JSON has been extended from JavaScript. 
  • It is mostly used to transmit data between a server and web applications. 
  • Web services and APIs use JSON format to provide public data.
  • JSON format is specifically structured and this helps to keep things organized and error free.
  • JSON is language independent.
A Basic JSON Example:
Prerequisites
Before we start, you should take a look at our Javascript Tutorial Series and Ajax Tutorial. If you already know these or looked at them now, let's begin;
What is JSON?
JSON (JavaScript Object Notation) is a lightweight text-based standard designed for human-readable data communication.
The following simple example shows how to use JSON to store information related to cell phones based on their brands and operating systems.

{"phones":[
    {
    "Brand":"Apple",
     "OS":"iOS"
     },
    {
    "Brand":"Samsung", 
    "OS":"Android"
    },
    {
    "Brand":"Motorola", 
    "OS":"Android"
    }
]}


As you can see from the example above, data in JSON is represented in name/value pairs. In the first entry, 'Brand' name corresponds to value 'Apple'. Square brackets represent a JSON Array node and Curly braces represent a JSON Object Node.

The following example shows how JSON is used in an HTML page with JavaScript:

<!-- HTML Code to manipulate by JS -->
<p id="demo"></p>


//JavaScript Code 
var text = '{"Brand":"Samsung","OS":"Android"}';
var obj = JSON.parse(text);

document.getElementById("demo").innerHTML =
obj.Brand + " devices use " + obj.OS + " operating system." ;


The Output (Click to View on Codepen):
Samsung devices use Android operating system.
JSON vs. XML
We already know what XML looks like from the AJAX tutorial which I advised you to take a look. Now let's investigate the commonalities and differences of these two.


If we compare JSON with XML, we see a lot of common properties:
  • They are both human readable (self describing),
  • They are both hierarchical (values within values),
  • Both can be parsed and used by various programming languages,
  • Both can be fetched with an XMLHttpRequest.
  • JSON doesn't use end tag
  • JSON is shorter
  • JSON is quicker to read and write
  • JSON can use arrays
JSON with Other Programming Languages:
However there are some important differences as well:
The biggest difference: XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function as we did in the previous example (JSON.parse()).
1 - JSON with Java
In order to be able to use JSON with Java we need to download and add a .jar file to our project directory (Download from here):
In this example we create an empty JSON object, then we populate this object by using the createJSON() method that we wrote, and then we print the result. Finally we convert this JSON format back into a form of single entries and print those as well.


package example;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JSONCodemio {
 public static void main(String[] args) {
       // Let's create an empty JSON object
       JSONObject obj = new JSONObject();

       ArrayList<Object> list = new ArrayList<>();
       list.add("John");
       list.add(33);
       list.add(false);
    
       // Give this object to our createJSON method 
       // to print JSON format and then decode this back into
       // an array with decodeJSON method
       decodeJSON(createJSON(obj,list));
 }
 
 /**
  * Creates and prints the given ArrayList in JSON format
  * @param json of type JSONObject
  * @param a of type ArrayList<Object>
  */
 public static String createJSON(JSONObject json, ArrayList<Object> a){
              // Fill it with data
       json.put("name", a.get(0));
       json.put("age", a.get(1));
       json.put("dead", a.get(2));
              System.out.println("After Creating:");
       System.out.println(json);
       return json.toString();
 }
 
 /**
  * Decodes a given JSON format string and prints
  * @param s of type String
  */
 public static void decodeJSON(String s){
       JSONParser parser = new JSONParser();
       try{
   JSONObject object = (JSONObject) parser.parse(s);
   // Note that JSONArray will be necessary 
   // if you have more than one entries in your JSON
          System.out.println("\nAfter Decoding:");
          System.out.println(object.get("name"));
   System.out.println(object.get("dead"));
   System.out.println(object.get("age"));
      }catch(Exception e){
                 System.out.println(e);
            }
 }
}

And this is the Output: 

2- JSON with Python
Before we start with encoding and decoding JSON using Python, we need to install any of the JSON modules available as shown below. (Download from here



$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install

The following example shows array encoding in JSON with Python:

#!/usr/bin/python
import demjson

data = [ { 'x' : 1, 'y' : 2, 'z' : 3, 'u' : 4, 't' : 5 } ]

json = demjson.encode(data)
print json

The Output:
[{"x":1,"y":2,"z":3,"u":4,"t":5}] 
The following example shows decoding in JSON with Python:

#!/usr/bin/python
import demjson

json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = demjson.decode(json)
print  text

The Output:
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} 
Alright everyone, you have reached the end of this tutorial. I hope you found it useful. Leave a comment below if you have any questions or comments. Happy Coding!
You can practice some of courses in here :

JavaScript For Beginners - Learn JavaScript From Scratch
JavaScript for Beginners
JavaScript Bootcamp - 2016
ES6 Javascript: The Complete Developer's Guide




    Thursday, August 11, 2016

    Introduction to JavaScript - Tutorial 2 - Arrays, Loops, Conditionals


    Hello everyone, in this tutorial we are going to continue learning the basics of JavaScript. After getting familiar with the coding environment setup, the data types and their use in JS from the first tutorial, now it is time to focus on arrays, loops and conditionals.

    ScreenHunter_002

    Arrays are useful elements of JS that enable us to define variables in an efficient way. Especially, if we have variables that can be classified under the same category, arrays are very helpful to store that information. The following example shows how arrays are created and used in JS;
    
    
         var fruits = new Array("apple","banana","cranberry");
    
         document.write("The 1st element of the array: " + fruits[0] + "<br/>");
         document.write("The 2nd element of the array: " + fruits[1] + "<br/>");
         document.write("The 3rd element of the array: " + fruits[2] + "<br/>");
    
    

    And the Output would be:
    Looks good, but imagine having thousands of entries like that... That would be a pain to manually write every single one of them.. Fortunately, we have a helper in such cases: Loops


      
    The 1st element of the array: apple
    The 2nd element of the array: banana
    The 3rd element of the array: cranberry

    In programming, a loop is a sequence of instructions that is repeated until a specified condition is reached. The following code shows how to use for loops with arrays;
    
    
         var fruits = new Array("apple","banana","cranberry");
    
         for (var i = 0 ; i <= fruits.length - 1; i++) {
            document.write("The " + (i+1) + ". element of the array: " + fruits[i] + "<br/>");
         }
    
    

    An easier alternative ( called enhanced for loop ) would be; 
    
    
         var fruits = new Array("apple","banana","cranberry");
         
         for (i in fruits) {
            document.write("The " + Number(Number(i)+1) + ". element of the array: " + fruits[i] + "<br/>");
         }
        
    

    Notice the difference between the structure of the for loops. for (i in fruits) starts visiting each index automatically from 0 until it reaches the end of the array. On the other hand, in the first for loop structure, we get to pick the initial index value, the increment and the final index value. 

    And the Outputs:
      
    The 1. element of the array: apple
    The 2. element of the array: banana
    The 3. element of the array: cranberry

    This looks pretty similar to our initial output, but again if you have for instance; a thousand entries, the loop method is definitely should be the preferred method. 

    In some specific cases,  using another type of loop called while loops might be beneficial. Especially, when we want our block of code to repeat itself until a specific condition is met, we use while loopsHere is an example,
    
    
       var counter = 0;
    
         while (counter != 8){
            document.write("Counter Value: " + counter + "<br/>");
            counter = counter + 1;
         }      
        
    

    As you can see from the code block above, we print and increment our counter value in each iteration until it reaches to 8. 

    Let's move on to another fundamental statement called a conditional statement. Conditionalstatements enable us to perform some operations when a specific condition is met. There are two different types of conditionals in programming. The first one is called the if-else statement and the other one is the switch-case statementThe following code shows the use of if-else statements in JS;
    
         
         var city = "New York";
    
         if (city=="London"){
          document.write("if condition is met");
         }
         else if(city=="Dubai"){
          document.write("else if condition is met");
         }
         else{
          document.write("else condition is met");
         }
    
    

     As you can see from the example, the string variable "New York" does not match with if andelse if conditions, therefore else condition is met ' will be the output. You can change this variable to "London" or "Dubai" and observe the output.

    The other conditional statementswitch-case, works in a similar fashion;
    
           
        var city = "New York";
    
        switch (city){
         
          case "London": 
            document.write("first case condition is met");
            break;
    
          case "Dubai": 
            document.write("second case condition is met");
            break;
    
          default: 
            document.write("default condition is met");
            break;
         }
    
    

    Notice how we 'break' after each case statement. The reason of this is to prevent other case statements to be met after one condition is satisfied. In this example, default condition is met ' will be the output.

    Read more at:


        Wednesday, August 10, 2016

        7 Things that You Didn’t Know About C++ Programming





        C++ Influenced Many Other Programming Languages
        C++ was Originally Called ‘The New C’
        C++ Introduces Object-Oriented Programming
        C++ has More than 35 Operators
        C++ has Two Main Concepts
        C++ Supports Four Types of Memory Management
        C++ was First Standardized in 1998


        Originally created in the early 1980s, C++ is a general-purpose, object-oriented programming language that supports generic programming and low-level memory manipulation. The language was designed with an emphasis on system programming and embedded large system. Today we’re going to reveal some fun facts about C++, some of which may surprise you.
        According to Wikipedia, C++ has influenced many other programming languages, some of which include C#Java and even newer versions of C. If C++ was never created, who knows what these programming languages would look like today.
        Computer programmer Rick Mascitti is credited with giving C++ its name, with the ++ indicating an improvement from C programming. But before it was given this name, C++ was actually referred to as “the new C.” This is because C++ draws inspiration from C, building upon its framework while adding new features and functions to the language.
        Although it was lacking in C, object-oriented programming was introduced in C++. Among other things, C++ supports the four primary features of OOP: abstraction, inheritance, polymorphism and encapsulation. With that said, C++ is unique in the sense that it supports deterministic destructors for classes — a feature that’s not found in other OOP languages.
        C++ currently has more than 35 different operators, ranging from arithmetic and bit manipulation to logical operations, comparisons and more. Virtually all of these operators can be overloaded for specific types, although there are a few exceptions, one of which is the conditional operator. This vast array of operators makes C++ user definitions more like built-in types.
        C++ has two primary concepts on which the language was built: direct mapping for hardware features and zero-overhead abstractions for mapping. Perhaps this is why the language is often touted as a lightweight abstraction programming language used for creating efficient abstractions while also offering hardware access.
        Yep, C++ supports four different types of memory management: static storage duration objects, thread storage duration objects, automatic storage duration objects, and dynamic storage duration objects.
        The working group known as JTC1/SC22/WG21 first standardized C++ in 1998. Since then, it has been standardized three other times, with the most recent being in 2014 (C++14). But that’s not the end of the line for the programming language. C++ is expected to be standardized again in 2017, although an exact date has yet to be announced.
        Thanks for reading, follow your passion by finding the perfect course, just for you over on
        Read more at:

        Monday, August 8, 2016

        Website Content Protection (Selection, Right Click) using CSS / HTML / JavaScript / Jquery


        Hello everyone, 
        In this post, I am going to explain some features of HTML/CSS that can protect your content on your website. Protection of the website content is a common problem that needs to be taken seriously, especially if you have unique content and you do not want this content to appear on any other websites. 
        content-protection-berk-soysal

        Let me begin with sharing a feature of CSS that disables the selection of some or any text on your website. In order to accomplish this we can use user-selectproperty in CSS. Also for images we can disable the user-drag property along with the right click however disabling the right click can decrease the user experience so please think twice before disabling it. 
        This is the CSS code to disable user-select and user-drag: 
        
        /* Disables the selection */
        .disableselect {
          -webkit-touch-callout: none; /* iOS Safari */
          -webkit-user-select: none;   /* Chrome/Safari/Opera */
          -khtml-user-select: none;    /* Konqueror */
          -moz-user-select: none;      /* Firefox */
          -ms-user-select: none;       /* Internet Explorer/Edge*/
           user-select: none;          /* Non-prefixed version, currently 
                                          not supported by any browser */
        }
        
        /* Disables the drag event 
        (mostly used for images) */
        .disabledrag{
           -webkit-user-drag: none;
          -khtml-user-drag: none;
          -moz-user-drag: none;
          -o-user-drag: none;
           user-drag: none;
        }
        
        

        This is the HTML code to be able to use the selection and drag disable. In the example you will see a normal text, a non-selectable text, a selectable but non-copyable text and a protected image. I used oncontextmenu property of img to disable the right click. When the user right clicks, he/she is going to see "All Rights Reserved ©" : 
        
        <p> You are free to select me :) </p>
        <p class="disableselect"><b> You can not select me!</b></p>
        <p oncopy="return false;" oncut="return false;" 
        oncontextmenu="window.alert('Nice try! Even Ctrl+C or Ctrl+X will not work!');return false;">
        <i>You can select but can not copy me ;)</i></p>
        
        <img oncontextmenu="window.alert('All Rights Reserved &copy;');return false;" 
        src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCBqMerGRgHeNvks4LxJL_2iDNLObVM0TsisodgspT7x_xkP26-4Wnq37Jmnt7KwhHMf__emcOXWDgXw9DN0JEXXrljVxitaEZFxDDtwl4Kv5hSeqieYFkBXb9t-tQFsEBON3F44j5rK4/s1600/logos-min.png" 
        class="disableselect disabledrag"/>
        
        
        Here is the result. Try it :) 


        If you would like to disable right click for all images on your website, we need to use JQuery:

        
        $('img').bind('contextmenu', function(e) {
          window.alert('All Rights Reserved \u00A9');  
          return false;
        });
        
        
        This is the result; 


        These methods are basic methods to prevent others from stealing your content, however it is not entirely possible to stop a determined person from doing that. Anything displayed on the screen has already been downloaded and cached so this information can easily be accessed by the user. Also most of the modern web browsers support some development tools to view or edit the elements on the website so this is another way to access the content. 
        Finally, you should know that preventing the visitor's abilities for the entire website is usually a bad practice and should be avoided.
        Please leave a comment if you have any questions or comments! Read more:
        Coding Made Easy: HTML & CSS For Beginners
        Bootstrap 4 Rapid web development framework HTML CSS JS
        Creating an MP3 Player with HTML5
        JavaScript for Absolute Beginners
        JavaScript For Beginners - Learn JavaScript From Scratch
        JavaScript for Beginners