Saturday, May 7, 2016

Disassembler for Python bytecode


It's possible to disassemble easely python bytecode. With python onboard tools. In this case the module 'dis'.



>>> def marcin(n):
...     print(n)
...
>>> import dis
>>> dis.dis(marcin)
  2           0 LOAD_GLOBAL              0 (print)
              3 LOAD_FAST                0 (n)
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
>>>

Friday, May 6, 2016

The Top 20 Hidden Features of Python

>Just A summary of the hidden possibilities.
>I will explain them in the following Posts


  • Braces
from __future__ import braces

  • List slicing
a = [1,2,3,4,5,6]
a[2:4]
[3,4]
a[2:]
[3,4,5,6]
a[:2]
[1,2]
a[::]
[1,2,3,4,5,6]


  • For .. else Syntax
for i in sfoo:
    if bar(i):
        #do something
        break
else:
    return -1

  • Yield statement
def primes(numb):
     while True:
         if isprime(numb):
              yield numb
         numb+=1

  • Multiple assignments
 a, b   = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2

  • Argument unpacking
def aMethod(arg1, arg2):
    # Do something

foo = (3, 4)
bar = {'y': 3, 'x': 2}

aMethod(*point_foo)
aMethod(**point_bar)

  • Decorators
def print_arguments(function):
     def wrapper(*args, **kwargs):
         print 'Arguments:', args, kwargs
         return function(*args, **kwargs)
     return wrapper


@print_args
    def write(text):
        print text

  • 'this' Module
>>> 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!

  • Descriptors
class Property(object):
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, obj, type):
        if obj is None:
            return self
        return self.fget(obj)
class MyClass(object):
    @Property
    def foo(self):
        return "Foo!"

  • Docstring Tests

  • Elipse slicing Syntax
>>> class C(object):
...  def __getitem__(self, item):
...   return item
... 
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)

  • Enumeration
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> for index, item in enumerate(a): print index, item
...
0 a
1 b
2 c
3 d
4 e

  • Generator Expressions
>>>x = [n for n in foo if bar(n)]

  • In place value swaping
>>>a, b = b, a

  • Multi-Line Regex
>>>> pattern = """
... ^                   # beginning of string
... M{0,4}              # thousands - 0 to 4 M's
... (CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
...                     #            or 500-800 (D, followed by 0 to 3 C's)
... (XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
...                     #        or 50-80 (L, followed by 0 to 3 X's)
... (IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
...                     #        or 5-8 (V, followed by 0 to 3 I's)
... $                   # end of string
... """
>>> re.search(pattern, 'M', re.VERBOSE)

  • Named string formatting
print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42}
The answer is 42.


  • New Types at runtime
>>> NewType = type("NewType", (object,), {"x": "hello"})
>>> n = NewType()
>>> n.x
"hello"


  • try exepet & else
try:
#Something to Try
Except(#Excetion):
#Do something
else:
#Do sth other
finally:
#Do always

  • .pth files
  • with statement
from __future__ import with_statement

with open('foo.txt', 'w') as f:
    f.write('hello!')


Python Hook Keyboard

I wrote once a keylogger in C. Today I want to show you that it's also possible to Hook the Keyboard with python.
All you need is to install the pyHook package and to follow my instructions in the code.

For the package: pip --install pyHook





# author:           Marcin Cherek
# python version:   2.7.11
# Date:             12th of April 2016
# language:         English
# License:          OpenSource

from pyHook import HookManager


def OnKeyboardEvent(event):
    print(event.Ascii)


hm = HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()

Thursday, May 5, 2016

Python access Clipbaord

First of all you need to install the clipboard package.
You can do this with pip.


->pip --install clipboard

I use it with python 3 but it will also work with version 2.
import clipboard #Import the package


To get datas from clipboard simply call:
clipboard.paste()



And to write them to the clipboard call:
clipboard.copy("Your Argument")



Python solve Algorithm

# author:           Marcin Cherek
# python version:   3.4
# Date:             5 of Mai 2016
# language:         English
# Title:            solve Algorithm python implementation
import decimal
import logging

logging.basicConfig()
logger= logging.getLogger(__name__)
logger.setLevel(logging.INFO)

#Prepares the the calculation
#this method splits the Operators
#from the Numbers
def _prepare(calculation):
        for i in ["+","-","*","/"]:
                calculation=calculation.replace(i,";"+i+";")
        return calculation.split(";")

#Replaces the sub calculation
#with the Result of it
def _replaceRes(deb,result,zähler):
        deb[zähler-1]=""
        deb[zähler]=""
        deb[zähler+1]=result
        return deb

#Normal calculation of two
#Numebers and one Operator
def _calc(z1,z2,op):
        if(op=="+"):return z1+z2
        elif(op=="-"):return z1-z2
        elif(op=="*"):return z1*z2
        elif(op=="/"):return z1/z2
        
#Shrinks the Array
#It removes the empty elements
def _popArr(deb):
        p=0
        while p<len(deb):
            if deb[p]=="":
                deb.pop(p)
                continue
            p+=1
        return deb

#Most important method
#It iterates the calculation
#and corrdinates the subcalcs with the
#results of it
def _solve_simple(deb,op):
        result=0;zähler=0
        for i in deb:
            if i==op:
                logger.info(deb)
                result=_calc(decimal.Decimal(deb[zähler-1]),decimal.Decimal(deb[zähler+1]),op)
                _replaceRes(deb,result,zähler)
                result=0
            zähler+=1
        deb = _popArr(deb)
        return deb

#Calls the simple Alg
#First of course */ and after that +-
def solve(calculation):
        calculation = _prepare(calculation)
        for i in ["*","/","+","-"]:
                calculation=_solve_simple(calculation,i)
        return decimal.Decimal(calculation[len(calculation)-1])

Tuesday, May 3, 2016

Programming Books


https://drive.google.com/open?id=0B18_gfM_Pmu-bEpyVU8wOTVPbjQ

  • Clean Code
  • code complete 2nd edition
  • Effective Java
  • HeadFirstDesignPatterns
  • Java Performance Tuning
  • Java Performance the definitive Guide
  • Python High Performance Programming
  • Software Architecture Design Pattern
  • Working Effectively with Legacy Code

Monday, May 2, 2016

KMP Algorithm in Python

# author:           Marcin Cherek
# python version:   2.7.11
# Date:             2 of Mai 2016
# language:         English
# Title:            KMP Algorithm python implementation

#Build the Prefix table
def lspTable(pattern):
    lsp = [0] * len(pattern)
    lsp[0] = 0
    for i in range(1,len(pattern)):
        j = int(lsp[i-1])
        while(j>0 and pattern[i]!=pattern[j]):
            j=int(lsp[j-1])
        if(pattern[i] == pattern[j]):
            j+=1
        lsp[i]=j
    return lsp

def kpm_search(pattern, text):
    lsp = lspTable(pattern)
    j = 0
    for i in range(0,len(text)):
        while( j>0 and text[i] != pattern[j]):
            j = lsp[j-1]
        if(text[i]==pattern[j]):
            j+=1
            if(j==len(pattern)):
               return i-(j-1) #returns the position
    return -1 #Not found