Blog

  • Merge Sort Algorithm

    Merge Sort Algorithm

    Basics

    Merge Sort is a divide and conquer algorithm.

    The algorithm is based on the principle that a one-element algorithm is sorted a priori.

    The algorithm starts by recursively dividing the list into smaller ones. This process is called “partitioning”. This continues until the length of the sublists becomes 1.

    Next, the elements of the list are merged with a simultaneous comparison of the elements. This process is called “merging”.

    The video below explains well how the algorithm works.

    This diagram shows how the algorithm works on the example of the list

    [10, 5, 7, 4, 1, 2, 5, 18]

    Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github
  • Binary Search algorithm

    Binary Search algorithm

    Basics

    The main requirement for the binary search is: Array must be sorted.

    The binary search work in the same way as searching phone number by person name in phonebook.

    Or similar to searching word in the dictionary.

    For example you need to find word “Mars”. What the steps people usually do:

    1. Open the dictionary in the middle and check any word
    2. If the word started from “P” then the word “Mars” located in the first part of the book.
    3. Then you divide the first part of the book and check the next word.
    4. The next word can start from “G”.
    5. In this case we need search second part of the first part of the book.

    So, the range for the search becomes 2 times less every step.

    The algorithm time complexity is O(log n)

    See the illustration below:

    Video with binary search in action

    Diagrams

    Loop implementation

    PlantUML Syntax:<br /> @startuml</p><p>skinparam padding 10</p><p>start</p><p> repeat</p><p> :Found element between start and finish index. Middle element;</p><p> if (“Middle element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return middle element index;<br /> stop<br /> elseif (“Start element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return start element index;<br /> stop<br /> elseif (“Finish element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return finish element index;<br /> stop<br /> elseif (“Middle element<br /> bigger than<br /> needed element?”) then (yes)<br /> :Finish index = Middle index – 1;<br /> elseif (“Middle element<br /> less than<br /> needed element?”) then (yes)<br /> :Start index = Middle index + 1;<br /> endif</p><p> repeat while (startIndex less than finishIndex) is (no)</p><p> :Search finished;<br /> :Return no item found result;</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h3 class=Recursively implementation

    PlantUML Syntax:<br /> @startuml</p><p>skinparam padding 10</p><p>start</p><p>:Found element between start and finish index. Middle element;</p><p>if (“Middle element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return middle element index;<br /> stop<br /> elseif (“Start element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return start element index;<br /> stop<br /> elseif (“Finish element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return finish element index;<br /> stop<br /> elseif (“Middle element<br /> bigger than<br /> needed element?”) then (yes)<br /> :Recursion.<br /> Start search from start index<br /> to (middle element – 1);<br /> stop<br /> elseif (“Middle element<br /> less than<br /> needed element?”) then (yes)<br /> :Recursion.<br /> Start search from (middle element + 1)<br /> to finish Index;<br /> stop<br /> else<br /> :Search finished;<br /> :Element not found;<br /> stop<br /> endif<br /> @enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github
  • Reverse a Linked List in groups of a given size

    Reverse a Linked List in groups of a given size

    Basics

    In the previous post, we talked about reverse the entire LinkedList. You also can get info about what is it LinkedList and a high-level view of how it works.

    Here is the link: https://www.hrupin.com/2020/12/reverse-a-linked-list-in-groups-of-given-size-algorithm

    Today we will talk about a case when we need to revert linked list nodes in groups of a given size.

    Algorithm theory

    Task definition

    Given LinkedList:
    5–>8–>13–>56–>12–>90–>53–>23–12–>NULL
    Given group size: 3
    We need split linked list into groups and reverse the nodes.
    The result linked list must be like this:
    13–>8–>5–>90–>12–>56–>12–>23–53–>NULL

    Solution

    1. Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and the pointer to the previous node be prev. See this post for reversing a linked list.
    2. head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )
    3. Return prev. Prev becomes the new head of the list

    Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github

  • Reverse a linked list algorithm

    Reverse a linked list algorithm

    Basics

    Linked list is a data structure each element of those has link to the next element.

    Each element of the linked list called node

    The node of linked list called head. To identify the whole linked list we need link to head only.

    The linked lists are great in insertion and deleting first and last elements. They can used for implementing stacks, queues.

    Time and complexity for LinkedList

    OperationComplexity explanationComplexity formula
    InsertionconstantO(1)
    DeletionconstantO(1)
    SearchlinearO(n)
    SpacelinearO(n)

    Algorithm theory

    Task definition

    We have a linked list.

    We need reverse items in the existing linked list.

    Solution

    The simplest way to solve the task is to iterate through the list and set the previous node as the next node for each node. The next node for the first node must be null.

    The complexity in this case will be 0(n).

    Diagram

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p> repeat</p><p> if (“Is Head Node?”) then (yes)<br /> :Set next node as NULL;<br /> else (no)<br /> :Set next node as previous;<br /> endif<br /> :Save current node in previous field;</p><p> repeat while (Next node is NULL) is (no)</p><p> :Save the previous field as head;</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github
  • Dijkstra algorithm

    Dijkstra algorithm

    Algorithm for finding the shortest path from one vertex of the graph to all the others.

    This algorithm was developed by the Dutch scientist Edsger Wybe Dijkstra in 1959.

    The algorithm works only for a directed graph in which the edges have no negative weight and do not have loops. Or is works only with DAG (Directed Acyclic Graph).

    Task:

    Given a weighted directed graph without negative weight arcs. Find the shortest paths from vertex “1” to all others

    Solution

    We make a table of distances from the vertex “1” to all the others, including the vertex “1”.

    Iteration 0.

    Mark vertex 1 as a base vertex. We know that the distance from vertex 1 to vertex 1 is 0. It is less than infinity. We write it down to the table. For the rest of the vertices, for now, write down the distance value equal to infinity. Select the smallest distance value from the first iteration. This is distance 1-1. Vertex 1 is resolved. Moving on to the next iteration

    # IterVertex 1
    (resolved)
    Vertex 2Vertex 3Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞

    Iteration 1.

    From vertex 1 you can go to vertex 2 and 3.
    The distance from vertex 1 to vertex 2 will be 0 + 6 = 6 (edge ​​weight 1-2). 6 is less than infinity. We write to the table.
    The distance from vertex 1 to vertex 3 will be 0 + 4 = 4 (edge ​​weight 1-3). 4 is less than infinity. We write to the table.
    Select the smallest distance value from the first iteration. This distance is from 1-3. Vertex 3 is resolved. It is now basic. Moving on to the next iteration

    # IterVertex 1
    (resolved)
    Vertex 2Vertex 3
    (resolved)
    Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞

    Iteration 2.

    From vertex 3 you can go to vertex 4 and 5.
    The distance from vertex 3 to vertex 4 will be 4 + 3 = 7. 7 is less than infinity. We write to the table.
    The distance from vertex 3 to vertex 5 will be 4 + 8 = 12. 12 less than infinity. We write to the table.
    Transfer the distance value 1-2 to the second iteration without changes.
    Select the smallest distance value from the second iteration. This distance is from 1-2. Vertex 2 is resolved. Vertex 2 is now basic. Moving on to the next iteration

    # IterVertex 1
    (res-d)
    Vertex 2
    (res-d)
    Vertex 3
    (res-d)
    Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞
    26712∞

    Iteration 3.

    From vertex 2 you can go to vertex 4, 5, and 6.
    The distance from vertex 2 to vertex 4 will be 6 + 7 = 13. 13 is greater than 7, which is already in the table. We transfer the value from the previous iteration to the current one.
    The distance from vertex 2 to vertex 5 will be 6 + 4 = 10. 10 is less than 12. Write it down in the table.
    The distance from vertex 2 to vertex 6 will be 6 + 2 = 8. 8 is less than infinity. We write to the table.
    Select the smallest distance value from the third iteration. This distance is from 1-4. Vertex 4 is resolved. Vertex 4 is now basic. Moving on to the next iteration

    # IterVertex 1
    (res-d)
    Vertex 2
    (res-d)
    Vertex 3
    (res-d)
    Vertex 4
    (res-d)
    Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞
    26712∞
    37108

    Iteration 4.

    From vertex 4, you can only get to vertex 6.
    The distance from vertex 4 to vertex 6 will be 7 + 10 = 17.17 is greater than 8, which is already in the table. We transfer the value from the previous iteration to the current one.
    The distance value 1-5 is transferred to the second iteration without changes.
    Choose the smallest distance value from the fourth iteration. This distance is from 1-6. Vertex 6 is resolved. Vertex 6 is now basic. Moving on to the next iteration

    # IterVertex 1
    (res-d)
    Vertex 2
    (res-d)
    Vertex 3
    (res-d)
    Vertex 4
    (res-d)
    Vertex 5Vertex 6
    (res-d)
    00∞∞∞∞∞
    164∞∞∞
    26712∞
    37108
    4108

    Iteration 5.

    From vertex 5, you can only go to vertex 6.
    The distance from vertex 5 to vertex 6 will be 10 + 1 = 11. 11 is greater than 8, which is already in the table. We transfer the value from the previous iteration to the current one.
    Vertex 5 has been resolved.

    All vertices are resolved. The algorithm is complete. The shortest distances from vertex 1 to all other vertices can be seen in the table.

    # IterVertex 1Vertex 2Vertex 3Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞
    26712∞
    37108
    4108
    58

    PlantUML diagram of the algorithm

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p>:Set path from the start point to start point is 0;<br /> :Set start point is base vertex;</p><p>repeat</p><p> :Calculate path from base to neibours as<br /> path to base vertex + edge weight;<br /> if (Path to neibour shortest than already calculated) then (yes)<br /> :Overwrite shortest path;<br /> endif</p><p> repeat<br /> if (Shortest path) then (yes)<br /> :Set vertex with shortest path as resolved;<br /> :Set vertex with shortest path as new base vertex;<br /> endif<br /> repeat while (End of vertex list) is (no)</p><p>repeat while (All vertexes resolved) is (no)</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get link to github repo with Kotlin, Java, and Python code

    Download it from github
  • Diagrams using PlantUml

    Diagrams using PlantUml

    This is not something new, but It can be useful for somebody.

    Sometimes we need to create diagrams. It is easy to do on paper. And what if we need to do it not on paper.

    We have a huge list of tools. My favorite is Draw.io. And in the case of Draw.io, we have to draw something.

    But what if you do not have drawing skills ?

    Here is PlantUML. Using this “language” you able to create diagrams from code. Here are some examples:

    Sequence diagram

    @startuml
    Alice -> Bob: message 1
    Bob --> Alice: ok
    |||
    Alice -> Bob: message 2
    Bob --> Alice: ok
    ||45||
    Alice -> Bob: message 3
    Bob --> Alice: ok
    @enduml

    PlantUML Syntax:<br /> @startuml<br /> Alice -> Bob: message 1<br /> Bob –> Alice: ok<br /> |||<br /> Alice -> Bob: message 2<br /> Bob –> Alice: ok<br /> ||45||<br /> Alice -> Bob: message 3<br /> Bob –> Alice: ok<br /> @enduml<br /> ” usemap=”#plantuml_map”></p><p class=Use Case Diagram

    @startuml
    :Main Admin: as Admin
    (Use the application) as (Use)
    
    User -> (Start)
    User --> (Use)
    
    Admin ---> (Use)
    
    note right of Admin : This is an example.
    
    note right of (Use)
    A note can also
    be on several lines
    end note
    
    note "This note is connected\nto several objects." as N2
    (Start) .. N2
    N2 .. (Use)
    @enduml

    PlantUML Syntax:<br /> @startuml<br /> :Main Admin: as Admin<br /> (Use the application) as (Use)</p><p>User -> (Start)<br /> User –> (Use)</p><p>Admin —> (Use)</p><p>note right of Admin : This is an example.</p><p>note right of (Use)<br /> A note can also<br /> be on several lines<br /> end note</p><p>note “This note is connected\nto several objects.” as N2<br /> (Start) .. N2<br /> N2 .. (Use)<br /> @enduml<br /> ” usemap=”#plantuml_map”></p><p class=Class Diagram

    @startuml
    
    abstract class AbstractList
    abstract AbstractCollection
    interface List
    interface Collection
    
    List <|-- AbstractList
    Collection <|-- AbstractCollection
    
    Collection <|- List
    AbstractCollection <|- AbstractList
    AbstractList <|-- ArrayList
    
    class ArrayList {
    Object[] elementData
    size()
    }
    
    enum TimeUnit {
    DAYS
    HOURS
    MINUTES
    }
    
    annotation SuppressWarnings
    
    @enduml

    PlantUML Syntax:<br /> @startuml</p><p>abstract class AbstractList<br /> abstract AbstractCollection<br /> interface List<br /> interface Collection</p><p>List <|– AbstractList<br /> Collection <|– AbstractCollection</p><p>Collection <|- List<br /> AbstractCollection <|- AbstractList<br /> AbstractList <|– ArrayList</p><p>class ArrayList {<br /> Object[] elementData<br /> size()<br /> }</p><p>enum TimeUnit {<br /> DAYS<br /> HOURS<br /> MINUTES<br /> }</p><p>annotation SuppressWarnings</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><p class=Activity Diagram

    @startuml
    
    start
    
    repeat :foo as starting label;
      :read data;
      :generate diagrams;
    backward:This is backward;
    repeat while (more data?)
    
    stop
    
    @enduml

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p>repeat :foo as starting label;<br /> :read data;<br /> :generate diagrams;<br /> backward:This is backward;<br /> repeat while (more data?)</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><p class=Component Diagram

    @startuml
    
    package "Some Group" {
      HTTP - [First Component]
      [Another Component]
    }
    
    node "Other Groups" {
      FTP - [Second Component]
      [First Component] --> FTP
    }
    
    cloud {
      [Example 1]
    }
    
    
    database "MySql" {
      folder "This is my folder" {
        [Folder 3]
      }
      frame "Foo" {
        [Frame 4]
      }
    }
    
    
    [Another Component] --> [Example 1]
    [Example 1] --> [Folder 3]
    [Folder 3] --> [Frame 4]
    
    @enduml

    PlantUML Syntax:<br /> @startuml</p><p>package “Some Group” {<br /> HTTP – [First Component]<br /> [Another Component]<br /> }</p><p>node “Other Groups” {<br /> FTP – [Second Component]<br /> [First Component] –> FTP<br /> }</p><p>cloud {<br /> [Example 1]<br /> }</p><p>database “MySql” {<br /> folder “This is my folder” {<br /> [Folder 3]<br /> }<br /> frame “Foo” {<br /> [Frame 4]<br /> }<br /> }</p><p>[Another Component] –> [Example 1]<br /> [Example 1] –> [Folder 3]<br /> [Folder 3] –> [Frame 4]</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><p class=State Diagram

    @startuml
    hide empty description
    [*] --> State1
    State1 --> [*]
    State1 : this is a string
    State1 : this is another string
    
    State1 -> State2
    State2 --> [*]
    @enduml

    PlantUML Syntax:<br /> @startuml<br /> hide empty description<br /> [*] –> State1<br /> State1 –> [*]<br /> State1 : this is a string<br /> State1 : this is another string</p><p>State1 -> State2<br /> State2 –> [*]<br /> @enduml<br /> ” usemap=”#plantuml_map”></p><p class=Timing Diagram

    @startuml
    robust "DNS Resolver" as DNS
    robust "Web Browser" as WB
    concise "Web User" as WU
    
    @0
    WU is Idle
    WB is Idle
    DNS is Idle
    
    @+100
    WU -> WB : URL
    WU is Waiting
    WB is Processing
    
    @+200
    WB is Waiting
    WB -> DNS@+50 : Resolve URL
    
    @+100
    DNS is Processing
    
    @+300
    DNS is Idle
    @enduml

    PlantUML Syntax:<br /> @startuml<br /> robust “DNS Resolver” as DNS<br /> robust “Web Browser” as WB<br /> concise “Web User” as WU</p><p>@0<br /> WU is Idle<br /> WB is Idle<br /> DNS is Idle</p><p>@+100<br /> WU -> WB : URL<br /> WU is Waiting<br /> WB is Processing</p><p>@+200<br /> WB is Waiting<br /> WB -> DNS@+50 : Resolve URL</p><p>@+100<br /> DNS is Processing</p><p>@+300<br /> DNS is Idle<br /> @enduml<br /> ” usemap=”#plantuml_map”></p><p class=Work Breakdown Structure (WBS)

    @startwbs
    * Business Process Modelling WBS
    ** Launch the project
    *** Complete Stakeholder Research
    *** Initial Implementation Plan
    ** Design phase
    *** Model of AsIs Processes Completed
    **** Model of AsIs Processes Completed1
    **** Model of AsIs Processes Completed2
    *** Measure AsIs performance metrics
    *** Identify Quick Wins
    ** Complete innovate phase
    @endwbs

    PlantUML Syntax:<br /> @startwbs<br /> * Business Process Modelling WBS<br /> ** Launch the project<br /> *** Complete Stakeholder Research<br /> *** Initial Implementation Plan<br /> ** Design phase<br /> *** Model of AsIs Processes Completed<br /> **** Model of AsIs Processes Completed1<br /> **** Model of AsIs Processes Completed2<br /> *** Measure AsIs performance metrics<br /> *** Identify Quick Wins<br /> ** Complete innovate phase<br /> @endwbs<br /> ” usemap=”#plantuml_map”></p><p class=Examples from plantuml.com

  • How to change/reset root MySQL password on Mac

    How to change/reset root MySQL password on Mac

    Here I want to describe tutorial which works on my Mac.

    MySQL version: mysql  Ver 14.14 Distrib 5.7.20, for macos10.12 (x86_64) using  EditLine wrapper
    Mac OS version: Sierra 10.12.6

    Please take care about root access in production environment. I’m feel free to connect to my MySQL db using root because it is my development environment.

    So, to change root password which you have forgot/loose you need run couple of commands and do couple of additional steps.

    1. Stop your MySQL server using System Preferences. Just open System Preferences–>MySQL and click “Stop MySQL Server” like on screenshot below:

    2. Open Terminal and run next command:

    sudo mysqld_safe --skip-grant-tables --skip-networking

    Command output should be the next:

    ➜  ~ sudo mysqld_safe --skip-grant-tables --skip-networking
    2018-01-07T22:58:07.6NZ mysqld_safe Logging to '/usr/local/mysql/data/Igors-MacBook-Pro-2.local.err'.
    2018-01-07T22:58:07.6NZ mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data

    Now MySQL launched in the save mode.

    3. Open new (second) terminal window and run the next command in it. Before it be sure you have mysqld in the PATH.

    mysql -u root

    Output should be next:

    ➜  ~ mysql -u root                                    
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 9
    Server version: 5.7.20 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql>

    You enter in the MySQL console. Now we need change password in the settings mysql table.

    4. Run next command in the MySQL console to change the root password

    update user set authentication_string=password('YOUR_NEW_PASSWORD_SHOULD_BE_HERE') where user='root';

    Before run the command you need replace YOUR_NEW_PASSWORD_SHOULD_BE_HERE with your new root password.

    Output should be next:

    mysql> update user set authentication_string=password('qwerty') where user='root';
    ERROR 1046 (3D000): No database selected
    mysql> use mysql;
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A
    
    Database changed
    mysql> update user set authentication_string=password('qwerty') where user='root';
    Query OK, 1 row affected, 1 warning (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 1
    
    mysql>

    If you will see Query OK, 1 row affected then all is ok and we can exit MySQL console. You can do it using next command:

    exit;

    Now you need restart MySQL using System Preferences. Just click on “Start MySQL Server”

    If you can’t do it using System Preferences then you need do it using Activity Monitor tool. You need open “CPU” tab then find and stop mysqld process.

    Process “Force quit”  button located in the top-left corner. Have a look screenshot.

    Hope it help you.
    Let me know if you know better approach.

     

     

  • How to install PhpMyAdmin + Nginx in Mac OS X

    How to install PhpMyAdmin + Nginx in Mac OS X

    In previous post I’ve talked about installing MySQL in Mac OS X.

    Today I want to talk about PhpMyAdmin. Tool which help work with MySQL databases.

    Here steps how to install it and configure under Nginx webserver.

    1. Create virtualhost for PhpMyAdmin.

    Create /usr/local/etc/nginx/sites-available/phpmyadmin file with next content

    server {
        listen   80; 
    
        server_name  phpmyadmin;
        
        root       /var/www/phpmyadmin/;
    
        index index.php index.html index.htm;
     
        access_log  /usr/local/etc/nginx/logs/phpmyadmin.access.log;
        error_log  /usr/local/etc/nginx/logs/phpmyadmin.error.log;
     
        location ~ \.php$ {
            try_files      $uri = 404;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    
        error_page  404     /404.html;
        error_page  403     /403.html;
    }

    Edit hosts for PhpMyAdmin

    Open /etc/hosts file and add next line

    127.0.0.1	phpmyadmin

    /etc/hosts file should looks like this:

    ##
    # Host Database
    #
    # localhost is used to configure the loopback interface
    # when the system is booting.  Do not change this entry.
    ##
    127.0.0.1	localhost
    127.0.0.1	phpmyadmin
    255.255.255.255	broadcasthost
    ::1             localhost

    Make symbolic link to sites-avalable/phpmyadmin into sites-enabled

    sudo ln -s /usr/local/etc/nginx/sites-available/phpmyadmin /usr/local/etc/nginx/sites-enabled/phpmyadmin

    Save files and restart Nginx

    sudo nginx -s stop
    sudo nginx

    2. Download PhpMyAdmin

    Link for downloading https://www.phpmyadmin.net/downloads/

    3. Put PhpMyAdmin into Nginx document root

    Unzip phpmyadmin archive into /var/www directory

    cd <folder with downloadded zip>
    unzip phpMyAdmin-4.7.5-all-languages.zip -d /var/www

    Rename /var/www/phpMyAdmin-4.7.5-all-languages into /var/www/phpmyadmin

    cd /var/www/
    mv phpMyAdmin-4.7.5-all-languages phpmyadmin

    4. Launch/restart nginx and start php-fpm

    sudo nginx -s stop
    sudo nginx
    sudo brew services start php71 
    

    5. Test phpmyadmin VirtualHost

    curl -IL http://phpmyadmin

    Output should be like this:

    HTTP/1.1 200 OK
    Server: nginx/1.12.1
    Date: Sun, 26 Nov 2017 22:12:23 GMT
    Content-Type: text/html; charset=utf-8
    Connection: keep-alive
    X-Powered-By: PHP/7.1.11
    Set-Cookie: pmaCookieVer=5; expires=Tue, 26-Dec-2017 22:12:22 GMT; Max-Age=2592000; path=/; HttpOnly
    Set-Cookie: pma_lang=en; expires=Tue, 26-Dec-2017 22:12:23 GMT; Max-Age=2592000; path=/; HttpOnly
    Set-Cookie: pma_collation_connection=utf8mb4_unicode_ci; expires=Tue, 26-Dec-2017 22:12:23 GMT; Max-Age=2592000; path=/; HttpOnly
    Set-Cookie: phpMyAdmin=c3acgrslgm88jlmvl2ovnoh2eq; path=/; HttpOnly
    X-ob_mode: 1
    X-Frame-Options: DENY
    Referrer-Policy: no-referrer
    Content-Security-Policy: default-src 'self' ;script-src 'self' 'unsafe-inline' 'unsafe-eval' ;;style-src 'self' 'unsafe-inline' ;img-src 'self' data:  *.tile.openstreetmap.org;
    X-Content-Security-Policy: default-src 'self' ;options inline-script eval-script;referrer no-referrer;img-src 'self' data:  *.tile.openstreetmap.org;
    X-WebKit-CSP: default-src 'self' ;script-src 'self'  'unsafe-inline' 'unsafe-eval';referrer no-referrer;style-src 'self' 'unsafe-inline' ;img-src 'self' data:  *.tile.openstreetmap.org;
    X-XSS-Protection: 1; mode=block
    X-Content-Type-Options: nosniff
    X-Permitted-Cross-Domain-Policies: none
    X-Robots-Tag: noindex, nofollow
    Expires: Sun, 26 Nov 2017 22:12:23 +0000
    Cache-Control: no-store, no-cache, must-revalidate,  pre-check=0, post-check=0, max-age=0
    Pragma: no-cache
    Last-Modified: Sun, 26 Nov 2017 22:12:23 +0000
    Vary: Accept-Encoding

    6. Test PhpMyAdmin in browser

    Open http://phpmyadmin in your browser. You should see next page:

    7. Login into PhpMyAdmin.

    Username: root
    Password: Which you have created for ROOT MySQL user during MySQL installation process.
    You will see next page:

     

    PhpMyAdmin installed. Happy codding!

  • Nginx + MySQL configurations

    Nginx + MySQL configurations

    Here is instructions how to install MySQL and PhpMyAdmin on Mac OS X

    1. Download and install DMG file.

    Link for downloading : https://dev.mysql.com/downloads/mysql/

    2. Installer will generate temporary root password. Save it in text file for next steps.

    3. Add /usr/local/mysql/bin to PATH

    If you use ZSH open ~/.zshrc file and add

    export PATH=/usr/local/mysql/bin:$PATH

    at the end of file. Save this file and restart all Terminal windows.

    4. Change MySQL root password

    mysqladmin -u root -p password root

    5. start MySQL service

    Open SystemPreferences and click on MySQL preferences.

    Click on “Start MySQL Server” and put tick on “Automatically Start MySQL Server on Startup”

    6. Check mysql from Terminal

    Open Terminal and run. Enter password which you have setup in step number 4.

    mysql -uroot -p

    You should see output like this:

    ➜  ~ mysql -uroot -p                       
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 123
    Server version: 5.7.20 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql>

    To exit from MySQL console type exit and hit ENTER

    You have installed MySQL.

    To make work with MySQL more comfortable I suggest to install PhpMyAdmin.

    Next post will be about it : https://www.hrupin.com/2017/11/how-to-install-phpmyadmin-nginx-in-mac-os-x

  • How to add Public Key Authentication for Ubuntu 16.04 server

    How to add Public Key Authentication for Ubuntu 16.04 server

    For better security we should use public key authentication on the server.

    Here is steps how to do it.

    1. Generate SSH key pair on your local computer.

    Skip if you already have ssh key pair in your local computer

    ssh-keygen

    Output:

    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/igor/.ssh/id_rsa):

    Hit ENTER and enter passphrase for your SSH key pair. Full output should be like this:

    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/igor/.ssh/id_rsa): 
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in /home/igor/.ssh/id_rsa.
    Your public key has been saved in /home/igor/.ssh/id_rsa.pub.
    The key fingerprint is:
    SHA256:agKodBlKuZFsGd/KGdoZYUeUjdsiyrbZy3jTctp9Q/s igor@ubuntu-server
    The key's randomart image is:
    +---[RSA 2048]----+
    |oo=.             |
    |.=*.o            |
    | O= oo           |
    |+oO.X            |
    |==oO    S        |
    |+o..   . .       |
    |o + o o . .      |
    | oo=.=.  +       |
    | .+.*. .. oE     |
    +----[SHA256]-----+

    Now you have SSH key pair on your local computer.

    2. Login to your server as root user and create new user.

    This step can be skipped if you already have user on your server

    ssh root@your_server_ip

    Output:

    The authenticity of host '45.55.152.45 (45.55.152.45)' can't be established.
    ECDSA key fingerprint is SHA256:+oRtSBmByAohvrz2o7J7Uuaf+bqTHpDt0Rm+JAj05qaQ.
    Are you sure you want to continue connecting (yes/no)?

    Type YES and continue connecting to your server

    Create new user. I will create user ‘igor’

    adduser igor

    You will be asked about Full name, Room name, phone numbers, etc. After you will be asked about information correctness. Hit ‘y‘ if all is correct.
    Sure this steps can be skipped.

    I’ve entered full info. So, my output is here. Your output should be like this:

    Adding user `igor' ...
    Adding new group `igor' (1000) ...
    Adding new user `igor' (1000) with group `igor' ...
    Creating home directory `/home/igor' ...
    Copying files from `/etc/skel' ...
    Enter new UNIX password: 
    Retype new UNIX password: 
    passwd: password updated successfully
    Changing the user information for igor
    Enter the new value, or press ENTER for the default
    	Full Name []: Igor Khrupin
    	Room Number []: 43
    	Work Phone []: +48790865345
    	Home Phone []: +48790865124
    	Other []: 
    Is the information correct? [Y/n] y

    You just have created new user in your server

    3. Add Root Privileges for your new user

    This step can be skipped if you already added root privileges for your user

    usermod -aG sudo igor

    Now your user able to run commands with sudo

    4. Add Public Key Authentication for your server

    There 2 ways how to do it. One using just one command. Second one is manually.

    Method 1. Using ssh-copy-id

    Just run next command on your local computer

    ssh-copy-id user@server_ip

    In my case command is:

    ssh-copy-id igor@45.51.151.45

    ssh-copy-id will do all for you. You just need enter password for your server’s user.
    Full output should be like this:

    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/igor/.ssh/id_rsa.pub"
    /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
    /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
    igor@45.51.151.45's password: 
    
    Number of key(s) added:        1
    
    Now try logging into the machine, with:   "ssh 'igor@45.51.151.45'"
    and check to make sure that only the key(s) you wanted were added.
    Method 2. Manually

    Add your PUBLIC key into~/.ssh/authorized_keys file on your server. First you need go to your local computer and copy this key into clipboard.
    I’ve showed my key into output and copy it from there.

    cat ~/.ssh/id_rsa.pub

    My output with SSH public key here. Your should be like this.

    ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU
    GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3
    Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA
    t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En
    mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx
    NrRFi9wrf+M7Q== igor@hrupin.com

    Copy it into clipboard.

    Login to your server as root and temporary switch to your user.
    I’m switching to my user ‘igor’

    su - igor

    Create ~/.ssh dir on your server if you don’t have it and change access rights for it

    mkdir ~/.ssh
    chmod 700 ~/.ssh

    Create ~/.ssh/authorized_keys file on your server if you don’t have it. Edit this file.

    nano ~/.ssh/authorized_keys

    Paste your PUBLIC ssh key into ~/.ssh/authorized_keys and save file.
    To do it in nano you need hit Command+X for Mac OS or CTRL-X for Windows after hit Y and ENTER

    5. Disable Password Authentication (Recommended)

    Now your new user can use SSH keys to log in.
    To make more better security you need disable password-only authentication.
    After this your server will have public key authentication only.

    Edit SSH daemon configuration using nano. It can be done using root or user with sudo rights.

    command for root:

    nano /etc/ssh/sshd_config

    command for user with root rights

    sudo nano /etc/ssh/sshd_config

    Find  PasswordAuthentication, uncomment it by deleting the #, then change its value to “no“. After it line should looks like this:

    PasswordAuthentication no

    Also ensure that you have

    PubkeyAuthentication yes
    ChallengeResponseAuthentication no

    Save file by hitting Command+X for Mac OS or CTRL-X for Windows after hit Y and ENTER

    Restart SSH Daemon

    Command for root:

    systemctl reload sshd

    Or for user with sudo rights

    sudo systemctl reload sshd

    That’s all your server is done. Let’s try how it works.

    Try to connect to your server using SSH.

    ssh user@your_server_ip

    In my case will be next:

    ssh igor@45.51.151.45

    Then you should see next output:

    ➜  ~ ssh igor@45.51.151.45
    Enter passphrase for key '/Users/igor/.ssh/id_rsa':

    Enter passphrase from YOUR COMPUTER‘s ssh key.
    If all is ok you will get access into your server. Like this:

    ➜  ~ ssh igor@45.51.151.45
    Enter passphrase for key '/Users/igor/.ssh/id_rsa': 
    Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-101-generic x86_64)
    
     * Documentation:  https://help.ubuntu.com
     * Management:     https://landscape.canonical.com
     * Support:        https://ubuntu.com/advantage
    
      Get cloud support with Ubuntu Advantage Cloud Guest:
        http://www.ubuntu.com/business/services/cloud
    
    0 packages can be updated.
    0 updates are security updates.
    
    
    Last login: Sat Nov 25 10:57:24 2017 from 222.196.100.5
    igor@ubuntu-server:~$

    Happy coding everyone!

    Share my post if you like it.