Thursday 23 August 2018

Python - Creating a Command Line Argument (argparse)


For those who often use the Terminal on Linux or cmd on Windows, they will often come into contact with the Command Line for example

$ cd -h
$ sudo apt-get -h
$ dpkg --help
$ arp -a


With python we can create programs to run on the terminal. Example :

import argparse #module
def server_start (server, port):
    print "Starting% s ... OK"% server
    print "% s port:% s"% (server, port)
    
def db_start (db, port):
    print "Starting% s ... OK"% db
    print "% s port:% s"% (db, port)
def main ():
    
    #create Instance parser
    parser = argparse.ArgumentParser (description = "Program start Server")
    
    parser.add_argument (
        "--server",
        type = str,
        required = True,
        help = "Your Server (apache, nginx etc)"
    )
    
    parser.add_argument (
        "--server_port",
        type = int,
        default = 80,
        help = "Your Server port"
    )
    
    parser.add_argument (
        "- db",
        type = str,
        required = True,
        help = "Your Database (mysql, oracle etc)"
    )
    
    parser.add_argument (
        "--db_port",
        type = int,
        default = 3060,
        help = "Your Database port"
    )
        # make the parser
    args = parser.parse_args ()
        #call function
    server_start (args.server, args.server_port)
    db_start (args.db, args.db_port)
if __name__ == '__main__':
    play ()
when we create a program / parser code, then by default we can use the -h command or --help to display help

$ python parser.py -h
or

$ python parser.py --help
then the output

Server start program
optional arguments:
  -h, --help show this help message and exit
  - server SERVER Your Server (apache, nginx etc)
  --db DB Your Database (mysql, oracle etc)
note that according to the coding code, our Command Line program

requires two arguments, namely - server and - db

If we run the program without any argument

$ python parser.py
then the message will appear as follows

usage: parser.py [-h] --server SERVER --db DB
parser.py: error: --server argument is required
With the code we make as above we require the User to

use the Command line as follows:

$ python parser.py --server = apache --server_port 81 --db mysql --db_port = 3030
or (without using = operator)

$ python parser.py - server apache --server_port 81 --db mysql --db_port 3030


Command Line Argument Details
In general, to make our arguments go in the following ways:

1. Positional Command line argument

   p.add_argument ("input_dir", ...)
   p.add_argument ("input_dir", "output_dir" ...)
   This means that the input_dir argument must be in the first position

   and then output_dir must be in the second position. so we have to

   run terminal like this:

  # $ python example.py {path / to / input} {path / to / output}
  $ python example.py / home / image / original / home / image / copy


2. Optional command line argument

    Because of Optional, we can place our arguments anywhere

    during execution. Therefore Optional Arguments must be added

    "-" or "-" sign

    Example:

$ python parser.py --db = mysql --db_port = 3021 --server = apache --server_port = 81
    note that the position is free (unlike the previous example)

In the example above we also see all the arguments using the "-" mark that actually means the Command length. we can short it by adding an argument marked "-"

parser.add_argument (
        
        "-s",
        "--server",
        type = str,
        required = True,
        help = "Your Server (apache, nginx etc)"
    )
- server can we rename or shorten with -s so the execution can be like this

python parser.py -s = apache --server_port 81 --db mysql --db_port = 3030
It's the same as shortened --help with -h



Parser Attribute
parser.add_argument (
    "--server",
    type = str,
    required = True,
    help = "Your Server (apache, nginx etc)"
)
in the example above type, required, help is an Attribute. Here are the main attributes

which is often used in .add_argument ()

  help

    help is a String that we can use for additional information on an Argument.

    highly recommended to add this attribute to make it easier for users to use

    Command that we make. Can be accessed by default with the -h or --help command

  required

    If we feel an argument is mandatory, it can use this attribute.

    required = True

    if we are set required, then we only use type 2 taitu Optional command line argument

    because the Positional Argument is certainly compulsory.

  type

    type is the data type of the Argument value. the most common are: int, float, str.

    type = str

  action

    Explain what will happen if a particular argument is executed. usually will

    save certain values. Yes

Install Slim Framework and Write Your First "Hello World"


Do you want to create a simple website but do you want to start from scratch or a complex framework? You need to try Slim Framework

Installing Slim Framework would be much easier if we're using Composer.

Create a folder (your project folder) in your Web server (htdocs for apache users). for example, we create "slim". create a new file "composer.json" inside slim and type this:

{
    "require": {
        "slim / slim": "2. *"
    }
}
Open you terminal and make sure its under slim folder for example

root @ AcerXtimeline: / opt / lampp / htdocs / slim #
now type: composer or php install composer.phar install (depending on how you install the composer). If you follow this Composer Install Tutorial, you just need the first option

 root @ AcerXtimeline: / opt / lampp / htdocs / slim # composer install
You 'll see the process

Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing slim / slim (2.4.3)
    Downloading: 100%
Writing lock file
Generating autoload files


Once its done, create index.php and type:

require "vendor / autoload.php";

$ app = new \ Slim \ Slim ();

$ app-> get ("/", function () {

    echo "Hello World";
});

$ app-> run ();


