Tuesday, November 3, 2015

David Beazley - Modules and Packages: Live and Let Die!

If you are Python developer don't miss this section from PyCon 2015 by David Beazly. This section is important for every python developer.
Why it's important? if you don't know about how python module, namespace and packaging in general manner you will die :-).
This section not talk about how to create package, but more general about what is package and module it self.
Good explanations by David, this section also compare which one that should and shouldn't do by developer.
for more information you can watch PyCon 2015 By David Beazley - Modules and Packages: Live and Let Die!

Monday, November 2, 2015

Android HTML5 App, how really it's?

In this post I just want to share HTML5 development, it's not using framework like apache cordova or something else. I just want to share how to communicate or interfacing between javascript and android java native code.

When I wrote this post, I use Android Studio Version 1.4.

For complete project you can download from this link  https://www.dropbox.com/s/02mor7925l1l3bg/MyApplication.zip?dl=0

Create new project with no activity using android studio

Tuesday, October 27, 2015

Python Access Java Through JNIus


Can python access java library or class?, yes it's possible. There are some project to do this, the popular one is PyJNIus and this project under Kyvi project https://github.com/kivy/pyjnius.

How it's work? PyJnius wrap java using JNI call so python can call it, don't worry if you don't know about it. Me to :-)

To install PyJNIus, we need to install
  1.  Java JDK installed (OpenJDK will do)
  2.  Python 3.4 (In this case I use 3.4 version)
  3.  Setup JAVA_HOME environment
  4.  Setup JRE_HOME environment

After install python, we need to install cython, use pip or easy install. In this case I use pip.
$ sudo pip install cython
After cython installed, then install PyJNIus through  php or easy install. In this case I use pip
$ sudo pip install PyJnius
After PyJnius installed then try import jnius from python, and let learn little thing about calling java from python.

On linux should be no problem when importing jnius,
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from jnius import autoclass
>>> 
But on OSX we sometime meet this error when import jnius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/barry/anaconda/envs/ovation-testing/lib/python2.7/site-packages/ovation/__init__.py", line 8, in <module>
    from jnius import autoclass, cast, JavaException
  File "/Users/barry/anaconda/envs/ovation-testing/lib/python2.7/site-packages/jnius/__init__.py", line 12, in <module>
    from .jnius import *
ImportError: dlopen(/Users/barry/anaconda/envs/ovation-testing/lib/python2.7/site-packages/jnius/jnius.so, 2): Library not loaded: @rpath/libjvm.dylib
  Referenced from: /Users/barry/anaconda/envs/ovation-testing/lib/python2.7/site-packages/jnius/jnius.so
  Reason: image not found
If you found that problem, you need to add this to .profile in your home file, and add this line then restart your terminal then try again to import jnius.
export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$(/usr/libexec/java_home)/jre/lib/server
now you can import jnius on python interpreter.

On windows, I have no luck to install PyJnius through pip or easy install using MinGW as compiler. But I still struggling with it :-(.

now let's test to access some java library
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import jnius
>>> from jnius import autoclass
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
'hello'
>>> stack.push('world')
'world'
>>> stack.pop()
'world'
>>> stack.pop()
'hello'
>>> System = autoclass('java.lang.System')
>>> System.out.println('Hello World')
Hello World
for more learning stuff you can refer to:
http://pyjnius.readthedocs.org/en/latest/
http://kivy.org/planet/2012/08/pyjnius-accessing-java-classes-from-python/

with this project, it's possible to develop android app using python. To create android package we can use http://python-for-android.readthedocs.org/en/latest/

Sunday, October 25, 2015

How to make android emulator run faster?

Android emulator running too slow? this is main problem when develop android application :-). I always trying to find other solution rather than using original google android emulator.

After do some googling and learn little about virtualization technology, I got little knowledge how to run android emulator using intel virtualization technology (VT) this feature must be activated through BIOS.

We need to access bios and activate intel virtualization technology, keep in mind that not all processor and motherboard support intel virtualization technology. But if intel virtualization technology exist in your bios setting you can use it to run android emulator using x86 image.

