Tech C**P
14 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
How to get method name in python?

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

You can use inspect module to do exactly this job:
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
caller_method = calframe[0][3]
The part that you are interested in, is calframe[0][3]. It returns function name of the current method. If this method is called from a parent method (caller method), you have to get that method name using calframe[1][3].

A sample code for the inspect module:
import inspect


class PDFtoJPG:
def _internal_conversion(self):
self.convert_to_jpg()

def convert_to_jpg(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print calframe[0][3]
print calframe[1][3]
print calframe[2][3]

def convert(self):
self._internal_conversion()


snd = PDFtoJPG()
snd.convert()
#python #inspect #calframe #method_name
Tech C**P
How to get method name in python? The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine…
You can also use inspect.stack()[2][3] instead of getting current frame and then getting its outer frames:
inspect.stack returns a list of frame records for the caller’s stack. The first entry in the returned list represents the caller; the last entry represents the outermost call on the stack.

#python #inspect #stack
How to work with stash in git?

Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don’t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the git stash command.

Stashing takes the dirty state of your working directory — that is, your modified tracked files and staged changes — and saves it on a stack of unfinished changes that you can reapply at any time.

Now you want to switch branches, but you don’t want to commit what you’ve been working on yet, to stash your modified files in your project use git stash:
$ git stash
Saved working directory and index state \
"WIP on master: 049d078 added the index file"
HEAD is now at 049d078 added the index file
(To restore them type "git stash apply")

Now your working directory should be clean:
$ git status
# On branch master
nothing to commit, working directory clean

To list all your stashes use git stash list:
$ git stash list
stash@{0}: WIP on master: 049d078 added the index file
stash@{1}: WIP on master: c264051 Revert "added file_size"
stash@{2}: WIP on master: 21d80a5 added number to log

Now if you want to apply the most recent stashed files:
$ git stash apply
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
#
# modified: index.html
# modified: lib/simplegit.rb

In order to remove a stash, use git stash drop YOUR_STASH:
$ git stash list
stash@{0}: WIP on master: 049d078 added the index file
stash@{1}: WIP on master: c264051 Revert "added file_size"
stash@{2}: WIP on master: 21d80a5 added number to log
$ git stash drop stash@{0}
Dropped stash@{0} (364e91f3f268f0900bc3ee613f9f733e82aaed43)

These are some general, most useful commands to work with stash. Enjoy the article :)

#git #stash #stash_apply #stash_list #stash_drop #stash_save
Commit part of a file in git:

You can use git add --patch <filename> (or -p for short), and git will begin to break down your file into what it thinks are sensible hunks (portions of the file). It will then prompt you with this question:
Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?

Here is a description of each option:
y stage this hunk for the next commit
n do not stage this hunk for the next commit
q quit; do not stage this hunk or any of the remaining hunks
a stage this hunk and all later hunks in the file
d do not stage this hunk or any of the later hunks in the file
g select a hunk to go to
/ search for a hunk matching the given regex
j leave this hunk undecided, see next undecided hunk
J leave this hunk undecided, see next hunk
k leave this hunk undecided, see previous undecided hunk
K leave this hunk undecided, see previous hunk
s split the current hunk into smaller hunks
e manually edit the current hunk

#git #patch #commit #hunk #stage #git_add #git_add_patch
View open ports without netstat or other tool:
# Get all open ports in hex format
declare -a open_ports=($(cat /proc/net/tcp | grep -v "local_address" | awk '{ print $2 }' | cut -d':' -f2))
# Show all open ports and decode hex to dec
for port in ${open_ports[*]}; do echo $((0x${port})); done


#linux #ports #netstat #tcp #open_ports #sysadmin
How to truncate a log file in Linux:


> logfile


or


cat /dev/null > logfile


If you want to be more eloquent, will empty logfile (actually they will truncate it to zero size). If you want to know how long it "takes", you may use

dd if=/dev/null of=logfile

(which is the same as dd if=/dev/null > logfile, by the way)

You can also use:


truncate logfile --size 0


to be perfectly explicit or, if you don't want to

rm logfile