Also edit .htaccess file:

RewriteEngine On
RewriteCond% {REQUEST_FILENAME}! -F
RewriteRule ^ index.php [QSA, L]


so you can now open it in Browser:

http: // localhost / slim


Separating Routes In Node.js Express 4


If you prefer using the Query builder in Laravel instead of Eloquent, I'm on your side: D because I also use the query Builder for most Query activities in my Laravel Application.


Well, usually the Coding default from birth might be: D, when the Insert, Update, Delete query might be something like this


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user

    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)

                                  -> update ($ data);

    if ($ update)

        return Redirect :: to ('user / profile');

     else

        // blablaa ...

}

or like this


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user

    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)

                                  -> update ($ data);

    if (! $ update) {


        // redirect with error

        return Redirect :: to ('user / profile') -> with ('error_update', true);

    

     }

     else

       return Redirect :: to ('user / profile');

}

To Update, Delete uses the query builder in laravel, the return is in the form of Affected rows. so the query above is not right and can cause problems.


We can simply handle this as well


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user


    try {


        DB :: table ('user') -> where ('user_id', Auth :: user () -> id) -> update ($ data);


    } catch (\ Exception $ e) {


        // The log will be stored in STorage / logs / laravel.log

        Log :: error ('Can not process update:'. $ E-> getMessage ());

        // redirect with Error

        return Redirect :: to ('user / profile') -> with ('error_update', true);

   }


   // redirect success

   return Redirect :: to ('user / profile') -> with ('success_update', true);

  

}

with try catch we can determine when our query is successful or not


CMIIW


Tips Error Handling Sederhana Pada Query Builder Laravel

If you prefer using the Query builder in Laravel instead of Eloquent, I'm on your side: D because I also use the query Builder for most Query activities in my Laravel Application.

Well, usually the Coding default from birth might be: D, when the Insert, Update, Delete query might be something like this

public function doUpdate ($ data) {

    $ data = array (
     'name' => $ data ['name'],
     'alamar' => $ data ['alamar']
    );

    // auth :: user () -> id: session logged user
    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)
                                  -> update ($ data);
    if ($ update)
        return Redirect :: to ('user / profile');
     else
        // blablaa ...
}
or like this

public function doUpdate ($ data) {

    $ data = array (
     'name' => $ data ['name'],
     'alamar' => $ data ['alamar']
    );

    // auth :: user () -> id: session logged user
    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)
                                  -> update ($ data);
    if (! $ update) {

        // redirect with error
        return Redirect :: to ('user / profile') -> with ('error_update', true);
   
     }
     else
       return Redirect :: to ('user / profile');
}
To Update, Delete uses the query builder in laravel, the return is in the form of Affected rows. so the query above is not right and can cause problems.

We can simply handle this as well

public function doUpdate ($ data) {

    $ data = array (
     'name' => $ data ['name'],
     'alamar' => $ data ['alamar']
    );

    // auth :: user () -> id: session logged user

    try {

        DB :: table ('user') -> where ('user_id', Auth :: user () -> id) -> update ($ data);

    } catch (\ Exception $ e) {

        // The log will be stored in STorage / logs / laravel.log
        Log :: error ('Can not process update:'. $ E-> getMessage ());
        // redirect with Error
        return Redirect :: to ('user / profile') -> with ('error_update', true);
   }

   // redirect success
   return Redirect :: to ('user / profile') -> with ('success_update', true);
 
}
with try catch we can determine when our query is successful or not

CMIIW

Example of Simple 'Advance Where' Query Builder in Laravel

Laravel tips this time I will give a simple code example for Searching the database using Query Builder in laravel.

For example, we want to Search in a table, say, the 'article' table. there may have been a code like this before

//MyModel.php

public static function getSearch ($ search = null) {
    
    // is_publish: 0 = pending, 1 = published

    $ result = DB :: table ('article')
        -> where ('article.is_publish', '1')
        -> where ('article.title', 'LIKE', '%'. $ search. '%')
        -> orWhere ('article.content', 'LIKE', '%'. $ search. '%')
        -> select ('*')
        -> orderBy ('article.id', 'desc') -> paginate (10);

    return $ result;
}
Query Scenario above is looking for WHERE article has been published (is_publish = 1) AND article title like '% ...%' OR article content like '% ...%'.

SELECT * FROM `article` WHERE` article`. `is_publish` = '1' AND `article '.` Title' LIKE '% search%' OR `article`.` Content` LIKE '% search%' ...

The query above is not an error but it will produce incorrect results where the article that is_publish = 0 also appears. To make it right, we must create a code like the following

public static function getSearch ($ search = null) {
    
    // is_publish: 0 = pending, 1 = published

    $ result = DB :: table ('article')
        -> where ('article.is_publish', '1')
        -> where (function ($ query) use ($ search) {

            $ query-> where ('article.title', 'LIKE', '%'. $ search. '%')
                  -> orWhere ('article.content', 'LIKE', '%'. $ search. '%');
        })
        -> select ('*')
        -> orderBy ('article.id', 'desc') -> paginate (10);

    return $ result;
}
The above code will generate the following Raw query