If your processor and motherboard support intel virtualization technology install haxm through android sdk manager


But if your computer doesn't support inter haxm don't worry just skip haxm installation step, then go to android sdk installation folder and goto extra/intel/Hardware_Accelerated_Execution_Manager then install using silent_install.bat must be using command prompt with administrator mode:
D:\SDK\android-sdk-windows\extras\intel\Hardware_Accelerated_Execution_Manager>silent_install.bat -m 512
-m parameter is memory will be used by haxm manager, don't use memory more than 1024MB, after installation succes you will get message in command prompt will return success message.

Next step install image x86 both, x86 image system and x86 google api image system.


Then setup your android virtual device (AVD), setup using one of x86 image system, don't forget to Use GPU Host


That's it, and let you got fast android emulation.

Tuesday, October 20, 2015

Python LinkedIn REST API Implementation

LinkedIn using OAuth Version 2.0 it's different process compare with OAuth Version 1.0. Newer version is more easy to implement we don't really need to create parameter with oauth_ prefix and generate signature on client side, for more information about oauth version 2.0 we can refer to official oauth page http://oauth.net/2/.

All request should use https protocol and redirect url must be accessible if not we can't get code for generate access token. The step is simple just 2 step only.

1. Generate grant access url, from here we will redirected to our redirect url and we will get code for authorization code
2. Generate access token using that code with POST method and we will get token access with specific time expired

We can use that token access to call API to provider. Token access will expired in specified time and we need to renew access token with both step.

You can grab pyLinkedinAPI from my github repository https://github.com/amru-rosyada/pyLinkedinAPI

Please if you use it, don't forget to give us feedback. Next project I will try to implement Facebook, G+, Instagram and Flickr as far as I have little time to make it :D

Python Tumblr REST API Implementation

In previous post I was implement python twitter API, today I will talk something about tumblr API implementation.

I guess twitter, tumblr, linkedin and yahoo used same oauth method and api implementation. I use pyTwitterAPI base code to implement tumblr rest API and still work but with little additional parameter.

Tumblr is yahoo like API implementation as we know tumblr was acquired by yahoo :-) so if it's worked with tumblr, it's also will work with yahoo API :D

The main different with twitter API call is tumblr add api_key parameter which is consumer key. So if I want to call tumblr rest API, I must pass api_key=MY_CONSUMER_KEY in api url.

ex:
http://api.tumblr.com/v2/blog/scipsy.tumblr.com/info?api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4

Most of tumblr api call need base hostname as parameter. For example my tumblr domain is http://xyzmind.tumblr.com, so I need to call it with http://api.tumblr.com/v2/blog/xyzmind.blogspot.com/info?api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4. It's also work with tumblr custom domain :D

You can grab my python tumblr API implementation from my github repository https://github.com/amru-rosyada/pyTumblrAPI

Let me know if something wrong, may you want to contribute with my project.

Python Twitter REST API Implementation

Before read this article maybe you need to read my previous article http://walkinsmile.blogspot.com/2015/04/python-oauth-implementation-its-not.html

I already wrote some codes in a day to implement wrapper for twitter REST API (OAuth V1.0 and REST API V1.1), this code will simplify process to call twitter REST API from python code.

It's not that complex and not that hard and just little code to help other developer if they need to simplify twitter REST API call.

I use python version 3.4 :-), you may need some modifications and tuning to run this code on older python, especially older than version 3.

You can grab my code on my github repository free to use, modify and redistribute https://github.com/amru-rosyada/pyTwitterAPI

Understanding python decorator in easy way

I still have enough energy to write something on my blog :D after one week trip to Jakarta for some work reason. I am so tired but I want to write and share something about python decorator before I sleep :-).

Lets see how python function work,

Code 1:
def myfunc(a):
    print(a)

decorator = myfunc
decorator('It\'s Works')
Output 1:
It's Works

Code 2:
def myfunc(*args):
    print(args)

decorator = myfunc
decorator('It\'s', 'Works', 'Yeah', 'Must be ok')
Output 2:
("It's", 'Works', 'Yeah', 'Must be ok')

Code 3:
def myfunc(**kwargs):
     print(kwargs)

