You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

911 lines
17 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. ![Monty Python](web/image_888.jpeg)
  4. Main
  5. ----
  6. ```python
  7. if __name__ == '__main__':
  8. main()
  9. ```
  10. List
  11. ----
  12. ```python
  13. <list>[from_inclusive : to_exclusive : step_size]
  14. <list>.append(<el>)
  15. <list>.extend(<list>)
  16. <list>.sort()
  17. <list>.reverse()
  18. <list> = sorted(<list>)
  19. <list> = reversed(<list>)
  20. ```
  21. ```python
  22. sum_of_elements = sum(<list>)
  23. sorted_by_second = sorted(<list>, key=lambda el: el[1])
  24. flattened_list = [item for sublist in <list> for item in sublist]
  25. list_of_chars = list(<str>)
  26. ```
  27. ```python
  28. a.insert(index, <el>)
  29. <el> = a.pop([index])
  30. a.remove(<el>)
  31. <int> = a.index(<el>)
  32. ```
  33. Dictionary
  34. ----------
  35. ```python
  36. <dict>.items()
  37. <dict>.get(key, default)
  38. <dict>.setdefault(key, default)
  39. <dict>.update(<dict>)
  40. ```
  41. ```python
  42. collections.defaultdict(<type>) # Creates a dictionary with default values.
  43. dict(<list>) # Initiates a dict from list of key/value pairs.
  44. dict(zip(keys, values)) # Initiates a dict from two lists.
  45. {k: v for k, v in <dict>.items() if k in <list>} # Filters a dict by keys.
  46. ```
  47. ### Counter
  48. ```python
  49. >>> from collections import Counter
  50. >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  51. >>> Counter(z)
  52. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  53. ```
  54. Set
  55. ---
  56. ```python
  57. <set> = set()
  58. <set>.add(<el>)
  59. <set>.update(<set>)
  60. <set>.union(<set>)
  61. <set>.intersection(<set>)
  62. <set>.difference(<set>)
  63. <set>.issubset(<set>)
  64. <set>.issuperset(<set>)
  65. ```
  66. ### Frozenset
  67. #### Is hashable and can be used as a key in dictionary:
  68. ```python
  69. <frozenset> = frozenset()
  70. ```
  71. Range
  72. -----
  73. ```python
  74. range(to_exclusive)
  75. range(from_inclusive, to_exclusive)
  76. range(from_inclusive, to_exclusive, step_size)
  77. range(from_inclusive, to_exclusive, -step_size)
  78. ```
  79. Enumerate
  80. ---------
  81. ```python
  82. for i, <el> in enumerate(<collection> [, i_start])
  83. ```
  84. Named Tuple
  85. -----------
  86. ```python
  87. >>> Point = collections.namedtuple('Point', ['x', 'y'])
  88. >>> a = Point(1, y=2)
  89. Point(x=1, y=2)
  90. >>> a.x
  91. 1
  92. >>> getattr(a, 'y')
  93. 2
  94. ```
  95. Iterator
  96. --------
  97. #### Skips first element:
  98. ```python
  99. next(<iter>)
  100. for element in <iter>:
  101. ...
  102. ```
  103. #### Reads input until it reaches an empty line:
  104. ```python
  105. for line in iter(input, ''):
  106. ...
  107. ```
  108. #### Same, but prints a message every time:
  109. ```python
  110. from functools import partial
  111. for line in iter(partial(input, 'Please enter value'), ''):
  112. ...
  113. ```
  114. Generator
  115. ---------
  116. ```python
  117. def step(start, step):
  118. while True:
  119. yield start
  120. start += step
  121. ```
  122. ```python
  123. stepper = step(10, 2)
  124. next(stepper) # 10 (, 12, 14, ...)
  125. ```
  126. Type
  127. ----
  128. ```python
  129. type(<el>) # <class 'int'> / <class 'str'> / ...
  130. ```
  131. ```python
  132. import numbers
  133. isinstance(<el>, numbers.Number) # Integral, Real, Rational, Complex
  134. ```
  135. String
  136. ------
  137. ```python
  138. str.replace(text, old, new)
  139. <str>.split(sep=None, maxsplit=-1)
  140. <str>.strip()
  141. <str>.join(<list>)
  142. <str>.startswith(<str>)
  143. <str>.isnumeric()
  144. ```
  145. ### Print
  146. ```python
  147. print(<el> [, <el>, end='', sep='', file=<file>])
  148. ```
  149. ### Regex
  150. ```python
  151. import re
  152. re.sub(<regex>, new, text, count=0)
  153. re.search(<regex>, text) # Searches for first occurrence of pattern.
  154. re.match(<regex>, text) # Searches only at the beginning of the string.
  155. re.findall(<regex>, text)
  156. re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  157. ```
  158. **'Search' and 'match' functions return a 'Match' object. Use '.group()' method on it to get the whole match, or '.group(1)' to get the part in first bracket.**
  159. **Parameter 'flags=re.IGNORECASE' can be used with all functions. Parameter 'flags=re.DOTALL' makes dot also accept newline.**
  160. **Use '\\\\1' or r'\1' for backreference.**
  161. #### Special Sequences:
  162. ```python
  163. # Use capital letter for negation.
  164. '\d' == '[0-9]' # Digit
  165. '\s' == '[ \t\n\r\f\v]' # Whitespace
  166. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  167. ```
  168. ### Format
  169. ```python
  170. '{}'.format(<el> [, <el>, ...])
  171. ```
  172. ```python
  173. {:min_width} # '<el> '
  174. {:>min_width} # ' <el>'
  175. {:^min_width} # ' <el> '
  176. {:_<min_width} # '<el>____'
  177. {:.max_width} # '<e>'
  178. {:max_width.min_width} # ' <e>'
  179. {:max_width.no_of_decimalsf} # ' 3.14'
  180. ```
  181. ```python
  182. >>> person = {'name': 'Jean-Luc', 'height': 187.1}
  183. >>> '{p[height]:.0f}'.format(p=person)
  184. '187'
  185. >>> f"{person['height']:.0f}"
  186. '187'
  187. ```
  188. ```python
  189. >>> f'{123:020b}'
  190. '00000000000001111011'
  191. ```
  192. #### Integer presentation types:
  193. * 'b' - Binary
  194. * 'c' - Character
  195. * 'o' - Octal
  196. * 'x' - Hex
  197. * 'X' - HEX
  198. ### Text Wrap
  199. ```python
  200. import textwrap
  201. textwrap.wrap(text, width)
  202. ```
  203. Random
  204. ------
  205. ```python
  206. import random
  207. random.random()
  208. random.randint(from_inclusive, to_inclusive)
  209. random.shuffle(<list>)
  210. random.choice(<list>)
  211. ```
  212. Infinity
  213. --------
  214. ```python
  215. float('inf')
  216. ```
  217. Datetime
  218. --------
  219. ```python
  220. import datetime
  221. now = datetime.datetime.now()
  222. now.month # 3
  223. now.strftime('%Y%m%d') # 20180315
  224. now.strftime('%Y%m%d%H%M%S') # 20180315002834
  225. ```
  226. Arguments
  227. ---------
  228. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:**
  229. ```python
  230. args = (1, 2)
  231. kwargs = {'x': 3, 'y': 4, 'z': 5}
  232. func(*args, **kwargs)
  233. ```
  234. #### Is the same as:
  235. ```python
  236. func(1, 2, x=3, y=4, z=5)
  237. ```
  238. Inline
  239. ------
  240. ### Lambda
  241. ```python
  242. lambda: <return_value>
  243. lambda <argument1>, <argument2>: <return_value>
  244. ```
  245. ### Comprehension
  246. ```python
  247. [i+1 for i in range(10)] # [1, 2, ..., 10]
  248. [i for i in range(10) if i>5] # [6, 7, ..., 9]
  249. {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  250. (x+5 for x in range(0, 10)) # (5, 6, ..., 14) -> Generator
  251. ```
  252. ```python
  253. [i+j for i in range(10) for j in range(10)]
  254. ```
  255. #### Is the same as:
  256. ```python
  257. out = []
  258. for i in range(10):
  259. for j in range(10):
  260. out.append(i+j)
  261. ```
  262. ### Map, Filter, Reduce
  263. ```python
  264. map(lambda x: x+1, range(10)) # [1, 2, ..., 10]
  265. filter(lambda x: x>5, range(10)) # [6, 7, ..., 9]
  266. functools.reduce(lambda sum, x: sum+x, range(10)) # 45
  267. ```
  268. ### Any, All
  269. ```python
  270. any(el[1] for el in <collection>)
  271. ```
  272. ### If - Else
  273. ```python
  274. <expression_if_true> if <condition> else <expression_if_false>
  275. ```
  276. Closure
  277. -------
  278. ```python
  279. def multiply_closure(x):
  280. def wrapped(y):
  281. return x * y
  282. return wrapped
  283. multiply_by_3 = multiply_closure(3)
  284. ```
  285. #### Or:
  286. ```python
  287. from functools import partial
  288. partial(<function>, <argument>)
  289. ```
  290. Decorator
  291. ---------
  292. ```python
  293. @closure_name
  294. def function_that_gets_passed_to_closure():
  295. pass
  296. ```
  297. #### Debugger example:
  298. ```python
  299. from functools import wraps
  300. def debug(func):
  301. @wraps(func) # Needed for metadata copying (func name, ...).
  302. def wrapper(*args, **kwargs):
  303. print(func.__name__)
  304. return func(*args, **kwargs)
  305. return wrapper
  306. @debug
  307. def add(x, y):
  308. return x + y
  309. ```
  310. Class
  311. -----
  312. ```python
  313. class <name>:
  314. def __init__(self, a):
  315. self.a = a
  316. def __repr__(self):
  317. return str({'a': self.a})
  318. def __str__(self):
  319. return str(self.a)
  320. ```
  321. ### Enum
  322. ```python
  323. import enum
  324. class <enum_name>(enum.Enum):
  325. <name1> = <value1>
  326. <name2> = <value2>
  327. <name3> = enum.auto() # Can be used for automatic indexing.
  328. ...
  329. ```
  330. ```python
  331. <enum_name>.<name> # == <enum>
  332. <enum_name>(value) # == <enum>
  333. <enum>.name # == <name>
  334. <enum>.value # == <value>
  335. ```
  336. ```python
  337. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  338. list(<enum_name>) # == [<enum1>, <enum2>, ...]
  339. random.choice(list(<enum_name>)) # == random <enum>
  340. ```
  341. ### Copy
  342. ```python
  343. import copy
  344. copy.copy(<object>)
  345. copy.deepcopy(<object>)
  346. ```
  347. System
  348. ------
  349. ### Arguments
  350. ```python
  351. import sys
  352. sys.argv
  353. ```
  354. ### Read File
  355. ```python
  356. def read_file(filename):
  357. with open(filename, encoding='utf-8') as file:
  358. return file.readlines()
  359. ```
  360. ### Write to File
  361. ```python
  362. def write_to_file(filename, text):
  363. with open(filename, 'w', encoding='utf-8') as file:
  364. file.write(text)
  365. ```
  366. ### Path
  367. ```python
  368. import os
  369. os.path.exists(<path>)
  370. os.path.isfile(<path>)
  371. os.path.isdir(<path>)
  372. os.listdir(<path>)
  373. ```
  374. ### Execute Command
  375. ```python
  376. import os
  377. os.popen(<command>).read()
  378. ```
  379. #### Or:
  380. ```python
  381. >>> import subprocess
  382. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  383. >>> a.stdout
  384. b'.\n..\nfile1.txt\nfile2.txt\n'
  385. >>> a.returncode
  386. 0
  387. ```
  388. ### Input
  389. ```python
  390. filename = input('Enter a file name: ')
  391. ```
  392. #### Prints lines until EOF:
  393. ```python
  394. while True:
  395. try:
  396. print(input())
  397. except EOFError:
  398. break
  399. ```
  400. JSON
  401. ----
  402. ```python
  403. import json
  404. ```
  405. ### Serialization
  406. ```python
  407. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  408. <object> = json.loads(<str>)
  409. ```
  410. ### Read File
  411. ```python
  412. def read_json_file(filename):
  413. with open(filename, encoding='utf-8') as file:
  414. return json.load(file)
  415. ```
  416. ### Write to File
  417. ```python
  418. def write_to_json_file(filename, an_object):
  419. with open(filename, 'w', encoding='utf-8') as file:
  420. json.dump(an_object, file, ensure_ascii=False, indent=2)
  421. ```
  422. SQLite
  423. ------
  424. ```python
  425. import sqlite3
  426. db = sqlite3.connect(filename)
  427. ```
  428. ### Read
  429. ```python
  430. cursor = db.execute(<query>)
  431. if cursor:
  432. cursor.fetchall() # Or cursor.fetchone()
  433. db.close()
  434. ```
  435. ### Write
  436. ```python
  437. db.execute(<query>)
  438. db.commit()
  439. ```
  440. Exceptions
  441. ----------
  442. ```python
  443. while True:
  444. try:
  445. x = int(input("Please enter a number: "))
  446. except ValueError:
  447. print("Oops! That was no valid number. Try again...")
  448. else:
  449. print("Thank you.")
  450. break
  451. ```
  452. Threading
  453. ---------
  454. ```python
  455. import threading
  456. ```
  457. ### Thread
  458. ```python
  459. thread = threading.Thread(target=<function>, args=(<first_arg>, ))
  460. thread.start()
  461. thread.join()
  462. ```
  463. ### Lock
  464. ```python
  465. lock = threading.Rlock()
  466. lock.acquire()
  467. lock.release()
  468. ```
  469. Itertools
  470. ---------
  471. **Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to the list() function.**
  472. ```python
  473. from itertools import *
  474. ```
  475. ### Chain
  476. ```python
  477. >>> chain([1, 2], range(3, 5))
  478. [1, 2, 3, 4]
  479. ```
  480. ### Combinations
  481. ```python
  482. >>> combinations("abc", 2)
  483. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  484. ```
  485. ### Permutations
  486. ```python
  487. >>> permutations("abc", 2)
  488. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  489. ```
  490. ### Product
  491. ```python
  492. >>> list(product('ab', [1, 2]))
  493. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  494. ```
  495. ### Compress
  496. ```python
  497. >>> compress("abc", [True, 0, 23])
  498. ['a', 'c']
  499. ```
  500. ### Count
  501. ```python
  502. >>> a = count(5, 2)
  503. >>> next(a), next(a)
  504. (5, 7)
  505. ```
  506. ### Cycle
  507. ```python
  508. >>> a = cycle("abc")
  509. >>> [next(a) for _ in range(10)]
  510. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  511. ```
  512. ### Groupby
  513. ```python
  514. >>> a = [{"id": 1, "name": "bob"},
  515. {"id": 2, "name": "bob"},
  516. {"id": 3, "name": "peter"}]
  517. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  518. {'bob': [{'id': 1, 'name': 'bob'},
  519. {'id': 2, 'name': 'bob'}],
  520. 'peter': [{'id': 3, 'name': 'peter'}]}
  521. ```
  522. ### Islice
  523. ```python
  524. islice([1, 2, 3], 1, None)
  525. [2, 3]
  526. ```
  527. ### Ifilter, imap and izip
  528. #### Filter, map and zip functions that return generators instead of iterators.
  529. Introspection and Metaprograming
  530. --------------------------------
  531. **Inspecting code at runtime and code that generates code. You can:**
  532. * **Look at the attributes**
  533. * **Set new attributes**
  534. * **Create functions dynamically**
  535. * **Traverse the parent classes**
  536. * **Change values in the class**
  537. ```python
  538. >>> class Z:
  539. ... def __init__(self):
  540. ... self.a = 'abcde'
  541. ... self.b = 12345
  542. >>> z = Z()
  543. ```
  544. ### Getattr, Hasattr, Setattr
  545. ```python
  546. >>> getattr(z, 'a') # Same as Z.__getattribute__(z, 'a')
  547. 'abcde'
  548. >>> hasattr(z, 'c')
  549. False
  550. >>> setattr(z, 'c', 10)
  551. ```
  552. ### Type
  553. **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!):**
  554. ```python
  555. type(class_name, parents<tuple>, attributes<dict>)
  556. ```
  557. ```python
  558. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  559. >>> z = Z()
  560. ```
  561. ### MetaClass
  562. #### Class that creates class:
  563. ```python
  564. def my_meta_class(name, parents, attrs):
  565. ...
  566. return type(name, parents, attrs)
  567. ```
  568. #### Or:
  569. ```python
  570. class MyMetaClass(type):
  571. def __new__(klass, name, parents, attrs):
  572. ...
  573. return type.__new__(klass, name, parents, attrs)
  574. ```
  575. ### Metaclass Attr
  576. **When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type:**
  577. ```python
  578. class BlaBla:
  579. __metaclass__ = Bla
  580. ```
  581. Eval
  582. ----
  583. ```python
  584. import ast
  585. import operator as op
  586. # Supported operators
  587. operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
  588. ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
  589. ast.USub: op.neg}
  590. def eval_expr(expr):
  591. return eval_(ast.parse(expr, mode='eval').body)
  592. def eval_(node):
  593. if isinstance(node, ast.Num): # <number>
  594. return node.n
  595. elif isinstance(node, ast.BinOp): # <left> <operator> <right>
  596. return operators[type(node.op)](eval_(node.left), eval_(node.right))
  597. elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
  598. return operators[type(node.op)](eval_(node.operand))
  599. else:
  600. raise TypeError(node)
  601. ```
  602. ```python
  603. >>> eval_expr('2^6')
  604. 4
  605. >>> eval_expr('2**6')
  606. 64
  607. >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  608. -5.0
  609. ```
  610. Libraries
  611. =========
  612. Plot
  613. ----
  614. ```python
  615. # pip3 install matplotlib
  616. from matplotlib import pyplot
  617. pyplot.plot(<data> [, <data>])
  618. pyplot.show()
  619. pyplot.savefig(filename)
  620. ```
  621. Web
  622. ---
  623. ```python
  624. # pip3 install bottle
  625. import bottle
  626. import urllib
  627. ```
  628. ### Run
  629. ```python
  630. bottle.run(host='localhost', port=8080)
  631. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  632. ```
  633. ### Static request
  634. ```python
  635. @route('/img/<image>')
  636. def send_image(image):
  637. return static_file(image, 'images/', mimetype='image/png')
  638. ```
  639. ### Dynamic request
  640. ```python
  641. @route('/<sport>')
  642. def send_page(sport):
  643. sport = urllib.parse.unquote(sport).lower()
  644. page = read_file(sport)
  645. return template(page)
  646. ```
  647. ### REST request
  648. ```python
  649. @post('/p/<sport>')
  650. def p_handler(sport):
  651. team = request.forms.get('team')
  652. team = urllib.parse.unquote(team).lower()
  653. db = sqlite3.connect(conf.DB_PATH)
  654. p_h, p_a = get_p(db, sport, team)
  655. db.close()
  656. response.headers['Content-Type'] = 'application/json'
  657. response.headers['Cache-Control'] = 'no-cache'
  658. return json.dumps([p_h, p_a])
  659. ```
  660. Curses
  661. ------
  662. ```python
  663. # pip3 install curses
  664. import curses
  665. def main():
  666. curses.wrapper(draw)
  667. def draw(screen):
  668. screen.clear()
  669. screen.addstr(0, 0, "Press ESC to quit.")
  670. while screen.getch() != 27:
  671. pass
  672. def get_border(screen):
  673. Coords = collections.namedtuple('Coords', ['x', 'y'])
  674. height, width = screen.getmaxyx()
  675. return Coords(width - 1, height - 1)
  676. ```
  677. #### Gets char from int:
  678. ```python
  679. chr(<int>)
  680. ```
  681. Profile
  682. -------
  683. #### Basic:
  684. ```python
  685. from time import time
  686. start_time = time()
  687. <code>
  688. duration = time() - start_time
  689. ```
  690. #### Times execution of the passed code:
  691. ```python
  692. from timeit import timeit
  693. timeit('"-".join(str(n) for n in range(100))', number=10000)
  694. ```
  695. #### Generates a PNG image of call graph and highlights the bottlenecks:
  696. ```python
  697. # pip3 install pycallgraph
  698. import pycallgraph
  699. graph = pycallgraph.output.GraphvizOutput()
  700. graph.output_file = get_filename()
  701. with pycallgraph.PyCallGraph(output=graph):
  702. <code_to_be_profiled>
  703. ```
  704. #### Utility code for unique PNG filenames:
  705. ```python
  706. def get_filename():
  707. return "{}-{}.png".format("profile", get_current_datetime_string())
  708. def get_current_datetime_string():
  709. now = datetime.datetime.now()
  710. return get_datetime_string(now)
  711. def get_datetime_string(a_datetime):
  712. return a_datetime.strftime('%Y%m%d%H%M%S')
  713. ```
  714. Audio
  715. -----
  716. #### Saves list of floats of size 0 to 1 to a WAV file:
  717. ```python
  718. import wave, struct
  719. frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
  720. wf = wave.open(filename, 'wb')
  721. wf.setnchannels(1)
  722. wf.setsampwidth(4)
  723. wf.setframerate(44100)
  724. wf.writeframes(b''.join(frames))
  725. wf.close()
  726. ```
  727. Progress Bar
  728. ------------
  729. #### Basic:
  730. ```python
  731. class Progressbar():
  732. def __init__(self, steps, width=40):
  733. self.steps = steps
  734. self.width = width
  735. self.filled = 0
  736. self.counter = 0
  737. self.treshold = self.filled * self.steps / self.width
  738. sys.stdout.write(f"[{' ' * width}]")
  739. sys.stdout.flush()
  740. sys.stdout.write('\b' * (width + 1))
  741. def tick(self):
  742. self.counter += 1
  743. while self.counter > self.treshold:
  744. self.filled += 1
  745. self.treshold = self.filled * self.steps / self.width
  746. sys.stdout.write("-")
  747. sys.stdout.flush()
  748. if self.counter == self.steps:
  749. sys.stdout.write("\n")
  750. ```
  751. ```python
  752. steps = 100
  753. bar = Progressbar(steps)
  754. for i in range(steps):
  755. <code>
  756. bar.tick()
  757. ```
  758. #### Progress:
  759. ```python
  760. # pip3 install progress
  761. from progress.bar import Bar
  762. steps = 100
  763. bar = Bar('Processing', max=steps)
  764. for i in range(steps):
  765. <code>
  766. bar.next()
  767. bar.finish()
  768. ```