Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
How to use if in jinja2 template engine?

Jinja2 is a modern and designer-friendly templating language for Python, modelled after Django’s templates. It is fast, widely used and secure.

If you want to use conditional statements like if inside of template engine you should use a syntax like below:
{% if status == 'success' %}
Some text for successful procedure
{% else %}
Some text for not successful procedure
{% endif %}

#python #jinja2 #template_engine #template
How do I remove the passphrase for the SSH key without having to create a new key?

I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (Git and SVN) to a remote location over SSH many times in an hour.
$ ssh-keygen -p
Enter file in which the key is (/Users/my_username/.ssh/id_rsa):
Enter old passphrase:
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.

This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (`which can be left blank to have no passphrase`).

If you would like to do it all on one line without prompts do:
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

NOTE: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is therefore is recommended that you use the first option unless you have a specific reason to do otherwise.

You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.

#id_rsa #ssh #passphrase #keygen #linux #osx #remove_passphrase
To set a variable in jinja2 you can use set as below:
{% set pages_title = 'Pages' %}

As you notice we have used {% %} to set a variable not { }.

#variable #define #jinja2 #template
Dear readers, tonight I do my best to publish the first video for DJANGO tutorials in Persian.
Stay tuned...
If you work with Flask and have an under heavy load API, you can setup a cache for your endpoints. One of the tools is Flask- Cache that can work with different cache backends like Memcached, Redis, Simple, etc.

To install it:
pip install Flask-Cache

To setup up:
from flask import Flask
from flask.ext.cache import Cache

app = Flask(__name__)
# Check Configuring Flask-Cache section for more details
cache_config = {
"CACHE_TYPE": "redis",
"CACHE_REDIS_HOST": "127.0.0.1",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 3
}
cache = Cache(app,config=cache_config})

Another redis implementation:
#: the_app/custom.py
class RedisCache(BaseCache):
def __init__(self, servers, default_timeout=500):
pass

def redis(app, config, args, kwargs):
args.append(app.config['REDIS_SERVERS'])
return RedisCache(*args, **kwargs)

Now to use the cache on a method use its decorator:
@cache.memoize(timeout=50)
def big_foo(a, b):
return a + b + random.randrange(0, 1000)

#python #flask #cache #redis #memcached
http://pygments.org/

This is a syntax highlighter that creates permanent link for your code in a variety of languages including python in the provided link.

#python #pip #syntax_highlighter #highlighter #pygments
clone is used in git to copy a project into your machine as a git project and do you works on it. Sometime a project (specially front projects) are so heavy and has lots of history which makes cloning to takes an hour or more (depending on the depth and the size of the repo).

The solution is --depth, with --depth you can specify how shallow a clone could be and how much commit of the past should be brought into your system. So for example you can clone like this:
git clone myhost:frontier/web.git --depth=1
It will copy the whole project BUT it just copies the last commit on the tip of the current branch in your server (most likely master) which is the default behaviour of git that set --single-branch. So if you checkout to dev you wont see your last changes
in dev branch. In case you want to shallow copy the whole project and retrieve the lat commit on the tip of all remote branches just use --no-single-branch.

So finally we can:
git clone myhost:frontier/web.git --depth=1 --no-single-branch

Now if you change your branch (checkout) to dev, you will see that recent changes of the dev branch on the remote repo server is present in your system.

to see the last commit ids that you have in your system, open YOUR_PROJECT/.git/shallow file and see the content of the file. Mine is as below:
8252b87c82b4be7b7b4edaa12f2168ff165fc7af #refers to my master last commit id
d50bdeeecc595e86818c68d734613542206bf972 #refers to my dev last commit id

#git #branch #no-single-branch #single-branch #depth #clone
format() is way better than % in many different ways. One of those is:
>>> names = ['ali', 'reza', 'alireza', 'mohsen']
>>> print map('Hello Mr. {}'.format, names)
['Hello Mr. ali', 'Hello Mr. reza', 'Hello Mr. alireza', 'Hello Mr. mohsen']