decorator = myfunc
decorator(a=1, b=2, c=3)
Output 3:
{'a':1, 'b':2, 'c':3}

Inner Function
Inner function is function inside function or we can call it nested function. Look at code bellow:
def myfunc(a):
    def inner_myfunc():
        print(a)

    return a

decorator = myfunc
decorator('inner myfunc')
Output should be:
'inner myfunc'
from the code we can se that, argument or parameter a is accessible from inner function.

I have some question why I always wrote decorator = myfunc? I just want to show python function can be assigned to var as alias or pointer.

@some_decorator
def myfunc():
    return a

it's mean:
myfunc = some_decorator(myfunc)

Lets try to the real code with decorator implementation:

# define logger function
# we will this for as decorator
def logger(func):
    def inner(*args, **kwargs): #1
        print "Arguments were: %s, %s" % (args, kwargs)
        return func(*args, **kwargs) #2
       
    return inner

# use the decorator
@logger
def myfunc1(x, y=1):
    return x * y

# use the decorator
@logger
def myfunc2():
    return 2

After define function now try to call myfunc1 and myfunc2:

# call function
myfunc1(5, 4)

# output should be
Arguments were: (5, 4), {}
20

# call function
myfunc1(1)

# output should be
Arguments were: (1,), {}
1

# call function
myfunc2()

# output should be
Arguments were: (), {}
2

If you need more explanation you can comment this post, just comment and I will try to answer :-).

Let Sleep.....

Python OAuth implementation it's not that hard!

Did you know about OAuth ? I will explain about OAuth from some resources,

Wikipedia: http://en.wikipedia.org/wiki/OAuth
OAuth is an open standard for authorization. OAuth provides client applications a 'secure delegated access' to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner, or end-user. The client then uses the access token to access the protected resources hosted by the resource server. OAuth is commonly used as a way for web surfers to log into third party web sites using their Microsoft, Google, Facebook or Twitter accounts, without worrying about their access credentials being compromised.

If you want to know more about OAuth standard you can refer to http://oauth.net/

In this post I will use Python version 3.4,

Something you need to know about OAouth implementation:
  1. Know about REST API from service provider like twitter, facebook, google, tumblr, yahoo etc. They have different method when request using oauth. some provider using POST only or GET only or both.
  2. Know about OAuth standard at least you have read it
  3. Know about term which is used by OAuth like oauth_callback, oauth_nonce, oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_token_secret, oauth_timestamp, oauth_signature, oauth_signature_method and oauth_version
  4. that's it
OAuth using CONSUMER_KEY and CONSUMER_SECRET to generate token, then this token will be use to access API from service provider.

How to request POST and GET using Python ?

I want to share about HTTP request using python, HTTP request can be done using POST or GET method. The main different between POST and GET is on HTTP header, POST method need Content-Type: application/x-www-form-urlencoded definition when sending data.

If you want to know about HTTP header you can refer to wiki page http://en.wikipedia.org/wiki/List_of_HTTP_header_fields or W3 page http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.

But I will not talk about HTTP Protocol standard in this post, I only will share about how to request POST and GET using python (I use python version 3.4).

POST Method:
# import url Request to create request object
from urllib.request import Request

# import urlopen to send request to web site
from urllib.request import urlopen

# for post request need define Content-Type : application/x-www-form-urlencoded on http header
header = {'Content-Type':'application/x-www-form-urlencoded'}

# create request object
# data query need to encode to byte, it is save to use standart ISO-8859-1
req = Request('http://localhost:8888/p/authenticate/google', 'firstname=amru&lastname=rosyada'.encode('ISO-8859-1'), header)

# send post request
post_response = urlopen(req)

GET Method:
GET code snippet is same with POST but without application/x-www-form-urlencoded on http header data parameter should be None of left it blank.
# import url Request to create request object
from urllib.request import Request

# import urlopen to send request to web site
from urllib.request import urlopen

# create request object
# data query need to encode to byte, it is save to use standart ISO-8859-1
req = Request('http://localhost:8888/p/authenticate/google?firstname=amru&lastname=rosyada', None)

