body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
b181446b301468f6fc4c9cb860f06fdb987f4324a097ca6aeddfae47c9688e50 | def powerOff(self) -> None:
'Выключает мотор.'
raise NotImplementedError | Выключает мотор. | trik/brick.py | powerOff | m1raynee/trikset.py-typehint | 1 | python | def powerOff(self) -> None:
raise NotImplementedError | def powerOff(self) -> None:
raise NotImplementedError<|docstring|>Выключает мотор.<|endoftext|> |
b80c9ab421122e3b5aa3114d7e41077a128d156e020e0897b4ad3c0b9527e5ca | def setPower(self, power: int) -> None:
'Включает мотор с указанной мощностью.\n\n Параметры\n ---------\n power: :class:`int`\n Мощность задаётся в диапазоне от -100 («полный назад») до 100 («полный вперёд»).\n 0 соответствует `force break`, то есть мотор останавливается,... | Включает мотор с указанной мощностью.
Параметры
---------
power: :class:`int`
Мощность задаётся в диапазоне от -100 («полный назад») до 100 («полный вперёд»).
0 соответствует `force break`, то есть мотор останавливается, при этом он заблокирован
и остаётся под напряжением. | trik/brick.py | setPower | m1raynee/trikset.py-typehint | 1 | python | def setPower(self, power: int) -> None:
'Включает мотор с указанной мощностью.\n\n Параметры\n ---------\n power: :class:`int`\n Мощность задаётся в диапазоне от -100 («полный назад») до 100 («полный вперёд»).\n 0 соответствует `force break`, то есть мотор останавливается,... | def setPower(self, power: int) -> None:
'Включает мотор с указанной мощностью.\n\n Параметры\n ---------\n power: :class:`int`\n Мощность задаётся в диапазоне от -100 («полный назад») до 100 («полный вперёд»).\n 0 соответствует `force break`, то есть мотор останавливается,... |
7a7b0e47e889bf8d30eab9bde4ce3a601ede0e8eff89727ebe534613a0a18f36 | def detect(self) -> None:
'Определяет доминирующий цвет в центре кадра и запоминает его\n как цвет объекта. После этого метод «read» начинает возвращать\n данные для объекта.\n '
raise NotImplementedError | Определяет доминирующий цвет в центре кадра и запоминает его
как цвет объекта. После этого метод «read» начинает возвращать
данные для объекта. | trik/brick.py | detect | m1raynee/trikset.py-typehint | 1 | python | def detect(self) -> None:
'Определяет доминирующий цвет в центре кадра и запоминает его\n как цвет объекта. После этого метод «read» начинает возвращать\n данные для объекта.\n '
raise NotImplementedError | def detect(self) -> None:
'Определяет доминирующий цвет в центре кадра и запоминает его\n как цвет объекта. После этого метод «read» начинает возвращать\n данные для объекта.\n '
raise NotImplementedError<|docstring|>Определяет доминирующий цвет в центре кадра и запоминает его
как цвет объе... |
d36bcac70106079af57412ba21911cf92435ea3c39feff101091859069466bff | def init(self, show_to_screen: bool) -> None:
'Включает видеокамеру и инициализирует её в режиме датчика объекта.\n\n Параметры\n ---------\n show_to_screen: :class:`int`\n Определяет, выводить ли на экран изображение с камеры\n '
raise NotImplementedError | Включает видеокамеру и инициализирует её в режиме датчика объекта.
Параметры
---------
show_to_screen: :class:`int`
Определяет, выводить ли на экран изображение с камеры | trik/brick.py | init | m1raynee/trikset.py-typehint | 1 | python | def init(self, show_to_screen: bool) -> None:
'Включает видеокамеру и инициализирует её в режиме датчика объекта.\n\n Параметры\n ---------\n show_to_screen: :class:`int`\n Определяет, выводить ли на экран изображение с камеры\n '
raise NotImplementedError | def init(self, show_to_screen: bool) -> None:
'Включает видеокамеру и инициализирует её в режиме датчика объекта.\n\n Параметры\n ---------\n show_to_screen: :class:`int`\n Определяет, выводить ли на экран изображение с камеры\n '
raise NotImplementedError<|docstring|>Вклю... |
25e3def6ecc6f2fd0f199d0403dcd80877c72633077b0b023453830a175f7220 | def read(self) -> List[int]:
'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра слева);\n - в первой ячейке — координата по оси Y центра объект... | Возвращает массив, в ячейках которого находятся следующие данные:
- в нулевой ячейке координата по оси X центра объекта относительно центра кадра
(от -100 до 100, -100 — центр объекта на краю кадра слева);
- в первой ячейке — координата по оси Y центра объекта относительно центра кадра
(от -100 до 100, -100 — центр объ... | trik/brick.py | read | m1raynee/trikset.py-typehint | 1 | python | def read(self) -> List[int]:
'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра слева);\n - в первой ячейке — координата по оси Y центра объект... | def read(self) -> List[int]:
'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра слева);\n - в первой ячейке — координата по оси Y центра объект... |
f7db3fc17c9d14c95d56c570e5a55f1e6c00f3716623a481ed9ba3685a137ddd | def stop(self) -> None:
'Выключает видеокамеру и прекращает работу датчика.'
raise NotImplementedError | Выключает видеокамеру и прекращает работу датчика. | trik/brick.py | stop | m1raynee/trikset.py-typehint | 1 | python | def stop(self) -> None:
raise NotImplementedError | def stop(self) -> None:
raise NotImplementedError<|docstring|>Выключает видеокамеру и прекращает работу датчика.<|endoftext|> |
8d846290f59da1ef947365b23ef67eff1eb40d69e3b391b81d15626ddc385eb9 | def down(self, color: _COLOR) -> None:
'Начать рисование маркером заданного цвета на полу.\n При движении робота в двумерной модели за ним будет оставаться цветная линия.\n Если был установлен маркер другого цвета, он будет заменен.\n\n Параметры\n ---------\n color: :class:`str`\... | Начать рисование маркером заданного цвета на полу.
При движении робота в двумерной модели за ним будет оставаться цветная линия.
Если был установлен маркер другого цвета, он будет заменен.
Параметры
---------
color: :class:`str`
Возможные цвета:
- white,
- red, darkRed,
- green, darkGreen,
- blue, ... | trik/brick.py | down | m1raynee/trikset.py-typehint | 1 | python | def down(self, color: _COLOR) -> None:
'Начать рисование маркером заданного цвета на полу.\n При движении робота в двумерной модели за ним будет оставаться цветная линия.\n Если был установлен маркер другого цвета, он будет заменен.\n\n Параметры\n ---------\n color: :class:`str`\... | def down(self, color: _COLOR) -> None:
'Начать рисование маркером заданного цвета на полу.\n При движении робота в двумерной модели за ним будет оставаться цветная линия.\n Если был установлен маркер другого цвета, он будет заменен.\n\n Параметры\n ---------\n color: :class:`str`\... |
ab3bfd10e6a96e62161f2b75d481af544b343e5786b7e3373f2e5dfcf74a5146 | def up(self) -> None:
'Закончить рисование маркером.'
raise NotImplementedError | Закончить рисование маркером. | trik/brick.py | up | m1raynee/trikset.py-typehint | 1 | python | def up(self) -> None:
raise NotImplementedError | def up(self) -> None:
raise NotImplementedError<|docstring|>Закончить рисование маркером.<|endoftext|> |
0349e9b8d5f62db68eabfa84d1e2951116ac8a4848d3cb9cc05b39ed860b9b86 | def isDown(self) -> bool:
'Возвращает `True`, если маркер активен, `False` - если нет.'
raise NotImplementedError | Возвращает `True`, если маркер активен, `False` - если нет. | trik/brick.py | isDown | m1raynee/trikset.py-typehint | 1 | python | def isDown(self) -> bool:
raise NotImplementedError | def isDown(self) -> bool:
raise NotImplementedError<|docstring|>Возвращает `True`, если маркер активен, `False` - если нет.<|endoftext|> |
99a767d6d8613b2d5d7ea4f6fecfd8e5df55772e13c1c0936cef63ab2eb1f9b4 | def setDown(self, pos: bool) -> None:
'Вызывает метод `down("black")`, или `up()` в зависимости от аргумента.'
raise NotImplementedError | Вызывает метод `down("black")`, или `up()` в зависимости от аргумента. | trik/brick.py | setDown | m1raynee/trikset.py-typehint | 1 | python | def setDown(self, pos: bool) -> None:
raise NotImplementedError | def setDown(self, pos: bool) -> None:
raise NotImplementedError<|docstring|>Вызывает метод `down("black")`, или `up()` в зависимости от аргумента.<|endoftext|> |
708218a9b2c1723e88dbb6611447441edac528c18715cf12bcc2fd54bc047eeb | def __init__(self, sensorName: _SENSOR_NAME) -> None:
'Представляет сенсор (аналоговый или цифровой), подключающийся к портам A1, …, A6, D1, D2.\n\n Параметры\n ---------\n sensorName: :class:`str`\n Имя порта\n '
raise NotImplementedError | Представляет сенсор (аналоговый или цифровой), подключающийся к портам A1, …, A6, D1, D2.
Параметры
---------
sensorName: :class:`str`
Имя порта | trik/brick.py | __init__ | m1raynee/trikset.py-typehint | 1 | python | def __init__(self, sensorName: _SENSOR_NAME) -> None:
'Представляет сенсор (аналоговый или цифровой), подключающийся к портам A1, …, A6, D1, D2.\n\n Параметры\n ---------\n sensorName: :class:`str`\n Имя порта\n '
raise NotImplementedError | def __init__(self, sensorName: _SENSOR_NAME) -> None:
'Представляет сенсор (аналоговый или цифровой), подключающийся к портам A1, …, A6, D1, D2.\n\n Параметры\n ---------\n sensorName: :class:`str`\n Имя порта\n '
raise NotImplementedError<|docstring|>Представляет сенсор (... |
6b5c59571adb86f478711ca29ef1a94fe3906da5b92f20a079a7f89731b313ec | def read(self) -> int:
'Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.\n Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается\n в файле `model-config.xml` в папке trik на роботе.\n\n Например, ИК-датчик расстоя... | Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.
Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается
в файле `model-config.xml` в папке trik на роботе.
Например, ИК-датчик расстояния возвращает значение в сантиметрах. | trik/brick.py | read | m1raynee/trikset.py-typehint | 1 | python | def read(self) -> int:
'Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.\n Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается\n в файле `model-config.xml` в папке trik на роботе.\n\n Например, ИК-датчик расстоя... | def read(self) -> int:
'Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.\n Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается\n в файле `model-config.xml` в папке trik на роботе.\n\n Например, ИК-датчик расстоя... |
9f0167c09c3737dd6094365926395199a3bde867c7ed75a74cb7cbd2d0b282e2 | def readRawData(self) -> int:
'Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),\n подключённого к данному порту. Диапазон значений зависит от конкретного сенсора\n и не учитывает конфигурацию робота (возвращаются физические показания сенсора,\n например, задержка принят... | Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),
подключённого к данному порту. Диапазон значений зависит от конкретного сенсора
и не учитывает конфигурацию робота (возвращаются физические показания сенсора,
например, задержка принятого ультразвукового сигнала). | trik/brick.py | readRawData | m1raynee/trikset.py-typehint | 1 | python | def readRawData(self) -> int:
'Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),\n подключённого к данному порту. Диапазон значений зависит от конкретного сенсора\n и не учитывает конфигурацию робота (возвращаются физические показания сенсора,\n например, задержка принят... | def readRawData(self) -> int:
'Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),\n подключённого к данному порту. Диапазон значений зависит от конкретного сенсора\n и не учитывает конфигурацию робота (возвращаются физические показания сенсора,\n например, задержка принят... |
2690c3829a01852eb80eddc1b64edfeec24eda0b4b1f51553ee6c628cdbbe31d | @classmethod
def connect(self, func: Callable[([KeysEnum, Literal[(0, 1)]], Any)]):
'\n Параметры\n ---------\n func: Callable[[:class:`KeysEnum`, Literal[0, 1]], Any]\n Первый параметр — код кнопки,\n второй — 1, если кнопка нажата, 0, если отпущена.\n... | Параметры
---------
func: Callable[[:class:`KeysEnum`, Literal[0, 1]], Any]
Первый параметр — код кнопки,
второй — 1, если кнопка нажата, 0, если отпущена. | trik/brick.py | connect | m1raynee/trikset.py-typehint | 1 | python | @classmethod
def connect(self, func: Callable[([KeysEnum, Literal[(0, 1)]], Any)]):
'\n Параметры\n ---------\n func: Callable[[:class:`KeysEnum`, Literal[0, 1]], Any]\n Первый параметр — код кнопки,\n второй — 1, если кнопка нажата, 0, если отпущена.\n... | @classmethod
def connect(self, func: Callable[([KeysEnum, Literal[(0, 1)]], Any)]):
'\n Параметры\n ---------\n func: Callable[[:class:`KeysEnum`, Literal[0, 1]], Any]\n Первый параметр — код кнопки,\n второй — 1, если кнопка нажата, 0, если отпущена.\n... |
6f47bdfc08e49f87184dafd5d747db1f64ff510bbc2dc95ed9847ccd3c96de18 | def main():
'main program'
with open(TWEETS_FILENAME, 'rb') as pickle_file:
df = pickle.load(pickle_file)
df = df.sort_values('query_datetime')
initial_tweets = df.groupby('tweet').first().reset_index()
print('unique tweets:', len(initial_tweets))
initial_tweets['query_datetime'] = initi... | main program | plot.py | main | bdzimmer/twittertool | 0 | python | def main():
with open(TWEETS_FILENAME, 'rb') as pickle_file:
df = pickle.load(pickle_file)
df = df.sort_values('query_datetime')
initial_tweets = df.groupby('tweet').first().reset_index()
print('unique tweets:', len(initial_tweets))
initial_tweets['query_datetime'] = initial_tweets['twe... | def main():
with open(TWEETS_FILENAME, 'rb') as pickle_file:
df = pickle.load(pickle_file)
df = df.sort_values('query_datetime')
initial_tweets = df.groupby('tweet').first().reset_index()
print('unique tweets:', len(initial_tweets))
initial_tweets['query_datetime'] = initial_tweets['twe... |
31f222867b4dfc34359216216858b45028e4e5598df649a3a0f60f3ba2e015d3 | def mirrorReflection(self, p, q):
'\n :type p: int\n :type q: int\n :rtype: int\n '
return (2 if ((p & (- p)) > (q & (- q))) else (0 if ((p & (- p)) < (q & (- q))) else 1)) | :type p: int
:type q: int
:rtype: int | Python/mirror-reflection.py | mirrorReflection | RideGreg/LeetCode | 1 | python | def mirrorReflection(self, p, q):
'\n :type p: int\n :type q: int\n :rtype: int\n '
return (2 if ((p & (- p)) > (q & (- q))) else (0 if ((p & (- p)) < (q & (- q))) else 1)) | def mirrorReflection(self, p, q):
'\n :type p: int\n :type q: int\n :rtype: int\n '
return (2 if ((p & (- p)) > (q & (- q))) else (0 if ((p & (- p)) < (q & (- q))) else 1))<|docstring|>:type p: int
:type q: int
:rtype: int<|endoftext|> |
05eab5e06cc097b83093e201f5411ee1e32f5d2229e09f81f7e1e92f487a3559 | def mirrorReflection(self, p, q):
'\n :type p: int\n :type q: int\n :rtype: int\n '
def gcd(a, b):
while b:
(a, b) = (b, (a % b))
return a
g = gcd(p, q)
np = ((p / g) % 2)
nq = ((q / g) % 2)
return (1 if (np and nq) else (0 if np else 2)) | :type p: int
:type q: int
:rtype: int | Python/mirror-reflection.py | mirrorReflection | RideGreg/LeetCode | 1 | python | def mirrorReflection(self, p, q):
'\n :type p: int\n :type q: int\n :rtype: int\n '
def gcd(a, b):
while b:
(a, b) = (b, (a % b))
return a
g = gcd(p, q)
np = ((p / g) % 2)
nq = ((q / g) % 2)
return (1 if (np and nq) else (0 if np else 2)) | def mirrorReflection(self, p, q):
'\n :type p: int\n :type q: int\n :rtype: int\n '
def gcd(a, b):
while b:
(a, b) = (b, (a % b))
return a
g = gcd(p, q)
np = ((p / g) % 2)
nq = ((q / g) % 2)
return (1 if (np and nq) else (0 if np else 2))<... |
8d4eaad00abb41cc503a7df0271edf9ebfb57a563fbbb43bcc1f767af7eea09b | def arg_parser():
'Parsing of command line arguments'
parser = argparse.ArgumentParser(description='Image classification')
parser.add_argument('--data_url', type=str, default=None, help='Dataset path')
parser.add_argument('--train_url', type=str, default=None, help='Train output path')
parser.add_ar... | Parsing of command line arguments | research/cv/mobilenetV3_small_x1_0/argparser.py | arg_parser | mindspore-ai/models | 77 | python | def arg_parser():
parser = argparse.ArgumentParser(description='Image classification')
parser.add_argument('--data_url', type=str, default=None, help='Dataset path')
parser.add_argument('--train_url', type=str, default=None, help='Train output path')
parser.add_argument('--dataset_path', type=str, ... | def arg_parser():
parser = argparse.ArgumentParser(description='Image classification')
parser.add_argument('--data_url', type=str, default=None, help='Dataset path')
parser.add_argument('--train_url', type=str, default=None, help='Train output path')
parser.add_argument('--dataset_path', type=str, ... |
b6babd847bf7e4165bf3120ca42ef45d5e6da15d8b9df1c2d8811baaa2bd8f22 | def getPostTags(post):
' returns primary, and all tags in post '
import re
item = post['caption']
primaryTag = re.findall('(?<=Tag ).\\S*', item['text'], flags=re.IGNORECASE)
allTags = re.findall('([#@][\\w_+#@]*)', item['text'])
print(primaryTag, allTags)
return (primaryTag, allTags) | returns primary, and all tags in post | instagramBot.py | getPostTags | the-rccg/instaCompetitionBot | 8 | python | def getPostTags(post):
' '
import re
item = post['caption']
primaryTag = re.findall('(?<=Tag ).\\S*', item['text'], flags=re.IGNORECASE)
allTags = re.findall('([#@][\\w_+#@]*)', item['text'])
print(primaryTag, allTags)
return (primaryTag, allTags) | def getPostTags(post):
' '
import re
item = post['caption']
primaryTag = re.findall('(?<=Tag ).\\S*', item['text'], flags=re.IGNORECASE)
allTags = re.findall('([#@][\\w_+#@]*)', item['text'])
print(primaryTag, allTags)
return (primaryTag, allTags)<|docstring|>returns primary, and all tags i... |
c143121d2ba69eaf69795bff2c9e9c7e2238f7e774636ddffbb7a47dacaf242e | def removeTags(text):
' removes all hash- and people tags '
import re
return re.sub('\\s[#@][\\w#.]*', '', text) | removes all hash- and people tags | instagramBot.py | removeTags | the-rccg/instaCompetitionBot | 8 | python | def removeTags(text):
' '
import re
return re.sub('\\s[#@][\\w#.]*', , text) | def removeTags(text):
' '
import re
return re.sub('\\s[#@][\\w#.]*', , text)<|docstring|>removes all hash- and people tags<|endoftext|> |
5a64c6642cbb20e0b444b24dff17317381d9705d607129773207f2d9590b1992 | def getPlainText(text):
' Only alphanumeric words '
return ' '.join([word for word in text.split(' ') if (word.isalnum() == True)]) | Only alphanumeric words | instagramBot.py | getPlainText | the-rccg/instaCompetitionBot | 8 | python | def getPlainText(text):
' '
return ' '.join([word for word in text.split(' ') if (word.isalnum() == True)]) | def getPlainText(text):
' '
return ' '.join([word for word in text.split(' ') if (word.isalnum() == True)])<|docstring|>Only alphanumeric words<|endoftext|> |
562fc551fc62a4a2633b3195b628f2748b03582edb3dc2e1ea01ea5aecde1835 | def verifyUser(instagram, userPk, minPosts, minFollower, minFollowing):
' verify user meets minimum required: posts, followers, followings '
attempt = 1
while (not instagram.getUsernameInfo(userPk)):
time.sleep((60 * attempt))
attempt += 1
userInfoDic = instagram.LastJson['user']
pos... | verify user meets minimum required: posts, followers, followings | instagramBot.py | verifyUser | the-rccg/instaCompetitionBot | 8 | python | def verifyUser(instagram, userPk, minPosts, minFollower, minFollowing):
' '
attempt = 1
while (not instagram.getUsernameInfo(userPk)):
time.sleep((60 * attempt))
attempt += 1
userInfoDic = instagram.LastJson['user']
postCountOK = (userInfoDic['media_count'] > minPosts)
followerC... | def verifyUser(instagram, userPk, minPosts, minFollower, minFollowing):
' '
attempt = 1
while (not instagram.getUsernameInfo(userPk)):
time.sleep((60 * attempt))
attempt += 1
userInfoDic = instagram.LastJson['user']
postCountOK = (userInfoDic['media_count'] > minPosts)
followerC... |
a26e2b9f80a5feb393681025e44fa24b8144cf498180b5a654cd44b432945bf7 | def checkPhoneNumber(item):
' search for all major phone number types, prints phone number '
import re
if (re.search('(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})', item) is not None):
print('phone number recognized', re.search('(\\d{3}[-... | search for all major phone number types, prints phone number | instagramBot.py | checkPhoneNumber | the-rccg/instaCompetitionBot | 8 | python | def checkPhoneNumber(item):
' '
import re
if (re.search('(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})', item) is not None):
print('phone number recognized', re.search('(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.... | def checkPhoneNumber(item):
' '
import re
if (re.search('(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})', item) is not None):
print('phone number recognized', re.search('(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.... |
5a98a1e394c7007d1f4e073694ed9a20ad9aec5dfde45236a7cb233d0e784877 | def checkLanguage(text):
' check if item is in the english language, prints if foreign '
global validLanguageList
from langdetect import detect
wordCaption = getPlainText(text)
if (detect(wordCaption) not in validLanguageList):
print(' foreign: ', detect(wordCaption))
return False
... | check if item is in the english language, prints if foreign | instagramBot.py | checkLanguage | the-rccg/instaCompetitionBot | 8 | python | def checkLanguage(text):
' '
global validLanguageList
from langdetect import detect
wordCaption = getPlainText(text)
if (detect(wordCaption) not in validLanguageList):
print(' foreign: ', detect(wordCaption))
return False
else:
return True | def checkLanguage(text):
' '
global validLanguageList
from langdetect import detect
wordCaption = getPlainText(text)
if (detect(wordCaption) not in validLanguageList):
print(' foreign: ', detect(wordCaption))
return False
else:
return True<|docstring|>check if item is ... |
8f696b841eed5eb5fb161632f69a9c3cdd0479ec985a0d9e86c265ccc567a544 | def translateToEnglish(text):
' uses google translate to translate post to english '
from langdetect import detect
wordCaption = getPlainText(text)
if (detect(wordCaption) != 'en'):
from googletrans import Translator
translator = Translator()
translation = None
while (not... | uses google translate to translate post to english | instagramBot.py | translateToEnglish | the-rccg/instaCompetitionBot | 8 | python | def translateToEnglish(text):
' '
from langdetect import detect
wordCaption = getPlainText(text)
if (detect(wordCaption) != 'en'):
from googletrans import Translator
translator = Translator()
translation = None
while (not translation):
try:
tr... | def translateToEnglish(text):
' '
from langdetect import detect
wordCaption = getPlainText(text)
if (detect(wordCaption) != 'en'):
from googletrans import Translator
translator = Translator()
translation = None
while (not translation):
try:
tr... |
3b347f58235478efacead15c88339c234c7f45f4ae69aa6c8ce10102a9fa8ff1 | def checkForContest(post, minScore):
' checks post for contest by keywords below rules below rules on keywords '
item = post['caption']['text'].lower()
contestScore = 0
allTags = []
positives = {'giveaway': 2, 'give away': 3, 'giving away': 3, 'free': 2, 'no purchase': 4, 'contest': 1, 'win': 1, 'co... | checks post for contest by keywords below rules below rules on keywords | instagramBot.py | checkForContest | the-rccg/instaCompetitionBot | 8 | python | def checkForContest(post, minScore):
' '
item = post['caption']['text'].lower()
contestScore = 0
allTags = []
positives = {'giveaway': 2, 'give away': 3, 'giving away': 3, 'free': 2, 'no purchase': 4, 'contest': 1, 'win': 1, 'comment': 1, 'chance': 2, 'like': 1, 'tag': 1, 'friend': 1, 'gift package... | def checkForContest(post, minScore):
' '
item = post['caption']['text'].lower()
contestScore = 0
allTags = []
positives = {'giveaway': 2, 'give away': 3, 'giving away': 3, 'free': 2, 'no purchase': 4, 'contest': 1, 'win': 1, 'comment': 1, 'chance': 2, 'like': 1, 'tag': 1, 'friend': 1, 'gift package... |
5367a993a5970c3c218076499052ebe159b6ad4d307f0a0cc167b23335523d4b | def mostCommonComment(instagram, post, minComments=10, minCount=3):
' Comment on Contest to enter: 1) most common answer 2) just yes '
commented = baseComment
if (('comments_disabled' in post.keys()) and (post['comments_disabled'] == True)):
return commented
if (post['comment_count'] > minCommen... | Comment on Contest to enter: 1) most common answer 2) just yes | instagramBot.py | mostCommonComment | the-rccg/instaCompetitionBot | 8 | python | def mostCommonComment(instagram, post, minComments=10, minCount=3):
' '
commented = baseComment
if (('comments_disabled' in post.keys()) and (post['comments_disabled'] == True)):
return commented
if (post['comment_count'] > minComments):
instagram.getMediaComments(post['id'])
co... | def mostCommonComment(instagram, post, minComments=10, minCount=3):
' '
commented = baseComment
if (('comments_disabled' in post.keys()) and (post['comments_disabled'] == True)):
return commented
if (post['comment_count'] > minComments):
instagram.getMediaComments(post['id'])
co... |
1b060ddbdd5e1bfffcb4f5751ef9e81112db5c7e867120a05912f040f232c2fc | def searchPost4PeopleTag(post):
' returns number of people needed to tag '
from re import findall, IGNORECASE
item = post['caption']['text'].lower()
import itertools
tagList = ['tag', 'tagging']
attList = ['at least', 'a minimum of', 'a minimal', 'me and']
phraseList = (tagList + [((tag + ' ... | returns number of people needed to tag | instagramBot.py | searchPost4PeopleTag | the-rccg/instaCompetitionBot | 8 | python | def searchPost4PeopleTag(post):
' '
from re import findall, IGNORECASE
item = post['caption']['text'].lower()
import itertools
tagList = ['tag', 'tagging']
attList = ['at least', 'a minimum of', 'a minimal', 'me and']
phraseList = (tagList + [((tag + ' ') + att) for (tag, att) in itertools.... | def searchPost4PeopleTag(post):
' '
from re import findall, IGNORECASE
item = post['caption']['text'].lower()
import itertools
tagList = ['tag', 'tagging']
attList = ['at least', 'a minimum of', 'a minimal', 'me and']
phraseList = (tagList + [((tag + ' ') + att) for (tag, att) in itertools.... |
230bc0c759dfe17003b1fec1552dc3f33641cc9d3a8e24637267a4da21b59e3e | def addPeopleTags(post, numPeopleToTag, instagram):
' returns string of tagged usernames in amount needed '
usernameList = usernamesToTagList(numPeopleToTag, instagram)
if (numPeopleToTag > 0):
print((' [ ] Tagging %s people required' % numPeopleToTag))
return ('@' + ' @'.join(usernameList)... | returns string of tagged usernames in amount needed | instagramBot.py | addPeopleTags | the-rccg/instaCompetitionBot | 8 | python | def addPeopleTags(post, numPeopleToTag, instagram):
' '
usernameList = usernamesToTagList(numPeopleToTag, instagram)
if (numPeopleToTag > 0):
print((' [ ] Tagging %s people required' % numPeopleToTag))
return ('@' + ' @'.join(usernameList))
else:
return | def addPeopleTags(post, numPeopleToTag, instagram):
' '
usernameList = usernamesToTagList(numPeopleToTag, instagram)
if (numPeopleToTag > 0):
print((' [ ] Tagging %s people required' % numPeopleToTag))
return ('@' + ' @'.join(usernameList))
else:
return <|docstring|>returns str... |
96a860a2b6c7f393d8af55685229679145dd78b7afbc589cdfe8c721f1812c0c | def repost(post, captionText, instagram):
' repost picture in post with previous caption attached '
global sleepCounter
selfImageHashDic = getSelfImageHashes(instagram)
duplicatePk = checkPrevPosted(selfImageHashDic, post, sensitivity=30)
if duplicatePk:
print(' Duplicate - not reposting')
... | repost picture in post with previous caption attached | instagramBot.py | repost | the-rccg/instaCompetitionBot | 8 | python | def repost(post, captionText, instagram):
' '
global sleepCounter
selfImageHashDic = getSelfImageHashes(instagram)
duplicatePk = checkPrevPosted(selfImageHashDic, post, sensitivity=30)
if duplicatePk:
print(' Duplicate - not reposting')
while (not instagram.mediaInfo(duplicatePk)):... | def repost(post, captionText, instagram):
' '
global sleepCounter
selfImageHashDic = getSelfImageHashes(instagram)
duplicatePk = checkPrevPosted(selfImageHashDic, post, sensitivity=30)
if duplicatePk:
print(' Duplicate - not reposting')
while (not instagram.mediaInfo(duplicatePk)):... |
b86353f4343e453a1fc96b9fd9a84f3b8c3af71bb69a0e8e75d68580bf6e0522 | def check4Repost(post):
' Check if repost of picture required '
import itertools
caption = post['caption']['text'].lower()
verbIndicators = ['post', 'posts', 'repost', 'reposts', 'share', 'shares', 'pot', 'repot', 'like/share', 'like&share', 'like &share', 'like & share']
adjIndicators = ['the', 'th... | Check if repost of picture required | instagramBot.py | check4Repost | the-rccg/instaCompetitionBot | 8 | python | def check4Repost(post):
' '
import itertools
caption = post['caption']['text'].lower()
verbIndicators = ['post', 'posts', 'repost', 'reposts', 'share', 'shares', 'pot', 'repot', 'like/share', 'like&share', 'like &share', 'like & share']
adjIndicators = ['the', 'this photo', 'this picture', 'this pi... | def check4Repost(post):
' '
import itertools
caption = post['caption']['text'].lower()
verbIndicators = ['post', 'posts', 'repost', 'reposts', 'share', 'shares', 'pot', 'repot', 'like/share', 'like&share', 'like &share', 'like & share']
adjIndicators = ['the', 'this photo', 'this picture', 'this pi... |
9d95a051c34a346384d7b9b665f92ddf439a5c2a0b66b4589793ac4cd87954b5 | def getPeopleTagged(post):
' Get all people tags in the post '
from re import findall
text = post['caption']['text'].lower()
allFollows = []
if (text.find('follow') != (- 1)):
allFollows = findall('([@][\\w@_.]*)', text)
print((' [ ] Follow requried: (%s)' % ', '.join(set(allFollows... | Get all people tags in the post | instagramBot.py | getPeopleTagged | the-rccg/instaCompetitionBot | 8 | python | def getPeopleTagged(post):
' '
from re import findall
text = post['caption']['text'].lower()
allFollows = []
if (text.find('follow') != (- 1)):
allFollows = findall('([@][\\w@_.]*)', text)
print((' [ ] Follow requried: (%s)' % ', '.join(set(allFollows))))
return allFollows | def getPeopleTagged(post):
' '
from re import findall
text = post['caption']['text'].lower()
allFollows = []
if (text.find('follow') != (- 1)):
allFollows = findall('([@][\\w@_.]*)', text)
print((' [ ] Follow requried: (%s)' % ', '.join(set(allFollows))))
return allFollows<|doc... |
9bc9f9c8beea69c33c09355cfe9977d117c4cfedc7b847b2d3aa9a023f6f2edb | def enterContest(instagram, sleepCounter, contests, post, commented, usernameList, caption=''):
' Likes, follows, comments, and reposts if required '
global searchList
userIdList = tagsToUserIds(usernameList)
sleepCounter += followUsers((userIdList + [post['user']['pk']]))
if (len(userIdList) > 0):
... | Likes, follows, comments, and reposts if required | instagramBot.py | enterContest | the-rccg/instaCompetitionBot | 8 | python | def enterContest(instagram, sleepCounter, contests, post, commented, usernameList, caption=):
' '
global searchList
userIdList = tagsToUserIds(usernameList)
sleepCounter += followUsers((userIdList + [post['user']['pk']]))
if (len(userIdList) > 0):
searchList = (searchList + [str(userId) for... | def enterContest(instagram, sleepCounter, contests, post, commented, usernameList, caption=):
' '
global searchList
userIdList = tagsToUserIds(usernameList)
sleepCounter += followUsers((userIdList + [post['user']['pk']]))
if (len(userIdList) > 0):
searchList = (searchList + [str(userId) for... |
f3a8a25f272d4989be69b861483a443216bbeca1bdcb1b653f866eba06c2b629 | def cleanUserSearch(userSearchJson, minFollowers):
' Cleans Json of User search, Returns Dataframe '
userSearchData = pd.DataFrame(userSearchJson['users'])
del userSearchData['byline']
userSearchData = userSearchData[(userSearchData['is_private'] == False)]
userSearchData = userSearchData[(userSearc... | Cleans Json of User search, Returns Dataframe | instagramBot.py | cleanUserSearch | the-rccg/instaCompetitionBot | 8 | python | def cleanUserSearch(userSearchJson, minFollowers):
' '
userSearchData = pd.DataFrame(userSearchJson['users'])
del userSearchData['byline']
userSearchData = userSearchData[(userSearchData['is_private'] == False)]
userSearchData = userSearchData[(userSearchData['follower_count'] > minFollowers)]
... | def cleanUserSearch(userSearchJson, minFollowers):
' '
userSearchData = pd.DataFrame(userSearchJson['users'])
del userSearchData['byline']
userSearchData = userSearchData[(userSearchData['is_private'] == False)]
userSearchData = userSearchData[(userSearchData['follower_count'] > minFollowers)]
... |
55a270618aac8e6a03827c5c90176ef97a109d47264d930b4f233cb00da5e8e6 | def findUser(searchUser, minFollowers, returnType='list'):
' given name, search, clean, return restults '
instagram.searchUsers(searchUser)
userSearchJson = instagram.LastJson
if (userSearchJson['status'] == 'fail'):
print('fail ', datetime.datetime.now())
return
else:
userSe... | given name, search, clean, return restults | instagramBot.py | findUser | the-rccg/instaCompetitionBot | 8 | python | def findUser(searchUser, minFollowers, returnType='list'):
' '
instagram.searchUsers(searchUser)
userSearchJson = instagram.LastJson
if (userSearchJson['status'] == 'fail'):
print('fail ', datetime.datetime.now())
return
else:
userSearchData = cleanUserSearch(userSearchJson,... | def findUser(searchUser, minFollowers, returnType='list'):
' '
instagram.searchUsers(searchUser)
userSearchJson = instagram.LastJson
if (userSearchJson['status'] == 'fail'):
print('fail ', datetime.datetime.now())
return
else:
userSearchData = cleanUserSearch(userSearchJson,... |
fa4c52589c5a0189574772b6f3ce6fa979e3a021e9808c079449f94ccb8558c4 | def getFollowIdList(instagram):
' returns list of IDs from people I follow '
followingList = instagram.getTotalSelfFollowings()
followingDf = pd.DataFrame(followingList)
try:
return followingDf['pk'].tolist()
except:
return [] | returns list of IDs from people I follow | instagramBot.py | getFollowIdList | the-rccg/instaCompetitionBot | 8 | python | def getFollowIdList(instagram):
' '
followingList = instagram.getTotalSelfFollowings()
followingDf = pd.DataFrame(followingList)
try:
return followingDf['pk'].tolist()
except:
return [] | def getFollowIdList(instagram):
' '
followingList = instagram.getTotalSelfFollowings()
followingDf = pd.DataFrame(followingList)
try:
return followingDf['pk'].tolist()
except:
return []<|docstring|>returns list of IDs from people I follow<|endoftext|> |
7a9bda2f3d085d9496ad23c3f92965b89f750bd7ae9095dd2c83524cac18b400 | def usernamesToTagList(peopleNeeded, instagram):
' returns List of n usernames from own followers '
instagram.getSelfUserFollowers()
followers = pd.DataFrame(instagram.LastJson['users'])
if (len(followers) < peopleNeeded):
print('not enough followers to tag')
followerNames = ['braidsbybr... | returns List of n usernames from own followers | instagramBot.py | usernamesToTagList | the-rccg/instaCompetitionBot | 8 | python | def usernamesToTagList(peopleNeeded, instagram):
' '
instagram.getSelfUserFollowers()
followers = pd.DataFrame(instagram.LastJson['users'])
if (len(followers) < peopleNeeded):
print('not enough followers to tag')
followerNames = ['braidsbybreann', 'brownhairedbliss', 'emmaa.w', 'daisy_c... | def usernamesToTagList(peopleNeeded, instagram):
' '
instagram.getSelfUserFollowers()
followers = pd.DataFrame(instagram.LastJson['users'])
if (len(followers) < peopleNeeded):
print('not enough followers to tag')
followerNames = ['braidsbybreann', 'brownhairedbliss', 'emmaa.w', 'daisy_c... |
24e3a0ff5931461006caee129c84bad12851c12fff31ec15e51c32bba98727c5 | def search4NewUsers(searchUserList, sleepCounter):
' search for new Users given list '
totalFollowingIdList = getFollowIdList(instagram)
for searchUser in searchUserList:
print('Searching for: ', searchUser)
newUserIds = findUser(searchUser, minFollowers)
for userId in newUserIds:
... | search for new Users given list | instagramBot.py | search4NewUsers | the-rccg/instaCompetitionBot | 8 | python | def search4NewUsers(searchUserList, sleepCounter):
' '
totalFollowingIdList = getFollowIdList(instagram)
for searchUser in searchUserList:
print('Searching for: ', searchUser)
newUserIds = findUser(searchUser, minFollowers)
for userId in newUserIds:
if (userId not in tot... | def search4NewUsers(searchUserList, sleepCounter):
' '
totalFollowingIdList = getFollowIdList(instagram)
for searchUser in searchUserList:
print('Searching for: ', searchUser)
newUserIds = findUser(searchUser, minFollowers)
for userId in newUserIds:
if (userId not in tot... |
30092f98bb50d733a89d00e0c8e249c8f9c84c3fd49e6bbe0f8e518222d70287 | def tagsToUserIds(tagList):
' given a list of userids, gets user tag by search and match '
ids = []
for tag in tagList:
if (len(tag) > 1):
added = False
instagram.searchUsers(tag)
userList = instagram.LastJson['users']
for user in userList:
... | given a list of userids, gets user tag by search and match | instagramBot.py | tagsToUserIds | the-rccg/instaCompetitionBot | 8 | python | def tagsToUserIds(tagList):
' '
ids = []
for tag in tagList:
if (len(tag) > 1):
added = False
instagram.searchUsers(tag)
userList = instagram.LastJson['users']
for user in userList:
if (user['username'].lower() == tag.lower()):
... | def tagsToUserIds(tagList):
' '
ids = []
for tag in tagList:
if (len(tag) > 1):
added = False
instagram.searchUsers(tag)
userList = instagram.LastJson['users']
for user in userList:
if (user['username'].lower() == tag.lower()):
... |
31a10f696ae344ef89e0925def7b81814fa502aeaddbd9ef0d94ac1b066ad987 | def followUsers(userIdList):
' follow a list of new users if not already followed '
totalFollowingIdList = getFollowIdList(instagram)
toFollow = set([str(userId) for userId in userIdList if (userId not in totalFollowingIdList)])
sleepCounter = 0
for userId in toFollow:
instagram.follow(userI... | follow a list of new users if not already followed | instagramBot.py | followUsers | the-rccg/instaCompetitionBot | 8 | python | def followUsers(userIdList):
' '
totalFollowingIdList = getFollowIdList(instagram)
toFollow = set([str(userId) for userId in userIdList if (userId not in totalFollowingIdList)])
sleepCounter = 0
for userId in toFollow:
instagram.follow(userId)
newFollows.append(userId)
sleep... | def followUsers(userIdList):
' '
totalFollowingIdList = getFollowIdList(instagram)
toFollow = set([str(userId) for userId in userIdList if (userId not in totalFollowingIdList)])
sleepCounter = 0
for userId in toFollow:
instagram.follow(userId)
newFollows.append(userId)
sleep... |
499665d5ff768b42104c9d37012f26b84c0e9592c1fec01ba60a49e4c858065f | def checkCaptions(contests):
' Check and update captions of posts '
changed = 0
selfFeed = instagram.getTotalSelfUserFeed()
postsToCheck = contests[(contests['shared'] == True)][::(- 1)]
for i in range(min(len(selfFeed), len(postsToCheck))):
if ((selfFeed[i]['caption'] == None) and (postsToC... | Check and update captions of posts | instagramBot.py | checkCaptions | the-rccg/instaCompetitionBot | 8 | python | def checkCaptions(contests):
' '
changed = 0
selfFeed = instagram.getTotalSelfUserFeed()
postsToCheck = contests[(contests['shared'] == True)][::(- 1)]
for i in range(min(len(selfFeed), len(postsToCheck))):
if ((selfFeed[i]['caption'] == None) and (postsToCheck.iloc[i]['shareCaption'] == 'n... | def checkCaptions(contests):
' '
changed = 0
selfFeed = instagram.getTotalSelfUserFeed()
postsToCheck = contests[(contests['shared'] == True)][::(- 1)]
for i in range(min(len(selfFeed), len(postsToCheck))):
if ((selfFeed[i]['caption'] == None) and (postsToCheck.iloc[i]['shareCaption'] == 'n... |
bab3472d38a65e95e8039c7a35c21ebc5dd13aa77987cc3aedc91d412c367b9a | def randomSleepTimer(start, stop):
' prevent spam / overflow / suspension '
count = (random.randrange(start, stop) * slowdownFactor)
print('sleeping ', ('.' * count))
time.sleep(count)
return count | prevent spam / overflow / suspension | instagramBot.py | randomSleepTimer | the-rccg/instaCompetitionBot | 8 | python | def randomSleepTimer(start, stop):
' '
count = (random.randrange(start, stop) * slowdownFactor)
print('sleeping ', ('.' * count))
time.sleep(count)
return count | def randomSleepTimer(start, stop):
' '
count = (random.randrange(start, stop) * slowdownFactor)
print('sleeping ', ('.' * count))
time.sleep(count)
return count<|docstring|>prevent spam / overflow / suspension<|endoftext|> |
dff34458f926fe3449f3c0e3e5a1d1aea876e0848d0426e8826a8fa477603601 | def searchWebsite4Account(website, account='instagram.com'):
' finds instagram (or other) account linked on website '
" e.g. print(searchWebsite4Account('https://www.thomaspink.com/', account='instagram.com')) "
import re, urllib
checkWebsite = account.encode('ascii')
req = urllib.request.Request(we... | finds instagram (or other) account linked on website | instagramBot.py | searchWebsite4Account | the-rccg/instaCompetitionBot | 8 | python | def searchWebsite4Account(website, account='instagram.com'):
' '
" e.g. print(searchWebsite4Account('https://www.thomaspink.com/', account='instagram.com')) "
import re, urllib
checkWebsite = account.encode('ascii')
req = urllib.request.Request(website)
with urllib.request.urlopen(req) as respo... | def searchWebsite4Account(website, account='instagram.com'):
' '
" e.g. print(searchWebsite4Account('https://www.thomaspink.com/', account='instagram.com')) "
import re, urllib
checkWebsite = account.encode('ascii')
req = urllib.request.Request(website)
with urllib.request.urlopen(req) as respo... |
f4255ec36b562f88cd8a5e7f1aeb267b43abe513ce1df133c2b4df1615714d08 | def test_record_id():
"Creating a ModelBase should create a new record id 'rid.' For each\n instance, a new 'rid' should be created."
@add_schema
class MyModel(ModelBase):
pass
@add_schema
class MyOtherModel(ModelBase):
pass
m = MyModel()
m2 = MyOtherModel()
m3 = MyM... | Creating a ModelBase should create a new record id 'rid.' For each
instance, a new 'rid' should be created. | tests/test_pydent/test_base.py | test_record_id | aquariumbio/trident | 5 | python | def test_record_id():
"Creating a ModelBase should create a new record id 'rid.' For each\n instance, a new 'rid' should be created."
@add_schema
class MyModel(ModelBase):
pass
@add_schema
class MyOtherModel(ModelBase):
pass
m = MyModel()
m2 = MyOtherModel()
m3 = MyM... | def test_record_id():
"Creating a ModelBase should create a new record id 'rid.' For each\n instance, a new 'rid' should be created."
@add_schema
class MyModel(ModelBase):
pass
@add_schema
class MyOtherModel(ModelBase):
pass
m = MyModel()
m2 = MyOtherModel()
m3 = MyM... |
c30552aa2199168af540ae76882be15915d1bf1e8c09454b59cf30b1abcc6337 | def test_deepcopy():
'Deepcopy should retain attributes exactly.'
@add_schema
class MyModel(ModelBase):
pass
m = MyModel()
copied = copy.deepcopy(m)
assert (m.rid == copied.rid) | Deepcopy should retain attributes exactly. | tests/test_pydent/test_base.py | test_deepcopy | aquariumbio/trident | 5 | python | def test_deepcopy():
@add_schema
class MyModel(ModelBase):
pass
m = MyModel()
copied = copy.deepcopy(m)
assert (m.rid == copied.rid) | def test_deepcopy():
@add_schema
class MyModel(ModelBase):
pass
m = MyModel()
copied = copy.deepcopy(m)
assert (m.rid == copied.rid)<|docstring|>Deepcopy should retain attributes exactly.<|endoftext|> |
3e97bf2345c89152d979308ae6a32e4697622fa17f31e8f9b6bdd739d092a033 | @pytest.mark.parametrize('copy_method', [pytest.param((lambda x: x.copy())), pytest.param((lambda x: copy.copy(x)))])
def test_copy(copy_method):
'Copy should anonymize models.'
@add_schema
class MyModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
m = MyModel(5)
... | Copy should anonymize models. | tests/test_pydent/test_base.py | test_copy | aquariumbio/trident | 5 | python | @pytest.mark.parametrize('copy_method', [pytest.param((lambda x: x.copy())), pytest.param((lambda x: copy.copy(x)))])
def test_copy(copy_method):
@add_schema
class MyModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
m = MyModel(5)
copied = copy_method(m)
as... | @pytest.mark.parametrize('copy_method', [pytest.param((lambda x: x.copy())), pytest.param((lambda x: copy.copy(x)))])
def test_copy(copy_method):
@add_schema
class MyModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
m = MyModel(5)
copied = copy_method(m)
as... |
859bbe5df64cf8788d677ce1289493a9fddb4f6bfef633d52421fa9bb601eb75 | def test_copy_anonymizes_nested_relationships():
'Copy should recursively anonymize all models.'
@add_schema
class MyModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
@add_schema
class MyOtherModel(ModelBase):
def __init__(self, id):
super(... | Copy should recursively anonymize all models. | tests/test_pydent/test_base.py | test_copy_anonymizes_nested_relationships | aquariumbio/trident | 5 | python | def test_copy_anonymizes_nested_relationships():
@add_schema
class MyModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
@add_schema
class MyOtherModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
m = MyModel(1)
m2 = M... | def test_copy_anonymizes_nested_relationships():
@add_schema
class MyModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
@add_schema
class MyOtherModel(ModelBase):
def __init__(self, id):
super().__init__(id=id)
m = MyModel(1)
m2 = M... |
0777c85f34582a856003704f7aa50d9d016b8b4750efef29f942e794a39d9deb | def test_basic_constructor(mymodel):
'Model should absorb the kwargs.'
m = mymodel(name='SomeName', id=2)
assert (m.name == 'SomeName')
assert (m.id == 2)
data = m.dump()
data.pop('rid')
assert (data == {'name': 'SomeName', 'id': 2}) | Model should absorb the kwargs. | tests/test_pydent/test_base.py | test_basic_constructor | aquariumbio/trident | 5 | python | def test_basic_constructor(mymodel):
m = mymodel(name='SomeName', id=2)
assert (m.name == 'SomeName')
assert (m.id == 2)
data = m.dump()
data.pop('rid')
assert (data == {'name': 'SomeName', 'id': 2}) | def test_basic_constructor(mymodel):
m = mymodel(name='SomeName', id=2)
assert (m.name == 'SomeName')
assert (m.id == 2)
data = m.dump()
data.pop('rid')
assert (data == {'name': 'SomeName', 'id': 2})<|docstring|>Model should absorb the kwargs.<|endoftext|> |
aee5ef9be7db0bc9072ef9388b50f8ecc2ae29c504cf765ad68263f0a0f40891 | def test_base_constructor_with_marshaller(mymodel):
'MyModel initializes should absorb kwargs into attributes.\n\n With a schema, those attributes are also tracked and available for\n dumping.\n '
m = mymodel(name='model', id=5)
assert (m.name == 'model')
assert (m.id == 5)
mdump = m.dump()... | MyModel initializes should absorb kwargs into attributes.
With a schema, those attributes are also tracked and available for
dumping. | tests/test_pydent/test_base.py | test_base_constructor_with_marshaller | aquariumbio/trident | 5 | python | def test_base_constructor_with_marshaller(mymodel):
'MyModel initializes should absorb kwargs into attributes.\n\n With a schema, those attributes are also tracked and available for\n dumping.\n '
m = mymodel(name='model', id=5)
assert (m.name == 'model')
assert (m.id == 5)
mdump = m.dump()... | def test_base_constructor_with_marshaller(mymodel):
'MyModel initializes should absorb kwargs into attributes.\n\n With a schema, those attributes are also tracked and available for\n dumping.\n '
m = mymodel(name='model', id=5)
assert (m.name == 'model')
assert (m.id == 5)
mdump = m.dump()... |
01d2e94c92a430132e62adf8d894d8530d42290fa8e2d58b24c18f6755210db2 | def test_connect_to_session(mymodel, fake_session):
'Connecting to other sessions afterward should not be allowed.'
m = mymodel()
assert (m.session is None)
m.connect_to_session(fake_session)
assert (m.session == fake_session)
fake_session2 = copy.copy(fake_session)
with pytest.raises(Except... | Connecting to other sessions afterward should not be allowed. | tests/test_pydent/test_base.py | test_connect_to_session | aquariumbio/trident | 5 | python | def test_connect_to_session(mymodel, fake_session):
m = mymodel()
assert (m.session is None)
m.connect_to_session(fake_session)
assert (m.session == fake_session)
fake_session2 = copy.copy(fake_session)
with pytest.raises(Exception):
m.connect_to_session(fake_session2) | def test_connect_to_session(mymodel, fake_session):
m = mymodel()
assert (m.session is None)
m.connect_to_session(fake_session)
assert (m.session == fake_session)
fake_session2 = copy.copy(fake_session)
with pytest.raises(Exception):
m.connect_to_session(fake_session2)<|docstring|>C... |
fa29c445537da671ec79b297df4018470bd778658702eef7422fe7d57e3a8c90 | def test_check_for_session(mymodel, fake_session):
'If session is none, _check_for_session should raise an\n AttributeError.'
m = mymodel()
with pytest.raises(NoSessionError):
m._check_for_session()
m.connect_to_session(fake_session)
m._check_for_session() | If session is none, _check_for_session should raise an
AttributeError. | tests/test_pydent/test_base.py | test_check_for_session | aquariumbio/trident | 5 | python | def test_check_for_session(mymodel, fake_session):
'If session is none, _check_for_session should raise an\n AttributeError.'
m = mymodel()
with pytest.raises(NoSessionError):
m._check_for_session()
m.connect_to_session(fake_session)
m._check_for_session() | def test_check_for_session(mymodel, fake_session):
'If session is none, _check_for_session should raise an\n AttributeError.'
m = mymodel()
with pytest.raises(NoSessionError):
m._check_for_session()
m.connect_to_session(fake_session)
m._check_for_session()<|docstring|>If session is none, ... |
0b9f092b8a7bea0cd6cf09c4381d307c2df8ec3dde0ebefdb8787d300f9d01c1 | def test_model_registry(mymodel):
'We expect get_model to return the value in the models dictionary.'
assert ('MyModel' in ModelRegistry.models)
assert (ModelRegistry.models['MyModel'] == mymodel)
assert (ModelRegistry.get_model('MyModel') == mymodel)
del ModelRegistry.models['MyModel'] | We expect get_model to return the value in the models dictionary. | tests/test_pydent/test_base.py | test_model_registry | aquariumbio/trident | 5 | python | def test_model_registry(mymodel):
assert ('MyModel' in ModelRegistry.models)
assert (ModelRegistry.models['MyModel'] == mymodel)
assert (ModelRegistry.get_model('MyModel') == mymodel)
del ModelRegistry.models['MyModel'] | def test_model_registry(mymodel):
assert ('MyModel' in ModelRegistry.models)
assert (ModelRegistry.models['MyModel'] == mymodel)
assert (ModelRegistry.get_model('MyModel') == mymodel)
del ModelRegistry.models['MyModel']<|docstring|>We expect get_model to return the value in the models dictionary.<|... |
0de2a0bb051dba059f7085ec41197e88392b440de06b1ce13274182694b44339 | def test_no_model_in_registry():
"ModelRegistry should raise error if model doesn't exist."
with pytest.raises(exceptions.ModelRegistryError):
ModelRegistry.get_model('SomeModelThatDoesntExist') | ModelRegistry should raise error if model doesn't exist. | tests/test_pydent/test_base.py | test_no_model_in_registry | aquariumbio/trident | 5 | python | def test_no_model_in_registry():
with pytest.raises(exceptions.ModelRegistryError):
ModelRegistry.get_model('SomeModelThatDoesntExist') | def test_no_model_in_registry():
with pytest.raises(exceptions.ModelRegistryError):
ModelRegistry.get_model('SomeModelThatDoesntExist')<|docstring|>ModelRegistry should raise error if model doesn't exist.<|endoftext|> |
77e5d38faa310185252a165f346ba59a74d9b965f67d8b75672a3a264c21ed8b | def test_find_no_session(mymodel):
'ModelBase should raise AttributeError if no session is attacheded.'
m = mymodel()
with pytest.raises(NoSessionError):
m.find_callback(None, None) | ModelBase should raise AttributeError if no session is attacheded. | tests/test_pydent/test_base.py | test_find_no_session | aquariumbio/trident | 5 | python | def test_find_no_session(mymodel):
m = mymodel()
with pytest.raises(NoSessionError):
m.find_callback(None, None) | def test_find_no_session(mymodel):
m = mymodel()
with pytest.raises(NoSessionError):
m.find_callback(None, None)<|docstring|>ModelBase should raise AttributeError if no session is attacheded.<|endoftext|> |
40c6718cf8cd242fa3aa28fafd5a3b702b9586bcc14d3c17ff94d67752a66cb5 | def test_where_no_session(mymodel):
'ModelBase should raise AttributeError if no session is attacheded.'
m = mymodel()
with pytest.raises(NoSessionError):
m.where_callback(None, None) | ModelBase should raise AttributeError if no session is attacheded. | tests/test_pydent/test_base.py | test_where_no_session | aquariumbio/trident | 5 | python | def test_where_no_session(mymodel):
m = mymodel()
with pytest.raises(NoSessionError):
m.where_callback(None, None) | def test_where_no_session(mymodel):
m = mymodel()
with pytest.raises(NoSessionError):
m.where_callback(None, None)<|docstring|>ModelBase should raise AttributeError if no session is attacheded.<|endoftext|> |
52e8dc1d5ce46f92cef56042c9e6d59b57f5814a88e895a094dd2574f7ef8298 | def test_where_and_find(mymodel, monkeypatch, fake_session):
"Calling the 'where' wrapper on a ModelBase should attempt to get a model\n interface and call 'where' or 'find' on the interface.\n\n In this case, a fake model interface is returned in which the\n methods return the parameter passed in\n "
... | Calling the 'where' wrapper on a ModelBase should attempt to get a model
interface and call 'where' or 'find' on the interface.
In this case, a fake model interface is returned in which the
methods return the parameter passed in | tests/test_pydent/test_base.py | test_where_and_find | aquariumbio/trident | 5 | python | def test_where_and_find(mymodel, monkeypatch, fake_session):
"Calling the 'where' wrapper on a ModelBase should attempt to get a model\n interface and call 'where' or 'find' on the interface.\n\n In this case, a fake model interface is returned in which the\n methods return the parameter passed in\n "
... | def test_where_and_find(mymodel, monkeypatch, fake_session):
"Calling the 'where' wrapper on a ModelBase should attempt to get a model\n interface and call 'where' or 'find' on the interface.\n\n In this case, a fake model interface is returned in which the\n methods return the parameter passed in\n "
... |
41b181f44cee0d18dc3c45c6f8e8947af5f52c3c20bc8096ba5fe6088141823e | def test_uri(base):
'Expect with with the `include_uri` key includes the default URI.'
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
assert (model.uri == 'http://aquarium.org/my_models/10') | Expect with with the `include_uri` key includes the default URI. | tests/test_pydent/test_base.py | test_uri | aquariumbio/trident | 5 | python | def test_uri(base):
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
assert (model.uri == 'http://aquarium.org/my_models/10') | def test_uri(base):
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
assert (model.uri == 'http://aquarium.org/my_models/10')<|docstring|>Expect with with the `include_uri` key includes the default URI.<|endoftext|> |
a68ae89b4462aa9597c670afb8f29dad4ee75d92b90de0030b5d5302ad48bbed | def test_dump_uri(base):
'Expect with with the `include_uri` key includes the default URI.'
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
no_uri = model.dump()
with_uri = model.dump(include_uri=True)
assert ('__uri__' not in no_uri)
assert ('__uri__' ... | Expect with with the `include_uri` key includes the default URI. | tests/test_pydent/test_base.py | test_dump_uri | aquariumbio/trident | 5 | python | def test_dump_uri(base):
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
no_uri = model.dump()
with_uri = model.dump(include_uri=True)
assert ('__uri__' not in no_uri)
assert ('__uri__' in with_uri)
assert (with_uri['__uri__'] == 'http://aquarium.o... | def test_dump_uri(base):
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
no_uri = model.dump()
with_uri = model.dump(include_uri=True)
assert ('__uri__' not in no_uri)
assert ('__uri__' in with_uri)
assert (with_uri['__uri__'] == 'http://aquarium.o... |
62dc6d6bf7d3891c164b8be150009cfb60598de3758ed0122592a184f79e0e6e | def test_dump_model(base):
'Expect with with the `include_uri` key includes the default URI.'
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
no_mt = model.dump()
with_mt = model.dump(include_model_type=True)
assert ('__model__' not in no_mt)
assert ('_... | Expect with with the `include_uri` key includes the default URI. | tests/test_pydent/test_base.py | test_dump_model | aquariumbio/trident | 5 | python | def test_dump_model(base):
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
no_mt = model.dump()
with_mt = model.dump(include_model_type=True)
assert ('__model__' not in no_mt)
assert ('__model__' in with_mt)
assert (with_mt['__model__'] == 'MyModel... | def test_dump_model(base):
@add_schema
class MyModel(base):
pass
model = MyModel()
model.id = 10
no_mt = model.dump()
with_mt = model.dump(include_model_type=True)
assert ('__model__' not in no_mt)
assert ('__model__' in with_mt)
assert (with_mt['__model__'] == 'MyModel... |
c80876228e44b48ddfc87ec0ae471aae679d3d4e06b05df80a6dea6870874646 | def fake_model_interface(self, model_name):
'A fake model interface to test where.'
class FakeInterface():
def find(id):
return id
def where(params):
return params
return FakeInterface | A fake model interface to test where. | tests/test_pydent/test_base.py | fake_model_interface | aquariumbio/trident | 5 | python | def fake_model_interface(self, model_name):
class FakeInterface():
def find(id):
return id
def where(params):
return params
return FakeInterface | def fake_model_interface(self, model_name):
class FakeInterface():
def find(id):
return id
def where(params):
return params
return FakeInterface<|docstring|>A fake model interface to test where.<|endoftext|> |
7642287bd9a57ae7c63490f597e267cfef9e75dd568d8fa283a47cd8074b7fd1 | def loss(self, model_response):
'Compute loss of given image w.r.t. initialized content.\n\n\t\tArguments:\n\t\t\tmodel_response (tensor): Model response to target image.\n\t\t'
losses = []
for l in self.layers:
content_response = getattr(self, 'content_response{}'.format(l))
target_response... | Compute loss of given image w.r.t. initialized content.
Arguments:
model_response (tensor): Model response to target image. | src/loss/content.py | loss | paulwarkentin/pytorch-neural-doodle | 15 | python | def loss(self, model_response):
'Compute loss of given image w.r.t. initialized content.\n\n\t\tArguments:\n\t\t\tmodel_response (tensor): Model response to target image.\n\t\t'
losses = []
for l in self.layers:
content_response = getattr(self, 'content_response{}'.format(l))
target_response... | def loss(self, model_response):
'Compute loss of given image w.r.t. initialized content.\n\n\t\tArguments:\n\t\t\tmodel_response (tensor): Model response to target image.\n\t\t'
losses = []
for l in self.layers:
content_response = getattr(self, 'content_response{}'.format(l))
target_response... |
c743def28c5642738a9b3ef659c95ab781e27b052fbadb5cbea00202e2757eb8 | def modellist(filename):
' Read NFAs from given file. '
content = json.load(open(filename, 'r', encoding='utf-8'))
model = content['nfa items']
tmplist = list()
for item in model:
tmplist.append(item)
return tmplist | Read NFAs from given file. | main.py | modellist | Micuks/Convert2DFA | 0 | python | def modellist(filename):
' '
content = json.load(open(filename, 'r', encoding='utf-8'))
model = content['nfa items']
tmplist = list()
for item in model:
tmplist.append(item)
return tmplist | def modellist(filename):
' '
content = json.load(open(filename, 'r', encoding='utf-8'))
model = content['nfa items']
tmplist = list()
for item in model:
tmplist.append(item)
return tmplist<|docstring|>Read NFAs from given file.<|endoftext|> |
d4e1c0e167ec523b2055d06befcaa8db307c62ba4d5226b7c4e290efb6165145 | def powerset(superset):
' Get all subsets of the given set. '
subsets = list()
for i in range((2 ** len(superset))):
subset = list()
for j in range(len(superset)):
if (((1 << j) & i) != 0):
subset.append(superset[j])
subset.sort()
subsets.append(su... | Get all subsets of the given set. | main.py | powerset | Micuks/Convert2DFA | 0 | python | def powerset(superset):
' '
subsets = list()
for i in range((2 ** len(superset))):
subset = list()
for j in range(len(superset)):
if (((1 << j) & i) != 0):
subset.append(superset[j])
subset.sort()
subsets.append(subset)
return subsets | def powerset(superset):
' '
subsets = list()
for i in range((2 ** len(superset))):
subset = list()
for j in range(len(superset)):
if (((1 << j) & i) != 0):
subset.append(superset[j])
subset.sort()
subsets.append(subset)
return subsets<|docstri... |
ea075f080dc9a13682e0f7a9f39d65a1fbd43022ce9d6f858a4adcda79b1e875 | def convert2dfa(dict_nfa):
' Convert NFA to DFA '
tmp_dfa = dfa(dict_nfa)
tmp_dfa.states = powerset(tmp_dfa.states)
tmp_delta_function = dict()
for alpha in tmp_dfa.delta_function:
tmp_delta_function[alpha] = dict()
tmpset = set()
for beta in tmp_dfa.states:
if (l... | Convert NFA to DFA | main.py | convert2dfa | Micuks/Convert2DFA | 0 | python | def convert2dfa(dict_nfa):
' '
tmp_dfa = dfa(dict_nfa)
tmp_dfa.states = powerset(tmp_dfa.states)
tmp_delta_function = dict()
for alpha in tmp_dfa.delta_function:
tmp_delta_function[alpha] = dict()
tmpset = set()
for beta in tmp_dfa.states:
if (len(beta) == 0):
... | def convert2dfa(dict_nfa):
' '
tmp_dfa = dfa(dict_nfa)
tmp_dfa.states = powerset(tmp_dfa.states)
tmp_delta_function = dict()
for alpha in tmp_dfa.delta_function:
tmp_delta_function[alpha] = dict()
tmpset = set()
for beta in tmp_dfa.states:
if (len(beta) == 0):
... |
985df05b1e3e9c11118be168760e30122210456d3568dac0f44229e49557ac4d | @retailers_v1_blueprint.route('/retailers', methods=['GET'])
@logged_in
def get_retailers():
'\n Get all retailer objects.\n\n :return: [{\n "id": "123",\n "address": {Address}\n }, {...}]\n\n '
retailers = retailer_service.get_retailers(token=g.auth['loopback_token'])
return Respo... | Get all retailer objects.
:return: [{
"id": "123",
"address": {Address}
}, {...}] | server/web/rest/retailers.py | get_retailers | abisubra/logistics-wizard-controller | 2 | python | @retailers_v1_blueprint.route('/retailers', methods=['GET'])
@logged_in
def get_retailers():
'\n Get all retailer objects.\n\n :return: [{\n "id": "123",\n "address": {Address}\n }, {...}]\n\n '
retailers = retailer_service.get_retailers(token=g.auth['loopback_token'])
return Respo... | @retailers_v1_blueprint.route('/retailers', methods=['GET'])
@logged_in
def get_retailers():
'\n Get all retailer objects.\n\n :return: [{\n "id": "123",\n "address": {Address}\n }, {...}]\n\n '
retailers = retailer_service.get_retailers(token=g.auth['loopback_token'])
return Respo... |
ad30dbba3cea3d524e4452dee84cb874d9aa7172ba5d0436019a0238b48faaa7 | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>', methods=['GET'])
@logged_in
def get_retailer(retailer_id):
'\n Retrieve a single retailer object.\n\n :param retailer_id: The retailer\'s id\n\n :return: {\n "id": "123",\n "address": {Address}\n }\n\n '
check_null_i... | Retrieve a single retailer object.
:param retailer_id: The retailer's id
:return: {
"id": "123",
"address": {Address}
} | server/web/rest/retailers.py | get_retailer | abisubra/logistics-wizard-controller | 2 | python | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>', methods=['GET'])
@logged_in
def get_retailer(retailer_id):
'\n Retrieve a single retailer object.\n\n :param retailer_id: The retailer\'s id\n\n :return: {\n "id": "123",\n "address": {Address}\n }\n\n '
check_null_i... | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>', methods=['GET'])
@logged_in
def get_retailer(retailer_id):
'\n Retrieve a single retailer object.\n\n :param retailer_id: The retailer\'s id\n\n :return: {\n "id": "123",\n "address": {Address}\n }\n\n '
check_null_i... |
3dce9a7f6b8a6bde97ebe309c7f94617e5834476b50d768f55ac8d25d78c694d | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>/shipments', methods=['GET'])
@logged_in
def get_retailer_shipments(retailer_id):
'\n Retrieve all shipments heading to the specified retailer.\n\n :param retailer_id: The retailer\'s id\n\n :return: [{\n "id": "123",\n "status":... | Retrieve all shipments heading to the specified retailer.
:param retailer_id: The retailer's id
:return: [{
"id": "123",
"status": "SHIPPED",
"createdAt": "2015-11-05T22:00:51.692765",
"updatedAt": "2015-11-08T22:00:51.692765",
"deliveredAt": "2015-11-08T22:00:51.692765",
"estimatedTimeOfArr... | server/web/rest/retailers.py | get_retailer_shipments | abisubra/logistics-wizard-controller | 2 | python | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>/shipments', methods=['GET'])
@logged_in
def get_retailer_shipments(retailer_id):
'\n Retrieve all shipments heading to the specified retailer.\n\n :param retailer_id: The retailer\'s id\n\n :return: [{\n "id": "123",\n "status":... | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>/shipments', methods=['GET'])
@logged_in
def get_retailer_shipments(retailer_id):
'\n Retrieve all shipments heading to the specified retailer.\n\n :param retailer_id: The retailer\'s id\n\n :return: [{\n "id": "123",\n "status":... |
f0c9a64a46092f20b1dcdfc6eef8921e54b5a94a765ef1a94e754b8248b428cd | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>/inventory', methods=['GET'])
@logged_in
def get_retailer_inventory(retailer_id):
'\n Retrieve all inventory at the specified retailer.\n\n :param retailer_id: The retailer\'s id\n\n :return: [{\n "id": "123",\n "quantity": 10,\n... | Retrieve all inventory at the specified retailer.
:param retailer_id: The retailer's id
:return: [{
"id": "123",
"quantity": 10,
"productId": "123",
"locationId": "123",
"locationType": "Retailer"
}, {...}] | server/web/rest/retailers.py | get_retailer_inventory | abisubra/logistics-wizard-controller | 2 | python | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>/inventory', methods=['GET'])
@logged_in
def get_retailer_inventory(retailer_id):
'\n Retrieve all inventory at the specified retailer.\n\n :param retailer_id: The retailer\'s id\n\n :return: [{\n "id": "123",\n "quantity": 10,\n... | @retailers_v1_blueprint.route('/retailers/<string:retailer_id>/inventory', methods=['GET'])
@logged_in
def get_retailer_inventory(retailer_id):
'\n Retrieve all inventory at the specified retailer.\n\n :param retailer_id: The retailer\'s id\n\n :return: [{\n "id": "123",\n "quantity": 10,\n... |
2b3752ce822cbeb9eb21061a8b8b84976e553ff7bf75fa6e1512574b261a6a00 | def __init__(self, environment):
'Initialize the extension with the given environment.'
super(JsonifyExtension, self).__init__(environment)
def jsonify(obj):
return json.dumps(obj, sort_keys=True, indent=4)
environment.filters['jsonify'] = jsonify | Initialize the extension with the given environment. | cookiecutter/extensions.py | __init__ | Benjamin-Lee/cookiecutter | 7 | python | def __init__(self, environment):
super(JsonifyExtension, self).__init__(environment)
def jsonify(obj):
return json.dumps(obj, sort_keys=True, indent=4)
environment.filters['jsonify'] = jsonify | def __init__(self, environment):
super(JsonifyExtension, self).__init__(environment)
def jsonify(obj):
return json.dumps(obj, sort_keys=True, indent=4)
environment.filters['jsonify'] = jsonify<|docstring|>Initialize the extension with the given environment.<|endoftext|> |
d1e8e33ec5d70dacfaade4ea85c68b6330a88ef2346bf2bbfc5698ad3200613a | def filter_headers(data):
'只设置host content-type 还有x开头的头部.\n :param data(dict): 所有的头部信息.\n :return(dict): 计算进签名的头部.\n '
headers = {}
for i in data.keys():
if ((i == 'Content-Type') or (i == 'Host') or (i[0] == 'x') or (i[0] == 'X')):
headers[i] = data[i]
return headers | 只设置host content-type 还有x开头的头部.
:param data(dict): 所有的头部信息.
:return(dict): 计算进签名的头部. | api/service.py | filter_headers | wonder-sy0618/youth_sx | 0 | python | def filter_headers(data):
'只设置host content-type 还有x开头的头部.\n :param data(dict): 所有的头部信息.\n :return(dict): 计算进签名的头部.\n '
headers = {}
for i in data.keys():
if ((i == 'Content-Type') or (i == 'Host') or (i[0] == 'x') or (i[0] == 'X')):
headers[i] = data[i]
return headers | def filter_headers(data):
'只设置host content-type 还有x开头的头部.\n :param data(dict): 所有的头部信息.\n :return(dict): 计算进签名的头部.\n '
headers = {}
for i in data.keys():
if ((i == 'Content-Type') or (i == 'Host') or (i[0] == 'x') or (i[0] == 'X')):
headers[i] = data[i]
return headers<|docst... |
0da0827b2470d2dabd73ef4e981957146f8b9fe152f2a7b86a086b72a258e5aa | def test_no_options(tmpdir):
"Verify help message when called with no options.\n\n Run mailmerge at the CLI with no options. Do this in an empty temporary\n directory to ensure that mailmerge doesn't find any default input files.\n "
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
... | Verify help message when called with no options.
Run mailmerge at the CLI with no options. Do this in an empty temporary
directory to ensure that mailmerge doesn't find any default input files. | tests/test_main.py | test_no_options | sudhanshu456/mailmerge | 1 | python | def test_no_options(tmpdir):
"Verify help message when called with no options.\n\n Run mailmerge at the CLI with no options. Do this in an empty temporary\n directory to ensure that mailmerge doesn't find any default input files.\n "
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
... | def test_no_options(tmpdir):
"Verify help message when called with no options.\n\n Run mailmerge at the CLI with no options. Do this in an empty temporary\n directory to ensure that mailmerge doesn't find any default input files.\n "
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
... |
eef14b5353a5a05d3027813c284ced483c6e18241823f14ca0da4cedc874363b | def test_sample(tmpdir):
'Verify --sample creates sample input files.'
with tmpdir.as_cwd():
output = sh.mailmerge('--sample')
assert Path((tmpdir / 'mailmerge_template.txt')).exists()
assert Path((tmpdir / 'mailmerge_database.csv')).exists()
assert Path((tmpdir / 'mailmerge_server.conf')).e... | Verify --sample creates sample input files. | tests/test_main.py | test_sample | sudhanshu456/mailmerge | 1 | python | def test_sample(tmpdir):
with tmpdir.as_cwd():
output = sh.mailmerge('--sample')
assert Path((tmpdir / 'mailmerge_template.txt')).exists()
assert Path((tmpdir / 'mailmerge_database.csv')).exists()
assert Path((tmpdir / 'mailmerge_server.conf')).exists()
assert (output.stderr.decode('utf... | def test_sample(tmpdir):
with tmpdir.as_cwd():
output = sh.mailmerge('--sample')
assert Path((tmpdir / 'mailmerge_template.txt')).exists()
assert Path((tmpdir / 'mailmerge_database.csv')).exists()
assert Path((tmpdir / 'mailmerge_server.conf')).exists()
assert (output.stderr.decode('utf... |
711c92ffc5671f7e583a508ef583d0d58f7ac39ebce70db9ba3e3f345318e234 | def test_sample_clobber_template(tmpdir):
"Verify --sample won't clobber template if it already exists."
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr ... | Verify --sample won't clobber template if it already exists. | tests/test_main.py | test_sample_clobber_template | sudhanshu456/mailmerge | 1 | python | def test_sample_clobber_template(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
... | def test_sample_clobber_template(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
... |
1290ecd6a380f57e89e8b68d060129d8da6c7f58e5c2fa9a6d9355ae9a7a9485 | def test_sample_clobber_database(tmpdir):
"Verify --sample won't clobber database if it already exists."
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_database.csv').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr ... | Verify --sample won't clobber database if it already exists. | tests/test_main.py | test_sample_clobber_database | sudhanshu456/mailmerge | 1 | python | def test_sample_clobber_database(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_database.csv').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
... | def test_sample_clobber_database(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_database.csv').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
... |
5a08318db915a57cac38348d48151f79df07991c4d6de8bf20f72aaca74b2512 | def test_sample_clobber_config(tmpdir):
"Verify --sample won't clobber config if it already exists."
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_server.conf').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = err... | Verify --sample won't clobber config if it already exists. | tests/test_main.py | test_sample_clobber_config | sudhanshu456/mailmerge | 1 | python | def test_sample_clobber_config(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_server.conf').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
... | def test_sample_clobber_config(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_server.conf').touch()
sh.mailmerge('--sample')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
... |
84d1348cf6f9bcc3d4bd03bc1faf271118cf37ccbd27f5e03652731412b27239 | def test_defaults(tmpdir):
'When no options are provided, use default input file names.'
with tmpdir.as_cwd():
sh.mailmerge('--sample')
output = sh.mailmerge()
assert (output.stderr.decode('utf-8') == '')
assert ('message 1 sent' in output)
assert ('Limit was 1 message' in output)
... | When no options are provided, use default input file names. | tests/test_main.py | test_defaults | sudhanshu456/mailmerge | 1 | python | def test_defaults(tmpdir):
with tmpdir.as_cwd():
sh.mailmerge('--sample')
output = sh.mailmerge()
assert (output.stderr.decode('utf-8') == )
assert ('message 1 sent' in output)
assert ('Limit was 1 message' in output)
assert ('This was a dry run' in output) | def test_defaults(tmpdir):
with tmpdir.as_cwd():
sh.mailmerge('--sample')
output = sh.mailmerge()
assert (output.stderr.decode('utf-8') == )
assert ('message 1 sent' in output)
assert ('Limit was 1 message' in output)
assert ('This was a dry run' in output)<|docstring|>When no o... |
68dceab0115a4c4419deb9492d8eaf5bf6389a701d92e3585b5ae2284413a05f | def test_bad_limit(tmpdir):
'Verify --limit with bad value.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.cs... | Verify --limit with bad value. | tests/test_main.py | test_bad_limit | sudhanshu456/mailmerge | 1 | python | def test_bad_limit(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_tex... | def test_bad_limit(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_tex... |
2b801eab2c515214d1de63731ea6c1632bb3a17cbc1653715c34d33d190e2a47 | def test_limit_combo(tmpdir):
'Verify --limit 1 --no-limit results in no limit.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir / 'm... | Verify --limit 1 --no-limit results in no limit. | tests/test_main.py | test_limit_combo | sudhanshu456/mailmerge | 1 | python | def test_limit_combo(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_t... | def test_limit_combo(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_t... |
fac5d56f6bd9f74dfc0eb21c6fe5b9821e49f336ff8757a4926a1079c7ba65e1 | def test_template_not_found(tmpdir):
'Verify error when template input file not found.'
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge('--template', 'notfound.txt')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
asser... | Verify error when template input file not found. | tests/test_main.py | test_template_not_found | sudhanshu456/mailmerge | 1 | python | def test_template_not_found(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge('--template', 'notfound.txt')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("Error: can't find temp... | def test_template_not_found(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge('--template', 'notfound.txt')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("Error: can't find temp... |
9039c9edb674cbb22fbd94d63cc02f7d0e64c14160b5ac0998e81cf91a723861 | def test_database_not_found(tmpdir):
'Verify error when database input file not found.'
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
sh.mailmerge('--database', 'notfound.csv')
stdout = error.value.stdout.decode('utf-8')
stderr... | Verify error when database input file not found. | tests/test_main.py | test_database_not_found | sudhanshu456/mailmerge | 1 | python | def test_database_not_found(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
sh.mailmerge('--database', 'notfound.csv')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (... | def test_database_not_found(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
sh.mailmerge('--database', 'notfound.csv')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (... |
20939e4d0cbfacb59055d4099371427f149daa1d162627999b2b59d7b449ab54 | def test_config_not_found(tmpdir):
'Verify error when config input file not found.'
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
Path('mailmerge_database.csv').touch()
sh.mailmerge('--config', 'notfound.conf')
stdout = err... | Verify error when config input file not found. | tests/test_main.py | test_config_not_found | sudhanshu456/mailmerge | 1 | python | def test_config_not_found(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
Path('mailmerge_database.csv').touch()
sh.mailmerge('--config', 'notfound.conf')
stdout = error.value.stdout.decode('utf-8')
stderr = err... | def test_config_not_found(tmpdir):
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
Path('mailmerge_template.txt').touch()
Path('mailmerge_database.csv').touch()
sh.mailmerge('--config', 'notfound.conf')
stdout = error.value.stdout.decode('utf-8')
stderr = err... |
9813fe99de93c7fa69389803c4483910d5ad1f055ac3464f51453091b818979b | def test_help():
'Verify -h or --help produces a help message.'
output = sh.mailmerge('--help')
assert (output.stderr.decode('utf-8') == '')
assert ('Usage:' in output)
assert ('Options:' in output)
output2 = sh.mailmerge('-h')
assert (output2.stderr.decode('utf-8') == '')
assert (output... | Verify -h or --help produces a help message. | tests/test_main.py | test_help | sudhanshu456/mailmerge | 1 | python | def test_help():
output = sh.mailmerge('--help')
assert (output.stderr.decode('utf-8') == )
assert ('Usage:' in output)
assert ('Options:' in output)
output2 = sh.mailmerge('-h')
assert (output2.stderr.decode('utf-8') == )
assert (output == output2) | def test_help():
output = sh.mailmerge('--help')
assert (output.stderr.decode('utf-8') == )
assert ('Usage:' in output)
assert ('Options:' in output)
output2 = sh.mailmerge('-h')
assert (output2.stderr.decode('utf-8') == )
assert (output == output2)<|docstring|>Verify -h or --help produ... |
9cc8eca3ae09bee038e9f761dd8342e5bc4b932e4ab6997057220f7591e790a3 | def test_version():
'Verify --version produces a version.'
output = sh.mailmerge('--version')
assert (output.stderr.decode('utf-8') == '')
assert ('mailmerge, version' in output) | Verify --version produces a version. | tests/test_main.py | test_version | sudhanshu456/mailmerge | 1 | python | def test_version():
output = sh.mailmerge('--version')
assert (output.stderr.decode('utf-8') == )
assert ('mailmerge, version' in output) | def test_version():
output = sh.mailmerge('--version')
assert (output.stderr.decode('utf-8') == )
assert ('mailmerge, version' in output)<|docstring|>Verify --version produces a version.<|endoftext|> |
aaf0e3d4c58e284c4e24614f13e747d6a907f56e979230ce4708d376a99f1b78 | def test_bad_template(tmpdir):
'Template mismatch with database header should produce an error.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{error_not_in_database}}\n SUBJECT: Testing mailmerge\n FROM: example@example.com\n... | Template mismatch with database header should produce an error. | tests/test_main.py | test_bad_template | sudhanshu456/mailmerge | 1 | python | def test_bad_template(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{error_not_in_database}}\n SUBJECT: Testing mailmerge\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir /... | def test_bad_template(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{error_not_in_database}}\n SUBJECT: Testing mailmerge\n FROM: example@example.com\n\n Hello world\n '))
database_path = Path((tmpdir /... |
682b1471212a484841eeae0808d211262713a6cb1064e9e2eefbd7470b05581b | def test_bad_database(tmpdir):
'Database read error should produce a sane error.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((... | Database read error should produce a sane error. | tests/test_main.py | test_bad_database | sudhanshu456/mailmerge | 1 | python | def test_bad_database(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_p... | def test_bad_database(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_p... |
bc26079fe1b5758b83dd38caba1e23764c177af313680d50eda675bc4c98fbc7 | def test_bad_config(tmpdir):
'Config containing an error should produce an error.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n '))
database_path = Path((tmpdir / 'mailmerge_da... | Config containing an error should produce an error. | tests/test_main.py | test_bad_config | sudhanshu456/mailmerge | 1 | python | def test_bad_config(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.d... | def test_bad_config(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.d... |
db439a834973e1a987320448ba6f4068a70f02c974aa828d83d08fe8853b1686 | def test_attachment(tmpdir):
'Verify attachments feature output.'
attachment1_path = Path((tmpdir / 'attachment1.txt'))
attachment1_path.write_text(u'Hello world\n')
attachment2_path = Path((tmpdir / 'attachment2.txt'))
attachment2_path.write_text(u'Hello mailmerge\n')
template_path = Path((tmpd... | Verify attachments feature output. | tests/test_main.py | test_attachment | sudhanshu456/mailmerge | 1 | python | def test_attachment(tmpdir):
attachment1_path = Path((tmpdir / 'attachment1.txt'))
attachment1_path.write_text(u'Hello world\n')
attachment2_path = Path((tmpdir / 'attachment2.txt'))
attachment2_path.write_text(u'Hello mailmerge\n')
template_path = Path((tmpdir / 'mailmerge_template.txt'))
... | def test_attachment(tmpdir):
attachment1_path = Path((tmpdir / 'attachment1.txt'))
attachment1_path.write_text(u'Hello world\n')
attachment2_path = Path((tmpdir / 'attachment2.txt'))
attachment2_path.write_text(u'Hello mailmerge\n')
template_path = Path((tmpdir / 'mailmerge_template.txt'))
... |
2f9bc3659bbc46e0144ebaabf63e0f52cb5e0039f1fbd83651bc32b128bc45fb | def test_utf8_template(tmpdir):
'Message is utf-8 encoded when only the template contains utf-8 chars.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Laȝamon 😀 klâwen\n '))
data... | Message is utf-8 encoded when only the template contains utf-8 chars. | tests/test_main.py | test_utf8_template | sudhanshu456/mailmerge | 1 | python | def test_utf8_template(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Laȝamon 😀 klâwen\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path... | def test_utf8_template(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n\n Laȝamon 😀 klâwen\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path... |
5f10496bff036f25024b3f8f990d25535529949f643591b2dc4dab1e7252ad48 | def test_utf8_database(tmpdir):
'Message is utf-8 encoded when only the databse contains utf-8 chars.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
d... | Message is utf-8 encoded when only the databse contains utf-8 chars. | tests/test_main.py | test_utf8_database | sudhanshu456/mailmerge | 1 | python | def test_utf8_database(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_... | def test_utf8_database(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_... |
ae4cac9cda20efb668070063015377915077b986dcf6e29cfa8d8745655e69f6 | def test_utf8_headers(tmpdir):
'Message is utf-8 encoded when headers contain utf-8 chars.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: Laȝamon <example@example.com>\n FROM: klâwen <example@example.com>\n SUBJECT: Laȝamon 😀 ... | Message is utf-8 encoded when headers contain utf-8 chars. | tests/test_main.py | test_utf8_headers | sudhanshu456/mailmerge | 1 | python | def test_utf8_headers(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: Laȝamon <example@example.com>\n FROM: klâwen <example@example.com>\n SUBJECT: Laȝamon 😀 klâwen\n\n {{message}}\n '))
database_path = P... | def test_utf8_headers(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: Laȝamon <example@example.com>\n FROM: klâwen <example@example.com>\n SUBJECT: Laȝamon 😀 klâwen\n\n {{message}}\n '))
database_path = P... |
008a44ebd6ee6bf0a0ab9796eecaa2bbc1c5029caf043d9fdf2ab12609115295 | def test_complicated(tmpdir):
'Complicated end-to-end test.\n\n Includes templating, TO, CC, BCC, UTF8 characters, emoji, attachments,\n encoding mismatch (header is us-ascii, characters used are utf-8). Also,\n multipart message in plaintext and HTML.\n '
attachment1_path = Path((tmpdir / 'attachm... | Complicated end-to-end test.
Includes templating, TO, CC, BCC, UTF8 characters, emoji, attachments,
encoding mismatch (header is us-ascii, characters used are utf-8). Also,
multipart message in plaintext and HTML. | tests/test_main.py | test_complicated | sudhanshu456/mailmerge | 1 | python | def test_complicated(tmpdir):
'Complicated end-to-end test.\n\n Includes templating, TO, CC, BCC, UTF8 characters, emoji, attachments,\n encoding mismatch (header is us-ascii, characters used are utf-8). Also,\n multipart message in plaintext and HTML.\n '
attachment1_path = Path((tmpdir / 'attachm... | def test_complicated(tmpdir):
'Complicated end-to-end test.\n\n Includes templating, TO, CC, BCC, UTF8 characters, emoji, attachments,\n encoding mismatch (header is us-ascii, characters used are utf-8). Also,\n multipart message in plaintext and HTML.\n '
attachment1_path = Path((tmpdir / 'attachm... |
14f85845da5890fcc5c62dd12e79ef40c9c6c4c6ed0dfa26c1b0fa695ec337c6 | def test_resume(tmpdir):
'Verify --resume option starts "in the middle" of the database.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path ... | Verify --resume option starts "in the middle" of the database. | tests/test_main.py | test_resume | sudhanshu456/mailmerge | 1 | python | def test_resume(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.wr... | def test_resume(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.wr... |
9bfa3fa2f84fafc5048c7a1631d518b8b35df41ecd83626f04f09c20457b50df | def test_resume_too_small(tmpdir):
'Verify --resume <= 0 prints an error message.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path(... | Verify --resume <= 0 prints an error message. | tests/test_main.py | test_resume_too_small | sudhanshu456/mailmerge | 1 | python | def test_resume_too_small(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
databa... | def test_resume_too_small(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
databa... |
0ffbcbfc7c80b99b8b8a5eab068f4830fc9df3de19e587e744c86d32ecbed518 | def test_resume_too_big(tmpdir):
'Verify --resume > database does nothing.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir... | Verify --resume > database does nothing. | tests/test_main.py | test_resume_too_big | sudhanshu456/mailmerge | 1 | python | def test_resume_too_big(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database... | def test_resume_too_big(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database... |
bfc2d314478d9063826dca9d1f2a62eb1698cd192dc472ebcdd32a3fc504f7b0 | def test_resume_hint_on_config_error(tmpdir):
'Verify *no* --resume hint when error is after first message.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))... | Verify *no* --resume hint when error is after first message. | tests/test_main.py | test_resume_hint_on_config_error | sudhanshu456/mailmerge | 1 | python | def test_resume_hint_on_config_error(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))... | def test_resume_hint_on_config_error(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))... |
f9199c5dac01207f13772c2c9e8638c7cc63e7b4778a932e28cb7cdd375ca4d1 | def test_resume_hint_on_csv_error(tmpdir):
'Verify --resume hint after CSV error.'
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path(... | Verify --resume hint after CSV error. | tests/test_main.py | test_resume_hint_on_csv_error | sudhanshu456/mailmerge | 1 | python | def test_resume_hint_on_csv_error(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
... | def test_resume_hint_on_csv_error(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: example@example.com\n FROM: example@example.com\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
... |
24f78d794013e3dacc70f710ade2f8a3f0d1ab671b36e39306aa88542ab5ef65 | def test_other_mime_type(tmpdir):
"Verify output with a MIME type that's not text or an attachment."
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n MIME-Version: 1.0\n Content-Type:... | Verify output with a MIME type that's not text or an attachment. | tests/test_main.py | test_other_mime_type | sudhanshu456/mailmerge | 1 | python | def test_other_mime_type(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n --boundary\... | def test_other_mime_type(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: example@example.com\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n --boundary\... |
b2f00babe9c9055914f519b00f972159624d5b5313bf9969d40309e50c9beb48 | def is_gaussian(file):
'Returns True if file is a Gaussian output'
for line in read_file(file):
if ('Gaussian' in line):
return True
return False | Returns True if file is a Gaussian output | autochem/scripts/fluorescence.py | is_gaussian | tommason14/monash_automation | 7 | python | def is_gaussian(file):
for line in read_file(file):
if ('Gaussian' in line):
return True
return False | def is_gaussian(file):
for line in read_file(file):
if ('Gaussian' in line):
return True
return False<|docstring|>Returns True if file is a Gaussian output<|endoftext|> |
7bc97ef0403fd600bed1bd328def4b456a91c701f856d2bc59029379909cf5f7 | def is_fluorescence(file):
'\n Assuming a time-dependent DFT calculation for fluorescence.\n Returns True if yes\n '
for line in read_file(file):
if ('TD=' in line.upper()):
return True
return False | Assuming a time-dependent DFT calculation for fluorescence.
Returns True if yes | autochem/scripts/fluorescence.py | is_fluorescence | tommason14/monash_automation | 7 | python | def is_fluorescence(file):
'\n Assuming a time-dependent DFT calculation for fluorescence.\n Returns True if yes\n '
for line in read_file(file):
if ('TD=' in line.upper()):
return True
return False | def is_fluorescence(file):
'\n Assuming a time-dependent DFT calculation for fluorescence.\n Returns True if yes\n '
for line in read_file(file):
if ('TD=' in line.upper()):
return True
return False<|docstring|>Assuming a time-dependent DFT calculation for fluorescence.
Returns ... |
dc100314ead6f09c28270f65d6f7a2d03187e1d15ce5072b616da417fd5c8e34 | def reassign_root_of_initial_spectra(d, name, root, iteration, transition_energy, intensity, wavelength, number, cutoff):
"\n If the file being searched is run to find the \n roots to take forward, need to know the roots!\n \n This function reassigns the value in the 'root'\n column to reflect this\n... | If the file being searched is run to find the
roots to take forward, need to know the roots!
This function reassigns the value in the 'root'
column to reflect this | autochem/scripts/fluorescence.py | reassign_root_of_initial_spectra | tommason14/monash_automation | 7 | python | def reassign_root_of_initial_spectra(d, name, root, iteration, transition_energy, intensity, wavelength, number, cutoff):
"\n If the file being searched is run to find the \n roots to take forward, need to know the roots!\n \n This function reassigns the value in the 'root'\n column to reflect this\n... | def reassign_root_of_initial_spectra(d, name, root, iteration, transition_energy, intensity, wavelength, number, cutoff):
"\n If the file being searched is run to find the \n roots to take forward, need to know the roots!\n \n This function reassigns the value in the 'root'\n column to reflect this\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.