Tuesday, December 3, 2019

How to Caching Post Requests to redis Server in Python Flask, Redis Using Decorators

from flask import Flask, jsonify, request
from functools import wraps
import redis
import json

r = redis.Redis('__ip_address_redis_server__')
cache_time = 10

def xcaching(f):
    @wraps(f)
    def decor(*args, **kwargs):
        check = request.get_json()
        get_from_redis = r.get(str(check))

        if get_from_redis:
            data = get_from_redis.decode('utf-8')
            ret = json.loads(data)
            r.expire(str(check), cache_time)
            return jsonify(ret)

        ret = f(*args, **kwargs)

        cache_to_redis = ret.get_data()
        r.set(str(check), cache_to_redis ex=cache_time)

        return ret
    return decor


@app.route('/search', methods=['POST'])
@xcaching
def main():
req = request.get_json()
ret = call_api_function(req)
return jsonify(ret)

'__repr__' example

class TestClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return '{self.__class__.__name__}({self.a}, {self.b})'.format(self=self)

Sunday, December 1, 2019

Convert dictionary 'key' in list to lowercase (python3)

Using List Comprehension and Dictionary Comprehension
>>> rs = [{'ABC': '123', 'DEF': '456'}]
>>> ret = [{k.lower():v for k,v in i.items()} for i in rs]
>>> ret
>>> [{'abc': '123', 'def': '456'}]

Using Lambda Function
>>> rs = list(map((lambda i: { k.lower(): v for k,v in i.items()}), rs))

Friday, November 22, 2019

How to set TimeZone in Linux Docker Container

#How to set TimeZone in Linux Docker Container

```
apk add tzdata
```
ex:
Dockerfile
```
from python:3.7-alpine
RUN apk add tzdata
ENV TZ=Asia/Bangkok
CMD xxxx
```

#TimeZone in slim and Ubuntu Linux Docker Container

ex:
Dockerfile
```
from python
ENV TZ=Asia/Bangkok
CMD xxxx
```

ex:
Run Container (slim or full linux images)
```
docker run --name container-name -e 'TZ=Asia/Bangkok' python
```

Wednesday, November 20, 2019

SET TimeZone on Ubuntu19 with Command Line

:Find Current TimeZone
$ timedatectl list-timezones | grep -i [zone]

ex:
$ timedatectl list-timezones | grep -i europe

:Remove link
$ sudo unlink /etc/localtime

:Set new TimeZone
sudo ln -s /usr/share/zoneinfo/[Zone/TimeZone] /etc/localtime

ex: 
sudo ln -s /usr/share/zoneinfo/Asia/Bangkok /etc/localtime

Monday, November 18, 2019

"tail -f" in Windows PowerShell

"tail -f" in Windows PowerShell