# send post request
get_response = urlopen(req)
Thanks :D

Python in a Minute

Today I will share about how to learn python in a minute, in this post I will use python version 3 only and discuss about python keyword, using python module, python mode, basic syntax, operator, function, python data type and class.

This post is not deep concept, but about basic concept before we start deep learning into python.

Python is easy programming language to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

Learning python is not hard because it's "human language" :-) it's mean that python language is more readable, portable, clean, easy to develop and easy to extends.

Ok lets start don't wasting time :D.

Python Mode
Python have two mode which is interpreter mode and scripting mode, we don't need to compile the code because compilation process to byte code will be handled by python interpreter.

You need to install python interpreter before you can start using python, can be downloaded from here python.org. Choose the right one for you distribution OS.

Interpreter mode can be access from terminal emulator in linux and mac or cmd in windows. Most linux distro include python interpreter on each their distribution.

From terminal emulator or cmd you simply type python you will get in to python interpreter depend on your system.
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
With interpreter method you can use it as calculator like sum, div, mod etc
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
2
>>> 3*3
9
>>> 3**4
81
>>> 6%2
0
>>>

Setup Python on windows platform

Hello guys, today I will share how to setup and install python on windows platform. Before installation process you need to download python installer for windows platform at https://www.python.org/downloads/windows/ I recommended to download python 3 latest version.

If you already finished download, run installer by double click your python installer and follow the wizzard :-).


No more Python 2.8

I use python for my daily programming stuff and I am so happy I can use it in my daily programming stuff, Python language it so beautiful, effective and clean.

Why it's beautiful? because it's easy to learn, easy to implement, easy to extends (we can extends python using C or C++). It's good programming language for people who want to learn basic programming concepts. But don't forget to have deep concept in C programming language :D, C is important thing and one thing you need to know about python it made from C.

Why it's effective? python syntax and idiom is well mature. We can create complicated stuff with python using few lines of code. Python built in method is complete you don't really need third party library if you not use it on specific purpose.

Why it's clean? Python functions have no explicit begin or end, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (:) and the indentation of the code itself. Python block of code is separate with indentation not curly braces so it clean and you will always got clean code structure.

But python 2.7 is the last python 2 development and will not supported in the future python release, because python development team decided to support python 3 version only. Don't worry python 3.4 is best python version ever, you can convert code from python 2.7 to python 3. :-) smart.

Tuesday, February 3, 2015

SQLite3 Review – Great for Beginners and Those Learning SQL

Essentialsql.com SQLite3 is a compact free database you can use easily create and use a database.  Though SQLite3 is not a full-featured database, it supports a surprisingly large set of the SQL standard, and is ideal for those just starting to learn SQL as well for developers that need a simple database engine to plug into their applications.  As such, SQLite has become very popular with smart phone developers.

Learn SQL with SQLite
There are several reasons I feel that SQLite3 is suitable for beginners.

The first is that you don’t need to be an expert to install and configure it.  In fact, getting SQLite3 to run is as simple as downloading the program and then running a simple command.

sqlite3 EssentialSQL.db

This is all that is needed to start up the database engine and start using the essential SQL database.

Second, the software is a really simple command line interface.  Now you may think that is a fault, but it isn’t, as our goal is to learn SQL.  And to really learn SQL you need to understand its commands and instructions (syntax).  SQLite lets you work distraction free with the essence of SQL.

Also, SQLite runs many different computer systems such as Apple OS X, Linux, and Windows.  This was important to me, since I wanted to provide everyone with easy to follow SQL lessons, and didn’t’ want to leave anyone out.

The last reason I recommend SQLite to beginners is that it is free to use.

Monday, January 26, 2015

solving a start job is running for create volatile files and directories : manjaro linux

I have used Manjaro Linux which is Arch Linux based system for several month. Manjaro using roling system update, so we don't need to install new distribution to use latest version. We only need to upgrade through update manager.

