Python, PHP, Javascript
Getting Started with Python
Python einrichten:
Python 3.6 + Jupyter Notebook
Options::
A- Development environment; VS Code + Python Extension
B- ANACONDA (Getting Python through Anaconda)
C- Google COLAB (Python on the web)
tupel () geordnet, nicht änderbar
list [] geordnet (array)
dictionary {key: value} (hash)
–
NumPy listen von listen (library, fast) ex. numpy.array[]
matrix numpy.array([],[],[])
matplotlib.pyplot
Shift + Alt + F can also be used for formatting ( Windows Platform )
Ctrl+Shift+P, F1: Show Command Palette
VS Code
Terminal:
pip install virtualenv
virtualenv env
env/bin|scripts/activate
Extensions:
Prettier Formatter (Automatic code formatting and style enforcement)
Auto rename tag (extension that automatically renames HTML/XML tags)
Code Spell Checker (extension checks for spelling errors in your code comments, strings, and markdown files)
Code Runner (extension is a tool that allows you to run code snippets on entire code files)
JavaScript Code Snippets
Indent-rainbow
Djngo
Setting up a virtual environment
py -m venv env_site
cd env_site\Scripts\
activate.bat
py -m pip install django
cd ..
django-admin startproject geeks_site
cd geeks_site
python manage.py migrate
python manage.py runserver
node.js | Python | PHP | |
---|---|---|---|
interpreter | $ node foo.js | $ python foo.py | $ php -f foo.php |
command line program | $ node -e “console.log(‘hi!’);” | $ python -c ‘print(“hi!”)’ | $ php -r ‘echo “hi!\n”;’ |
end-of-line comment | // comment | # comment | // comment # comment |
multiple line comment | /* line another line */ | use triple quote string literal: ”’comment line another line”’ | /* comment line another line */ |
variables and expressions | |||
local variable | let x = 1; let y = 2, z = 3;// older alternative to let: var x = 1;// let local scope is nearest | # in function body: x = 1 y, z = 2, 3 | # in function body: $x = 1; list($y, $z) = [2, 3]; |
file scope variable | // outside any function body: let n = 1;incrFileVar () { n++; } | none | none |
global variable | global.g = 1; incrGlobal () { global.g++; } | g = 1 def incr_global(): | $g = 1; function incr_global() { global $g; ++$g; } |
constant | // new in ES6 const PI = 3.14; | # uppercase identifiers # constant by convention PI = 3.14 | define(“PI”, 3.14); const PI = 3.14; |
assignment | v = 1; | # assignments can be chained # but otherwise don’t return values: v = 1 | $v = 1; |
parallel assignment | // new in ES6: let [x, y, z] = [1, 2, 3]; | x, y, z = 1, 2, 3 # raises ValueError: x, y = 1, 2, 3 # raises ValueError: x, y, z = 1, 2 | list($x, $y, $z) = [1 ,2, 3]; # 3 is discarded: list($x, $y) = [1, 2, 3]; # $z set to NULL: list($x, $y, $z) = [1, 2]; |
swap | // new in ES6: [x, y] = [y, x]; | x, y = y, x | list($x, $y) = [$y, $x]; |
compound assignment arithmetic, string, logical, bit | += -= *= /= none %= += none <<= >>= &= |= ^= | # do not return values: += -= *= /= //= %= **= += *= &= |= ^= <<= >>= &= |= ^= | += -= *= none /= %= **= .= none &= |= none <<= >>= &= |= ^= |
increment and decrement | let x = 1; let y = ++x; let z = —y; | none | $x = 1; $y = ++$x; $z = —$y; |
null test | v === null | v is None | is_null($v) ! isset($v) |
conditional expression | x > 0 ? x : -x | x if x > 0 else -x | $x > 0 ? $x : -$x |
arithmetic and logic | |||
true and false | true false | True False | TRUE FALSE # case insensitive |
falsehoods | false null undefined ” 0 NaN | False None 0 0.0 ” [] {} | FALSE NULL 0 0.0 “” “0” [] |
logical operators | && || ! | and or not | && || ! lower precedence: and or xor |
relational operators | === !== < > >= <= perform type coercion: == != | relational operators are chainable: == != > < >= <= | == != or <> > < >= <= no conversion: === !== |
min and max | Math.min(1, 2, 3) Math.max(1, 2, 3)Math.min.apply(Math, [1, 2, 3]) Math.max.apply(Math, [1, 2, 3]) | min(1, 2, 3) max(1, 2, 3)min([1, 2, 3]) max([1, 2, 3]) | min(1, 2, 3) max(1, 2, 3) $a = [1, 2, 3] min($a) max($a) |
arithmetic operators addition, subtraction, multiplication, float division, quotient, remainder | + – * / none % | + – * / // % In Python 2, / performs integer division. | + – * / none % |
integer division | Math.floor(22 / 7) | 22 // 7 | (int)(22 / 7) |
divmod | none | q, r = divmod(22, 7) | none |
integer division by zero | Returns Infinity, NaN, or -Infinity depending upon sign of dividend. There are literals for Infinity and NaN. | raises ZeroDivisionError | returns FALSE with warning |
float division | 22 / 7 | 22 / 7 # Python 2: float(22) / 7 | 22 / 7 |
float division by zero | same behavior as for integers | raises ZeroDivisionError | returns FALSE with warning |
power | Math.pow(2, 32) | 2 ** 32 | pow(2, 32) |
sqrt | Math.sqrt(2) | import math math.sqrt(2) | sqrt(2) |
sqrt -1 | NaN | # raises ValueError: import math math.sqrt(-1)# returns complex float: import cmath cmath.sqrt(-1) | NaN |
transcendental functions | Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2 | from math import exp, log, \ sin, cos, tan, asin, acos, atan, atan2 | exp log sin cos tan asin acos atan atan2 |
transcendental constants π and e | Math.PI Math.E | import math math.pi math.e | M_PI M_E |
float truncation | none Math.round(3.1) Math.floor(3.1) Math.ceil(3.1) | import math int(x) int(round(x)) math.ceil(x) math.floor(x) | (int)$x round($x) ceil($x) floor($x) |
absolute value | Math.abs(-3) | abs(x) | abs($x) |
integer overflow | all numbers are floats | becomes arbitrary length integer of type long | converted to float |
float overflow | Infinity | raises OverflowError | INF |
rational construction | none | from fractions import Fraction x = Fraction(22, 7) | none |
rational decomposition | none | x.numerator x.denominator | none |
complex construction | none | z = 1 + 1.414j | none |
complex decomposition real and imaginary component, argument, absolute value, conjugate | none | import cmath z.real z.imag cmath.phase(z) abs(z) z.conjugate() | none |
random number uniform integer, uniform float, normal float | Math.floor(Math.random() * 100) Math.random() none | import random random.randint(0, 99) | rand(0,99) lcg_value() none |
random seed set, get, restore | none | import random random.seed(17) seed = random.getstate() random.setstate(seed) | srand(17); none |
bit operators | << >> & | ^ ~ | << >> & | ^ ~ | << >> & | ^ ~ |
binary, octal, and hex literals | none 052 // deprecated 0x2a | 0b101010 0o52# also 052 in Python 2 0x2a | 0b101010 052 0x2a |
radix convert integer to and from string with radix | (42).toString(7) parseInt(’60’, 7) | none int(’60’, 7) | base_convert(“42”, 10, 7); base_convert(“60”, 7, 10); |
Strings | |||
string type | String | str # Python 2: | # array of bytes: string |
string literal | ‘don\’t say “no”‘ “don’t say \”no\”” | ‘don\’t say “no”‘ “don’t say \”no\”” “don’t ” ‘say “no”‘# Python 2 (and Python 3): u’lorem’ u”ipsum” | “don’t say \”no\”” ‘don\’t say “no”‘ |
newline in literal | // backquote literals only: `first line second line`// Backslashes can be used to break // long strings. | # triple quote literals only: ”’first line second line”'”””first line second line””” | ‘first line second line'”first line second line” |
literal escapes | single and double quotes: \b \f \n \r \t \v \xhh \” \’ \\ \uhhhh \u{hhhhh} | \newline \\ \’ \” \a \b \f \n \r \t \v \ooo \xhh \uhhhh \Uhhhhhhhh In Python 2, \u and \U only available in string literals with u prefix | double quoted: \f \n \r \t \v \xhh \$ \” \\ \ooosingle quoted: \’ \\ |
variable interpolation | let count = 3; let item = ‘ball’; let s = `${count} ${item}s`; | count = 3 item = ‘ball’ print(‘{count} {item}s’.format( **locals()))# Python 3.6: print(f'{count} {item}s’) | $count = 3; $item = “ball”; echo “$count ${item}s\n”; |
expression interpolation | `1 + 1 = ${1 + 1}` | ‘1 + 1 = {}’.format(1 + 1) # Python 3.6: f’1 + 1 = {1 + 1}’ | none |
format string | // None; use string concatenation. // Evaluates to “12.35”: 12.3456.toFixed(2) | ‘lorem %s %d %f’ % (‘ipsum’, 13, 3.7) fmt = ‘lorem {0} {1} {2}’ | $fmt = “lorem %s %d %f”; sprintf($fmt, “ipsum”, 13, 3.7); |
are strings mutable? | no | no | $s = “bar”; $s2 = $s; # sets s to “baz”; s2 is unchanged: $s[2] = “z”; |
copy string | none | none | $s2 = $s; |
concatenate | s = ‘Hello, ‘ + ‘World!’; | s = ‘Hello, ‘ s2 = s + ‘World!’# juxtaposition can be used to # concatenate literals: s2 = ‘Hello, ‘ “World!” | $s = “Hello, “; $s2 = $s . “World!”; |
replicate | let hbar = _.repeat(‘-‘, 80); | hbar = ‘-‘ * 80 | $hbar = str_repeat(“-“, 80); |
translate case to upper, to lower | ‘lorem’.toUpperCase() ‘LOREM’.toLowerCase() | ‘lorem’.upper() ‘LOREM’.lower() | mb_strtoupper(“lorem”) mb_strtolower(“LOREM”) # strtoupper/strtolower are ASCII only |
capitalize string, words | _.capitalize(‘lorem’); none | import string ‘lorem’.capitalize() | # ASCII only: ucfirst(strtolower(“lorem”)) ucwords(strtolower(“lorem ipsum”)) # Unicode title case: mb_convert_case(“lorem ipsum”, MB_CASE_TITLE) |
trim both sides, left, right | ‘ lorem ‘.trim() ‘ lorem’.trimLeft() ‘lorem ‘.trimRight() | ‘ lorem ‘.strip() ‘ lorem’.lstrip() ‘lorem ‘.rstrip() | trim(” lorem “) ltrim(” lorem”) rtrim(“lorem “) |
pad on right, on left, centered | _.padStart(‘lorem’, 10) _.padEnd(‘lorem’, 10) _.pad(‘lorem’, 10) | ‘lorem’.ljust(10) ‘lorem’.rjust(10) ‘lorem’.center(10) | $s = “lorem”; $delta = strlen($s) – mb_strlen($s); str_pad($s, 10 + $delta) str_pad(“$s, 10 + $delta, ” “, STR_PAD_LEFT) str_pad($s, 10 + $delta, ” “, STR_PAD_BOTH) |
number to string | ‘value: ‘ + 8 | ‘value: ‘ + str(8) | “value: ” . 8 |
format float | ” + Math.round(Math.PI * 100) / 100 | import math ‘%.2f’ % math.pi | number_format(M_PI, 2) |
string to number | 7 + parseInt(’12;, 10) 73.9 + parseFloat(‘.037’)// 12: parseInt(’12A’) // NaN: parseInt(‘A’) | 7 + int(’12’) 73.9 + float(‘.037’)# raises ValueError: int(’12A’) # raises ValueError: int(‘A’) | 7 + “12” 73.9 + “.037”# 12: 0 + “12A” # 0: 0 + “A” |
string join | [‘do’, ‘re’, ‘mi’].join(‘ ‘) | ‘ ‘.join([‘do’, ‘re’, ‘mi’, ‘fa’]) # raises TypeError: | $a = [“do”, “re”, “mi”, “fa”]; implode(” “, $a) |
split | // [ ‘do’, ‘re’, ”, ‘mi’, ” ]: ‘do remi ‘.split(‘ ‘)// [ ‘do’, ‘re’, ‘mi’, ” ]: ‘do remi ‘.split(/\s+/) | # [‘do’, ‘re’, ”, ‘mi’, ”]: ‘do remi ‘.split(‘ ‘)# [‘do’, ‘re’, ‘mi’]: ‘do remi ‘.split() | # [ “do”, “re”, “”, “mi”, “” ]: explode(” “, “do remi “)# [ “do”, “re”, “mi”, “” ]: preg_split(‘/\s+/’, “do remi “) |
split in two | ‘do re mi fa’.split(/\s+/, 2) | ‘do re mi fa’.split(None, 1) | preg_split(‘/\s+/’, “do re mi fa”, 2) |
split and keep delimiters | none | re.split(‘(\s+)’, ‘do re mi fa’) | preg_split(‘/(\s+)/’, “do re mi fa”, NULL, PREG_SPLIT_DELIM_CAPTURE) |
prefix and suffix test | ‘foobar’.startsWith(‘foo’) ‘foobar’.endsWith(‘bar’) | ‘foobar’.startswith(‘foo’) ‘foobar’.endswith(‘bar’) | |
length | ‘lorem’.length | len(‘lorem’) | mb_strlen(“lorem”) # strlen() counts bytes |
index of substring first, last | // returns -1 if not found: ‘lorem ipsum’.indexOf(‘ipsum’) | # raises ValueError if not found: ‘do re re’.index(‘re’) ‘do re re’.rindex(‘re’)# returns -1 if not found: ‘do re re’.find(‘re’) ‘do re re’.rfind(‘re’) | # returns FALSE if not found: mb_strpos(“do re re”, “re”) mb_strrpos(“do re re”, “re”) |
extract substring by start and length, by start and end, by successive starts | ‘lorem ipsum’.substr(6, 5) ‘lorem ipsum’.substring(6, 11) | none none ‘lorem ipsum'[6:11] | mb_substr(“lorem ipsum”, 6, 5) none none |
byte array type | Buffer | bytes # In Python 2, str also byte array type | string |
byte array to string | let a = Buffer.from([0xce, 0xbb]); let s = a.toString(‘utf-8’); | s = b’\xce\xbb’.decode(‘utf-8’) | strings are byte arrays |
string to byte array | a = Buffer.from(‘\u03bb’) | a = ‘\u03bb’.encode(‘utf-8’) # Python 2: a = u’\u03bb’.encode(‘utf-8’) | strings are byte arrays |
character lookup | ‘lorem ipsum'[6] | ‘lorem ipsum'[6] | mb_substr(“lorem ipsum”, 6, 1) # byte lookup: “lorem ipsum”[6] |
chr and ord | String.fromCharCode(65) ‘A’.charCodeAt(0) | chr(65) ord(‘A’) | # ASCII only: chr(65) ord(“A”) |
to array of characters | ‘abcd’.split(”) | list(‘abcd’) | str_split(“abcd”) |
translate characters | none | from string import ascii_lowercase ins = ascii_lowercase outs = ins[13:] + ins[:13] table = str.maketrans(ins, outs) ‘hello’.translate(table) | $ins = implode(range(“a”, “z”)); $outs = substr($ins, 13, 13) . substr($ins, 0, 13); strtr(“hello”, $ins, $outs) |
delete characters | none | table = {ord(ch): None for ch in “aeiou”} “disemvowel me”.translate(table) | $vowels = str_split(“aeiou”); $s = “disemvowel me”; $s = str_replace($vowels, “”, $s); |
squeeze characters | none | re.sub(‘(\s)+’, r’\1′, ‘too much space’) | $s = “too much space”; $s = = preg_replace(‘/(\s)+/’, ‘\1’, $s); |
regular expressions | |||
literal, custom delimited literal | /lorem|ipsum/ | re.compile(r’lorem|ipsum’) none | ‘/lorem|ipsum/’ ‘(/etc/hosts)’ |
ascii character class abbreviations | . [^\n] \d[0-9] \D[^0-9] \s[ \t\r\n\f] \S[^ \t\r\n\f] \w[A-Za-z0-9_] \W[^A-Za-z0-9_] | . [^\n]with re.S modifier matches all chars \d[0-9] \D[^0-9] \s[ \t\r\n\f] \S[^ \t\r\n\f] \w[A-Za-z0-9_] \W[^A-Za-z0-9_]In Python 3, the above definitions are used when re.A is in effect. | . [^\n] \d[0-9] \D[^0-9] \h[ \t] \H[^ \t] \s[ \t\r\n\f] \S[^ \t\r\n\f] \w[A-Za-z0-9_] \W[^A-Za-z0-9_] |
unicode character class abbreviations | none | . [^\n]with re.S modifier matches all chars \d[Nd]Nd: Number, decimal digit \D[^Nd] \s[Z\t\n\r\f\v\x1c\x1d\x1e\x1f\x85] \S[^Z\t\n\r\f\v\x1c\x1d\x1e\x1f\x85] \w [LN_]L: Letter; N: Number \W [^LN_]In Python 2, the above definitions are used when re.U is in effect. | POSIX character classes such as [[:alpha:]] are available, but they match sets of ASCII characters. General category values (e.g. \p{L}, \p{Lu}) can be used. Morever, they can be used inside character classes (.e.g. [\p{L}\p{N}]). |
anchors | ^ start of string or line with m modifier $ end of string or line with m modifier \bword boundary: \w\W or \W\w \Bnon word boundary | ^ start of string or line with re.M $ end of string or line with re.M \Astart of string \bword boundary: \w\W or \W\w \Bnon word boundary \Zend of string | ^ start of string or line with m modifier $ end of string or line with m modifier \Astart of string \bword boundary: \w\W or \W\w \Bnon word boundary \zend of string \Zend of string, excluding final newline |
match test | if (s.match(/1999/)) { console.log(‘party!’); } | if re.search(‘1999’, s): print(‘party!’) | if (preg_match(‘/1999/’, $s)) { echo “party!\n”; } |
case insensitive match test | ‘Lorem’.match(/lorem/i) | re.search(‘lorem’, ‘Lorem’, re.I) | preg_match(‘/lorem/i’, “Lorem”) |
modifiers | gused for global substitution and scanning imake case insensitive mchange meaning of ^ and $ u\u{} syntax and astral character support yused to scan in loop | re.Achange meaning of \b \B \d \D \s \S \w \W re.Imake case insensitive re.Mchange meaning of ^ and $ re.Schange meaning of . re.Xignore whitespace outside char class | imake case insensitive mchange meaning of ^ and $ schange meaning of . xignore whitespace outside char class |
substitution | s = ‘do re mi mi mi’; s.replace(/mi/g, ‘ma’); | s = ‘do re mi mi mi’ s = re.compile(‘mi’).sub(‘ma’, s) | $s = “do re mi mi mi”; $s = preg_replace(‘/mi/’, “ma”, $s); |
match, prematch, postmatch | m = /\d{4}/.exec(s); if (m) { match = m[0]; // no prematch or postmatch } | m = re.search(‘\d{4}’, s) if m: match = m.group() prematch = s[0:m.start(0)] postmatch = s[m.end(0):len(s)] | none |
group capture | rx = /^(\d{4})-(\d{2})-(\d{2})$/; m = rx.exec(‘2009-06-03’); yr = m[1]; mo = m[2]; dy = m[3]; | rx = ‘(\d{4})-(\d{2})-(\d{2})’ m = re.search(rx, ‘2010-06-03’) yr, mo, dy = m.groups() | $s = “2010-06-03”; $rx = ‘/(\d{4})-(\d{2})-(\d{2})/’; preg_match($rx, $s, $m); list($_, $yr, $mo, $dy) = $m; |
named group capture | none | rx = ‘^(?P<file>.+)\.(?P<suffix>.+)$’ m = re.search(rx, ‘foo.txt’)m.groupdict()[‘file’] m.groupdict()[‘suffix’] | $s = “foo.txt”; $rx = ‘/^(?P<file>.+)\.(?P<suffix>.+)$/’; preg_match($rx, $s, $m);$m[“file”] $m[“suffix”] |
scan | let a = ‘dolor sit amet’.match(/\w+/g); | s = ‘dolor sit amet’ a = re.findall(‘\w+’, s) | $s = “dolor sit amet”; preg_match_all(‘/\w+/’, $s, $m); $a = $m[0]; |
backreference in match and substitution | /(\w+) \1/.exec(‘do do’) ‘do re’.replace(/(\w+) (\w+)/, ‘$2 $1’) | none rx = re.compile(‘(\w+) (\w+)’) rx.sub(r’\2 \1′, ‘do re’) | preg_match(‘/(\w+) \1/’, “do do”) $s = “do re”; $rx = ‘/(\w+) (\w+)/’; $s = preg_replace($rx, ‘\2 \1’, $s); |
dates and time | |||
broken-down datetime type | Date | datetime.datetime | DateTime |
current datetime | let t = new Date(); | import datetime t = datetime.datetime.now() utc = datetime.datetime.utcnow() | $t = new DateTime(“now”); $utc_tmz = new DateTimeZone(“UTC”); $utc = new DateTime(“now”, $utc_tmz); |
current unix epoch | (new Date()).getTime() / 1000 | import datetime t = datetime.datetime.now() epoch = int(t.strftime(“%s”)) | $epoch = time(); |
broken-down datetime to unix epoch | Math.round(t.getTime() / 1000) | from datetime import datetime as dt epoch = int(t.strftime(“%s”)) | $epoch = $t->getTimestamp(); |
unix epoch to broken-down datetime | let epoch = 1315716177; let t2 = new Date(epoch * 1000); | t = dt.fromtimestamp(1304442000) | $t2 = new DateTime(); $t2->setTimestamp(1304442000); |
format datetime | // npm install moment let moment = require(‘moment’);let t = moment(new Date()); let fmt = ‘YYYY-MM-DD HH:mm:ss’; console.log(t.format(fmt)); | t.strftime(‘%Y-%m-%d %H:%M:%S’) | strftime(“%Y-%m-%d %H:%M:%S”, $epoch); date(“Y-m-d H:i:s”, $epoch); $t->format(“Y-m-d H:i:s”); |
parse datetime | // npm install moment let moment = require(‘moment’);let fmt = ‘YYYY-MM-DD HH:mm:ss’; let s = ‘2011-05-03 10:00:00’; let t = moment(s, fmt); | from datetime import datetime s = ‘2011-05-03 10:00:00’ fmt = ‘%Y-%m-%d %H:%M:%S’ t = datetime.strptime(s, fmt) | $fmt = “Y-m-d H:i:s”; $s = “2011-05-03 10:00:00”; $t = DateTime::createFromFormat($fmt, $s); |
parse datetime w/o format | let t = new Date(‘July 7, 1999’); | # pip install python-dateutil import dateutil.parsers = ‘July 7, 1999’ t = dateutil.parser.parse(s) | $epoch = strtotime(“July 7, 1999”); |
date parts | t.getFullYear() t.getMonth() + 1 t.getDate() // getDay() is day of week | t.year t.month t.day | (int)$t->format(“Y”) (int)$t->format(“m”) (int)$t->format(“d”) |
time parts | t.getHours() t.getMinutes() t.getSeconds() | t.hour t.minute t.second | (int)$t->format(“H”) (int)$t->format(“i”) (int)$t->format(“s”) |
build broken-down datetime | let yr = 1999; let mo = 9; let dy = 10; let hr = 23; let mi = 30; let ss = 0; let t = new Date(yr, mo – 1, dy, hr, mi, ss); | import datetime yr = 1999 mo = 9 dy = 10 hr = 23 mi = 30 ss = 0 t = datetime.datetime(yr, mo, dy, hr, mi, ss) | |
datetime subtraction | number containing time difference in milliseconds | datetime.timedelta object use total_seconds() method to convert to float representing difference in seconds | # DateInterval object if diff method used: $fmt = “Y-m-d H:i:s”; $s = “2011-05-03 10:00:00”; $then = DateTime::createFromFormat($fmt, $s); $now = new DateTime(“now”); $interval = $now->diff($then); |
add duration | let t1 = new Date(); let delta = (10 * 60 + 3) * 1000; let t2 = new Date(t1.getTime() + delta); | import datetime delta = datetime.timedelta( minutes=10, seconds=3) t = datetime.datetime.now() + delta | $now = new DateTime(“now”); $now->add(new DateInterval(“PT10M3S”); |
nonlocal time zone | # pip install pytz import pytz import datetimetmz = pytz.timezone(‘Asia/Tokyo’) utc = datetime.datetime.utcnow() utc_dt = datetime.datetime( *utc.timetuple()[0:6], tzinfo=pytz.utc) jp_dt = utc_dt.astimezone(tmz) | ||
time zone info name and UTC offset | import time tm = time.localtime() time.tzname[tm.tm_isdst] (time.timezone / -3600) + tm.tm_isdst | $tmz = date_timezone_get($t); timezone_name_get($tmz); date_offset_get($t) / 3600; | |
daylight savings test | // npm install moment let moment = require(‘moment’);moment(new Date()).isDST() | import time tm = time.localtime() tm.tm_isdst | $t->format(“I”); |
microseconds | t.getMilliseconds() * 1000 // [sec, nanosec] since system boot: | t.microsecond | list($frac, $sec) = explode(” “, microtime()); $usec = $frac * 1000 * 1000; |
Arrays | |||
literal | a = [1, 2, 3, 4] | a = [1, 2, 3, 4] | $a = [1, 2, 3, 4]; # older syntax: $a = array(1, 2, 3, 4); |
size | a.length | len(a) | count($a) |
empty test | // TypeError if a is null or undefined: a.length === 0 | # None tests as empty: not a | # NULL tests as empty: !$a |
lookup | a[0] | a[0] # returns last element: a[-1] | $a[0] # PHP uses the same type for arrays and # dictionaries; indices can be negative # integers or strings |
update | a[0] = ‘lorem’ | a[0] = ‘lorem’ | $a[0] = “lorem”; |
out-of-bounds behavior | returns undefined | a = [] # raises IndexError: a[10] # raises IndexError: a[10] = ‘lorem’ | $a = []; # evaluates as NULL: $a[10]; # increases array size to one: $a[10] = “lorem”; |
element index first and last occurrence | // return -1 if not found: [6, 7, 7, 8].indexOf(7) [6, 7, 7, 8].lastIndexOf(7) | a = [‘x’, ‘y’, ‘y’, ‘z’] # raises ValueError if not found: a.index(‘y’) none | $a = [“x”, “y”, “y”, “z”]; # returns FALSE if not found: |
slice by endpoints, by length | // select 3rd and 4th elements: [‘a’, ‘b’, ‘c’, ‘d’].slice(2, 4) none | # select 3rd and 4th elements: a[2:4] a[2:2 + 2] | # select 3rd and 4th elements: none array_slice($a, 2, 2) |
slice to end | [‘a’, ‘b’, ‘c’, ‘d’].slice(1) | a[1:] | array_slice($a, 1) |
manipulate back | a = [6, 7, 8]; a.push(9); i = a.pop(); | a = [6, 7, 8] a.append(9) a.pop() | $a = [6, 7, 8]; array_push($a, 9); $a[] = 9; # same as array_push array_pop($a); |
manipulate front | a = [6, 7, 8]; a.unshift(5); i = a.shift(); | a = [6, 7, 8] a.insert(0, 5) a.pop(0) | $a = [6, 7, 8]; array_unshift($a, 5); array_shift($a); |
concatenate | a = [1, 2, 3].concat([4, 5, 6]); | a = [1, 2, 3] a2 = a + [4, 5, 6] a.extend([4, 5, 6]) | $a = [1, 2, 3]; $a2 = array_merge($a, [4, 5, 6]); $a = array_merge($a, [4, 5, 6]); |
replicate | Array(10).fill(null) | a = [None] * 10 a = [None for i in range(0, 10)] | $a = array_fill(0, 10, NULL); |
copy address copy, shallow copy, deep copy | a = [1, 2, [3, 4]]; a2 = a; a3 = a.slice(0); a4 = JSON.parse(JSON.stringify(a)); | import copy a = [1,2,[3,4]] a2 = a a3 = list(a) a4 = copy.deepcopy(a) | $a = [1, 2, [3, 4]]; $a2 =& $a; none $a4 = $a; |
iterate over elements | [6, 7, 8].forEach((n) => { console.log(n); });// new in ES6: for (let n of [6, 7, 8]) { console.log(n); } | for i in [1, 2, 3]: print(i) | foreach ([1, 2, 3] as $i) { echo “$i\n”; } |
iterate over indices and elements | for (let i = 0; i < a.length; ++i) { console.log(a[i]); }// indices not guaranteed to be in order: for (let i in a) { console.log(a[i]); } | a = [‘do’, ‘re’, ‘mi’, ‘fa’] for i, s in enumerate(a): print(‘%s at index %d’ % (s, i)) | $a = [“do”, “re”, “mi” “fa”]; foreach ($a as $i => $s) { echo “$s at index $i\n”; } |
iterate over range | not space efficient; use C-style for loop | # use range() in Python 3: for i in xrange(1, 1000001): code | not space efficient; use C-style for loop |
instantiate range as array | let a = _.range(1, 11); | a = range(1, 11) Python 3: a = list(range(1, 11)) | $a = range(1, 10); |
reverse non-destructive, in-place | let a = [1, 2, 3]; let a2 = a.slice(0).reverse(); a.reverse(); | a = [1, 2, 3] a[::-1] a.reverse() | $a = [1, 2, 3]; array_reverse($a); $a = array_reverse($a); |
sort non-destructive, in-place, custom comparision | let a = [3, 1, 4, 2]; let a2 = a.slice(0).sort(); a.sort(); | a = [‘b’, ‘A’, ‘a’, ‘B’] sorted(a) a.sort() # custom binary comparision # removed from Python 3: a.sort(key=str.lower) | $a = [“b”, “A”, “a”, “B”]; none |
dedupe non-destructive, in-place | let a = [1, 2, 2, 3]; let a2 = _.uniq(a); a = _.uniq(a); | a = [1, 2, 2, 3] a2 = list(set(a)) a = list(set(a)) | $a = [1, 2, 2, 3]; $a2 = array_unique($a); $a = array_unique($a); |
membership | a.includes(7) | 7 in a | in_array(7, $a) |
intersection | _.intersection([1, 2], [2, 3, 4]) | {1, 2} & {2, 3, 4} | $a = [1, 2]; $b = [2, 3, 4] array_intersect($a, $b) |
union | _.union([1, 2], [2, 3, 4]) | {1, 2} | {2, 3, 4} | $a1 = [1, 2]; $a2 = [2, 3, 4]; array_unique(array_merge($a1, $a2)) |
relative complement, symmetric difference | _.difference([1, 2, 3], [2]) none | {1, 2, 3} – {2} {1, 2} ^ {2, 3, 4} | $a1 = [1, 2, 3]; $a2 = [2]; array_values(array_diff($a1, $a2)) none |
map | // callback gets 3 args: // value, index, array a.map((x) => x * x) | map(lambda x: x * x, [1, 2, 3]) # or use list comprehension: [x * x for x in [1, 2, 3]] | array_map(function ($x) { return $x * $x; }, [1, 2, 3]) |
filter | a.filter((x) => x > 1) | filter(lambda x: x > 1, [1, 2, 3]) # or use list comprehension: [x for x in [1, 2, 3] if x > 1] | array_filter([1, 2, 3], function ($x) { return $x>1; }) |
reduce | a.reduce((m, o) => m + o, 0) | # import needed in Python 3 only from functools import reducereduce(lambda x, y: x + y, [1, 2, 3], 0) | array_reduce([1, 2, 3], function($x,$y) { return $x + $y; }, 0) |
universal and existential tests | let a = [1, 2, 3, 4]; a.every((n) => n % 2 === 0) a.some((n) => n % 2 === 0) | all(i % 2 == 0 for i in [1, 2, 3, 4]) any(i % 2 == 0 for i in [1, 2, 3, 4]) | use array_filter |
shuffle and sample | let a = [1, 2, 3, 4]; a = _.shuffle(a); let samp = _.sampleSize([1, 2, 3, 4], 2); | from random import shuffle, sample a = [1, 2, 3, 4] shuffle(a) samp = sample([1, 2, 3, 4], 2) | $a = [1, 2, 3, 4]; shuffle($a); $samp = array_rand(|[1, 2, 3, 4], 2); |
flatten one level, completely | let a = [1, [2, [3, 4]]]; let a2 = _.flatten(a); let a3 = _.flattenDeep(a); | none | none |
zip | let a = _.zip([1, 2, 3], [‘a’, ‘b’, ‘c’]); // shorter array padded with undefined: | list(zip([1, 2, 3], [‘a’, ‘b’, ‘c’])) # extras in longer array dropped: | $a = array_map(NULL, [1, 2, 3], [“a”, “b”, “c”]);# shorter array padded with NULLs |
Dictionaries | |||
literal | d = {t: 1, f: 0}; | d = {‘t’: 1, ‘f’: 0} | $d = [“t” => 1, “f” => 0]; # older syntax: $d = array(“t” => 1, “f” => 0); |
size | _.size(d) Object.getOwnPropertyNames(d).length | len(d) | count($d) |
lookup | d.hasOwnProperty(“t”) ? d[“t”] : undefined d.hasOwnProperty(“t”) ? d.t : undefined | d[‘t’] | $d[“t”] |
update | d[‘t’] = 2; d.t = 2; | d[‘t’] = 2 # provide default to avoid KeyError: | $d[“t”] = 2; |
missing key behavior | let d = {}; // undefined: d[“lorem”]; // adds key/value pair: d[“lorem”] = “ipsum”; | d = {} # raises KeyError: d[‘lorem’] # adds key/value pair: d[‘lorem’] = ‘ipsum’ | $d = []; # NULL: $d[“lorem”]; # adds key/value pair: $d[“lorem”] = “ipsum”; |
is key present | d.hasOwnProperty(“t”); | ‘y’ in d | array_key_exists(“y”, $d); |
delete | delete d[“t”]; delete d.t; | d = {1: True, 0: False} del d[1] | $d = [1 => “t”, 0 => “f”]; unset($d[1]); |
from array of pairs, from even length array | let a = [[‘a’, 1], [‘b’, 2], [‘c’, 3]]; let d = _.fromPairs(a);none | a = [[‘a’, 1], [‘b’, 2], [‘c’, 3]] d = dict(a)a = [‘a’, 1, ‘b’, 2, ‘c’, 3] d = dict(zip(a[::2], a[1::2])) | |
merge | let d1 = {a: 1, b: 2}; let d2 = {b: 3, c: 4}; // d2 overwrites shared keys in d1: d1 = _.assignIn(d1, d2); | d1 = {‘a’: 1, ‘b’: 2} d2 = {‘b’: 3, ‘c’: 4} d1.update(d2) | $d1 = [“a” => 1, “b” => 2]; $d2 = [“b” => 3, “c” => 4]; $d1 = array_merge($d1, $d2); |
invert | let let2num = {t: 1, f: 0}; let num2let = _.invert(let2num); | to_num = {‘t’: 1, ‘f’: 0} # dict comprehensions added in 2.7: to_let = {v: k for k, v in to_num.items()} | $to_num = [“t” => 1, “f” => 0]; $to_let = array_flip($to_num); |
iterate | for (let k in d) { console.log(`value at ${k} is ${d[k]}`); } | for k, v in d.items(): print(‘value at {} is {}’.format(k, v)# Python 2: use iteritems() | foreach ($d as $k => $v) { echo “value at ${k} is ${v}”; } |
keys and values as arrays | Object.keys(d) _.values(d) | list(d.keys()) list(d.values())# keys() and values return iterators # in Python 3 and lists in Python 2 | array_keys($d) array_values($d) |
sort by values | let cmp = (a, b) => a[1] – b[1]; let d = {t: 1, f: 0};for (let p of _.toPairs(d).sort(cmp)) { console.log(p); } | from operator import itemgetter pairs = sorted(d.items(), key=itemgetter(1)) for k, v in pairs: print(‘{}: {}’.format(k, v)) | asort($d); foreach ($d as $k => $v) { print “$k: $v\n”; } |
none | from collections import defaultdict counts = defaultdict(lambda: 0) counts[‘foo’] += 1 class Factorial(dict): def __missing__(self, k): if k > 1: return k * self[k-1] else: return 1 factorial = Factorial() | $counts = []; $counts[‘foo’] += 1;# For computed values and defaults other than # zero or empty string, extend ArrayObject. | |
Functions | |||
define | function add3 (x1, x2, x3) { return x1 + x2 + x3; } | def add3(x1, x2, x3): return x1 + x2 + x3 | function add3($x1, $x2, $x3) { return $x1 + $x2 + $x3; } |
invoke | add3(1, 2, 3) | add3(1, 2, 3) | add3(1, 2, 3); # function names are case insensitive: ADD3(1, 2, 3); |
default argument | // new in ES6: function myLog (x, base = 10) { return Math.log(x) / Math.log(base); } | import math def my_log(x, base=10): return math.log(x) / math.log(base) my_log(42) my_log(42, math.e) | function my_log($x, $base=10) { return log($x) / log($base); }my_log(42); my_log(42, M_E); |
variadic function | function firstAndLast() { if (arguments.length >= 1) { console.log(‘first: ‘ + arguments[0]); } if (arguments.length >= 2) { console.log(‘last: ‘ + arguments[1]); } }// … operator new in ES6: function firstAndLast(…a) { if (a.length >= 1) { console.log(‘first: ‘ + a[0]); } if (a.length >= 2) { console.log(‘last: ‘ + a[1]); } } | def first_and_last(*a): if len(a) >= 1: if len(a) >= 2: | function first_and_last() {$arg_cnt = func_num_args();if ($arg_cnt >= 1) { $n = func_get_arg(0); echo “first: ” . $n . “\n”; }if ($arg_cnt >= 2) { $a = func_get_args(); $n = $a[$arg_cnt-1]; echo “last: ” . $n . “\n”; } } |
pass array elements as separate arguments | let a = [1, 2, 3]; let sum = add3(…a); | a = [2, 3] add3(1, *a) # splat operator can only be used once # and must appear after other # unnamed arguments | $a = [1, 2, 3]; call_user_func_array(“add3”, $a); |
parameter alias | none | none | function first_and_second(&$a) { return [$a[0], $a[1]]; } |
named parameters | none | def fequal(x, y, eps=0.01): return abs(x – y) < epsfequal(1.0, 1.001) fequal(1.0, 1.001, eps=0.1**10) | none |
multiple return values | function firstAndSecond(a) { return [a[0], a[1]]; }let [x, y] = firstAndSecond([6, 7, 8]); | def first_and_second(a): return a[0], a[1]x, y = first_and_second([6, 7, 8]) | function first_and_second(&$a) { return [$a[0], $a[1]]; }$a = [6, 7, 8]; list($x, $y) = first_and_second($a); |
anonymous function literal | let square = function (x) { return x * x; };// => new in ES6: let square = (x) => { return x * x; };// expression body variant: let square = (x) => x * x; | # body must be an expression: square = lambda x: x * x | $square = function ($x) { return $x * $x; }; |
invoke anonymous function | square(2) ((x) => (x * x)(2) | square(2) (lambda x: x * x)(2) | $square(2) |
function as value | let func = add3; | func = add3 | $func = “add3”; |
function with private state | function counter() { counter.i += 1; return counter.i; }counter.i = 0; console.log(counter()); | # state not private: def counter(): counter.i += 1 return counter.icounter.i = 0 print(counter()) | function counter() { static $i = 0; return ++$i; }echo counter(); |
closure | function makeCounter () { let i = 0;return function () { i += 1; return i; }; }let nays = makeCounter(); console.log(nays()); | def make_counter(): i = 0 def counter(): # new in Python 3: nonlocal i i += 1 return i return counternays = make_counter() print(nays()) | function make_counter() { $i = 0; return function () use (&$i) { return ++$i; }; }$nays = make_counter(); echo $nays(); |
generator | function * makeCounter () { let i = 0; while (true) { yield ++i; } }let nays = makeCounter(); for (let cnt of nays) { console.log(cnt); if (cnt > 100) { break; } } | # cf. itertools library def make_counter(): | # PHP 5.5: function make_counter() { $i = 0; while (1) { yield ++$i; } }$nays = make_counter(); # does not return a value: $nays->next(); # runs generator if generator has not # yet yielded: echo $nays->current(); |
decorator | none | def logcall(f): def wrapper(*a, **opts): print(‘calling ‘ + f.__name__) f(*a, **opts) print(‘called ‘ + f.__name__) return wrapper@logcall def square(x): return x * x | |
execution control | |||
if | if (n === 0) { console.log(‘no hits’); } else if (n === 1) { console.log(‘1 hit’); } else { console.log(n + ‘ hits’); } | if 0 == n: print(‘no hits’) elif 1 == n: print(‘one hit’) else: print(str(n) + ‘ hits’) | if ( 0 == $n ) { echo “no hits\n”; } elseif ( 1 == $n ) { echo “one hit\n”; } else { echo “$n hits\n”; } |
switch | switch (n) { case 0: console.log(‘no hits\n;); break; case 1: console.log(‘one hit\n’); break; default: console.log(n + ‘ hits\n’); } | none | switch ($n) { case 0: echo “no hits\n”; break; case 1: echo “one hit\n”; break; default: echo “$n hits\n”; } |
while | while (i < 100) { i += 1; } | while i < 100: i += 1 | while ( $i < 100 ) { $i++; } |
for | for (let i = 0; i < 10; ++i) { console.log(i); } | for i in range(1, 11): print(i) | for ($i = 1; $i <= 10; $i++) { echo “$i\n”; } |
break | for (let i = 30; i < 50; ++i) { if (i % 7 === 0) { console.log(‘first multiple: ‘ + i); break; } } | break | break |
continue | for (let i = 30; i < 50; ++i) { if (i % 7 === 0) { continue; } console.log(‘not divisible: ‘ + i); } | continue | continue |
Exceptions | |||
base exception | Any value can be thrown. | BaseException User-defined exceptions should subclass Exception. In Python 2 old-style classes can be thrown. | Exception |
raise exception | throw new Error(“bad arg”); | raise Exception(‘bad arg’) | throw new Exception(“bad arg”); |
catch-all handler | try { risky(); } catch (e) { console.log( ‘risky failed: ‘ + e.message); } | try: risky() except: print(‘risky failed’) | try { risky(); } catch (Exception $e) { echo “risky failed: “, $e->getMessage(), “\n”; } |
re-raise exception | try { throw new Error(“bam!”); } catch (e) { console.log(‘re-raising…‘); throw e; } | try: raise Exception(‘bam!’) except: print(‘re-raising…‘) raise | |
define exception | function Bam(msg) { this.message = msg; }Bam.prototype = new Error; | class Bam(Exception): def __init__(self): super(Bam, self).__init__(‘bam!’) | class Bam extends Exception { function __construct() { parent::__construct(“bam!”); } } |
handle exception | try { throw new Bam(“bam!”); } catch (e) { if (e instanceof Bam) { console.log(e.message); } else { throw e; } } | try: raise Bam() except Bam as e: print(e) | try { throw new Bam; } catch (Bam $e) { echo $e->getMessage(), “\n”; } |
finally block | acquireResource(); try { risky(); } finally { releaseResource(); } | acquire_resource() try: risky() finally: release_resource() | acquire_resource(); try { risky(); } finally { release_resource(); } |
Threads | |||
start thread | class sleep10(threading.Thread): def run(self): time.sleep(10)thr = sleep10() thr.start() | ||
wait on thread | thr.join() | ||
sleep | import time time.sleep(0.5) | # a float argument will be truncated # to an integer: sleep(1); | |
timeout | import signal, time class Timeout(Exception): pass def timeout_handler(signo, fm): raise Timeout() signal.signal(signal.SIGALRM, timeout_handler) try: signal.alarm(5) might_take_too_long() except Timeout: pass signal.alarm(0) | use set_time_limit to limit execution time of the entire script; use stream_set_timeout to limit time spent reading from a stream opened with fopen or fs |