Get-Content .\file_name -wait | Where {$_ -match "search_name"}
Get-Content .\file_name -wait -tail 30 | Where {$_ -match "search_name"}
Get-Content .\file_name -wait | Where {$_ -match "search_name-1" -and $_ -match "search_name-2}

Friday, November 8, 2019

GGATE Error 'OCI Error ORA-01407: cannot update ("HRIS"."SYS_CLIENTIDENTIFIER"."SYS_USER_ID") to NULL (status = 1407)'

Transaction can't update table column to NULL

ex:

table name: "HRIS"."SYS_CLIENTIDENTIFIER"
column name: "SYS_USER_ID"

check constraint in "DBA_CONS_COLUMNS" or "ALL_CONS_COLUMNS"

SELECT
CONSTRAINT_NAME, TABLE_NAME, COLUMN_NAME
FROM
DBA_CONS_COLUMNS
WHERE
OWNER LIKE 'HRIS'
AND
TABLE_NAME LIKE 'SYS_CLIENTIDENTIFIER'

CONSTRAINT_NAME                TABLE_NAME                     COLUMN_NAME
------------------------------ ------------------------------ --------------------
FK_SYS_CLIENTIDENTIFIER_USER   SYS_CLIENTIDENTIFIER           SYS_USER_ID <--------------
PK_SYS_CLIENTIDENTIFIER        SYS_CLIENTIDENTIFIER           ID
SYS_C0024107                   SYS_CLIENTIDENTIFIER           TERMINALIP
SYS_C0024106                   SYS_CLIENTIDENTIFIER           CREATEBY
SYS_C0024105                   SYS_CLIENTIDENTIFIER           CREATEDATETIME
SYS_C0024104                   SYS_CLIENTIDENTIFIER           GUID
SYS_C0024103                   SYS_CLIENTIDENTIFIER           ID
SYS_C00241XXX        SYS_CLIENTIDENTIFIER           SYS_USER_ID <--------------

DROP CONFLICT CONSTRAINT

ALTER TABLE "HRIS"."SYS_CLIENTIDENTIFIER" DROP CONSTRAINT SYS_C00241XXX;

and restart GGATE replicat

Thursday, October 31, 2019

Backup Docker container

Convert Container to Docker images:

docker commit container_name name/tag

Save docker images to files:

docker save name/tag > backupfile.tar

Import docker images from Files

docker load -i backupfile.tar

Wednesday, October 30, 2019

Fix iSCSI DataStore is Connected But inaccessible

Remount a iSCSI datastore in ESXI host after network failure or
iSCSI DataStore is Connected But inaccessible 

:Scan volume
esxcfg-volume -l

[root@esxi-11:/vmfs/volumes] esxcfg-volume -l
Scanning for VMFS-6 host activity (4096 bytes/HB, 1024 HBs).
VMFS UUID/label: 5b9279dd-659af4f5-9f6c-1866daf4b576/QNAP-01:GRAYLOG
Can mount: Yes
Can resignature: Yes
Extent name: naa.6e843b61b1c7f97dd817d4d65d8bddd7:1     range: 0 - 8388351 (MB)
Extent name: naa.6e843b6ab3d267ad2373d43a8d9645da:1     range: 8388352 - 16776703 (MB)

Scanning for VMFS-6 host activity (4096 bytes/HB, 1024 HBs).
VMFS UUID/label: 5b91fa1a-8d4ad5f5-8747-1866daf3466e/QNAP-01:DS-01
Can mount: Yes
Can resignature: Yes
Extent name: naa.6e843b69306f933db3d1d4045da669da:1     range: 0 - 4194047 (MB)

:Mount Volume

esxcfg-volume -m QNAP-01:DS-01
esxcfg-volume -m QNAP-01:GRAYLOG

Wednesday, October 16, 2019

Oracle EXPORT(expdp) by Tables in SCHEMAS

Oracle EXPORT(expdp) by Tables in SCHEMAS

export:
expdp system/manager directory=TEMP tables=SCHEMA1.TABLENAME1,SCHEMA2.TABLENAME2 dumpfile=SCHEMA_TABLES.dmp logfile=expdp_SCHEMATABLES.log

import:
impdp system/manager directory=DATA_PUMP_DIR dumpfile=SCHEMA_TABLES.dmp logfile=impdp_SCHEMATABLES.log

Friday, September 27, 2019

Set TimeZone Ubuntu 18

Set TimeZone Ubuntu

$ timedatectl list-timezones
$ sudo timedatectl set-timezone Asia/Bankok

Thursday, September 26, 2019

Tmux Tips

Tmux Tips

Tmux copy to ClipBoard

- ctrl + b, [ :Enter To Copy Mode
- Move Start/End with Arrow KEY
- ctrl + space :Start select hi-light
- alt + w :Copy To ClipBoard
- ctrl +b, ] :Paste

Tmux Create New windows

- ctrl + b, c :Create New Windows Terminal
- ctrl + b, n :Next Windows
- ctrl + b, 0-n :Select Windows by Number
- ctrl + b, w :List Windows Terminal

Tmux split panes

- ctrl + b, % :Split Vertical
- ctrl + b, " :Split Horizontal

SEND HTTP POST request using UTL_HTTP in Oracle Database 11G


grant execute on utl_http to wc
grant execute on dbms_lock to wc;

BEGIN
  DBMS_NETWORK_ACL_ADMIN.create_acl (
    acl          => 'local_test_acl_file.xml', 
    description  => 'A test of the ACL functionality',
    principal    => 'WC',
    is_grant     => TRUE, 
    privilege    => 'connect',
    start_date   => SYSTIMESTAMP,
    end_date     => NULL);
end;
/

begin
  DBMS_NETWORK_ACL_ADMIN.assign_acl (
    acl         => 'local_test_acl_file.xml',
    host        => 'ws.domain.local', 
    lower_port  => 5000,
    upper_port  => NULL);    
end;
/


create or replace
procedure send_post_requests
( p_string in varchar2
, p_number in number
) is
  req utl_http.req;
  res utl_http.resp;
  url varchar2(4000) := 'http://ws.domain.local:5000/test';
  name varchar2(4000);
  buffer varchar2(4000); 
  content varchar2(4000) := '{
"string_type":"'||p_string||'",
"number_type":"'||p_number||'"
}';