After several times I used roling update then I restart my system boot time take long time, and plymouth like freeze. When I press escape to view error message on boot time. I got this message.
a start job is running for create volatile files and directories
 I search internet but I got nothing to solve my problems, then I try to view my manjaro setting then I take look on kernel section, I know that my kernel is need to be upgrade. Manjaro system will notif recommended kernel version for installed system if newer kernel exist.



Install Recommended kernel from kernel section, after installation finish I restart my system and  it's like a magic all error message and boot time back to normal :).

#good luck have fun

Wednesday, January 21, 2015

The first Ubuntu Phone will go on sale in Europe in the second week of February.

Read original post here.


Made by Spanish device company Bq, the handset will mark the first time that an Ubuntu Phone is sold directly to consumers

The First Phone: Specifications

For its first Ubuntu Phone Bq is launching a repurposed version of the its popular Aquaris e4.5 handset preloaded with Ubuntu for Phones.
Unlike the version that developers can (and have) been downloading and flashing to their Nexus devices, the commercial version of Ubuntu on phones will ship with a number of differences in software, including new ‘Aggregator Scopes’, ‘Today Scope’, and support for paid content.
Specifications wise the Aquaris e4.5 is a capable daily driver. It’s a stylish, well built and dependable handset.
  • 4.5-inch screen (qHD resolution @ 540×960)
  • 1.3 GHz Quad Core ARM Cortex A7 (MediaTek)
  • Mali 400 GPU @ 500 MHz (MediaTek)
  • 8GB eMMC Storage
  • 1GB RAM
  • 2150 mAh Battery
  • Dual micro-SIM

Tuesday, January 20, 2015

Manjaro XFCE Post Installation Tips and Tricks

To read original article go to here.

It's nearly a year since my last post, a lot of things had happened in between, Placement preparation, couple of interviews, six month internship in Blackberry Platform at Payoda Technologies  and finally completion of my studies. During this period a lot of distros had been released but I stayed with the stable Opensuse, but then I felt KDE version of opensuse is little bit heavy, which can be felt during both start-up and during normal day to day usage(say Eclipse+amarok+chrome) even with 4GB RAM and i3 Processor.

I started my quest for "The best GNU/Linux OS" with distrowatch.com. Since I wanted a lighter distro but not certainly like Puppy/Tiny and no Ubuntu/Debian forks then by default I left with Arch. But the fear of  two earlier failed attempts to install Arch forced me to try arch fork than arch. Seeing Manjaro  Linux description "Manjaro Linux is a desktop-oriented, user-friendly distribution based on Arch Linux" , I thought I would give it a try. Downloaded and Installed manjaro-xfce-0.8.5.1-x86_64 from Manjaro site.

The first thing I noticed with Manjaro is, it's fast start-up and shutdown time, it is comparatively faster than opensuse. Here are the some of tricks which I had done to achieve what's in their description user-friendly distribution. NOTE: No Graphics driver installation tips are given because author himself followed the steps listed in Beginner's guide and finally ended with blank screen even though he only have Intel's Integrated graphics card. 

Saturday, January 17, 2015

Manjaro Linux: Arch For People Who Don’t Have Time

I am manjaro Linux user, and want to share how arch linux based system transform into friendly distro for end user.

This article originaly from make use of site.

There are plenty of things that make Arch Linux highly appealing to users: it’s always up-to-date, it’s a rolling release, and there’s tons of software available for it in its repositories. But what isn’t so appealing is the learning curve and pure difficulty of setting up an Arch system. If you want the best aspects of Arch, without the bad parts, you need Manjaro Linux.

About Manjaro Linux

Manjaro Linux is an Arch-based distribution, meaning that it runs on the same backbone and the same repositories as Arch itself. It also implements the rolling release upgrade model, meaning that you never have to perform a major upgrade from “release 1″ to “release 2″ – just update your packages and you’ll be up-to-date.
majaro-logo
However, unlike Arch, it doesn’t require that users build up systems on their own. This isn’t to say that setting up the Arch way is a bad thing, or that it’s too difficult – there’s plenty of documentation for the job. But some people simply don’t have the time, regardless of their skill level.
There’s a lot of fuss among Arch users whether they should support Manjaro, and while some believe that it goes against everything Arch stands for, I think it’s a good option for those who want it.
Also unlike Arch, there are some defaults when it comes to the included software. For example, Manjaro defaults to the Xfce desktop environment (which is lightweight and awesome), although official Openbox,(a very minimal desktop environment), and KDE (a desktop environment with lots of eye candy) versions are available as well. Other desktop environments, such as Gnome, are available as “Community Editions”.

