This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
def flatter(items): | |
"""Реккурсивный итератор. | |
Обходит все ключи в словаре, работает со спискам любой длины. | |
Исходный словарь предполагается без вложенных словарей. | |
>>> d = {'a': [2, 5, 6], 'b': [8, 3, 6]} | |
>>> map(dict, flatter(d.items())) | |
[{'a': 2, 'b': 8}, {'a': 2, 'b': 3}, {'a': 2, 'b': 6}, {'a': 5, 'b': 8}, {'a': 5, 'b': 3}, {'a': 5, 'b': 6}, {'a': 6, 'b': 8}, {'a': 6, 'b': 3}, {'a': 6, 'b': 6}] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [1]: class Foo(object): | |
...: attr = {'initial_state': True} | |
...: def bar_class(self): | |
...: self.attr['initial_state'] = False | |
...: def bar_instance(self): | |
...: self.attr = {'initial_state': False} | |
...: | |
In [2]: foo = Foo() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Requirements: `pip install nose coverage` | |
# ЗАМЕНИТЬ | |
# <pymodule_name> - название python-модуля для прогона тестов | |
# <tests_dirname> - название папки где храним тесты | |
# <webserver_adderss> - поднимаем на dev-машине вебсервер и путь отдает статику по этому имени из /tmp/coverage | |
# ... | |
# PROFIT! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Макдак продает нагитсы в коробках по 6, 9 или 20 кусочков. | |
Возможно купить 15 кусочков (одна коробка 6 кусочков и одна 9), но не возможно купить ровно 16 кусочков. | |
Напишите функцию McNuggets, которая принимает один аргумент, n, и возвращает true, если возможно купить такое количество кусочков комбинируя упаковки по 6, 9 и 20 кусочков в каждой, иначе возвратить false. | |
*/ | |
var isDivisible = function(number, modulo) { | |
return (number % modulo) === 0; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -* coding: utf-8 -*- | |
u""" | |
1. Самый важный фактор в разработке ПО – это не методы и средства, применяемые программистами, а сами программисты. | |
2. По результатам исследования персональных отличий лучшие программисты до 28 раз превосходят слабейших. Если учесть, что оплата их труда никогда не бывает соразмерной, то лучший программист и есть самое выгодное приобретение в индустрии ПО. | |
3. Если проект не укладывается в сроки, то добавление рабочей силы задержит его еще больше. | |
4. Условия труда оказывают сильное влияние на продуктивность и качество результата. | |
5. Рекламный звон вокруг инструментов и методов это чума индустрии ПО. Большая часть усовершенствований средств и методов приводит к увеличению производительности и качества примерно на 5–35%. Но многие из этих усовершенствований были заявлены как дающие преимущество «на порядок». | |
6. Изучение нового метода или средства сначала понижает производительность программистов и качество продукта. Пользу из обучения можно извлечь только после того, как пройдена крив |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ~*~ coding: utf-8 ~*~ | |
import datetime | |
import os | |
import sys | |
import subprocess | |
""" | |
Документация по модулю subprocess, который позволяет вызывать другие процессы, | |
писать им в stdin, читать из stdout и stderr, проверять код их завершения | |
https://docs.python.org/2/library/subprocess.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import logging | |
class ColoredFormatter(logging.Formatter): | |
""" | |
See more colors and styles at http://stackoverflow.com/a/21786287 | |
""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Имеется лабиринт, нужно провести игрока к сокровищу | |
""" | |
import os | |
LOCATION_FILENAME = '.location' | |
TEST_LOCATION = [ | |
[1, 1, 1], | |
[1, 0, 1], |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -* coding: utf-8 -*- | |
""" | |
Memento | |
Не нарушая инкапсуляцию, определяет и сохраняет внутреннее состояние объекта и позволяет позже восстановить объект в этом состоянии | |
Chain of responsibility | |
Избегает связывания отправителя запрос с его получателем, давая возможность обработать запрос более чем одному объекту. Связывает объекты-получатели и передает запрос по цепочке пока объект не обработает его | |
Observer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Watchdog which can do one trick only - to sniff for a pattern in a log file and | |
"bark" by running some command. The program won't stop after "barking". | |
Usage: | |
python watch_bro.py <filename> <pattern> <command> | |
filename: A file to watch for changes | |
pattern: A string to look for in the file | |
command: What to execute when the pattern occurs |
OlderNewer