#python #format #string_formatter #map
Tech C**P
format() is way better than % in many different ways. One of those is: >>> names = ['ali', 'reza', 'alireza', 'mohsen'] >>> print map('Hello Mr. {}'.format, names) ['Hello Mr. ali', 'Hello Mr. reza', 'Hello Mr. alireza', 'Hello Mr. mohsen'] #python #format…
format() is way better than %:
>>> a = {'name': 'ali', 'credit': '$2.0', 'status': 'active'}
>>> 'User {name} is {status} and has balance equal to {credit}'.format(**a)
'User ali is active and has balance equal to $2.0'
Media is too big
VIEW IN TELEGRAM
Django interactive shell

#python #django #shell #django_part7
Tech C**P
Photo
Adding, deleting, and cloning carets in pyCharm:

To add carets, do one of the following:
- Press Alt (Windows or UNIX)/Cmd (macOS) and click the left mouse button at the location of the caret.
- Press Ctrl (Windows or UNIX)/Alt(macOS) twice, and then without releasing it, press up or down arrow keys.

The new carets are added to the specified locations, according to setting of the Allow placement of caret after end of line check box.

To delete carets, do one of the following:
- Press Esc to delete all the existing carets, except the primary one.
- Press Shift+Alt and click the left mouse button on a caret to be deleted.

#pycharm #caret #multi_selection #carets
https://electron.atom.io/

Build cross platform desktop apps with JavaScript, HTML, and CSS

#multi_platform #cross_platform #css #js #electron #osx #windows #linux #desktop #application
Tech C**P
Photo
Except the first video, all the videos are totally non-sense and after a lot of results there some related video clips. This is where MACHINE LEARNING could save the project and enhance the UX (user experience).

Aparat needs to take this matter seriously.

#aparat #machine_learning #startup
If you are a PHP programmer and are using Yii2 for your project, I would suggest using the Twig template engine renderer rather
than the default one. No more php coding inside of templates plus the readability and much more:

https://github.com/yiisoft/yii2-twig

Install it using php composer, first add "yiisoft/yii2-twig": "~2.0.0" to composer.json file:
composer install

#php #composer #twig #yii2 #template #template_engine
with python compound statement in depth [ADVANCE]:

with is ported into python in version 2.5.

with is used to wrap the execution of a code block using methods defined by a context manager.

The process of with statement:
- The expression given in front of with statement is evaluated to obtain a context manager.
- The context manager’s __exit__() is loaded (it is not executed, it is just loaded for later use).
- The context manager’s __enter__() method is invoked.
- If a target was included in the with statement, the return value from __enter__() is assigned to it (like opening a file)
- The suite is executed (your code block)
- The context manager’s __exit__() method is invoked.

Now consider the example below:
with VAR = EXPR:
BLOCK

Would roughly translates to:
VAR = EXPR
VAR.__enter__()
try:
BLOCK
finally:
VAR.__exit__()

The moral of the story is that when you open a file it will close the file automatically at the end:
@contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()

At the finally stage, the file will always be closed, and you don't need to manage it.

Another example:
f = open(filename)
with f:
BLOCK1
with f:
BLOCK2

NOTE: The above code does not do what one might think (f is closed before BLOCK2 is entered!).

List of types which can be as a context manager (can be used in `with`):
- file
- thread.LockType
- threading.Lock
- threading.RLock
- threading.Condition
- threading.Semaphore
- threading.BoundedSemaphore

What is a context manager: it is an object that consists of __enter__() and __exit__() methods.

What is a context expression: the expression immediately following the with keyword in the statement is a context expression.

There is more about with to talk about, but I think it is more advanced and not needed for the time being :)

#python #with #context_manager #with_statement #advance
Shift time in python using datetime & timedelta:
import datetime
from datetime import timedelta

date1 = datetime.datetime.utcnow()
# output of date1: datetime.datetime(2017, 11, 8, 10, 24, 25, 19492)
date2 = date1 + timedelta(days=1)
# output of date2: datetime.datetime(2017, 11, 9, 10, 24, 25, 19492)

To get your new date in EPOCH:
at_epoch = (date2 - datetime.datetime(1970, 1, 1)).total_seconds()
# output of subtract: 1510223065.019492

To turn EPOCH to datetime:
import time

from_epoch = time.localtime(1510223065.019492)
# output: time.struct_time(tm_year=2017, tm_mon=11, tm_mday=9, tm_hour=13, tm_min=54, tm_sec=25, tm_wday=3, tm_yday=313, tm_isdst=0)

formatted_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1510223065.019492))
# output: 2017-11-09 13:54:25

#python #epoch #datetime #time #timedelta #strftime