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.

881 lines
16 KiB

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