begin
  req := utl_http.begin_request(url, 'POST',' HTTP/1.1');
  utl_http.set_header(req, 'user-agent', 'mozilla/4.0'); 
  utl_http.set_header(req, 'content-type', 'application/json'); 
  utl_http.set_header(req, 'Content-Length', length(content));

  utl_http.write_text(req, content);
  res := utl_http.get_response(req);
  -- process the response from the HTTP call
  begin
    loop
      utl_http.read_line(res, buffer);
      dbms_output.put_line(buffer);
    end loop;
    utl_http.end_response(res);
  exception
    when utl_http.end_of_body 
    then
      utl_http.end_response(res);
  end;
end send_post_requests;
/

begin
   send_post_requests('stringggggggg', 123456789);
end;
/

drop procedure send_post_requests;

begin
   DBMS_NETWORK_ACL_ADMIN.UNASSIGN_ACL(
     host        => 'tko.nida.local',
     lower_port  => 5000);
end;


begin
   DBMS_NETWORK_ACL_ADMIN.DROP_ACL(
      acl => 'local_test_acl_file.xml');
end;

/








Tuesday, September 10, 2019

Example Python Decorator

ex.1
====

from functools import wraps

from flask import request, jsonify

def token_admin_required(f):
    @wraps(f)
    def decorated(*agrs, **kwagrs):

        token = None

        if 'X-API-KEY' in request.headers:
            token = request.headers['X-API-KEY']

        if not token:
            return jsonify({'message': 'Token is missing.'})

        if token != 'token-key':
            return jsonify({'message': 'Your Token is Wrong or Invalid'})

       # check token
        # print('TOKEN: {}'.format(token) )
        return f(*agrs, **kwagrs)

    return decorated

ex.2
====

import time
import datetime


def decorators(f):
    def wrappers(*args, **kwargs):
        print('Before')
        ret = f(*args, **kwargs)
        print('After')
        return ret
    return wrappers


def timer(f):
    def wrappers(*args, **kwargs):
        before = time.time()
        ret = f(*args, **kwargs)
        print("Function took: ", time.time() - before, "second")
        return ret
    return wrappers


def logger(func):
    def wrappers(*args, **kwargs):
        with open('log.txt', 'a') as f:
            f.write("called function with " + " ".join(
                [str(arg) for arg in args]) + " at " + str(datetime.datetime.now()) + "\n")
            ret = func(*args, **kwargs)
            return ret
    return wrappers


@logger
def add(a, b):
    return a + b


print(add(3, 4))




Monday, September 9, 2019

MongoDB --auth Mode with Docker

#create volume mongo-auth
docker create volume --name mongo-auth

​#Start Container id with option --auth:
​docker run -d --name mongo_auth -p 27017:27017 -v mongo-auth:/data/db mongo --auth
docker exec -it container_id mongo admin

#Add administrator user for "admin" database
db.createUser({ user: 'admin', pwd: 'password', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });

#Logout and Login Again with user/password
docker exec -it container_id mongo -u username databasename
ex.

docker exec -it container_id mongo -u admin admin

#Create News Database

use NEWDB

#Add AD admin user for "NEWDB" database
db.createUser({ user: 'app', pwd: 'password', roles: ["readWrite", "dbAdmin"] });

#Login New Mongo DB with user Authentication
​docker exec -it Container_ID mongo -u database_username  DatabaseName​
ex.

​docker exec -it Container_ID mongo -u app NEWDB​

Tuesday, August 27, 2019

Force start Oracle Goldengate Replicat from Sequence Number

Force start Oracle Goldengate Replicat from Goldengate Sequence Number

error:

OGG-00446 No data selecting position from checkpoint table GGATE.CHECKPOINTTABLE for group


REPLICAT   RMEIS     Last Started 2019-08-26 17:11   Status ABENDED
Checkpoint Lag       00:00:00 (updated 01:09:02 ago)
Log Read Checkpoint  File /data/ggate/dirdat/MEIS/rm000005
                     2019-08-27 09:37:19.154883  RBA 46919569

alter RMEIS extseqno 000005 extrba 46919569

Wednesday, July 24, 2019

VIM Setting Example

setup vundle

git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim


edit .vimrc

set nocompatible
syntax on
"enable syntax

set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
colorscheme monokai
set visualbell

" enable line Number
set number

"show hiden charactor
set list

" turn relative line numbers on
set rnu
set paste
set cursorline

set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
Plugin 'vim-airline/vim-airline'
Plugin 'tpope/vim-surround'
Plugin 'scrooloose/nerdtree'
Plugin 'sickill/vim-monokai'
Plugin 'vim-airline/vim-airline-themes'
Plugin 'Yggdroot/indentLine'

call vundle#end()

set autoindent
set smartindent

filetype plugin indent on


"disable arrows keys

nnoremap <up> <nop>
nnoremap <down> <nop>
nnoremap <left> <nop>
nnoremap <right> <nop>