(applications usually do recreate a logfile if it doesn't exist already).

However, since logfiles are usually useful, you might want to compress and save a copy. While you could do that with your own script, it is a good idea to at least try using an existing working solution, in this case logrotate, which can do exactly that and is reasonably configurable.

#linux #sysadmin #truncate #dd #dev_null #logfile
How to check whether your site is served in gzip or not by using cURL linux command:
curl -H "Accept-Encoding: gzip" -I https://www.google.com

If you find the bloew line in the returned response, your site supports gzip:
content-encoding: gzip

NOTE: gzip can speed up your site speed tremendously, sometimes by 90% compression! It also affects your google rank.

#linux #curl #gzip #seo
-> VERY IMPORTANT <-

How to solve a technical problem in any scale?

Keep Calm:
Keep calm and focus. The first and the most important factor of solving a problem is to get a grip on yourself and get confident and focused. They are excited, angry or maybe out of control. If you get angry too, or excited, solving the problem will get more time than you would think of. Believe you me!

Truthify:
Is the problem explained is really the problem that has happened?
Most of the time problems are explained in a non-technical, wrong way! You are responsible to question him/her to see what actually has happened? You are the detective of the crime scene.

Isolation:
Is there any possibilty to isolate the problem from the sorroundings. Finding the real problem when different metrics affect the result will guide to a wrong path. For example if it is said that emails are not sent, try to just send email from mail server to see if everything is working, put aside your web application entirely to detect the root cause of the problem. Or when it is said that no one can upload files, check your server free disk space, inode, etc.

Cross Check:
To solve a problem try to test the result from different sources. If for example your payments are stored in 3 places (for BI or even the architecture needs in 2 places in different forms) check them all over again from bottom up and vice versa. Or if you have the app in different platforms, check them from web, iOS, android to see whether problem is platform-dependent or not.

#problem_solving #truthify #keep_calm #isolation #cross_check
simple introduction to Cement framework and its usage. Cement framework is mostly used for creating a command line application using python.

In version 2.6 of Cement you can initiate an app using with:
from cement.core.foundation import CementApp

with CementApp('myapp') as app:
app.run()

It hides complexieties in your application initiation. That is the above code would be something like below without using with:
from cement.core.foundation import CementApp

app = CementApp('myapp')
app.setup()
app.run()
app.close()

As you can see with procedure is more clear and straight forward with less code. I know it's silly to have an app like above, but that's just an introduction to the world of Cement.

To add logger to your framework you need to set log level in log.logging as below:
from cement.utils.misc import init_defaults
from cement.core.foundation import CementApp

defaults = init_defaults('myapp', 'log.logging')
defaults['log.logging']['level'] = 'DEBUG'
defaults['log.logging']['file'] = 'cementy.log'
defaults['log.logging']['to_console'] = True

with CementApp('myapp', config_defaults=defaults) as app:
app.run()
app.log.debug('This is debug')

init_defaults is used to setup logging. level sets the log level to DEBUG. file would write log data into cementy.log file.
By setting to_console param you can also write the data written to file into console too. So if you run your python application, a file would be created for logging and data will be printed out.

#python #cement #framework #logging #log #level #foundation
To get on going processes in mysql client and see which queries are taking longer use:

SHOW PROCESSLIST;

It will show you a table with list of all connection from different hosts (if applicable) and their PID number. You can use this number to kill a process that consumes your server CPU, Memory, etc.:

KILL <pid>;

#mysql #client #kill #processlist #sysadmin #dba #linux
nmap (Network Mapper) is a security scanner, originally written by Gordon Lyon.

Nmap features include:
Host discovery – Identifying hosts on a network. For example, listing the hosts that respond to TCP and/or ICMP requests or have a particular port open.

Port scanning – Enumerating the open ports on target hosts.

Version detection – Interrogating network services on remote devices to determine application name and version number.[7]

OS detection – Determining the operating system and hardware characteristics of network devices.

Scriptable interaction with the target – using Nmap Scripting Engine[8] (NSE) and Lua programming language.

If you want to check whether a port on remote host is open:
sudo nmap -v -p 80 google.com

In response it shows that the port is open/closed/filtered:
Not shown: 987 filtered ports
20/tcp closed ftp-data
80/tcp open http

In case you want to scan all port using nmap:
sudo nmap -v your_target_victim.com

It lists all the gathered information about open ports.

#nmap #security #port #open #open_port #port_scanner