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.

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