inoremap <up> <nop>
inoremap <down> <nop>
inoremap <left> <nop>
inoremap <right> <nop>

" enable AirlineColorscheme bubblegum 
let g:airline_theme='bubblegum'

" Windows move shortcut
map <C-h> :call WinMove('h')<cr>
map <C-j> :call WinMove('j')<cr>
map <C-k> :call WinMove('k')<cr>
map <C-l> :call WinMove('l')<cr>

" Window movement shortcuts
" move to the window in the direction shown, or create a new window
function! WinMove(key)
    let t:curwin = winnr()
    exec "wincmd ".a:key
    if (t:curwin == winnr())
        if (match(a:key,'[jk]'))
            wincmd v
        else
            wincmd s
        endif
        exec "wincmd ".a:key
    endif

endfunction


Install ColorScheme Monokai
mkdir ~/.vim/colors
cd ~/.vim/colors
ln -s ./../bundle/vim-monokai/colors/monokai.vim monokai.vim

:PluginInstall

How to use vim in sqlplus

edit file $ORACLE_HOME/sqlplus/admin/glogin.sql

define_editor=vim

Wednesday, July 3, 2019

SSH Config file

vi ~/.ssh/config

Host *
        HostKeyAlgorithms +ssh-dss
        MACs hmac-sha1
        Ciphers aes256-ctr,aes128-cbc
        # KexAlgorithms diffie-hellman-group-exchange-sha256

        KexAlgorithms diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1


ssh option name check 

ssh -Q cipher       # List supported ciphers
ssh -Q mac          # List supported MACs
ssh -Q key          # List supported public key types
ssh -Q kex          # List supported key exchange algorithms

Monday, July 1, 2019

Install Python3.7 on Windows Subsystem for Linux (WSL)

​1. Install the python3.7 package using apt-get
sudo apt-get install python3.7

2. Add python3.6 & python3.7 to update-alternatives

​sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2

3. Update python3 to point to python3.7
sudo update-alternatives --config python3

4. Test the version of python
python3 -v

5. Solve Error
sudo apt-get remove python3-apt -y

Error Permission Pipenv on /home/$USER/.cache in WLS

add $USER to root group

change Permission /home/$USER/.cache to 775

How to change default WSL mount Point

​create /etc/wsl.conf file

[automount]
root = /
options = "metadata"

reboot WSL Services

How to restart Windows Subsystem for Linux (WSL)

​open services.msc

LxssManager -> restart

Setup Docker in Windows Subsystem for Linux (WSL)

​Docker Setup:

Download Docker for Windows​

​docker -> settings -> general -> "expose deamon on tcp://localhost:2375 without TLS"

On WSL:

$sudo apt update -y
$sudo apt upgrade -y

$sudo apt install docker.io
$sudo usermod -aG docker $USER

Add PATH:

check:
echo $PATH | grep /home/$USER

if not exist
add path:

vi  ~/.profile

export PATH="$PATH:$HOME/.local/bin"

​Setup Docker in WSL

$echo "export DOCKER_HOST=tcp://localhost:2375" >> ~/.bashrc && source ~/.bashrc

Docker 101

Build images:
​docker built -t tag/name .

List Images:
docker images

Check Process RUN:
docker ps

Check Process ALL:
docker ps -a

Docker run Daemon Mode :
docker run -d -p 80:5000 images/name

Docker run and delete when Stop Container:
docker run --rm -d -p 80:5000 images/name (daemon mode)
docker run --rm -it -p 80:5000 images/name (run and show terminal)

Connect to Container
docker exec -it docker_instance_id shell_in_container

Docker Save Images:
​docker save images_name > images_name.tar
docker save -o images_name.tar images_name


Docker Load Images:
docker load < test_save.tar
docker load -i test_save.tar

Docker Copy :
docker cp filename container_id:/path_to_file/file
docker cp container_id:/path_to_file/file src_file/file
​​On Python FLASK

Dockerfile Example:
​from python
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
ENV FLASK_APP=app.py
ENV FLASK_DEBUG=1
CMD flask run --host=0.0.0.0

Monday, January 7, 2019

How to Connect SharePoint Online via PowerShell

Check Module:

Get-Module -Name Microsoft.Online.SharePoint.PowerShell -ListAvailable | Select Name,Version

Install Module:

Install-Module -Name Microsoft.Online.SharePoint.PowerShell

Connect SPO Script

$adminUPN="username@domain.name"
$orgName="nida365"
$userCredential = Get-Credential -UserName $adminUPN -Message "Type the password."
Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential

ALCATEL 6900

write memory copy running certified reload from working no rollback-timeout