Change server timezone on Linux CentOS

Here’s way to change timezone on CentOS.

  1. Access to SSH through root account.
  2. Check timezone setting using date command.
  3. Check the timezone list using timedatectl list-timezonescommand.
  4. Change timezone, for example.
    timedatectl set-timezone America/New_York
  5. Check if that applied using date command again.
Facebook Comments

Install phpMyAdmin ubuntu via command line

phpMyAdmin is useful tool to check database content. And I would like to use it on my development server. It’s quite simple and straight forward steps.

You will need root privilege to install this and supposed to be mysql installed and configured already.

  1. First prepare apt-get up to date
    apt-get update && apt-get upgrade
  2. Install phpMyAdmin
    apt-get install phpmyadmin

    When you install and will see and option to choose a web server to choose. If you have apache2 installed, select the option. By default, it’s  blank and looks like chosen but actually need to press space key to select. Then press tab and click OK.

    phpmyadmin install choose apache2
    phpmyadmin install choose apache2

    Another option window is asking if I want to use dbconfig-common. If you already db configured, simply choose “No”.

    phpmyadmin install config

    It will ask password for phpmyadmin user if you choose dbconfig-common as Yes. Put desired password there.

  3. Now you can try access http://yourdomain.com/phpmyadmin

    phpmyadmin installed
    phpmyadmin installed
Facebook Comments

mysql allow remote access from any host

Granting mysql access from remote is not secure, so it’s not recommendable but sometimes we need to do it. Here’s how to do.

  1. Login to mysql with root and create user with remote connect.
    GRANT ALL PRIVILEGES ON remote_db.* TO 'remote_user'@'%' IDENTIFIED BY 'passwordhere';
    
    FLUSH PRIVILEGES;
  2. We need to allow remote connection from mysql configuration. mysql.cnf or mysqld.cnf files locations are differ but in my case, it is located in /etc/mysql/mysql.conf.d/ folder.
    vi /etc/mysql/mysql.conf.d/mysqld.cnf And comment out  below line.
    #bind-address = 127.0.0.1
    After that mysql restart desired.
    service mysql restart
  3.  Now if you have any firewall or network security, allow the port. In my case, I needed to allow 3306 port in AWS inbound rule.
  4. Try to connect from remote.

    mysql -u {username} -p -h {ip address}

    mysql remote connection
    mysql remote connection
Facebook Comments

Use HipChat PHP API

Hipchat is good communication platform not just between people but also between machine and apps.

I am using HipChat to monitor deployment in Jenkins. There’s HipChat plugin for Jenkins.

Hipchat Jenkins plugin
Hipchat Jenkins plugin

And I would like to get this deployment result using API.

hipchat log
hipchat log

Here we go.

First we need to install composer if it is not installed on the server.

sudo apt-get update
sudo apt-get install curl php-cli php-mbstring git unzip
cd ~
curl -sS https://getcomposer.org/installer -o composer-setup.php

After get composer setup file, we can verify the installer. go to https://composer.github.io/pubkeys.html and get key.
Run this command after replace key.

php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

You will see the message like “Installer verified”. Then turn this.

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Next step is get HipChat PHP API and configure composer accordingly.

git clone https://github.com/vanilla/hipchat-api.git
curl -sS https://getcomposer.org/installer | php
php composer.phar install

When you git clone, the git repository has composer.json file and run curl -sS https://getcomposer.org/installer | php  will down load composer.phar file and all sub folders will be created after run php composer.phar install

Now we need to get API Token.  Login to HipChat and go to Profile > API access menu > create new token.

get hipchat api token
get hipchat api token

Finally, we can make example script.

<?php
// The library lives in the HipChat namespace.
use HipChat\v2\HipChatClient;

// Require composer's autoloader.
require_once 'vendor/autoload.php';
  
// Define the cli options.
$client = new HipChatClient();
$client->setAuth('{your api token put here}');

// Start making calls!
$options['max-results']=5;
$options['start-index']=0;
$message = $client->roomsAPI()->getHistory('{room number goes here}',$options);
print_r($message);

I got this chat history. Yay!

hipchat api result
hipchat api result

I put it on my Raspberry Pi LCD display to monitor quickly.

hipchat on my raspberry pi
hipchat on my raspberry pi
Facebook Comments

Software serial monitor on Attiny85

Attiny85 is cheap and tiny MCU and it’s useful for small project.

However, It’s difficult to monitor what’s going on inside of tiny chip.

Serial monitor is useful to check that out.

