piątek, 13 grudnia 2013

clear cin cout cpp

#include <iostream>
using namespace std;

int main()
{
string name = "";
cout << "enter your name: ";
getline(cin, name);
if (name.empty())
{
cout << "You should enter something ";
}
cout << "hello, " <<name << " you are user " <<endl;
return 0;

poniedziałek, 9 grudnia 2013

change fedora keymap

$ localectl status
To list available keymaps:

$ localectl list-keymaps
To set the default console keymap:

$ localectl set-keymap [keymap]
see man localectl for further information.

if you still don't have your keys try to:

setxkbmap -print -verbose 10

┌─[marek@localhost]─[~]
└──╼ setxkbmap -print -verbose 10
Setting verbose level to 10
locale is C
Trying to load rules file ./rules/evdev...
Trying to load rules file /usr/share/X11/xkb/rules/evdev...
Success.
Applied rules from evdev:
rules:      evdev
model:      pc104
layout:     us,pl
variant:    ,
Trying to build keymap using the following components:
keycodes:   evdev+aliases(qwerty)
types:      complete
compat:     complete
symbols:    pc+us+pl:2+inet(evdev)
geometry:   pc(pc104)
xkb_keymap {
xkb_keycodes  { include "evdev+aliases(qwerty)" };
xkb_types     { include "complete" };
xkb_compat    { include "complete" };
xkb_symbols   { include "pc+us+pl:2+inet(evdev)" };
xkb_geometry  { include "pc(pc104)" };
};
to change marked settings:

setxkbmap -layout xkb_layout
setxkbmap -model pc104 -layout cz,us -variant ,dvorak -option grp:alt_shift_toggle

czwartek, 5 grudnia 2013

Java scanner IO

import java.util.Scanner;
class helloworld
{
    public static void main (String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter name: ");
        String name = input.nextLine();
        System.out.println("Hello " +name);
    }
}

wtorek, 3 grudnia 2013

how to check db version - sql request JAVA

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class dbConnection {

    public static void main(String[] args) {

        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/mysql";
        String user = "user";
        String password = "password";

        try {
            con = DriverManager.getConnection(url, user, password);
            st = con.createStatement();
            rs = st.executeQuery("SELECT VERSION()");

            if (rs.next()) {
                System.out.println(rs.getString(1));
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(dbConnection.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(dbConnection.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
    }
}

remember about your jdbc driver:
mariadb-java-client-1.1.5.jar

IO - Java

Read from file:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class fil{
public static void main(String[] args) throws FileNotFoundException{

File file = new File("/home/marek/workspace/java/myfile.txt");
System.out.print("Reading from file: " + file);
Scanner in = new Scanner(file);
String zdanie = in.nextLine();

System.out.println("\n: -> " + zdanie);

}


write to file:

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class save_to_file {
public static void main(String[] args) throws FileNotFoundException{
PrintWriter zapis = new PrintWriter("test.dat");
zapis.println("Marek Borkowski\n");
zapis.close();
System.out.println("success");
}
}

poniedziałek, 2 grudnia 2013

how to make jar

1. create manifest file - the name of the file should end with do .mf sufix

Manifest-Version: 1.0
Main-Class: hello

2. jar cmf manifest.mf hello.jar hello.class

3. to view the content of the JAR type:

jar tf jar_file.jar jar_file.class

4. to execute app:
java -jar jar_file.jar

sobota, 30 listopada 2013

few first step in Java

1.

public class for_loop {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println("Marek");
        }
    }
}


remember that name of the class should be equal to filename

2.

to compile your "program" type:
javac for.loop.java

3.

execute:

┌─[marek@localhost]─[~/Dokumenty/java]
└──╼ ls -ltr
razem 8
-rwxrwxr-x 1 marek marek 167 11-30 23:39 for_loop.java
-rw-rw-r-- 1 marek marek 467 11-30 23:39 for_loop.class

java for_loop 

czwartek, 28 listopada 2013

check if service is running - systemd fedora

┌─[marek@localhost]─[~]
└──╼ systemctl is-enabled sshd.service; echo $?
enabled
0

file reader python

#!/usr/bin/python

import time

try:
    f = file('/etc/passwd')
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print "cleaning up ... closed the file"

almost like kindle :)


python lits again

#!/usr/bin/python

a = [1, 2, 3, 33, 123, 111]
print a
print "total element's len: ",len(a)

a.insert(2, -1) """insert in second place value - -1"""
a.append(666) """append 666 to list"""
print a, len(a)

data = raw_input("enter something: ")

a.append(data) """append from variable"""
print a, len(a)

print "sorting"
a.sort() """sorting the list"""
print a

from file 2 file python

#!/usr/bin/python

from sys import argv
from os.path import exists

script, from_file, to_file = argv
try:
    print "copying from %s to %s" % (from_file, to_file)
    print "check if first file is excist"
    in_file = open(from_file)
    indata = in_file.read()

    print "The input file is %d bytes long" %len(indata)
    raw_input()
    out_file = open(to_file, 'w')
    out_file.write(indata)
    print "all done"
    out_file.close()
    in_file.close()
except IOError:
    print "I/O Error"

file truncate python

#!/usr/bin/python
from sys import argv
import os

script, filename = argv

check = os.stat(filename)[6]==0

if check == False:
    print "the file %r. " %filename, "will be erased"
    print "press enter to continue.."
    raw_input("?")
    print "opening the file: ..%r" %filename
    target = open(filename, 'w')
    print "erasing..."
    target.truncate()

    print "closing ... "
    target.close()
else:
    print "file is empty"


check if file is empty - python


#!/usr/bin/python
import os
check = os.stat("testfile")[6]==0
if check == True:
    print "file is empty"
else:
    print "open file"
    with open("testfile", "rt") as in_file:
        text = in_file.read()
    print (text)


python
Python 2.7.5 (default, Nov 12 2013, 16:18:42)
[GCC 4.8.2 20131017 (Red Hat 4.8.2-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; import os
&gt;&gt;&gt; os.stat("testfile")
posix.stat_result(st_mode=33204, st_ino=5113343, st_dev=2056L, st_nlink=1, st_uid=1000, st_gid=1000, <i><b>st_size=0</b></i>, st_atime=1385626955, st_mtime=1385627001, st_ctime=1385627001)

poniedziałek, 25 listopada 2013

vim file compare

[marek@lati]─[/tmp] echo marek > 1 && echo borkowski > 2 [marek@lati]─[/tmp] ╼ vim -d 1 2 2 file to edit

python mysql mariadb fedora :)


yum install python-pip.noarch
yum install python-devel
yum install mysql-devel

┌─[lati]─[~]
└──╼ easy_install mysql-python

┌─[lati]─[~]
└──╼ pip install MySQL-python

change mysql default password in fedora

After installation we need to:
1. start service: service mysqld start

┌─[lati]─[~]
└──╼ service mysqld status
Redirecting to /bin/systemctl status  mysqld.service
mysqld.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled)
   Active: active (running) since pon 2013-11-25 13:28:14 CET; 2s ago
  Process: 5746 ExecStartPost=/usr/libexec/mysqld-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 5672 ExecStartPre=/usr/libexec/mysqld-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 5745 (mysqld_safe)
   CGroup: name=systemd:/system/mysqld.service
           ├─5745 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           └─5902 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql...

lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: The latest information abou...
lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: You can find additional inf...
lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: http://dev.mysql.com
lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: Support MariaDB development...
lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: Monty Program Ab. You can c...
lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: Alternatively consider join...
lis 25 13:28:11 lati mysqld-prepare-db-dir[5672]: http://kb.askmonty.org/en/c...
lis 25 13:28:12 lati mysqld_safe[5745]: 131125 13:28:12 mysqld_safe Logging ....
lis 25 13:28:12 lati mysqld_safe[5745]: 131125 13:28:12 mysqld_safe Starting...l
lis 25 13:28:14 lati systemd[1]: Started MariaDB database server.

2. go to mysql "admin shell"
mysql -u root -p [password is blank press enter]

3. in mysql shell execute-
use mysql;

MariaDB [(none)]> 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


MariaDB [mysql]> update user set password=PASSWORD("marek1983") where User='root';Query OK, 4 rows affected (0.00 sec)Rows matched: 4  Changed: 4  Warnings: 0


flush privileges;
quit


wtorek, 19 listopada 2013

os.module Python part1

#!/usr/bin/python
import os

path = raw_input("enter path: ")
state = os.path.isdir(path)
print state
if state == False:
print "there is no: ",path

check_size = raw_input("enter full path to file: ")
fo = os.path.getsize(check_size)
print fo

print "path2file"
print "select only file name"
only_file = os.path.split(check_size)
print only_file

print "get the extension of a file"
sufix = os.path.splitext(check_size)
print sufix

poniedziałek, 4 listopada 2013

postgresql - add account and change password

marek@lati:/var/cache/apt$ sudo -u postgres createuser marek

marek@lati:/var/cache/apt$ sudo -u postgres psql
psql (9.2.5)
Wpisz "help" by uzyskać pomoc.

postgres=# postgres=# \password marek

Wprowadź nowe hasło:
Powtórz podane hasło:

postgres-#
postgres-# \q

niedziela, 3 listopada 2013

apt

apt ubuntu tutorial:

1. install

marek::mbo { ~ }-> sudo apt-get install apache2
Czytanie list pakietów... Gotowe
Budowanie drzewa zależności      
Odczyt informacji o stanie... Gotowe
Zostaną zainstalowane następujące dodatkowe pakiety:
  apache2-mpm-worker apache2-utils apache2.2-bin apache2.2-common
  libaprutil1-dbd-sqlite3 libaprutil1-ldap
Sugerowane pakiety:
  apache2-doc apache2-suexec apache2-suexec-custom
Zostaną zainstalowane następujące NOWE pakiety:
  apache2 apache2-mpm-worker apache2-utils apache2.2-bin apache2.2-common
  libaprutil1-dbd-sqlite3 libaprutil1-ldap
0 aktualizowanych, 7 nowo instalowanych, 0 usuwanych i 81 nieaktualizowanych.
Konieczne pobranie 3472 kB archiwów.
Po tej operacji zostanie dodatkowo użyte 10,3 MB miejsca na dysku.
Kontynuować [T/n]?



2. search

marek::mbo { ~ }-> sudo apt-cache search xclock
x11-apps - Aplikacje X
xarclock - reversed xclock
rxvt - Emulator terminala VT102 dla X Window System
rxvt-beta - Emulator terminala VT102 dla X Window System

3. package info

marek::mbo { ~ }-> apt-cache show xterm
Package: xterm
Priority: optional
Section: x11
Installed-Size: 1437
Maintainer: Ubuntu X-SWAT <ubuntu-x@lists.ubuntu.com>
Original-Maintainer: Debian X Strike Force <debian-x@lists.debian.org>
Architecture: amd64
Version: 278-1ubuntu2

..

4. check package dependenties

marek::mbo { ~ }-> apt-cache showpkg xterm
Package: xterm
Versions:
278-1ubuntu2 (/var/lib/apt/lists/pl.archive.ubuntu.com_ubuntu_dists_raring_main_binary-amd64_Packages) (/var/lib/dpkg/status)
 Description Language:
                 File: /var/lib/apt/lists/pl.archive.ubuntu.com_ubuntu_dists_raring_main_binary-amd64_Packages
                  MD5: c1e47d60a01948be9aae7a2a4f63a0fe
 Description Language: en
                 File: /var/lib/apt/lists/pl.archive.ubuntu.com_ubuntu_dists_raring_main_i18n_Translation-en
                  MD5: c1e47d60a01948be9aae7a2a4f63a0fe
 Description Language: pl
                 File: /var/lib/apt/lists/pl.archive.ubuntu.com_ubuntu_dists_raring_main_i18n_Translation-pl
                  MD5: c1e47d60a01948be9aae7a2a4f63a0fe


Reverse Depends:
  kdm,xterm
  xterm:i386,xterm
....
  grun,xterm
  grass-gui,xterm
  grace,xterm
  gman,xterm
  gkdebconf,xterm
  gfceu,xterm
  gexec,xterm
  exmh,xterm
  epoptes-client,xterm
  epoptes,xterm
  dwb,xterm
  draai,xterm
  debroster,xterm
  debian-installer-launcher,xterm
  ddd,xterm
  codelite,xterm
  codeblocks,xterm
  clusterssh,xterm
  barrydesktop,xterm
  axel-kapt,xterm
  apt-watch-backend,xterm
  advi-examples,xterm
  xorg,xterm
  xinit,xterm
  ubuntu-desktop,xterm
  tk8.5,xterm
Dependencies:
278-1ubuntu2 - xbitmaps (0 (null)) libc6 (2 2.15) libfontconfig1 (2 2.9.0) libice6 (2 1:1.0.0) libtinfo5 (0 (null)) libutempter0 (2 1.1.5) libx11-6 (0 (null)) libxaw7 (0 (null)) libxft2 (4 2.1.1) libxmu6 (0 (null)) libxt6 (0 (null)) xfonts-cyrillic (0 (null)) x11-utils (0 (null)) xterm:i386 (0 (null))
Provides:
278-1ubuntu2 - xterm:i386 x-terminal-emulator:i386 x-terminal-emulator
Reverse Provides:
xterm:i386 278-1ubuntu2



ncdu

ncdu (NCurses Disk Usage) is a command line version of the most popular du command. 
If you don't have much time to compose advanced command. Use ncdu:

1. sudo apt-get install ncdu (also availavle in redhat distros)
2. ncdu

ncdu 1.10 ~ Use the arrow keys to navigate, press ? for help                        
--- /home/marek/Pobrane ------------------------------------------------------------
  694,0MiB [##########]  elementaryos-stable-amd64.20130810.iso                     
  390,3MiB [#####     ] /occam-jwr66y
  355,0MiB [#####     ]  occam-jwr66y-factory-74b1deab.tgz
  276,1MiB [###       ] /pa_aosp_mako
  190,0MiB [##        ]  pa_gapps-full-4.4-20131102-signed.zip
  166,6MiB [##        ]  pa_aosp_mako.zip
   40,2MiB [          ]  google-chrome-stable_current_i386.deb
    8,1MiB [          ]  openrecovery-twrp-2.4.1.0-mako.img
    4,4MiB [          ]  recovery-clockwork-5.0.2.8-marvel.img
    1,2MiB [          ]  UPDATE-SuperSU-v1.50.zip
   60,0KiB [          ]  elementaryos-stable-amd64.20130810.iso.torrent
   24,0KiB [          ]  Harmonogram_szczyt_klimatyczny.xlsx




ncdu / - it will be scan all your disk and give you:

ncdu 1.10 ~ Use the arrow keys to navigate, press ? for help                        
--- / ------------------------------------------------------------------------------
.   8,3GiB [##########] /home                                                       
    2,8GiB [###       ] /usr
.   1,7GiB [##        ] /var
  411,0MiB [          ] /lib
  173,7MiB [          ] /opt
   57,6MiB [          ] /boot
.  13,2MiB [          ] /etc
   10,8MiB [          ] /sbin
    9,5MiB [          ] /bin
.   1,5MiB [          ] /run
.  36,0KiB [          ] /tmp
!  16,0KiB [          ] /lost+found
    8,0KiB [          ] /media
    4,0KiB [          ] /dev
    4,0KiB [          ] /lib64
e   4,0KiB [          ] /srv
!   4,0KiB [          ] /root
e   4,0KiB [          ] /mnt
e   4,0KiB [          ] /cdrom
.   0,0  B [          ] /proc
.   0,0  B [          ] /sys
@   0,0  B [          ]  initrd.img.old
@   0,0  B [          ]  initrd.img
@   0,0  B [          ]  vmlinuz.old
@   0,0  B [          ]  vmlinuz

short introduction to dpkg ubuntu/debian

1. install package
dpkg -i package_name.deb

2. list all installed package
dpkg -l
dpkg -l vlc

marek@lati:~$ dpkg -l vlc

Wybór:U=nieznany/I=instalacja/R=usunięcie/P=wyczyszczenie/H=zatrzymanie
| Stan:N=brak/I=zainstalowany/C=skonfigurowany/U=rozpakowany/
|/  F=częśc. skonfigurowany/H=częśc. zainstalowany/W=wyzw. czek./T=wyzw. zapl.

|| Błędy?=(brak)/R-do pon. inst. (duże litery w "Stan" i "Błędy"=problemy)
||/ Nazwa          Wersja       Architektura Opis
+++-==============-============-============-=================================
ii  vlc            2.0.8-1      amd64        multimedia player and streamer


3. remove package
dpkg -r packagename.deb

4. view the package content

dpkg -c packagename.deb

marek@lati:~/Pobrane$ dpkg -c google-chrome-stable_current_i386.deb
drwx------ root/root         0 2013-10-21 20:00 ./
drwxr-xr-x root/root         0 2013-10-21 20:00 ./opt/
drwxr-xr-x root/root         0 2013-10-21 20:00 ./opt/google/
drwxr-xr-x root/root         0 2013-10-21 20:00 ./opt/google/chrome/
-rw-r--r-- root/root   2327028 2013-10-21 20:00 ./opt/google/chrome/libffmpegsumo.so
-rw-r--r-- root/root      4818 2013-10-21 20:00 ./opt/google/chrome/product_logo_32.xpm
......


5. check if package is installed or not

marek::mbo { ~ }-> sudo dpkg -s zip
Package: zip
Status: install ok installed
Priority: optional
Section: utils
Installed-Size: 589
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: amd64
Multi-Arch: foreign
Version: 3.0-6ubuntu1
Replaces: zip-crypt (<= 2.30-2)
Depends: libbz2-1.0, libc6 (>= 2.14)
Recommends: unzip
Conflicts: zip-crypt (<= 2.30-2)
Description: Archiver for .zip files
 This is InfoZIP's zip program. It produces files that are fully
 compatible with the popular PKZIP program; however, the command line
 options are not identical. In other words, the end result is the same,
 but the methods differ. :-)
 .
 This version supports encryption.
Homepage: http://www.info-zip.org/Zip.html
Original-Maintainer: Santiago Vila <sanvila@debian.org>

środa, 2 października 2013

get the first half of the string - python

root::Lati { /tmp }-> python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> book = "marek borkowski python tutorial"
>>> book[0:len(book)/2]
'marek borkowski'


Playing with files in python

#!/usr/bin/python
import time
def line():
    print "-" *50
 
start = time.time()
try:
    print "check stats of the file\n"
    file = open("/tmp/file.dat")
    print "name of the file is: ",file.name
    print "closed or not", file.closed
    print "opening mode :", file.mode
    print "softspace flag: ",file.softspace

except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
line()
try:
    print "insert var value to file\n"
    fo = open("/tmp/file.dat")
    print "the name of the file is: ", fo.name
    print "closing mode: ", fo.mode
    fo.close()
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
 

line()
print "write to file\n"
try:
    file = open("/tmp/file.dat","wb")
    file.write("Marek Borkowski")
    file.close()
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
 
 
line()
try:
    file = open("/tmp/file.dat","r+")
    str = file.read();
    print "Read String from file:", file, " \nis\n", str
    file.close()
 
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
line()

print "Elapsed time: %s s." % (time.time()-start)


----------------------------------------------------



#!/usr/bin/python
import os.path

def line():
    print "-" *50
 
def create_file():
    fname = "/tmp/test.file"
    check = os.path.exists(fname)
 
    if check == True:
        print "file is excist all ok"
    else:
        os.popen("touch /tmp/test.file")
        print "file has been created\n"

try:
    create_file()
    print "write to file\n"
    f=open("/tmp/test.file")
 
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
 




-------------------------------------------------------------------------


#!/usr/bin/python
import os

def create_file():
    fname = "/tmp/file.dat"
    check = os.path.exists(fname)
    if check == True:
        print "file is excist all ok"
    else:
        os.popen("touch /tmp/file.dat")
        print "file has been created\n"
try:
    create_file()
    with open("/tmp/file.dat","wt") as out_file:
        print "inserted"
        out_file.write("Marek Borkowski\n")
 
    with open("/tmp/file.dat", "rt") as in_file:
        text = in_file.read()
 
    print(text)
except:
    print "error"
 


wtorek, 1 października 2013

check page access code status and report possible errors

#!/usr/bin/python
import os
def line():
    print '-' *50
import urllib2
import time

try:
    hosts = ["http://www.google.pl","http://www.opitz-consulting.com","http://www.facebook.com"]
    for key in hosts:
   
        req = urllib2.Request(key)
        response = urllib2.urlopen(req)
        print key
        print response.getcode()
        code = response.getcode()
        if code == 200:
            print "ok"
        elif code != 200:
            print "warning"
        print response.read(200)
        line()
   
except:
     print "oppps something goes wrong check the network connection\n\n"
     network = os.popen("ifconfig wlan0 && ifconfig eth0").read()
     print network
 

simple python threading example

#!/usr/bin/python

import threading
import datetime

class ThreadClass(threading.Thread):
    def run(self):
        now = datetime.datetime.now()
        print "%s says hello world at time: %s" %(self.getName(), now)
       
for i in range(2):
    t = ThreadClass()
    t.start()

piątek, 27 września 2013

mount remount android filesystem

1. adb shell
2. su -
3. mount | grep system

shell@android:/ $ mount | grep system
/dev/block/platform/msm_sdcc.1/by-name/system /system ext4 ro,relatime,data=ordered 0 0

4. mount -o rw,remount /dev/block/platform/msm_sdcc.1/by-name/system /system


sobota, 21 września 2013

bash shortcut

$ cd /home/user/foo

cd: /home/user/foo: No such file or directory

$ mkdir !*

mkdir /home/user/foo

alternative for bash --> key[alt]+.[key]

sed basics

sed 's/^/# /' test
sed 's/^/> /' test

insert # sing and ">" to file name's test :)

to save change permanent use -i param


sobota, 14 września 2013

how to start wifi from adb site

adb shell svc wifi enable/disable

scapy python

a=sniff(iface="wlan0", prn=lambda x: x.show()) - qool "part" of the Python family - SCAPY:

example output bellow.


###[ Raw ]###
           load= 'HTTP/1.1 204 No Content\r\nPragma: no-cache\r\nCache-Control: private, no-cache\r\nExpires: Wed, 17 Sep 1975 21:32:10 GMT\r\nAccess-Control-Allow-Origin: *\r\nLast-Modified: Wed, 21 Jan 2004 19:51:30 GMT\r\nContent-Type: image/gif\r\nDate: Sat, 14 Sep 2013 22:20:03 GMT\r\nServer: Golfe2\r\nContent-Length: 0\r\nAlternate-Protocol: 80:quic\r\n\r\n'
###[ Ethernet ]###
  dst= 00:b0:0c:47:f8:00
  src= 24:77:03:49:b5:cc
  type= 0x800
###[ IP ]###
     version= 4L
     ihl= 5L
     tos= 0x0
     len= 52
     id= 9305
     flags= DF
     frag= 0L
     ttl= 64
     proto= tcp
     chksum= 0x2672
     src= 192.168.0.100
     dst= 74.125.228.111
     \options\
###[ TCP ]###
        sport= 45577
        dport= http
        seq= 3167215318
        ack= 215831554
        dataofs= 8L
        reserved= 0L
        flags= A
        window= 207
        chksum= 0xf01f
        urgptr= 0
        options= [('NOP', None), ('NOP', None), ('Timestamp', (5630168, 1289009574))]

2. sniff(prn=lambda x:x.sprintf("{IP:%IP.src% -->%IP.dst%\n}{Raw:%Raw. load%\n}"))
sample output:
192.168.0.1 -->239.255.255.250
??

192.168.0.1 -->239.255.255.250
??

192.168.0.1 -->239.255.255.250
??

192.168.0.1 -->239.255.255.25

apk package menagement

how to install apk app.
1. adb install app.apk
2. we can list installed app by:
adb pm list packages
3. we can uninstall this app by:
adb uninstall app.apk


http://forum.xda-developers.com/showthread.php?t=2300873

tip to eliminate wifi problem in nexus 4

adb push Nexus4_wifi_solution_by_kalo86.zip 

install from recovery mode.

Till now no problemy with wifi

how to: python rights permission check

   #!/usr/bin/python                                                               
                                                                                   
   import os                                                                       
   import sys                                                                      
                                                                                   
   if not os.geteuid() == 0:                                                       
       sys.exit('script must be run as root')                                      
   else:                                                                           
       print 'root part'                                                           

piątek, 13 września 2013

when you have problem with mysql The partition with /var/lib/mysql is too full!

* Stopping MySQL database server mysqld [ OK ]
* /etc/init.d/mysql: ERROR: The partition with /var/lib/mysql is too full!


try to restart myql with sudo permissions and flush db logs
mysqladmin -u root -p flush-logs

of flush something more:

  flush-all-statistics    Flush all statistics tables
  flush-all-status        Flush status and statistics
  flush-client-statistics Flush client statistics
  flush-hosts             Flush all cached hosts
  flush-index-statistics  Flush index statistics
  flush-logs              Flush all logs
  flush-privileges        Reload grant tables (same as reload)
  flush-slow-log          Flush slow query log
  flush-status  Clear status variables
  flush-table-statistics  Clear table statistics
  flush-tables            Flush all tables
  flush-threads           Flush the thread cache
  flush-user-statistics   Flush user statistics
  kill id,id,... Kill mysql threads

czwartek, 12 września 2013

servier client python code

client.py
#!/usr/bin/python
import socket
host = 'localhost'
port = 8081

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #s.connect(('localhost', 8081))
    s.connect((host, port))
    s.send('Marek Borkowski')
    data = s.recv(1024)
    s.close()
    print 'received: '
    print data
except Exception, e:
    print 'Uupss, something goes wrong, check network connection'


server.py

#!/usr/bin/python
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_address=("localhost", 8081)
print 'starting up on %s port %s' %server_address
server.bind(server_address)

server.listen(5)

connection,client_address = server.accept()
print 'connection from: ', connection.getpeername()

data = connection.recv(4096)
if data:
    print "Received: ", repr(data)

    data = data.rstrip()
    connection.send("%s\n%s\n%s\n" % ('-'*80, data.center(80), '-'*80))
    print "send reponse"


connection.shutdown(socket.SHUT_RD | socket.SHUT_WR)
connection.close()
print "connection closed."
server.close()

wtorek, 10 września 2013

count request per minut access apache log

grep "10/Sep/2013" access.log| cut -d[ -f2 | cut -d] -f1 | awk -F: '{print $2":"$3}' | sort -nk1 -nk2 | uniq -c | awk '{ if ($1 > 10) print $0}'

poniedziałek, 9 września 2013

adb logcat - sms has been received.

I/ActivityManager(  543): Start proc com.android.mms for broadcast com.android.mms/.transaction.PrivilegedSmsReceiver: pid=14617 uid=10030 gids={50030, 3003, 1015, 1028}
V/MmsConfig(14617): mnc/mcc: 26006
V/MmsConfig(14617): tag: bool value: enabledMMS - true
V/MmsConfig(14617): tag: int value: maxMessageSize - 307200
V/MmsConfig(14617): tag: int value: maxImageHeight - 480
V/MmsConfig(14617): tag: int value: maxImageWidth - 640
V/MmsConfig(14617): tag: int value: defaultSMSMessagesPerThread - 500
V/MmsConfig(14617): tag: int value: defaultMMSMessagesPerThread - 50
V/MmsConfig(14617): tag: int value: minMessageCountPerThread - 10
V/MmsConfig(14617): tag: int value: maxMessageCountPerThread - 5000
V/MmsConfig(14617): tag: string value: uaProfUrl - http://www.google.com/oha/rdf/ua-profile-kila.xml
V/MmsConfig(14617): tag: int value: recipientLimit - -1
V/MmsConfig(14617): tag: bool value: enableSlideDuration - true
V/MmsConfig(14617): tag: int value: maxMessageTextSize - -1
V/MmsConfig(14617): tag: string value: userAgent - Nexus4
V/SmsReceiverService(14617): onStart: #1 mResultCode: -1 = Activity.RESULT_OK
D/dalvikvm(  543): GC_CONCURRENT freed 1974K, 24% free 21699K/28452K, paused 13ms+28ms, total 284ms
D/MmsSmsProvider(  865): getThreadId: create new thread_id for recipients xxxxxxxx
D/MmsSmsProvider(  865): insertThread: created new thread_id 5 for recipientIds xxxxxxx
D/SmsReceiverService(14617): handleSmsReceived messageUri: content://sms/2 threadId: 5
D/MediaPlayer(  720): Couldn't open file on client side, trying server side
E/MediaPlayerService(  165): Couldn't open fd for content://settings/system/notification_sound
E/MediaPlayer(  720): Unable to to create media player
W/RingtonePlayer(  720): error loading sound for content://settings/system/notification_sound
W/RingtonePlayer(  720): java.io.IOException: setDataSource failed.: status=0x80000000
W/RingtonePlayer(  720): at android.media.MediaPlayer._setDataSource(Native Method)
W/RingtonePlayer(  720): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:958)
W/RingtonePlayer(  720): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:946)
W/RingtonePlayer(  720): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:899)
W/RingtonePlayer(  720): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:854)
W/RingtonePlayer(  720): at com.android.systemui.media.NotificationPlayer$CreationAndCompletionThread.run(NotificationPlayer.java:88)
D/dalvikvm(  720): GC_CONCURRENT freed 1625K, 60% free 12287K/30052K, paused 18ms+15ms, total 181ms
D/dalvikvm(  720): WAIT_FOR_CONCURRENT_GC blocked 59ms
W/MediaPlayer-JNI(  720): MediaPlayer finalized without being released

but now soud has been asign to this action.


dumsys service list

marek::lati { ~ }-> adb shell dumpsys | grep -i "dump of service"
DUMP OF SERVICE SurfaceFlinger:
DUMP OF SERVICE accessibility:
DUMP OF SERVICE account:
DUMP OF SERVICE activity:
DUMP OF SERVICE alarm:
DUMP OF SERVICE appwidget:
DUMP OF SERVICE assetredirection:
DUMP OF SERVICE audio:
DUMP OF SERVICE backup:
DUMP OF SERVICE battery:
DUMP OF SERVICE batteryinfo:
DUMP OF SERVICE bluetooth_manager:
DUMP OF SERVICE clipboard:
DUMP OF SERVICE commontime_management:
DUMP OF SERVICE connectivity:
DUMP OF SERVICE content:
DUMP OF SERVICE country_detector:
DUMP OF SERVICE cpuinfo:
DUMP OF SERVICE dbinfo:
DUMP OF SERVICE device_policy:
DUMP OF SERVICE devicestoragemonitor:
DUMP OF SERVICE diskstats:
DUMP OF SERVICE display:
DUMP OF SERVICE display.qservice:
DUMP OF SERVICE dreams:
DUMP OF SERVICE drm.drmManager:
DUMP OF SERVICE dropbox:
DUMP OF SERVICE entropy:
DUMP OF SERVICE fm_receiver:
DUMP OF SERVICE fm_transmitter:
DUMP OF SERVICE gfxinfo:
DUMP OF SERVICE hardware:
DUMP OF SERVICE input:
DUMP OF SERVICE input_method:
DUMP OF SERVICE iphonesubinfo:
DUMP OF SERVICE isms:
DUMP OF SERVICE location:
DUMP OF SERVICE lock_settings:
DUMP OF SERVICE media.audio_flinger:
DUMP OF SERVICE media.audio_policy:
DUMP OF SERVICE media.camera:
DUMP OF SERVICE media.player:
DUMP OF SERVICE meminfo:
DUMP OF SERVICE mount:
DUMP OF SERVICE netpolicy:
DUMP OF SERVICE netstats:
DUMP OF SERVICE network_management:
DUMP OF SERVICE nfc:
DUMP OF SERVICE notification:
DUMP OF SERVICE package:
DUMP OF SERVICE permission:
DUMP OF SERVICE phone:
DUMP OF SERVICE pieservice:
DUMP OF SERVICE power:
DUMP OF SERVICE profile:
DUMP OF SERVICE samplingprofiler:
DUMP OF SERVICE scheduling_policy:
DUMP OF SERVICE search:
DUMP OF SERVICE sensorservice:
DUMP OF SERVICE serial:
DUMP OF SERVICE servicediscovery:
DUMP OF SERVICE simphonebook:
DUMP OF SERVICE sip:
DUMP OF SERVICE statusbar:
DUMP OF SERVICE telephony.registry:
DUMP OF SERVICE textservices:
DUMP OF SERVICE throttle:
DUMP OF SERVICE uimode:
DUMP OF SERVICE updatelock:
DUMP OF SERVICE usagestats:
DUMP OF SERVICE usb:
DUMP OF SERVICE user:
DUMP OF SERVICE vibrator:
DUMP OF SERVICE wallpaper:
DUMP OF SERVICE wifi:
DUMP OF SERVICE wifip2p:
DUMP OF SERVICE window:

complex information about battery usage android adb

marek::lati { ~ }-> adb shell dumpsys batteryinfo| more
Battery History:
       -2h27m24s342ms 100 04120041 status=discharging health=good plug=none temp=280 volt=4267 +sc
reen +wifi +wifi_running brightness=dim signal_strength=great
       -2h27m15s233ms 100 44120031 +wake_lock signal_strength=good
       -2h27m15s065ms 100 04120031 -wake_lock
       -2h27m10s980ms 100 04120031 volt=4316
       -2h27m05s706ms 100 04120031
       -2h26m59s710ms 100 04120041 signal_strength=great
       -2h26m57s454ms 100 04120040 brightness=dark
       -2h26m50s745ms 100 04020040 -screen
       -2h26m38s110ms 100 04120041 +screen brightness=dim
       -2h26m34s609ms 100 44120031 +wake_lock signal_strength=good
       -2h26m31s143ms 100 04120031 -wake_lock
       -2h26m28s454ms 100 04120041 signal_strength=great
       -2h26m21s343ms 100 64060041 volt=4226 -screen +phone_in_call +wake_lock +sensor
       -2h26m16s116ms 100 64060031 signal_strength=good
       -2h26m10s976ms 100 64060031 volt=4315
       -2h26m08s340ms 100 64060041 signal_strength=great
       -2h26m05s501ms 100 64060031 signal_strength=good
       -2h26m01s432ms 100 64060041 signal_strength=great
       -2h25m46s121ms 100 64060040 brightness=dark
       -2h25m32s915ms 100 44120041 volt=4280 +screen -phone_in_call -sensor brightness=dim
       -2h25m28s318ms 100 44120041
       -2h25m26s795ms 100 04120041 -wake_lock
       -2h25m22s564ms 100 04120044 brightness=bright
       -2h25m10s992ms 100 04120044 temp=291
       -2h24m46s199ms 100 04020044 -screen
       -2h24m43s920ms 099 04020044 volt=4316
       -2h17m32s686ms 099 04120044 +screen
       -2h17m25s330ms 099 44020044 -screen +wake_lock
       -2h17m25s057ms 099 04020044 -wake_lock
       -2h13m25s680ms 099 04120044 +screen
       -2h13m18s735ms 099 24120044 temp=272 volt=4285 +sensor
       -2h13m12s418ms 099 04120044 -sensor
       -2h13m09s376ms 099 04020044 -screen
       -2h07m59s699ms 099 04120044 +screen
       -2h07m46s293ms 099 04020044 -screen
       -2h01m48s671ms 099 04120044 +screen
       -2h01m46s419ms 099 00100044 -wifi -wifi_running
       -2h01m41s255ms 100 00100044
       -2h01m26s357ms 100 00000044 -screen
       -2h00m55s395ms 100 40140044 +screen +phone_in_call +wake_lock
       -2h00m53s549ms 100 00140044 -wake_lock
       -2h00m26s066ms 100 00140044 temp=296 volt=4237
       -2h00m20s886ms 100 00100044 -phone_in_call
       -2h00m18s537ms 100 00000044 -screen
       -2h00m09s250ms 100 00000044 volt=4302

mmssms database android

root@android:/ # find /data/data -name *.db | grep sms                        
/mmssms.db
cd /data/data/com.android.providers.telephony/databases && sqlite3 mmssds.db

SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addr                 pdu                  threads          
android_metadata     pending_msgs         words            
attachments          rate                 words_content    
canonical_addresses  raw                  words_segdir      
drm                  sms                  words_segments    
part                 sr_pending  


sqlite> select * from sms;
1|1|535 123 321||1378726606185|0||1|-1|2|||Test||0|0|1
2|1|+485351236321||1378726609910|1378726608000|0|1|-1|1|0||Test|+48123998250|0|0|1

android proces list.

for example:

marek::lati { ~ }-> adb shell ps | awk '{print $9}' | grep com
krfcommd
/system/bin/sensors.qcom
/system/bin/qseecomd
/system/bin/qseecomd
com.android.systemui
com.android.inputmethod.latin
com.android.phone
com.android.nfc
com.cyanogenmod.trebuchet
com.android.nfc:handover
com.google.process.location
com.android.smspush
com.android.location.fused
com.google.process.gapps
com.google.android.gms
com.google.android.gsf.login
com.android.calendar
com.google.android.gm
com.android.deskclock
com.android.providers.calendar
com.cyanogenmod.lockclock
com.bel.android.dspmanager

niedziela, 8 września 2013

cyanogenmod after install tip

If you wan't to have all google apps: google play store, gmail app, calendar app etc. install

http://goo.im/gapps - all packages

http://www.androidfilehost.com/?fid=23060877490000128 - for last stable cyano

two way to read data from file

#!/usr/bin/python3

with open("myfile.txt") as f:
        for line in f:
                print(line)


in_file = open("myfile.txt", "rt")
text = in_file.read()
in_file.close()
print(text)

a little more advanced user error exceptions

#!/usr/bin/python3

import sys

try:
        f = open('myfile.txt')
        s = f.readline()
        i = int(s.strip())
except IOError as err:
        print("I/O error: {0}".format(err))
except ValueError:
        print("Could not convert data to an integer")
except:
        print("unexpected error",sys.exc_info()[0])
        raise
~                                  

error maping

#!/usr/bin/python3

while True:
        try:
                x = int(input("Enter number: "))
                break
        except ValueError as error:
                print ("ooops", error)


result:

marek@mbo:~/Dokumenty$ ./true.py 
Enter number: f
ooops invalid literal for int() with base 10: 'f'

czwartek, 5 września 2013

pip install python problem

root::lati { ~/Dokumenty/python }-> pip install MySQL-python
Downloading/unpacking MySQL-python
  Running setup.py egg_info for package MySQL-python
    The required version of distribute (>=0.6.28) is not available,
    and can't be installed while this script is running. Please
    install a more recent version first, using
    'easy_install -U distribute'.
   
    (Currently using distribute 0.6.24dev-r0 (/usr/lib/python2.7/dist-packages))
    Complete output from command python setup.py egg_info:
    The required version of distribute (>=0.6.28) is not available,

and can't be installed while this script is running. Please

install a more recent version first, using

'easy_install -U distribute'.



(Currently using distribute 0.6.24dev-r0 (/usr/lib/python2.7/dist-packages))

----------------------------------------
Command python setup.py egg_info failed with error code 2
Storing complete log in /home/marek/.pip/pip.log
root::lati { ~/Dokumenty/python }-> easy_install -U distribute
Searching for distribute
Reading http://pypi.python.org/simple/distribute/
Best match: distribute 0.7.3
Downloading https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a
Processing distribute-0.7.3.zip
Running distribute-0.7.3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-czy2vB/distribute-0.7.3/egg-dist-tmp-8Dpl5x
warning: install_lib: 'build/lib.linux-x86_64-2.7' does not exist -- no Python modules to install

Adding distribute 0.7.3 to easy-install.pth file

Installed /usr/local/lib/python2.7/dist-packages/distribute-0.7.3-py2.7.egg
Processing dependencies for distribute
Searching for setuptools>=0.7
Reading http://pypi.python.org/simple/setuptools/
Reading https://pypi.python.org/pypi/setuptools
Reading http://peak.telecommunity.com/snapshots/
Best match: setuptools 1.1.1
Downloading https://pypi.python.org/packages/source/s/setuptools/setuptools-1.1.1.tar.gz#md5=c8d19510c03b0e2e01880c0d8f080083
Processing setuptools-1.1.1.tar.gz
Running setuptools-1.1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-vatpeG/setuptools-1.1.1/egg-dist-tmp-87BDp5
Adding setuptools 1.1.1 to easy-install.pth file
Installing easy_install script to /usr/local/bin
Installing easy_install-2.7 script to /usr/local/bin

Installed /usr/local/lib/python2.7/dist-packages/setuptools-1.1.1-py2.7.egg
Finished processing dependencies for distribute
root::lati { ~/Dokumenty/python }-> pip install MySQL-python
Downloading/unpacking MySQL-python
  Running setup.py egg_info for package MySQL-python
    Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
    Extracting in /tmp/tmpJjLZmX
    Now working in /tmp/tmpJjLZmX/distribute-0.6.28
    Building a Distribute egg in /home/marek/Dokumenty/python/build/MySQL-python
    /home/marek/Dokumenty/python/build/MySQL-python/distribute-0.6.28-py2.7.egg
   
Installing collected packages: MySQL-python
  Running setup.py install for MySQL-python
    building '_mysql' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
    In file included from _mysql.c:44:0:
    /usr/include/mysql/my_config.h:422:0: warning: "HAVE_WCSCOLL" redefined [enabled by default]
    /usr/include/python2.7/pyconfig.h:890:0: note: this is the location of the previous definition
    gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so
   
Successfully installed MySQL-python
Cleaning up...

środa, 4 września 2013

python modules

mymodule.py

#!/usr/bin/python
import os
import datetime

def autor():
        print 'Hello it\'s me Marek Borkowski'
def cpu():
        os.system("lscpu")

version = '1.0'
now = datetime.datetime.now()


test.py
#!/usr/bin/pypy

import mymodule
from mymodule import version
from mymodule import now

mymodule.autor()

print 'present version is: ', version, 'we have: ', now
mymodule.cpu()
~                


simple python function

#!/usr/bin/pypy

def printMax(a, b):
        if a > b:
                print a, 'is max'
        else:
                print b, 'is max'

x = int(raw_input("Enter int: "))
y = int(raw_input( "Enter int: "))

printMax(x, y)

show details about CPU

marek::lati { ~ }-> lscpu
Architecture:          x86_64
Tryb(y) pracy CPU:     32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Wątków na rdzeń:    2
Rdzeni na gniazdo:     4
Socket(s):             1
Węzłów NUMA:        1
ID producenta:         GenuineIntel
Rodzina CPU:           6
Model:                 42
Wersja:                7
CPU MHz:               800.000
BogoMIPS:              4789.10
Wirtualizacja:         VT-x
Cache L1d:             32K
Cache L1i:             32K
Cache L2:              256K
Cache L3:              6144

wtorek, 3 września 2013

ls

ls -lSrd /var/log/*{,/*} # Show a reverse sorted by size list of the files in both /var/log and subdirs of /var/log together.

niedziela, 1 września 2013

isert data to db from raw_input

#!/usr/bin/python


import MySQLdb as mdb
name = str(raw_input('enter name: '))
surname = str(raw_input('enter surname: '))
con = mdb.connect('localhost', 'root', 'password', 'baza');

with con:

        cur = con.cursor()
        cur.execute("INSERT INTO adresy(imie,nazwisko) VALUES('"+name+"', '"+surname+"')")

        cur.execute("Select * from baza.adresy")
        for row in cur.fetchall():
                id = str(row[0])
                imie = str(row[1])
                nazwisko = str(row[2])

                print "id: ",id
                print "imie: ",imie
                print "nazwisko: ",nazwisko
                print "--------"
        cur.close()

sobota, 31 sierpnia 2013

python and mysql

#!/usr/bin/python

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', 'password', 'baza');

with con:

        cur = con.cursor()
        cur.execute("INSERT INTO adresy(imie,nazwisko) VALUES('Marek', 'Borkowski')")

        cur.execute("Select * from baza.adresy")
        for row in cur.fetchall():
                id = str(row[0])
                imie = str(row[1])
                nazwisko = str(row[2])

                print "id: ",id
                print "imie: ",imie
                print "nazwisko: ",nazwisko
                print "--------"
        cur.close()

czwartek, 29 sierpnia 2013

very simple mathematics

#!/usr/bin/python

for i in range(1, 10):
        for j in range(1, 10):
                iloczyn = i*j
                print ('i wynosi: ',i)
                print ('j wynosi: ',j)
                print iloczyn

niedziela, 25 sierpnia 2013

User-defined Exceptions in Python

#!/usr/bin/pypy

try:
        fo = open("/tmp/foo.txt", "wb")
        fo.write ("Marek Borkowski \n")
        if True:
                print 'ok'
        fo.close()
except IOError:
        print 'Something goes wrong'


and more advanced:

#!/usr/bin/pypy
import sys
total = len(sys.argv)

if len(sys.argv) > 1:
        try:
                fo = open(sys.argv[1], "wb")
                fo.write ("Marek Borkowski \n")
                if True:
                        print 'ok'
                fo.close()
        except IOError:
                print 'Something goes wrong'
else:
        print '

python philosophy

marek::lati { ~/Dokumenty/python }-> python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

sobota, 17 sierpnia 2013

swiss army knife - netcat.

1. file transfer

root::lati { ~ }-> nc -v -l 81 < test.txt
Connection from 127.0.0.1 port 81 [tcp/*] accepted
GET / HTTP/1.1
User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
Host: localhost:81
Accept: */*


other site/terminal:

root::lati { ~ }-> wget localhost:81
--2013-08-17 21:50:09--  http://localhost:81/
Translacja localhost (localhost)... 127.0.0.1
Łączenie się z localhost (localhost)|127.0.0.1|:81... połączono.
Żądanie HTTP wysłano, oczekiwanie na odpowiedź... Brak danych w odpowiedzi.
Ponawianie próby.

--2013-08-17 21:50:10--  (próba: 2)  http://localhost:81/
Łączenie się z localhost (localhost)|127.0.0.1|:81... nieudane: Połączenie odrzucone.
Translacja localhost (localhost)... 127.0.0.1
Łączenie się z localhost (localhost)|127.0.0.1|:81... nieudane: Połączenie odrzucone.
(you can ignore all error in this case)

root::lati { ~ }-> ll
razem 0
-rw-r--r-- 1 root root 0 sie 17 21:34 test.tx

poniedziałek, 12 sierpnia 2013

adb monitoring commands

1. adb shell dumpsys battery

root@ubu:~# adb shell dumpsys battery
Current Battery Service state:
  AC powered: false
  USB powered: true
  Wireless powered: false
  status: 2
  health: 2
  present: true
  level: 83
  scale: 100
  voltage:4193
  temperature: 297
  technology: Li-ion


2. adb shell dumpsys wifi - to wide to publicate :)

3. adb shell dumpsys cpuinfo
root@ubu:~# adb shell dumpsys cpuinfo
Load: 0.69 / 0.35 / 0.52
CPU usage from 9881ms to 2399ms ago with 99% awake:
  1.6% 523/system_server: 0.6% user + 0.9% kernel / faults: 53 minor
  0.4% 29973/com.android.providers.calendar: 0.4% user + 0% kernel / faults: 12 minor
  0.2% 183/mpdecision: 0% user + 0.2% kernel
  0.2% 1511/com.google.android.calendar: 0.2% user + 0% kernel / faults: 11 minor
  0% 152/jbd2/mmcblk0p23: 0% user + 0% kernel
  0% 634/com.android.systemui: 0% user + 0% kernel
  0.1% 7488/kworker/0:3: 0% user + 0.1% kernel
  0% 28295/kworker/0:5: 0% user + 0% kernel
  0% 32376/kworker/0:1: 0% user + 0% kernel
2.8% TOTAL: 1.6% user + 0.8% kernel + 0.4% iowait


4. adb shell dumpsys meminfo


root@ubu:~# adb shell dumpsys cpuinfo
Load: 0.69 / 0.35 / 0.52
CPU usage from 9881ms to 2399ms ago with 99% awake:
  1.6% 523/system_server: 0.6% user + 0.9% kernel / faults: 53 minor
  0.4% 29973/com.android.providers.calendar: 0.4% user + 0% kernel / faults: 12 minor
  0.2% 183/mpdecision: 0% user + 0.2% kernel
  0.2% 1511/com.google.android.calendar: 0.2% user + 0% kernel / faults: 11 minor
  0% 152/jbd2/mmcblk0p23: 0% user + 0% kernel
  0% 634/com.android.systemui: 0% user + 0% kernel
  0.1% 7488/kworker/0:3: 0% user + 0.1% kernel
  0% 28295/kworker/0:5: 0% user + 0% kernel
  0% 32376/kworker/0:1: 0% user + 0% kernel
2.8% TOTAL: 1.6% user + 0.8% kernel + 0.4% iowait
root@ubu:~#
root@ubu:~#
root@ubu:~#
root@ubu:~#
root@ubu:~# adb shell dumpsys meminfo
Applications Memory Usage (kB):
Uptime: 37179113 Realtime: 88324695

Total PSS by process:
    86097 kB: com.android.chrome (pid 4767)
    67054 kB: system (pid 523)
    44244 kB: com.android.launcher (pid 800)
    44235 kB: com.android.systemui (pid 634)
    36618 kB: com.facebook.katana (pid 30545)
    31162 kB: com.google.android.googlequicksearchbox (pid 5048)
    27171 kB: com.android.chrome:sandboxed_process3 (pid 12512)
    25688 kB: com.facebook.orca (pid 27691)
    22199 kB: com.google.android.inputmethod.latin (pid 719)
    19538 kB: com.google.android.apps.plus (pid 5355)
    19059 kB: com.android.phone (pid 774)
    17500 kB: com.android.dialer (pid 17592)
    16791 kB: com.facebook.katana:dash (pid 8465)
    12976 kB: com.google.android.gms (pid 2245)
    12791 kB: com.google.process.location (pid 757)
    12684 kB: com.google.process.gapps (pid 844)
    12185 kB: com.twitter.android (pid 8198)
    11349 kB: com.google.android.talk (pid 6276)
    10067 kB: android.process.acore (pid 15669)
     8282 kB: com.google.android.youtube (pid 8099)
     7782 kB: com.google.android.music:main (pid 7629)
     7755 kB: com.sand.airdroid:push (pid 827)
     7555 kB: com.android.vending (pid 8302)
     7066 kB: com.google.android.gallery3d (pid 6834)
     6916 kB: com.google.android.calendar (pid 1511)
     5884 kB: android.process.media (pid 2703)
     5597 kB: com.android.mms (pid 8075)
     5068 kB: com.android.providers.calendar (pid 29973)
     4831 kB: com.android.nfc (pid 785)
     3740 kB: com.google.android.apps.uploader (pid 8062)
     3401 kB: com.google.android.deskclock (pid 8420)
     3145 kB: dev.ukanth.ufirewall (pid 8184)
     2843 kB: com.android.nfc:handover (pid 862)

Total PSS by OOM adjustment:
    67054 kB: System
               67054 kB: system (pid 523)
    68125 kB: Persistent
               44235 kB: com.android.systemui (pid 634)
               19059 kB: com.android.phone (pid 774)
                4831 kB: com.android.nfc (pid 785)
    61035 kB: Foreground
               44244 kB: com.android.launcher (pid 800)
               16791 kB: com.facebook.katana:dash (pid 8465)
    38385 kB: Visible
               12791 kB: com.google.process.location (pid 757)
               12684 kB: com.google.process.gapps (pid 844)
               10067 kB: android.process.acore (pid 15669)
                2843 kB: com.android.nfc:handover (pid 862)
    22199 kB: Perceptible
               22199 kB: com.google.android.inputmethod.latin (pid 719)
    20731 kB: A Services
               12976 kB: com.google.android.gms (pid 2245)
                7755 kB: com.sand.airdroid:push (pid 827)
    17500 kB: Previous
               17500 kB: com.android.dialer (pid 17592)
     7782 kB: B Services
                7782 kB: com.google.android.music:main (pid 7629)
   306462 kB: Background
               86097 kB: com.android.chrome (pid 4767)
               36618 kB: com.facebook.katana (pid 30545)
               31162 kB: com.google.android.googlequicksearchbox (pid 5048)
               27171 kB: com.android.chrome:sandboxed_process3 (pid 12512)
               25688 kB: com.facebook.orca (pid 27691)
               19538 kB: com.google.android.apps.plus (pid 5355)
               12185 kB: com.twitter.android (pid 8198)
               11349 kB: com.google.android.talk (pid 6276)
                8282 kB: com.google.android.youtube (pid 8099)
                7555 kB: com.android.vending (pid 8302)
                7066 kB: com.google.android.gallery3d (pid 6834)
                6916 kB: com.google.android.calendar (pid 1511)
                5884 kB: android.process.media (pid 2703)
                5597 kB: com.android.mms (pid 8075)
                5068 kB: com.android.providers.calendar (pid 29973)
                3740 kB: com.google.android.apps.uploader (pid 8062)
                3401 kB: com.google.android.deskclock (pid 8420)
                3145 kB: dev.ukanth.ufirewall (pid 8184)

Total PSS by category:
   254338 kB: Dalvik
   157642 kB: Unknown
    72263 kB: .dex mmap
    58141 kB: .so mmap
    37848 kB: Other dev
    19339 kB: .apk mmap
     6190 kB: Stack
     2865 kB: Other mmap
      431 kB: .ttf mmap
      122 kB: .jar mmap
       92 kB: Cursor
        2 kB: Ashmem
        0 kB: Native

Total PSS: 609273 kB
      KSM: 0 kB saved from shared 0 kB
           0 kB unshared; 0 kB volatile



5. adb shell dumpsys activity - to looong


sobota, 3 sierpnia 2013

rm in verbose mode

rm -rf * -vf

root@ubu:/tmp# rm -rf * -vf
usunięty „1”
usunięty „10”
usunięty „2”
usunięty „3”
usunięty „4”
usunięty „5”
usunięty „6”
usunięty „7”
usunięty „8”
usunięty „9”

-v, --verbose
              explain what is being done

for part2

for i in `seq 1 100`; do touch $i; done - create 101 files



for - way to do the same thing

for I in {1..10}; do echo $I; done

for I in 1 2 3 4 5 6 7 8 9 10; do echo $I; done

for I in $(seq 1 10); do echo $I; done

for ((I=1; I <= 10 ; I++)); do echo $I; done

piątek, 2 sierpnia 2013

apt-get update NO_PUBKEY error

if you have a problem with your apt in ubuntu

like:
Pobrano 348 kB w 21s (15,9 kB/s)
Czytanie list pakietów... Gotowe
W: Błąd GPG: http://download.opensuse.org  Release: Następujące podpisy nie mogły zostać zweryfikowane z powodu braku klucza publicznego: NO_PUBKEY 977C43A8BA684223


you should:

sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 977C43A8BA684223

czwartek, 1 sierpnia 2013

supersu for android 4.3

Start with nexus 4 rooting procedure:
1. wget http://techerrata.com/file/twrp2/mako/openrecovery-twrp-2.4.1.0-mako.img
2. fastboot flash recovery openrecovery-twrp-2.4.1.0-mako.img
sending 'recovery' (8294 KB)...
OKAY [ 0.520s]
writing 'recovery'...
OKAY [ 0.424s]
finished. total time: 0.945s
3. Since now when we start recovery mode we should have user friendly tool
4. restart boot loader
fastboot reboot-bootloader
rebooting into bootloader...
OKAY [ 0.001s]
finished. total time: 0.001s
5. download app for android 4.3 http://download.chainfire.eu/344/SuperSU/UPDATE-SuperSU-v1.50.zip
6. copy to mobile sd card or use adb:
adb push 'UPDATE-SuperSU-v1.50.zip' /sdcard/
7.  After you’ve flashed the superuser package, wipe cache and dalvik cache, just to be on the safe side.
8. Restart

After this 8 steps you should have root mode enabled in your nexus.


use adb to execute phone procedure

adb shell am start -a android.intent.action.CALL tel:5148888888

how to send sms from linux shell

1. add repo key
sudo add-apt-repository ppa:nilarimogard/webupd8
2. # sudo apt-get update
3. # sudo apt-get install android-tools-adb android-tools-fastboot

now when you type in command prompe bellowed command you can send sms from you terminal window, when you of course connect your pc with your mobile.

adb shell am start -a android.intent.action.SENDTO -d sms:728403930 --es sms_body "test" --ez exit_on_sent true

adb shell input keyevent 22
adb shell input keyevent 66

piątek, 26 lipca 2013

start if stop WLST script

print 'reading domain ...'
readDomain('/u01/middleware/user_projects/domains/marek')
nmConnect('weblogic', 'password', 'localhost', '5556', 'marek', '/u01/middleware/user_projects/domains/marek','ssl')


status = nmServerStatus('AdminServer')
if status == True:
        print 'ok'
elif status == 'SHUTDOWN':
        print 'server is in SHUTDOWN state, starting ...'
        nmStart("AdminServer")
else:
        print 'dupa'

how to decode weblogic password

1. Make a file with name decryptpasswd.py under your_domain/security folder  with below  
    contents
2.
from weblogic.security.internal import *
from weblogic.security.internal.encryption import *

#This will prompt you to make sure you have SerializedSystemIni.dat file under #current directory from where you are running command
raw_input("Please make sure you have SerializedSystemIni.dat inside the current directory, if yes press ENTER to continue.")

# Encryption service
encryptionService = SerializedSystemIni.getEncryptionService(".")
clearOrEncryptService = ClearOrEncryptedService(encryptionService)

# Take encrypt password from user
pwd = raw_input("Please enter encrypted password (Eg. {3DES}Bxt5E3...): ")

# Delete unnecessary escape characters
preppwd = pwd.replace("\\", "")

# Decrypt password
print "Your password is: " + clearOrEncryptService.decrypt(preppwd)

3. Get your encrypt password
4. Now go to  your_domain/bin directory
5. Run setDomainEnv.(sh/cmd)
6. Change directory to your_domain/security ( where you placed decryptpasswd.py script )
7. Run below command

$ java weblogic.WLST decryptpasswd.py

poniedziałek, 22 lipca 2013

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

In basic system like CentOS there can be one problem when we want to install for example weblogic version wls1211_linux32.bin:

yum install glibc.i686 or yum install glibc.i386

oracle xe allow remote login

SQL> EXEC DBMS_XDB.SETLISTENERLOCALACCESS(FALSE);  
  
PL/SQL procedure successfully completed.

oracle xe in centos

Few step to start oracle xe database in centos distro:

1. set oracle ENV - shell script default in: /u01/app/oracle/product/11.2.0/xe/bin/

  • . oracle_env.sh

2. check env

  • echo $ORACALE_HOME

3. enter to sqlplus

  • cd $ORACLE_HOME/bin && ./sqlplus /nolog

prompt:
4. Enter to DB

  • SQL:> connect sys@xe as sysdba

enter password:

du

du -hsx * | sort -rh | head -10 -> show size of all directory in present localization.
du --max-depth=1 /home/ | sort -n -r - show size of all directory from path

środa, 3 lipca 2013

python subprocess module example

>>>import subprocess
>>>subprocess.call('ls | wc -l', shell=True)
3
0 --> finish successfully
>>>subprocess.call(['touch', 'plik'])
0
>>>subprocess.call(['ls', '-ltr'])
razem 8
-rw-r--r-- 1 root root  28 lip  2 14:28 plik.tajemny
-rwxr-xr-x 1 root root 680 lip  3 10:24 test.py
-rw-r--r-- 1 root root   0 lip  3 10:34 plik
0

error example:
>>>subprocess.call('ls | wc -lasd', shell=True)
wc: błędna opcja -- 'a' -->; error message
Napisz 'wc --help' dla uzyskania informacji.
ls: błąd zapisu: Przerwany potok
1 -->; error code

the same error code OS use when we try to execute wrong command
simple example from the OS

root@ubu:~# cat /etc/passwd123
cat: /etc/passwd123: there is no file
root@ubu:~# echo $?
1

very cool script

What is Subprocess?
The subprocess module in Python allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.

This module intends to replace several other, older modules and functions,
like: os.system, os.spawn*, os.popen*, popen2.* commands.

Subprocess is probably the most important Python module for system administrators.

#!/usr/bin/env python
import subprocess
import os

def find():
    y = raw_input("Enter a text you want to search on the system!")
    s = y.rstrip("\n")
    print "string", s
    find = subprocess.Popen([r"/usr/bin/find", "/", "-name", y, "-print"], stdout=subprocess.PIPE)
    for line in find.stdout.readlines():
        print "line", line
        l = line.rstrip("\n")
        list = subprocess.Popen([r"ls", "-l", l], stdout=subprocess.PIPE)
        list_stdout = list.communicate()[0]
        print list_stdout
    file = subprocess.Popen([r"file", l], stdout=subprocess.PIPE)
    file_stdout = file.communicate()[0]
    print file_stdout

def main():
    find()

python - shell command execute

1. install python-pip - alternative Python package installer
2. pip install sh - install sh module
3. from python shell:


>>> import sh

print sh.ifconfig("wlan0")

>>> from sh import ifconfig

print ifconfig("wlan0")

# print the contents of this directory

>>> print ls ("-ltr")

razem 4 -rw-r--r-- 1 root root 28 lip 2 14:28 plik.tajemny 

vim file encryption

Vim is very powerful tool and give you even simple encryption service

1. marek@ubu:~$ vim -x testfile
enter passphrase key twice

2. marek@ubu:~$ cat testfile
VimCrypt~01!wUmarek@ubu:~$ file testfile

3. file testfile: Vim encrypted file data


wtorek, 2 lipca 2013

Run build in PHP server

1. Install package:
-- yum install php5-cli
-- apt-get install php5-cli
2. execute command
-- php -S 127.0.0.1:8080 for the comfortable ussage i recommend to use:

  • nohup php -S 127.0.0.1:8080 & -- all the output now we have in nohup.out file and the PHP server process are in the background.




środa, 26 czerwca 2013

poniedziałek, 24 czerwca 2013

Work with linux cmd line.

Quick way to check battery cappacity:


upower -i /org/freedesktop/UPower/devices/battery_BAT0
 

Here’s a quick way to get the service tag (serial number):

 
dmidecode | grep "Serial Number" | head -n1
        Serial Number: DJ6GH3H