AWS LAMBDA – NODE JS – DATABASE CONNECTION

var mysql = require(‘mysql’);

var connection = mysql.createConnection({
host : ‘localhost’,
user : ‘user’,
password : ‘password’,
database : ‘test_db’
});

connection.connect();

exports.handler = (event, context) => {

connection.query(“SELECT * FROM test_table LIMIT 1”, function(err, rows, fields) {
if (err) throw err;
console.log(“rows: ” + rows);
context.succeed(‘Success’);
});

};

Python – Convert Zip File To Base64

# Reference1 : https://stackoverflow.com/questions/11511705/base64-encode-a-zip-file-in-python
# Reference2 : https://stackoverflow.com/questions/13613738/python-how-to-create-a-new-file-and-write-contents-of-variable-to-it

import base64

with open("file_name.zip", "rb") as f:
    bytes = f.read()
    encode_string = base64.b64encode(bytes)

with open('output_file.txt', 'wb') as result:
    result.write(encode_string)

PHP – Multi Dimesional Array – Specific Key Retrieve

<?php 
$a = array(
        'a'=>array( 1=> 'php'),
	array('a' => array(1=> 'java')),
	array('a' => array('a' => array('a'=>array('y1'=>'python'))))
);

$t = array();
$y = array();
function recursive_array_search($needle,$haystack) {
    global $y;
    foreach($haystack as $key=>$value) {
    	if (!array_key_exists($needle, $value)){
            $y[] = $value;
            $t = array_merge($t,$value);
    	} else {
    		recursive_array_search($needle,$value);
    	}
    }
    return $t;
}

$ids = recursive_array_search('a',$a);
print_r($y);
exit();

PyMysql – Example for Select And Insert Query


import pymysql
from pprint import pprint

host_name = 'localhost'
user_name = 'root'
password = 'password'
db_name = 'db_name'

conn = pymysql.connect(host=host_name,user=user_name,passwd=password,db=db_name)
cur = conn.cursor(pymysql.cursors.DictCursor)

sel_res = cur.execute('SELECT id, name, email FROM users')

for row in cur:
	values = str(row['id'])+",'"+str(row['name'])+"','"+str(row['email'])+"'"
	pprint (values)
	conn.cursor(pymysql.cursors.DictCursor).execute("INSERT INTO users1 VALUES ("+values+")")

Python – Substring Count Puzzle

# INPUT - aaabbccdaa
# OUTPUT - a3b2c2d1a2
def encode(s):
    r = ''
    y = 0
    x1 = ''
    for x in s:
        if x1 != x and x1!='':
            r += str(x1)+str(y)
            y = 1
        else:
            y += 1
        x1 = x
    r += str(x1)+str(y)
    return r

print (encode('aaabbccdaa')) # a3b2c2d1a2

# INPUT - a3b2c2d1a2
# OUTPUT - aaabbccdaa

def decode(s):
    a = 0
    r = ''
    x1 = ''
    for x in s:
        if a%2 > 0:
            r += x1*int(x)
        else:
            x1 = x
        a += 1
    return r
    
print (decode('a3b2c2d1a2')) # aaabbccdaa