There’s many example to check this on the web, but some how the result showing up with reversed question mark.

Finally I found out that we can specify type of serial data read.

attiny85 serial monitor (TX)
attiny85 serial monitor (TX)
attiny85 serial monitor (RX)
attiny85 serial monitor (RX)
Facebook Comments

Google Structured data testing tool

Google algorithm changed and it’s checking structured data with schema.

Here’s brief instruction for making news page structured.

The Google structured data testing tool is available from here.

It is look like this.

google structured data testing tool
  1. First need to put NewsArticle schema in the html tag.
    <html itemscope itemtype="http://schema.org/NewsArticle" lang="en">
  2. Adding meta tags in the head tag (thumbnailUrl, mainEntityOfPage, description, articleSection)
    <meta name="news_keywords" content="Facebook,Facebook Today In,Facebook local news,Facebook testing Today In,Facebook fake news,Facebook Journalism Project" /><meta
    property="article:published_time" content="2018-01-11T23:01:57-05:00" /><meta
    property="article:modified_time" content="2018-01-11T23:01:56-05:00" /><meta
    itemprop="thumbnailUrl" content="http://image.techtimes.com/data/images/full/319769/facebook.jpg" />
    <meta itemprop="mainEntityOfPage" content="http://www.techtimes.com/articles/218601/20180111/facebook-is-testing-a-new-today-in-feature-to-bring-you-vetted-local-news.htm">
    <meta itemprop="description" content="Facebook is currently experimenting with a new city-based section called Today In. In it, users will be able to see local information, announcements, and news."/>
    <meta itemprop="articleSection" content="Society"/>
  3. Updated time (dateModified, datePublished) and author on the published date and reporter name
    <meta itemprop="datePublished" content="2018-01-12T08:37:24-05:00"/>
    <time class="time-format" itemprop="dateModified" datetime="2018-01-12T08:37:24-05:00" data-timestamp="1515764244">12 January 2018, 8:37 am EST</time>
    <span class="t1" itemscope itemtype="http://schema.org/Person" itemprop="author"> By <a href="/reporters/erik-pineda" itemprop="url"><em itemprop="name">Erik Pineda</em></a> Tech Times</span>
  4. Adding name and headline on the article title
    <h1 itemprop="name headline">Google Compiles List Of Chromebooks Vulnerable To Meltdown: Here&#039;s What You Need To Know</h1>
  5. Adding image in the image box
    <figure itemscope itemprop="image" itemtype="http://schema.org/ImageObject">
      <meta itemprop="url" content="http://image.techtimes.com/data/images/full/319798/google-chromebooks.jpg">
      <meta itemprop="width" content="804">
      <meta itemprop="height" content="420">
    </figure>
  6. Adding publisher, logo
    <div class="container" itemscope itemtype="http://schema.org/Organization" itemprop="publisher">
      <meta itemprop="name" content="Tech Times">
      <div class="logo" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
        <meta itemprop="url" content="http://asset.techtimes.com/static/common/_v0.0.1/images/logo.png">
        <meta itemprop="width" content="410">
        <meta itemprop="height" content="44">  
      </div>  
    </div>
  7. Adding Article body
    <div class="at-body" itemprop="articleBody">
      Article body text goes here
    </div>

    This is just an example, and checkout and testing more with the google structured data tool.

Facebook Comments

Mysql root password reset on Ubuntu

Stop mysql service

sudo /etc/init.d/mysql stop

Start without password

sudo mysqld_safe --skip-grant-tables &

Connect to Mysql

mysql -uroot

Reset password

use mysql;

update user set password=PASSWORD("passwordgoeeshere") where User='root';

flush privileges;

quit

Restart mysql

sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start
Facebook Comments

Shell script to change files content on multiple git repository

Continuing last post, change content in multiple files, I made another script to change multiple files on each git repository and push the code.

1. Make folder list in array

#!/bin/sh

array=( site1 site2 site3 )

2. For each loop for each sites

for site in "${array[@]}"
do
  #some command
done

3. Replace content in each file

cd ~/home/"$site"/
rpl ".title" ".h1_title" ~/home/"$site"/css/common.css

4. Commit the changes

git pull
git add .
git commit -am 'title changed to h1 title on css file'
git push

5. This is the final code.

#!/bin/sh

array=( site1 site2 site3 )

for site in "${array[@]}"
do
  cd ~/home/"$site"/
  rpl ".title" ".h1_title" ~/home/"$site"/css/common.css
  git pull
  git add .
  git commit -am 'title changed to h1 title on css file'
  git push