Don’t Fear the Beta!

manjaro_installer


Technically speaking, Manjaro is still a beta distribution – its version sits at 0.8.9 at time of writing. This shouldn’t push away any potential users. The main reason why Manjaro is still considered a beta distribution is because of the Manjaro additions to the otherwise stable Arch packages that are installed. Things like the Manjaro installer and the Pacman (package manager) graphical frontend are still beta, but everything else that is on the system are stable versions of the software that Arch offers in its repositories.

Scary Steam for Linux bug erases all the personal files on your PC



Original Article From pcworld

If you’re a Steam fan running Linux, the last thing you’ll want to do in the next few days is mess with your Steam files. Users on Valve’s GitHub Steam for Linux page are complaining about a nasty bug that has the potential to wipe out every single personal file on your PC. Even worse, users say the bug will even wipe out documents on USB connected drives. So much for local backups.
The impact on you at home: The obvious implication if you’re running Steam on Linux is to be wary of the program right now. As a precaution, don’t connect any local external hard drives while you’re running Steam. Users complaining of this bug appear to have moved their .steam or ~/.local/share/steam directories, or invoked Steam’s Bash script with the —reset option enabled.
UPDATE: Valve gave us the following statement: "So far we have had a handful of users report this issue, after they manually moved their Steam install. We have not been able to reproduce the reported issue, but we are adding some additional checks to ensure this is not possible while we continue to investigate. If anyone else has experienced this or has more information, they should email linux@valvesoftware.com."

Ouch

Steam’s bug appears to be caused by a line in the Steam.sh Bash script: rm -rf “$STEAMROOT/“*. That command is a basic Bash instruction that tells the computer to remove the STEAMROOT directory and all its sub-directories (folders).
That’s all well and good, but the issue is that if the STEAMROOT folder is not there then the computer interprets the command as rm -rf “/“*, as first reported by Bit-Tech. If you’re not familiar with Bash, that command tells the system to delete everything on your hard drive starting from the root directory.
The saving grace for Linux users is that you can only erase files you have write permissions over. That means the system itself can’t be erased, but pretty much all of a user’s files—including photos and personal documents—would be at risk.
Ironically, the instruction at issue is preceded by a comment from the developer: # Scary!.
Indeed.
Editor's note: This article originally published on 1/16/15, but was updated on 1/17/15 to include Valve's statement.

Porting Code to Python 3 with 2to3

Diving In

So much has changed between Python 2 and Python 3, there are vanishingly few programs that will run unmodified under both. But don’t despair! To help with this transition, Python 3 comes with a utility script called 2to3, which takes your actual Python 2 source code as input and auto-converts as much as it can to Python 3. Case study: porting chardet to Python 3 describes how to run the 2to3 script, then shows some things it can’t fix automatically. This appendix documents what it can fix automatically. 

Unicode string literals

In Python 2, print was a statement. Whatever you wanted to print simply followed the print keyword. In Python 3, print() is a function. Whatever you want to print, pass it to print() like any other function.

Notes Python 2 Python 3
print print()
print 1 print(1)
print 1, 2 print(1, 2)
print 1, 2, print(1, 2, end=' ')
print >>sys.stderr, 1, 2, 3 print(1, 2, 3, file=sys.stderr)

  1. To print a blank line, call print() without any arguments.
  2. To print a single value, call print() with one argument.
  3. To print two values separated by a space, call print() with two arguments.
  4. This one is a little tricky. In Python 2, if you ended a print statement with a comma, it would print the values separated by spaces, then print a trailing space, then stop without printing a carriage return. (Technically, it’s a little more complicated than that. The print statement in Python 2 used a now-deprecated attribute called softspace. Instead of printing a space, Python 2 would set sys.stdout.softspace to 1. The space character wasn’t really printed until something else got printed on the same line. If the next print statement printed a carriage return, sys.stdout.softspace would be set to 0 and the space would never be printed. You probably never noticed the difference unless your application was sensitive to the presence or absence of trailing whitespace in print-generated output.) In Python 3, the way to do this is to pass end=' ' as a keyword argument to the print() function. The end argument defaults to '\n' (a carriage return), so overriding it will suppress the carriage return after printing the other arguments.
  5. In Python 2, you could redirect the output to a pipe — like sys.stderr — by using the >>pipe_name syntax. In Python 3, the way to do this is to pass the pipe in the file keyword argument. The file argument defaults to sys.stdout (standard out), so overriding it will output to a different pipe instead.