SELECT * FROM `article` WHERE` article`. `is_publish` = '1' AND (`article`.` Title` LIKE '% search%' OR `article` .`content` LIKE '% search%') .. .
Note that we must use Closure

....
-> where (function ($ query) use ($ search) {

    $ query-> where ('article.title', 'LIKE', '%'. $ search. '%')
           -> orWhere ('article.content', 'LIKE', '%'. $ search. '%');
 })
because we access variables outside the function.

Learn Basic OOP in Python

Completing the Basic Python Series before, this time we will learn OOP in Python. Same As with OOP in other programming languages, OOP is of course we will discuss

Class
Object
Constructor
Method
etc.
Writing (syntax)

class ClassName:
    
        # ....
        # ....
or

Employee class (object):

In python we can make a Class Description / Documentation that we make in String form

Employee class:
    'This Class is for Managing Employees'
    
# access outside Class
print employee .__ doc__

#output: This Class to Manage Employees


Class, Object, Constructor and Method
Consider the following example:

Employee class (object):

    'This class is for Employee data'
    jml_karyawan = 0 #Class variable
    
    #constructor
    def __init __ (self, kid, name, position):
        
        self.kid = kid
        self.name = name
        self. position = position
        Employee.jml_ employee + = 1
    
    # method
    def infoKaryawan (self):
    
        print "New employee enters"
        print "==================="
        print "ID:% s"% self.kid
        print "Name:% s"% self.nama
        print "Position:% s"% self. position


# how to access / use classes / create Objects

obj = Employee ("K001", "Reward", "Technician")
obj.infoKaryawan ()

# Add new employees
obj2 = Employee ("K002", "Nadya", "Accounting")
obj2.infoKaryawan ()

# Show total employees
print "-----------------------------"
print "Total Employees:% d"% Employees.jml_karyawan
The program above the output is

New employee enters
===================
ID: K001
Name: Ganjar
Position: Technician
New employee enters
===================
ID: K002
Name: Nadya
Position: Accounting
-----------------------------
Total Employees: 2

We are operating the one code above

__init__, what is that? __init__ is a constructor. The first method will be executed when we first create an Instance from Class. As in other languages ​​we can add Arguments to __init__. The Instance of Class will be initialized in __init__ and we can call it anywhere in that class.

Self, what is that? self is the Instance Class used to access Instance

  self.kid = kid
  self.name = name
  self. position = position
can also call methods in other methods

def method1 (self, argument):
   print "% s argument"% arg

def method2 ():
    self.method1 ("Argument")
Other programming languages ​​also have self or this. the self parameter is written first in the Argument method

def method (self, arg1, arg2, arg3 ....)


The way to classify Classes is generally the same as other Languages

obj = Employee ("K001", "Reward", "Technician")
obj.infoKaryawan ()


CLass variable? note the variable employee. we can create and define a variable in Class. and can be accessed anywhere either in the Class or outside the Class by Syntax

ClassName.variable_name
# Show total employees
print "-----------------------------"
print "Total Employees:% d"% Employees.jml_karyawan


Keep in mind that Python is not like OOP like other languages. therefore we do not find: private, protected and public. The reasons are many and honestly it is difficult to explain it. what is clear Python makers and developers have agreed that they don't need to add that functionality.

If you study deeper for what purpose, for such spaces, it is suitable for systems like what Python is. Maybe we will know more about the reason.



So brief explanation of OOP Python. there are still many that have not been explained from OOP material in python. But of course it will be discussed in the next OOP Python article.

Tips Login dengan Username atau Email di Laravel


Not infrequently we include Username and Email in the registration form like this

Email:

Username:

Password:

....



then after the user has successfully registered, we usually ask to log in by including the username and password. But not infrequently can include either a Username or Email along with a password like this:


Your Email or Username ..


password ...


Sign in



So the user can log in with his username or email. This simple tip is actually possible in PHP native or in other groups.

Here's the simple way in Laravel



# AuthController.php

public function doLogin () {
 
   $ username = Input :: get ('username');
   $ password = Input :: get ('password');

   $ field = filter_var ($ username, FILTER_VALIDATE_EMAIL)? 'email': 'username';
 
   if (Auth :: attempt (array ($ field => $ username, 'password' => $ password)))
   {
      return Redirect :: intended ();
   }
   else
   {
       return Redirect :: to ('login') -> with ('error', 'Invalid username / email or password')
-> withInput ();
   }


} // end of function
       

The login form is quite normal

<input type = "text" name = "username" placeholder = "Email or username ...">
<input type = "password" name = "password" placeholder = "password ..."


Explanation:

 note the following code:

if (Auth :: attempt (array ($ field => $ username, 'password' => $ password)))


By default Auth :: attempt () requires (normally) 2 input-tan namely username and password. We only need to create a flexible username field.

filter_var ($ username, FILTER_VALIDATE_EMAIL)? 'email': 'username';
with the method above the username field we have created dynamically and automatically checks whether the input is an email or not.



So, this time. Happy coding !!!

Python - Creating a Command Line Argument (argparse)

For those who often use the Terminal on Linux or cmd on Windows, they will often come into contact with the Command Line for example $...