done

This is especially useful when I have many sites with same structure.

 

Facebook Comments

Change content text on multiple files using shell script

When I want to change text in several files, it’s hard to open each single file and replace.
So I made one shell script to do the job.
Here’s one example using sed command.

find /home/user/directory -name \*.* -exec sed -i “s/search_text/replace_text/g” {} \;

BTW, it’s hard to remember. Also if I want to change including special character, it’s more harder. like this one. <?php echo $text;?> 

I searched for easy way and found good command. rpl – replace string in files

It’s really easy to use. If you don’t have rpl installed, install it using brew.

$ brew install rpl
rpl "<?php echo $search_text;?>" "<?php echo $replace_text;?>" /home/user/directory

Amazing! I don’t need to remember complicate command line.
However, I want to change in multiple files at the same time, moreover I would like to make easier input without change core programming.

#!/bin/sh
echo "Please enter search: "
read search_variable
echo "Search: $search_variable"
echo "Please enter replace: "
read replace_variable
echo "Replace: $replace_variable"

This bash script will get user input, both find and replace text.

for file in `find . -type f`
do
    rpl "$search_variable" "$replace_variable" $file
done

And this will find all files and replace text. Here’s final code. Save to replace.sh file in good place.

#!/bin/sh
echo "Please enter search: "
read search_variable
echo "Search: $search_variable"
echo "Please enter replace: "
read replace_variable
echo "Replace: $replace_variable"


for file in `find . -type f`
do
    rpl "$search_variable" "$replace_variable" $file
done

One more, I would like to use this command from every where.

alias replace="~/home/shell/replace.sh"

Put this in the .bash_profile, so the comman is available from any where.

 

Facebook Comments

Real time user count from Google analytics API

I posted how to say hello to Google Analytics API.

Continuing the post, I would like to get Real-time user number using Google Analytics API.

1. Initialize google analytics API.

require '../composer/vendor/autoload.php';

function initializeAnalytics(){
  // Creates and returns the Analytics Reporting service object.

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_Analytics($client);

  return $analytics;
}

$analytics = initializeAnalytics();

2. Function for Real-time user number.

function get_realtime_active_user($analytics, $ga_internal_id){
  $optParams = array(
      'dimensions' => 'rt:medium');
  try {
    $results = $analytics->data_realtime->get(
        'ga:'.$ga_internal_id,
        'rt:activeUsers',
        $optParams);
    // Success. 
    $return = $results->totalsForAllResults['rt:activeUsers'];
    return $return;
  } catch (apiServiceException $e) {
    // Handle API service exceptions.
    $error = $e->getMessage();
  }
  
}

3. Get multiple site’s data, change $ga_id_array variable according to your GA account number.
You can get GA account number just like the below.

ga account number
ga account number copy from here
$data = array();
$ga_id_array = array('site1'=>'1234567','site2'=>'12345678','site3'=>'123456789');
foreach($ga_id_array as $name => $ga_id){
  $each_data = array();
  $each_data['name'] = $name;
  $each_data['num'] = get_realtime_active_user($analytics, $ga_id);
  $data[] = $each_data;
}
echo json_encode($data);

4. All together.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
  
require '../composer/vendor/autoload.php';

function initializeAnalytics(){
  // Creates and returns the Analytics Reporting service object.

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_Analytics($client);

  return $analytics;
}

$analytics = initializeAnalytics();

function get_realtime_active_user($analytics, $ga_internal_id){
  $optParams = array(
      'dimensions' => 'rt:medium');
  try {
    $results = $analytics->data_realtime->get(
        'ga:'.$ga_internal_id,
        'rt:activeUsers',
        $optParams);
    // Success. 
    $return = $results->totalsForAllResults['rt:activeUsers'];
    return $return;
  } catch (apiServiceException $e) {
    // Handle API service exceptions.
    $error = $e->getMessage();
  }
  
}

$data = array();
$ga_id_array = array('site1'=>'1234567','site2'=>'12345678','site3'=>'123456789');
foreach($ga_id_array as $name => $ga_id){
  $each_data = array();
  $each_data['name'] = $name;
  $each_data['num'] = get_realtime_active_user($analytics, $ga_id);
  $data[] = $each_data;
}
echo json_encode($data);

That’s all, this will return with JSON format like this.

[{"name":"site1","num":"722"},{"name":"site2","num":"100"},{"name":"site3","num":"20"}]

 

Facebook Comments