Friday, January 16, 2015

Recursive File and Directory Manipulation in Python (Part 3)



Repost from python central.

In Part 2 of this series we expanded our file-searching script to be able to search for multiple file extensions under a tree, and to write the results (all paths to files of matching extensions found) to a log file. Now that we've come to the final part of the series, we'll add more functionality (in the form of functions) to our script to be able to move, copy, and even delete the results of the search.
Before looking at the move/copy/delete functions, we'll first take the subroutine of logging the results to file and encapsulate that in a function also. The following is what that part of our script looked like before:

Recursive File and Directory Manipulation in Python (Part 2)



Repost from python central.

In Part 1 we looked at how to use the os.path.walk and os.walk methods to find and list files of a certain extension under a directory tree. The former function is only present in the Python 2.x, and the latter is available in both Python 2.x and Python 3.x. As we saw in the previous article, the os.path.walk method can be awkward to use, so from now on we'll stick to the os.walk method, this way the script will be simpler and compatible with both branches.
In Part 1 our script traversed all the folders under the topdir variable, but only found files of one extension. Let's now expand that to find files of multiple extensions in select folders under the topdir path. We'll first search for files of three different file extensions: .txt, .pdf, and .doc. Our extens variable will be a list of strings instead of one:

Recursive File and Directory Manipulation in Python (Part 1)




Repost from python central.

If you are looking to utilize Python to manipulate your directory tree or files on your system, there are many tools to help, including Python's standard os module. The following is a simple/basic recipe to assist with finding certain files on your system by file extension.
If you have had the experience of "losing" a file in your system where you don't remember its location and are not even sure of its name, though you remember its type, this is where you might find this recipe useful.
In a way this recipe is a combination of How to Traverse a Directory Tree and Recursive Directory Traversal in Python: Make a list of your movies!, but we'll tweak it a bit and build upon it in part two.
To script this task, we can use the walk function in the os.path module or the walk function in the os module (using Python version 2.x or Python 3.x, respectively).

Thursday, January 15, 2015

30 Python Language Features and Tricks You May Not Know About

I re post this one, from here, when I surfing other python programmer and developer.

Sometimes we don't know about secret of python code, it should be find by self exploring or should be discuss with other python programmer. :-) soo we will get new knowledges. Don't forget to share to other programmer if you have good tips or trick to tweak something. Let's make good knowledges share media with wathever you want.

1.1   Unpacking

>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)
>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)
>>> a, b, c = (2 * i + 1 for i in range(3))
>>> a, b, c
(1, 3, 5)
>>> a, (b, c), d = [1, (2, 3), 4]
>>> a
1
>>> b
2
>>> c
3
>>> d
4

Python Performance Tips

Have Been 5 year or may be more :D I used python for create many automation script. In this section I will share something about how to improve performance to speedup python code. This is originally I got from wiki.python.org

You can only know what makes your program slow after first getting the program to give correct results, then running it to see if the correct program is slow. When found to be slow, profiling can show what parts of the program are consuming most of the time. A comprehensive but quick-to-run test suite can then ensure that future optimizations don't change the correctness of your program. In short:
  1. Get it right.  
  2. Test it's right. 
  3. Profile if slow.  
  4. Optimise. 
  5. Repeat from 2.  
Certain optimizations amount to good programming style and so should be learned as you learn the language. An example would be moving the calculation of values that don't change within a loop, outside of the loop.