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`, то есть мотор останавливается, при этом он заблокирован\n и остаётся под напряжением.\n '
raise NotImplementedError | Включает мотор с указанной мощностью.
Параметры
---------
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`, то есть мотор останавливается, при этом он заблокирован\n и остаётся под напряжением.\n '
raise NotImplementedError | def setPower(self, power: int) -> None:
'Включает мотор с указанной мощностью.\n\n Параметры\n ---------\n power: :class:`int`\n Мощность задаётся в диапазоне от -100 («полный назад») до 100 («полный вперёд»).\n 0 соответствует `force break`, то есть мотор останавливается, при этом он заблокирован\n и остаётся под напряжением.\n '
raise NotImplementedError<|docstring|>Включает мотор с указанной мощностью.
Параметры
---------
power: :class:`int`
Мощность задаётся в диапазоне от -100 («полный назад») до 100 («полный вперёд»).
0 соответствует `force break`, то есть мотор останавливается, при этом он заблокирован
и остаётся под напряжением.<|endoftext|> |
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|>Определяет доминирующий цвет в центре кадра и запоминает его
как цвет объекта. После этого метод «read» начинает возвращать
данные для объекта.<|endoftext|> |
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|>Включает видеокамеру и инициализирует её в режиме датчика объекта.
Параметры
---------
show_to_screen: :class:`int`
Определяет, выводить ли на экран изображение с камеры<|endoftext|> |
25e3def6ecc6f2fd0f199d0403dcd80877c72633077b0b023453830a175f7220 | def read(self) -> List[int]:
'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра слева);\n - в первой ячейке — координата по оси Y центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра сверху);\n - во второй ячейке — относительный размер объекта, число от 0 до 100\n (100 — объекта занимает почти весь кадр, 0 — объекта нет на кадре).\n '
raise NotImplementedError | Возвращает массив, в ячейках которого находятся следующие данные:
- в нулевой ячейке координата по оси X центра объекта относительно центра кадра
(от -100 до 100, -100 — центр объекта на краю кадра слева);
- в первой ячейке — координата по оси Y центра объекта относительно центра кадра
(от -100 до 100, -100 — центр объекта на краю кадра сверху);
- во второй ячейке — относительный размер объекта, число от 0 до 100
(100 — объекта занимает почти весь кадр, 0 — объекта нет на кадре). | trik/brick.py | read | m1raynee/trikset.py-typehint | 1 | python | def read(self) -> List[int]:
'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра слева);\n - в первой ячейке — координата по оси Y центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра сверху);\n - во второй ячейке — относительный размер объекта, число от 0 до 100\n (100 — объекта занимает почти весь кадр, 0 — объекта нет на кадре).\n '
raise NotImplementedError | def read(self) -> List[int]:
'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра слева);\n - в первой ячейке — координата по оси Y центра объекта относительно центра кадра\n (от -100 до 100, -100 — центр объекта на краю кадра сверху);\n - во второй ячейке — относительный размер объекта, число от 0 до 100\n (100 — объекта занимает почти весь кадр, 0 — объекта нет на кадре).\n '
raise NotImplementedError<|docstring|>Возвращает массив, в ячейках которого находятся следующие данные:
- в нулевой ячейке координата по оси X центра объекта относительно центра кадра
(от -100 до 100, -100 — центр объекта на краю кадра слева);
- в первой ячейке — координата по оси Y центра объекта относительно центра кадра
(от -100 до 100, -100 — центр объекта на краю кадра сверху);
- во второй ячейке — относительный размер объекта, число от 0 до 100
(100 — объекта занимает почти весь кадр, 0 — объекта нет на кадре).<|endoftext|> |
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`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n '
raise NotImplementedError | Начать рисование маркером заданного цвета на полу.
При движении робота в двумерной модели за ним будет оставаться цветная линия.
Если был установлен маркер другого цвета, он будет заменен.
Параметры
---------
color: :class:`str`
Возможные цвета:
- white,
- red, darkRed,
- green, darkGreen,
- blue, darkBlue,
- cyan, darkCyan,
- magenta, darkMagenta,
- yellow, darkYellow,
- gray, darkGray, lightGray,
- black. | 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`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n '
raise NotImplementedError | def down(self, color: _COLOR) -> None:
'Начать рисование маркером заданного цвета на полу.\n При движении робота в двумерной модели за ним будет оставаться цветная линия.\n Если был установлен маркер другого цвета, он будет заменен.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n '
raise NotImplementedError<|docstring|>Начать рисование маркером заданного цвета на полу.
При движении робота в двумерной модели за ним будет оставаться цветная линия.
Если был установлен маркер другого цвета, он будет заменен.
Параметры
---------
color: :class:`str`
Возможные цвета:
- white,
- red, darkRed,
- green, darkGreen,
- blue, darkBlue,
- cyan, darkCyan,
- magenta, darkMagenta,
- yellow, darkYellow,
- gray, darkGray, lightGray,
- black.<|endoftext|> |
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|>Представляет сенсор (аналоговый или цифровой), подключающийся к портам A1, …, A6, D1, D2.
Параметры
---------
sensorName: :class:`str`
Имя порта<|endoftext|> |
6b5c59571adb86f478711ca29ef1a94fe3906da5b92f20a079a7f89731b313ec | def read(self) -> int:
'Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.\n Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается\n в файле `model-config.xml` в папке trik на роботе.\n\n Например, ИК-датчик расстояния возвращает значение в сантиметрах.\n '
raise NotImplementedError | Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.
Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается
в файле `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 Например, ИК-датчик расстояния возвращает значение в сантиметрах.\n '
raise NotImplementedError | def read(self) -> int:
'Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.\n Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается\n в файле `model-config.xml` в папке trik на роботе.\n\n Например, ИК-датчик расстояния возвращает значение в сантиметрах.\n '
raise NotImplementedError<|docstring|>Возвращает текущее показание сенсора (цифрового или аналогового), подключённого к данному порту.
Возвращается приведённое значение, зависящее от конфигурации порта, которая описывается
в файле `model-config.xml` в папке trik на роботе.
Например, ИК-датчик расстояния возвращает значение в сантиметрах.<|endoftext|> |
9f0167c09c3737dd6094365926395199a3bde867c7ed75a74cb7cbd2d0b282e2 | def readRawData(self) -> int:
'Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),\n подключённого к данному порту. Диапазон значений зависит от конкретного сенсора\n и не учитывает конфигурацию робота (возвращаются физические показания сенсора,\n например, задержка принятого ультразвукового сигнала).\n '
raise NotImplementedError | Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),
подключённого к данному порту. Диапазон значений зависит от конкретного сенсора
и не учитывает конфигурацию робота (возвращаются физические показания сенсора,
например, задержка принятого ультразвукового сигнала). | trik/brick.py | readRawData | m1raynee/trikset.py-typehint | 1 | python | def readRawData(self) -> int:
'Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),\n подключённого к данному порту. Диапазон значений зависит от конкретного сенсора\n и не учитывает конфигурацию робота (возвращаются физические показания сенсора,\n например, задержка принятого ультразвукового сигнала).\n '
raise NotImplementedError | def readRawData(self) -> int:
'Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),\n подключённого к данному порту. Диапазон значений зависит от конкретного сенсора\n и не учитывает конфигурацию робота (возвращаются физические показания сенсора,\n например, задержка принятого ультразвукового сигнала).\n '
raise NotImplementedError<|docstring|>Возвращает текущее «сырое» показание сенсора (цифрового или аналогового),
подключённого к данному порту. Диапазон значений зависит от конкретного сенсора
и не учитывает конфигурацию робота (возвращаются физические показания сенсора,
например, задержка принятого ультразвукового сигнала).<|endoftext|> |
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 '
raise NotImplementedError | Параметры
---------
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 '
raise NotImplementedError | @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 '
raise NotImplementedError<|docstring|>Параметры
---------
func: Callable[[:class:`KeysEnum`, Literal[0, 1]], Any]
Первый параметр — код кнопки,
второй — 1, если кнопка нажата, 0, если отпущена.<|endoftext|> |
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'] = initial_tweets['tweet_datetime']
initial_tweets['retweets'] = 0
initial_tweets['likes'] = 0
df = pd.concat([initial_tweets, df])
df = df.sort_values('query_datetime')
df['summary'] = ((((df['user'] + '<br />') + df['text']) + '<br />') + df['tweet_datetime'].astype(str))
df['engagements'] = (df['likes'] + df['retweets'])
print('rows before filter:', len(df))
today_midnight = datetime.combine(date.today(), datetime.min.time())
today_midnight = LOCAL_TIMEZONE.localize(today_midnight)
print('filtering tweets and queries after:', today_midnight)
df = df.loc[(df['query_datetime'] > today_midnight)]
df = df.loc[(df['tweet_datetime'] > today_midnight)]
print('removing replies')
df = df.loc[(~ df['is_reply'])]
print('rows after filter:', len(df))
df['query_datetime'] = df['query_datetime'].map((lambda x: x.replace(tzinfo=None)))
df['tweet_datetime'] = df['tweet_datetime'].map((lambda x: x.replace(tzinfo=None)))
fig = px.line(df, x='query_datetime', y='likes', color='user', line_group='tweet', hover_name='summary').update_traces(mode='lines+markers')
fig.show() | 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['tweet_datetime']
initial_tweets['retweets'] = 0
initial_tweets['likes'] = 0
df = pd.concat([initial_tweets, df])
df = df.sort_values('query_datetime')
df['summary'] = ((((df['user'] + '<br />') + df['text']) + '<br />') + df['tweet_datetime'].astype(str))
df['engagements'] = (df['likes'] + df['retweets'])
print('rows before filter:', len(df))
today_midnight = datetime.combine(date.today(), datetime.min.time())
today_midnight = LOCAL_TIMEZONE.localize(today_midnight)
print('filtering tweets and queries after:', today_midnight)
df = df.loc[(df['query_datetime'] > today_midnight)]
df = df.loc[(df['tweet_datetime'] > today_midnight)]
print('removing replies')
df = df.loc[(~ df['is_reply'])]
print('rows after filter:', len(df))
df['query_datetime'] = df['query_datetime'].map((lambda x: x.replace(tzinfo=None)))
df['tweet_datetime'] = df['tweet_datetime'].map((lambda x: x.replace(tzinfo=None)))
fig = px.line(df, x='query_datetime', y='likes', color='user', line_group='tweet', hover_name='summary').update_traces(mode='lines+markers')
fig.show() | 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['tweet_datetime']
initial_tweets['retweets'] = 0
initial_tweets['likes'] = 0
df = pd.concat([initial_tweets, df])
df = df.sort_values('query_datetime')
df['summary'] = ((((df['user'] + '<br />') + df['text']) + '<br />') + df['tweet_datetime'].astype(str))
df['engagements'] = (df['likes'] + df['retweets'])
print('rows before filter:', len(df))
today_midnight = datetime.combine(date.today(), datetime.min.time())
today_midnight = LOCAL_TIMEZONE.localize(today_midnight)
print('filtering tweets and queries after:', today_midnight)
df = df.loc[(df['query_datetime'] > today_midnight)]
df = df.loc[(df['tweet_datetime'] > today_midnight)]
print('removing replies')
df = df.loc[(~ df['is_reply'])]
print('rows after filter:', len(df))
df['query_datetime'] = df['query_datetime'].map((lambda x: x.replace(tzinfo=None)))
df['tweet_datetime'] = df['tweet_datetime'].map((lambda x: x.replace(tzinfo=None)))
fig = px.line(df, x='query_datetime', y='likes', color='user', line_group='tweet', hover_name='summary').update_traces(mode='lines+markers')
fig.show()<|docstring|>main program<|endoftext|> |
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))<|docstring|>:type p: int
:type q: int
:rtype: int<|endoftext|> |
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_argument('--dataset_path', type=str, default=None, help='Dataset path')
parser.add_argument('--checkpoint_path', type=str, default=None, help='Checkpoint file path')
parser.add_argument('--run_distribute', type=ast.literal_eval, default=False, help='Run distribute')
parser.add_argument('-dt', '--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='Device target, support Ascend and GPU.')
parser.add_argument('--device_id', type=int, default=0, help='Device id')
parser.add_argument('--device_num', type=int, default=1, help='Device number')
parser.add_argument('--run_modelarts', type=ast.literal_eval, default=False, help='Run mode')
parser.add_argument('--pre_trained', type=str, default=None, help='Pretrained checkpoint path')
return parser.parse_args() | 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, default=None, help='Dataset path')
parser.add_argument('--checkpoint_path', type=str, default=None, help='Checkpoint file path')
parser.add_argument('--run_distribute', type=ast.literal_eval, default=False, help='Run distribute')
parser.add_argument('-dt', '--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='Device target, support Ascend and GPU.')
parser.add_argument('--device_id', type=int, default=0, help='Device id')
parser.add_argument('--device_num', type=int, default=1, help='Device number')
parser.add_argument('--run_modelarts', type=ast.literal_eval, default=False, help='Run mode')
parser.add_argument('--pre_trained', type=str, default=None, help='Pretrained checkpoint path')
return parser.parse_args() | 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, default=None, help='Dataset path')
parser.add_argument('--checkpoint_path', type=str, default=None, help='Checkpoint file path')
parser.add_argument('--run_distribute', type=ast.literal_eval, default=False, help='Run distribute')
parser.add_argument('-dt', '--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='Device target, support Ascend and GPU.')
parser.add_argument('--device_id', type=int, default=0, help='Device id')
parser.add_argument('--device_num', type=int, default=1, help='Device number')
parser.add_argument('--run_modelarts', type=ast.literal_eval, default=False, help='Run mode')
parser.add_argument('--pre_trained', type=str, default=None, help='Pretrained checkpoint path')
return parser.parse_args()<|docstring|>Parsing of command line arguments<|endoftext|> |
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 in post<|endoftext|> |
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']
postCountOK = (userInfoDic['media_count'] > minPosts)
followerCountOK = (userInfoDic['follower_count'] > minFollower)
followingCountOK = (userInfoDic['following_count'] > minFollowing)
if (postCountOK and followerCountOK and followingCountOK):
return True
else:
return False | 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)
followerCountOK = (userInfoDic['follower_count'] > minFollower)
followingCountOK = (userInfoDic['following_count'] > minFollowing)
if (postCountOK and followerCountOK and followingCountOK):
return True
else:
return False | 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)
followerCountOK = (userInfoDic['follower_count'] > minFollower)
followingCountOK = (userInfoDic['following_count'] > minFollowing)
if (postCountOK and followerCountOK and followingCountOK):
return True
else:
return False<|docstring|>verify user meets minimum required: posts, followers, followings<|endoftext|> |
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}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})', item).group(1))
return True
else:
return False | 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}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})', item).group(1))
return True
else:
return False | 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}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})', item).group(1))
return True
else:
return False<|docstring|>search for all major phone number types, prints phone number<|endoftext|> |
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
else:
return True | 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 in the english language, prints if foreign<|endoftext|> |
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 translation):
try:
translation = translator.translate(wordCaption, dest='en').text
except:
randomSleepTimer(1, 3)
return translation
else:
return text | 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:
translation = translator.translate(wordCaption, dest='en').text
except:
randomSleepTimer(1, 3)
return translation
else:
return text | 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:
translation = translator.translate(wordCaption, dest='en').text
except:
randomSleepTimer(1, 3)
return translation
else:
return text<|docstring|>uses google translate to translate post to english<|endoftext|> |
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, 'comment': 1, 'chance': 2, 'like': 1, 'tag': 1, 'friend': 1, 'gift package': 2}
negatives = {'open house': 1, 'raffle': 3, 'snap': 1, 'best': 1, 'class': 1, 'go to': 1, 'casino': 1, 'stay tuned': 3, 'fundraiser': 6, 'fundraising': 6, 'donate': 1, 'donations': 4, 'raredisease': 6, '#slime': 8, ' slime': 8, 'dragon ball': 6, 'csgo': 6, 'stickers': 4, 'pokemon': 6, 'weed': 8, 'photoshoot': 4, 'ebook': 8, 'e-book': 8, 'mommy': 6, 'mother': 6, 'service desired': 9, 'tell us': 2, 'post a photo': 6, 'post a pic': 5, 'best photo': 6, 'answer this question': 6, 'tell us why': 7, 'tell me why': 7, 'screenshot': 2, 'your order': 3, 'every order': 3, "we're at": 4, '#roadshow': 8, 'find us': 6, 'come down to': 8, 'stop in': 1, 'get down here': 7, 'come out to': 9, 'sign up': 2, 'check it out': 2, 'message me': 2, 'register': 2, 'free event': 2, 'must be new to': 12, 'fill out': 6, 'watch us live': 10, 'tune in live': 10, ' live at ': 9, 'www.': 1, '.com': 1, 'http://': 3, 'https://': 3, '.net': 3, 'facebook': 3, 'facebook page': 3, 'fb page': 3, 'facebook.com': 3, 'page on facebook': 3, 'like us on fb': 6, 'iphone': 6, 'dm or ws': 8, 'twitter': 4, 'email': 2, 'e-mail': 2, 'youtube channel': 3, 'bitly': 8, 'goo.gl': 5, 'whatsapp': 4, 'twitch': 8, 'instastory': 5, 'link in': 5, 'link on my': 5, 'click link': 4, '#linkinbio': 5, 'dm me': 2, 'on orders': 2, 'call today': 7, 'call now': 6, 'with every order': 6, 'coupon': 6, 'sale': 1, 'purchase': 1, 'purchasing': 1, 'place an order': 6, 'with the purchase': 8, 'with every purchase': 6, 'buy': 4, 'forsale': 4, 'invoice': 4, 'sales event': 10, '% off': 5, 'with any purchase': 6, 'with every purchase': 6, 'book now': 4, 'when you order': 6, 'for participating': 2, 'thank you for participating': 4, 'the winner of': 6, 'better luck': 4, 'closed': 2, 'now closed': 4, 'is our giveaway winner': 6, 'have our first winner': 8, 'won this': 3, '#repost': 8, '#reposting': 8, 'repost @': 8, ' via ': 8, 'wish me luck': 10, 'pickme': 6, 'reposted using': 10, 'visit her ': 6}
dealbreakers = {'spend $': 6, 'sales over $': 6, 'purchase over': 12, 'order over': 12, 'buy 1 get 1 free': 6, 'order now': 9, 'order something': 9, 'free followers': 9, 'famenow': 9, 'head over': 8, 'head back': 7, 'over at @': 7, 'over on my blog': 5, 'pop over': 10, 'check out @': 4, 'check out the @': 4, 'jump over': 10, 'earlier post': 4, 'previous post': 10, 'last post': 10, 'posts back': 5, 'post back': 5, 'original post': 10, 'see their acc': 8, 'already posted': 8, 'past post': 3, 'swing over': 4, 'back few posts': 5, 'back a few posts': 5, 'few posts': 5, 'original photo': 4, 'check out our post': 11, 'out latest post': 5, 'see my previous': 5, 'i received': 4, 'thanks to @': 4, 'thank you to @': 4, '@instatoolsapp': 6, '@regram.app': 6, 'repostapp': 6, 'regrann': 6, 'regram': 6, '@get_repost': 6, '@renstapp': 6, 'repost any': 6, 'respost from @': 6, 'repost from @': 6, 'repost from @': 8, 'repostby @': 6, 'Posted @withrepost': 6, '@ziapplications': 8, 'congratulation': 6, 'congrats ': 6, 'congrats to': 6, 'winner is @': 6, 'winner is... @': 6, 'winners are @': 6, 'winner was @': 6, 'winner @': 6, '1st winner': 6, 'won my giveaway': 6, 'we have a winner': 6, 'giveaway closed': 6}
if (not checkMinLength(item)):
return (contestScore, allTags)
if (not checkLanguage(item)):
return (contestScore, allTags)
item = translateToEnglish(item)
if checkPhoneNumber(item):
return (contestScore, allTags)
if (item[0] == '@'):
return (contestScore, allTags)
try:
positiveList = [phrase for phrase in positives.keys() if (phrase in item)]
contestScore += sum((positives[phrase] for phrase in positives.keys() if (phrase in item)))
if (contestScore >= minScore):
negativeList = [phrase for phrase in negatives.keys() if (phrase in item)]
contestScore -= sum((negatives[phrase] for phrase in negatives.keys() if (phrase in item)))
contestScore -= sum((10 for phrase in dealbreakers.keys() if (phrase in item)))
if (len(negativeList) > 0):
print(' Negatives:', ' ', negativeList)
except:
print('failed to determine score!')
try:
if (contestScore >= minScore):
print((' Contest Score: %i (%s)' % (contestScore, ', '.join(print(positiveList)))))
if (item.find('tag') != (- 1)):
(primaryTag, allTags) = getPostTags(post)
except:
print(' Failed: Determining any Tags!')
return (contestScore, allTags) | 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': 2}
negatives = {'open house': 1, 'raffle': 3, 'snap': 1, 'best': 1, 'class': 1, 'go to': 1, 'casino': 1, 'stay tuned': 3, 'fundraiser': 6, 'fundraising': 6, 'donate': 1, 'donations': 4, 'raredisease': 6, '#slime': 8, ' slime': 8, 'dragon ball': 6, 'csgo': 6, 'stickers': 4, 'pokemon': 6, 'weed': 8, 'photoshoot': 4, 'ebook': 8, 'e-book': 8, 'mommy': 6, 'mother': 6, 'service desired': 9, 'tell us': 2, 'post a photo': 6, 'post a pic': 5, 'best photo': 6, 'answer this question': 6, 'tell us why': 7, 'tell me why': 7, 'screenshot': 2, 'your order': 3, 'every order': 3, "we're at": 4, '#roadshow': 8, 'find us': 6, 'come down to': 8, 'stop in': 1, 'get down here': 7, 'come out to': 9, 'sign up': 2, 'check it out': 2, 'message me': 2, 'register': 2, 'free event': 2, 'must be new to': 12, 'fill out': 6, 'watch us live': 10, 'tune in live': 10, ' live at ': 9, 'www.': 1, '.com': 1, 'http://': 3, 'https://': 3, '.net': 3, 'facebook': 3, 'facebook page': 3, 'fb page': 3, 'facebook.com': 3, 'page on facebook': 3, 'like us on fb': 6, 'iphone': 6, 'dm or ws': 8, 'twitter': 4, 'email': 2, 'e-mail': 2, 'youtube channel': 3, 'bitly': 8, 'goo.gl': 5, 'whatsapp': 4, 'twitch': 8, 'instastory': 5, 'link in': 5, 'link on my': 5, 'click link': 4, '#linkinbio': 5, 'dm me': 2, 'on orders': 2, 'call today': 7, 'call now': 6, 'with every order': 6, 'coupon': 6, 'sale': 1, 'purchase': 1, 'purchasing': 1, 'place an order': 6, 'with the purchase': 8, 'with every purchase': 6, 'buy': 4, 'forsale': 4, 'invoice': 4, 'sales event': 10, '% off': 5, 'with any purchase': 6, 'with every purchase': 6, 'book now': 4, 'when you order': 6, 'for participating': 2, 'thank you for participating': 4, 'the winner of': 6, 'better luck': 4, 'closed': 2, 'now closed': 4, 'is our giveaway winner': 6, 'have our first winner': 8, 'won this': 3, '#repost': 8, '#reposting': 8, 'repost @': 8, ' via ': 8, 'wish me luck': 10, 'pickme': 6, 'reposted using': 10, 'visit her ': 6}
dealbreakers = {'spend $': 6, 'sales over $': 6, 'purchase over': 12, 'order over': 12, 'buy 1 get 1 free': 6, 'order now': 9, 'order something': 9, 'free followers': 9, 'famenow': 9, 'head over': 8, 'head back': 7, 'over at @': 7, 'over on my blog': 5, 'pop over': 10, 'check out @': 4, 'check out the @': 4, 'jump over': 10, 'earlier post': 4, 'previous post': 10, 'last post': 10, 'posts back': 5, 'post back': 5, 'original post': 10, 'see their acc': 8, 'already posted': 8, 'past post': 3, 'swing over': 4, 'back few posts': 5, 'back a few posts': 5, 'few posts': 5, 'original photo': 4, 'check out our post': 11, 'out latest post': 5, 'see my previous': 5, 'i received': 4, 'thanks to @': 4, 'thank you to @': 4, '@instatoolsapp': 6, '@regram.app': 6, 'repostapp': 6, 'regrann': 6, 'regram': 6, '@get_repost': 6, '@renstapp': 6, 'repost any': 6, 'respost from @': 6, 'repost from @': 6, 'repost from @': 8, 'repostby @': 6, 'Posted @withrepost': 6, '@ziapplications': 8, 'congratulation': 6, 'congrats ': 6, 'congrats to': 6, 'winner is @': 6, 'winner is... @': 6, 'winners are @': 6, 'winner was @': 6, 'winner @': 6, '1st winner': 6, 'won my giveaway': 6, 'we have a winner': 6, 'giveaway closed': 6}
if (not checkMinLength(item)):
return (contestScore, allTags)
if (not checkLanguage(item)):
return (contestScore, allTags)
item = translateToEnglish(item)
if checkPhoneNumber(item):
return (contestScore, allTags)
if (item[0] == '@'):
return (contestScore, allTags)
try:
positiveList = [phrase for phrase in positives.keys() if (phrase in item)]
contestScore += sum((positives[phrase] for phrase in positives.keys() if (phrase in item)))
if (contestScore >= minScore):
negativeList = [phrase for phrase in negatives.keys() if (phrase in item)]
contestScore -= sum((negatives[phrase] for phrase in negatives.keys() if (phrase in item)))
contestScore -= sum((10 for phrase in dealbreakers.keys() if (phrase in item)))
if (len(negativeList) > 0):
print(' Negatives:', ' ', negativeList)
except:
print('failed to determine score!')
try:
if (contestScore >= minScore):
print((' Contest Score: %i (%s)' % (contestScore, ', '.join(print(positiveList)))))
if (item.find('tag') != (- 1)):
(primaryTag, allTags) = getPostTags(post)
except:
print(' Failed: Determining any Tags!')
return (contestScore, allTags) | 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': 2}
negatives = {'open house': 1, 'raffle': 3, 'snap': 1, 'best': 1, 'class': 1, 'go to': 1, 'casino': 1, 'stay tuned': 3, 'fundraiser': 6, 'fundraising': 6, 'donate': 1, 'donations': 4, 'raredisease': 6, '#slime': 8, ' slime': 8, 'dragon ball': 6, 'csgo': 6, 'stickers': 4, 'pokemon': 6, 'weed': 8, 'photoshoot': 4, 'ebook': 8, 'e-book': 8, 'mommy': 6, 'mother': 6, 'service desired': 9, 'tell us': 2, 'post a photo': 6, 'post a pic': 5, 'best photo': 6, 'answer this question': 6, 'tell us why': 7, 'tell me why': 7, 'screenshot': 2, 'your order': 3, 'every order': 3, "we're at": 4, '#roadshow': 8, 'find us': 6, 'come down to': 8, 'stop in': 1, 'get down here': 7, 'come out to': 9, 'sign up': 2, 'check it out': 2, 'message me': 2, 'register': 2, 'free event': 2, 'must be new to': 12, 'fill out': 6, 'watch us live': 10, 'tune in live': 10, ' live at ': 9, 'www.': 1, '.com': 1, 'http://': 3, 'https://': 3, '.net': 3, 'facebook': 3, 'facebook page': 3, 'fb page': 3, 'facebook.com': 3, 'page on facebook': 3, 'like us on fb': 6, 'iphone': 6, 'dm or ws': 8, 'twitter': 4, 'email': 2, 'e-mail': 2, 'youtube channel': 3, 'bitly': 8, 'goo.gl': 5, 'whatsapp': 4, 'twitch': 8, 'instastory': 5, 'link in': 5, 'link on my': 5, 'click link': 4, '#linkinbio': 5, 'dm me': 2, 'on orders': 2, 'call today': 7, 'call now': 6, 'with every order': 6, 'coupon': 6, 'sale': 1, 'purchase': 1, 'purchasing': 1, 'place an order': 6, 'with the purchase': 8, 'with every purchase': 6, 'buy': 4, 'forsale': 4, 'invoice': 4, 'sales event': 10, '% off': 5, 'with any purchase': 6, 'with every purchase': 6, 'book now': 4, 'when you order': 6, 'for participating': 2, 'thank you for participating': 4, 'the winner of': 6, 'better luck': 4, 'closed': 2, 'now closed': 4, 'is our giveaway winner': 6, 'have our first winner': 8, 'won this': 3, '#repost': 8, '#reposting': 8, 'repost @': 8, ' via ': 8, 'wish me luck': 10, 'pickme': 6, 'reposted using': 10, 'visit her ': 6}
dealbreakers = {'spend $': 6, 'sales over $': 6, 'purchase over': 12, 'order over': 12, 'buy 1 get 1 free': 6, 'order now': 9, 'order something': 9, 'free followers': 9, 'famenow': 9, 'head over': 8, 'head back': 7, 'over at @': 7, 'over on my blog': 5, 'pop over': 10, 'check out @': 4, 'check out the @': 4, 'jump over': 10, 'earlier post': 4, 'previous post': 10, 'last post': 10, 'posts back': 5, 'post back': 5, 'original post': 10, 'see their acc': 8, 'already posted': 8, 'past post': 3, 'swing over': 4, 'back few posts': 5, 'back a few posts': 5, 'few posts': 5, 'original photo': 4, 'check out our post': 11, 'out latest post': 5, 'see my previous': 5, 'i received': 4, 'thanks to @': 4, 'thank you to @': 4, '@instatoolsapp': 6, '@regram.app': 6, 'repostapp': 6, 'regrann': 6, 'regram': 6, '@get_repost': 6, '@renstapp': 6, 'repost any': 6, 'respost from @': 6, 'repost from @': 6, 'repost from @': 8, 'repostby @': 6, 'Posted @withrepost': 6, '@ziapplications': 8, 'congratulation': 6, 'congrats ': 6, 'congrats to': 6, 'winner is @': 6, 'winner is... @': 6, 'winners are @': 6, 'winner was @': 6, 'winner @': 6, '1st winner': 6, 'won my giveaway': 6, 'we have a winner': 6, 'giveaway closed': 6}
if (not checkMinLength(item)):
return (contestScore, allTags)
if (not checkLanguage(item)):
return (contestScore, allTags)
item = translateToEnglish(item)
if checkPhoneNumber(item):
return (contestScore, allTags)
if (item[0] == '@'):
return (contestScore, allTags)
try:
positiveList = [phrase for phrase in positives.keys() if (phrase in item)]
contestScore += sum((positives[phrase] for phrase in positives.keys() if (phrase in item)))
if (contestScore >= minScore):
negativeList = [phrase for phrase in negatives.keys() if (phrase in item)]
contestScore -= sum((negatives[phrase] for phrase in negatives.keys() if (phrase in item)))
contestScore -= sum((10 for phrase in dealbreakers.keys() if (phrase in item)))
if (len(negativeList) > 0):
print(' Negatives:', ' ', negativeList)
except:
print('failed to determine score!')
try:
if (contestScore >= minScore):
print((' Contest Score: %i (%s)' % (contestScore, ', '.join(print(positiveList)))))
if (item.find('tag') != (- 1)):
(primaryTag, allTags) = getPostTags(post)
except:
print(' Failed: Determining any Tags!')
return (contestScore, allTags)<|docstring|>checks post for contest by keywords below rules below rules on keywords<|endoftext|> |
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'] > minComments):
instagram.getMediaComments(post['id'])
commentDf = pd.DataFrame(instagram.LastJson['comments'])
commentDf['text'] = commentDf['text'].str.replace('([@][\\w_.@]*)', '')
commentDf = commentDf[(commentDf['text'].apply(set).apply(len) > 2)]
commentDf['text'] = commentDf['text'].str.replace(' ', ' ')
decOrder = commentDf['text'].str.lower().value_counts()
print(decOrder)
if ((len(decOrder) > 0) and (decOrder[0] > minCount)):
print(' commented: ', decOrder[0], decOrder.index[0])
mostCommented = decOrder.index[0]
commented = mostCommented
else:
commented = baseComment
return commented | 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'])
commentDf = pd.DataFrame(instagram.LastJson['comments'])
commentDf['text'] = commentDf['text'].str.replace('([@][\\w_.@]*)', )
commentDf = commentDf[(commentDf['text'].apply(set).apply(len) > 2)]
commentDf['text'] = commentDf['text'].str.replace(' ', ' ')
decOrder = commentDf['text'].str.lower().value_counts()
print(decOrder)
if ((len(decOrder) > 0) and (decOrder[0] > minCount)):
print(' commented: ', decOrder[0], decOrder.index[0])
mostCommented = decOrder.index[0]
commented = mostCommented
else:
commented = baseComment
return commented | 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'])
commentDf = pd.DataFrame(instagram.LastJson['comments'])
commentDf['text'] = commentDf['text'].str.replace('([@][\\w_.@]*)', )
commentDf = commentDf[(commentDf['text'].apply(set).apply(len) > 2)]
commentDf['text'] = commentDf['text'].str.replace(' ', ' ')
decOrder = commentDf['text'].str.lower().value_counts()
print(decOrder)
if ((len(decOrder) > 0) and (decOrder[0] > minCount)):
print(' commented: ', decOrder[0], decOrder.index[0])
mostCommented = decOrder.index[0]
commented = mostCommented
else:
commented = baseComment
return commented<|docstring|>Comment on Contest to enter: 1) most common answer 2) just yes<|endoftext|> |
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 + ' ') + att) for (tag, att) in itertools.product(tagList, attList)])
for phrase in phraseList:
hitList = findall((('(?<=' + phrase) + ' ).[0-9]*'), item, flags=IGNORECASE)
hitList = [int(k) for k in hitList if k.isdigit()]
if (len(hitList) == 1):
return hitList[0]
elif (len(hitList) > 1):
print(hitList)
randomSleepTimer(9, 10)
return hitList[0]
if ('tag a friend' in item):
return 1
elif ('mention a friend' in item):
return 1
elif ('tag a mate' in item):
return 1
elif ('tag the friend' in item):
return 1
elif ('tag one friend' in item):
return 1
elif ('tag your bff' in item):
return 1
elif ('tag your friend' in item):
return 1
elif ('tag someone' in item):
return 1
elif ('comment who' in item):
return 1
elif ('tag as many' in item):
return 1
elif ('tag at least one' in item):
return 1
elif ('tag your friends' in item):
return 2
elif ('tag two friends' in item):
return 2
elif ('tag two people' in item):
return 2
elif ('tag two ' in item):
return 2
elif ('tag two of your friends' in item):
return 2
elif ('tag two or' in item):
return 2
elif ('tag some' in item):
return 2
elif ('tag lots' in item):
return 2
elif ('tag firend' in item):
return 2
elif ('tag three friends' in item):
return 3
elif ('tag four friends' in item):
return 4
elif ('tag five friends' in item):
return 5
elif ('get tagging' in item):
return 2
else:
print(' [ ] No people tags necessary')
return 0 | 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.product(tagList, attList)])
for phrase in phraseList:
hitList = findall((('(?<=' + phrase) + ' ).[0-9]*'), item, flags=IGNORECASE)
hitList = [int(k) for k in hitList if k.isdigit()]
if (len(hitList) == 1):
return hitList[0]
elif (len(hitList) > 1):
print(hitList)
randomSleepTimer(9, 10)
return hitList[0]
if ('tag a friend' in item):
return 1
elif ('mention a friend' in item):
return 1
elif ('tag a mate' in item):
return 1
elif ('tag the friend' in item):
return 1
elif ('tag one friend' in item):
return 1
elif ('tag your bff' in item):
return 1
elif ('tag your friend' in item):
return 1
elif ('tag someone' in item):
return 1
elif ('comment who' in item):
return 1
elif ('tag as many' in item):
return 1
elif ('tag at least one' in item):
return 1
elif ('tag your friends' in item):
return 2
elif ('tag two friends' in item):
return 2
elif ('tag two people' in item):
return 2
elif ('tag two ' in item):
return 2
elif ('tag two of your friends' in item):
return 2
elif ('tag two or' in item):
return 2
elif ('tag some' in item):
return 2
elif ('tag lots' in item):
return 2
elif ('tag firend' in item):
return 2
elif ('tag three friends' in item):
return 3
elif ('tag four friends' in item):
return 4
elif ('tag five friends' in item):
return 5
elif ('get tagging' in item):
return 2
else:
print(' [ ] No people tags necessary')
return 0 | 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.product(tagList, attList)])
for phrase in phraseList:
hitList = findall((('(?<=' + phrase) + ' ).[0-9]*'), item, flags=IGNORECASE)
hitList = [int(k) for k in hitList if k.isdigit()]
if (len(hitList) == 1):
return hitList[0]
elif (len(hitList) > 1):
print(hitList)
randomSleepTimer(9, 10)
return hitList[0]
if ('tag a friend' in item):
return 1
elif ('mention a friend' in item):
return 1
elif ('tag a mate' in item):
return 1
elif ('tag the friend' in item):
return 1
elif ('tag one friend' in item):
return 1
elif ('tag your bff' in item):
return 1
elif ('tag your friend' in item):
return 1
elif ('tag someone' in item):
return 1
elif ('comment who' in item):
return 1
elif ('tag as many' in item):
return 1
elif ('tag at least one' in item):
return 1
elif ('tag your friends' in item):
return 2
elif ('tag two friends' in item):
return 2
elif ('tag two people' in item):
return 2
elif ('tag two ' in item):
return 2
elif ('tag two of your friends' in item):
return 2
elif ('tag two or' in item):
return 2
elif ('tag some' in item):
return 2
elif ('tag lots' in item):
return 2
elif ('tag firend' in item):
return 2
elif ('tag three friends' in item):
return 3
elif ('tag four friends' in item):
return 4
elif ('tag five friends' in item):
return 5
elif ('get tagging' in item):
return 2
else:
print(' [ ] No people tags necessary')
return 0<|docstring|>returns number of people needed to tag<|endoftext|> |
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))
else:
return '' | 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 string of tagged usernames in amount needed<|endoftext|> |
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')
while (not instagram.mediaInfo(duplicatePk)):
sleepCounter += randomSleepTimer(20, 60)
if (instagram.LastJson['items'][0]['caption'] is None):
checkCaptions(contests)
while (not instagram.mediaInfo(duplicatePk)):
sleepCounter += randomSleepTimer(20, 60)
oldCaption = instagram.LastJson['items'][0]['caption']['text']
if (post['user']['username'] not in oldCaption):
newCaption = ((((oldCaption[:oldCaption.find('@')] + '@') + post['user']['username']) + ' ') + oldCaption[oldCaption.find('@'):])
instagram.editMedia(duplicatePk, newCaption)
print((' Added tag @%s' % post['user']['username']))
print((' Already tagged @%s' % post['user']['username']))
return True
else:
url = post['image_versions2']['candidates'][0]['url']
photoName = (post['user']['username'] + '.jpg')
try:
urllib.request.urlretrieve(url, photoName)
instagram.uploadPhoto(photoName, caption=captionText, upload_id=None)
print(' [x] Reposted')
return True
except:
print(' Failed: repost')
return False | 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)):
sleepCounter += randomSleepTimer(20, 60)
if (instagram.LastJson['items'][0]['caption'] is None):
checkCaptions(contests)
while (not instagram.mediaInfo(duplicatePk)):
sleepCounter += randomSleepTimer(20, 60)
oldCaption = instagram.LastJson['items'][0]['caption']['text']
if (post['user']['username'] not in oldCaption):
newCaption = ((((oldCaption[:oldCaption.find('@')] + '@') + post['user']['username']) + ' ') + oldCaption[oldCaption.find('@'):])
instagram.editMedia(duplicatePk, newCaption)
print((' Added tag @%s' % post['user']['username']))
print((' Already tagged @%s' % post['user']['username']))
return True
else:
url = post['image_versions2']['candidates'][0]['url']
photoName = (post['user']['username'] + '.jpg')
try:
urllib.request.urlretrieve(url, photoName)
instagram.uploadPhoto(photoName, caption=captionText, upload_id=None)
print(' [x] Reposted')
return True
except:
print(' Failed: repost')
return False | 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)):
sleepCounter += randomSleepTimer(20, 60)
if (instagram.LastJson['items'][0]['caption'] is None):
checkCaptions(contests)
while (not instagram.mediaInfo(duplicatePk)):
sleepCounter += randomSleepTimer(20, 60)
oldCaption = instagram.LastJson['items'][0]['caption']['text']
if (post['user']['username'] not in oldCaption):
newCaption = ((((oldCaption[:oldCaption.find('@')] + '@') + post['user']['username']) + ' ') + oldCaption[oldCaption.find('@'):])
instagram.editMedia(duplicatePk, newCaption)
print((' Added tag @%s' % post['user']['username']))
print((' Already tagged @%s' % post['user']['username']))
return True
else:
url = post['image_versions2']['candidates'][0]['url']
photoName = (post['user']['username'] + '.jpg')
try:
urllib.request.urlretrieve(url, photoName)
instagram.uploadPhoto(photoName, caption=captionText, upload_id=None)
print(' [x] Reposted')
return True
except:
print(' Failed: repost')
return False<|docstring|>repost picture in post with previous caption attached<|endoftext|> |
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', 'this photo', 'this picture', 'this pic', 'this post', 'this image', 'this and', 'and', 'a screenshot', 'picture', 'image', '&']
specIndicators = ['shoutout this account', 'shout out this account']
repostIndicators = ([((verb + ' ') + adj) for (verb, adj) in itertools.product(verbIndicators, adjIndicators)] + specIndicators)
repostIndicators.remove('post and')
repostIndicators.remove('posts and')
repostIndicators.remove('share the')
repostIndicators.remove('post &')
repostIndicators.remove('posts &')
repostIndicators.append('repost n tag')
repostIndicators.append('repost with')
repostIndicators.append('& share')
for indicator in repostIndicators:
if (caption.find(indicator) != (- 1)):
print(' [ ] Repost required')
return True
return False | 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 pic', 'this post', 'this image', 'this and', 'and', 'a screenshot', 'picture', 'image', '&']
specIndicators = ['shoutout this account', 'shout out this account']
repostIndicators = ([((verb + ' ') + adj) for (verb, adj) in itertools.product(verbIndicators, adjIndicators)] + specIndicators)
repostIndicators.remove('post and')
repostIndicators.remove('posts and')
repostIndicators.remove('share the')
repostIndicators.remove('post &')
repostIndicators.remove('posts &')
repostIndicators.append('repost n tag')
repostIndicators.append('repost with')
repostIndicators.append('& share')
for indicator in repostIndicators:
if (caption.find(indicator) != (- 1)):
print(' [ ] Repost required')
return True
return False | 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 pic', 'this post', 'this image', 'this and', 'and', 'a screenshot', 'picture', 'image', '&']
specIndicators = ['shoutout this account', 'shout out this account']
repostIndicators = ([((verb + ' ') + adj) for (verb, adj) in itertools.product(verbIndicators, adjIndicators)] + specIndicators)
repostIndicators.remove('post and')
repostIndicators.remove('posts and')
repostIndicators.remove('share the')
repostIndicators.remove('post &')
repostIndicators.remove('posts &')
repostIndicators.append('repost n tag')
repostIndicators.append('repost with')
repostIndicators.append('& share')
for indicator in repostIndicators:
if (caption.find(indicator) != (- 1)):
print(' [ ] Repost required')
return True
return False<|docstring|>Check if repost of picture required<|endoftext|> |
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))))
return 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<|docstring|>Get all people tags in the post<|endoftext|> |
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):
searchList = (searchList + [str(userId) for userId in userIdList])
instagram.comment(post['pk'], commented)
print(' [x] Commented')
reposted = False
if (len(caption) > 1):
repost(post, caption, instagram)
reposted = True
newRow = {'username': post['user']['username'], 'userPk': post['user']['pk'], 'timestamp': post['taken_at'], 'postPk': post['pk'], 'postId': post['id'], 'caption': post['caption']['text'].strip().replace('\n', ' ').replace('\n', ' '), 'commented': commented, 'commentNumber': post['comment_count'], 'commentTimestamp': round(time.time()), 'liked': True, 'shared': reposted, 'shareCaption': caption}
instagram.like(post['pk'])
print(' [x] Liked')
print(' Successfully entered contest!')
sleepCounter += randomSleepTimer(0, 3)
return contests.append(newRow, ignore_index=True) | 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 userId in userIdList])
instagram.comment(post['pk'], commented)
print(' [x] Commented')
reposted = False
if (len(caption) > 1):
repost(post, caption, instagram)
reposted = True
newRow = {'username': post['user']['username'], 'userPk': post['user']['pk'], 'timestamp': post['taken_at'], 'postPk': post['pk'], 'postId': post['id'], 'caption': post['caption']['text'].strip().replace('\n', ' ').replace('\n', ' '), 'commented': commented, 'commentNumber': post['comment_count'], 'commentTimestamp': round(time.time()), 'liked': True, 'shared': reposted, 'shareCaption': caption}
instagram.like(post['pk'])
print(' [x] Liked')
print(' Successfully entered contest!')
sleepCounter += randomSleepTimer(0, 3)
return contests.append(newRow, ignore_index=True) | 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 userId in userIdList])
instagram.comment(post['pk'], commented)
print(' [x] Commented')
reposted = False
if (len(caption) > 1):
repost(post, caption, instagram)
reposted = True
newRow = {'username': post['user']['username'], 'userPk': post['user']['pk'], 'timestamp': post['taken_at'], 'postPk': post['pk'], 'postId': post['id'], 'caption': post['caption']['text'].strip().replace('\n', ' ').replace('\n', ' '), 'commented': commented, 'commentNumber': post['comment_count'], 'commentTimestamp': round(time.time()), 'liked': True, 'shared': reposted, 'shareCaption': caption}
instagram.like(post['pk'])
print(' [x] Liked')
print(' Successfully entered contest!')
sleepCounter += randomSleepTimer(0, 3)
return contests.append(newRow, ignore_index=True)<|docstring|>Likes, follows, comments, and reposts if required<|endoftext|> |
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[(userSearchData['follower_count'] > minFollowers)]
userSearchData = userSearchData.set_index('username')
return userSearchData | 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)]
userSearchData = userSearchData.set_index('username')
return userSearchData | def cleanUserSearch(userSearchJson, minFollowers):
' '
userSearchData = pd.DataFrame(userSearchJson['users'])
del userSearchData['byline']
userSearchData = userSearchData[(userSearchData['is_private'] == False)]
userSearchData = userSearchData[(userSearchData['follower_count'] > minFollowers)]
userSearchData = userSearchData.set_index('username')
return userSearchData<|docstring|>Cleans Json of User search, Returns Dataframe<|endoftext|> |
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:
userSearchData = cleanUserSearch(userSearchJson, minFollowers)
print('Users found: ', len(userSearchData))
if (returnType == 'list'):
return userSearchData['pk'].tolist()
elif (returnType == 'dict'):
return userSearchData['pk'].to_dict()
else:
print('return type not recognized, returning List')
return userSearchData['pk'].tolist() | 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, minFollowers)
print('Users found: ', len(userSearchData))
if (returnType == 'list'):
return userSearchData['pk'].tolist()
elif (returnType == 'dict'):
return userSearchData['pk'].to_dict()
else:
print('return type not recognized, returning List')
return userSearchData['pk'].tolist() | 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, minFollowers)
print('Users found: ', len(userSearchData))
if (returnType == 'list'):
return userSearchData['pk'].tolist()
elif (returnType == 'dict'):
return userSearchData['pk'].to_dict()
else:
print('return type not recognized, returning List')
return userSearchData['pk'].tolist()<|docstring|>given name, search, clean, return restults<|endoftext|> |
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 = ['braidsbybreann', 'brownhairedbliss', 'emmaa.w', 'daisy_cullenn', 'tara_sagexo', 'madisinw', 'jenny_filt', 'garymannwx', 'cam_raee', 'tori_auricht', 'braids_by_lisa', 'mybraidings', 'ellaboag', 'Jada_autumn', 'mimi_floreani', 'saramccoy11', 'jovanoviclj', 'dulce_lo_', 'saraawegz', 'brunosaltor', 'nailp0lish_', 'natalieszenas', 'mia__chan', 'indieconnolly', 'zoerelf', 'tay.k.18', 'fatom_3sk', 'dyna_kd', 'meryemlaaraich', 'maryam_tariq', 'lujain_alesawy', '______555suzi__', 'xx_anoode', 'omneat', 'saragrammm', 'joslexispam']
elif (peopleNeeded == 0):
followerNames = ['']
else:
followerNames = followers['username'].tolist()
try:
followerNames.remove(primaryAccount)
except ValueError:
pass
followerNames = [name for name in followerNames if (not any([('follow' in name), ('golf' in name), ('shop' in name), ('app' in name), ('furniture' in name), ('free' in name), ('hack' in name), ('store' in name)]))]
try:
firstTagIx = random.randrange(0, ((len(followerNames) - 1) - peopleNeeded))
except:
firstTagIx = 0
followerNames = ([primaryAccount] + followerNames[firstTagIx:((firstTagIx + peopleNeeded) - 1)])
return followerNames | 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_cullenn', 'tara_sagexo', 'madisinw', 'jenny_filt', 'garymannwx', 'cam_raee', 'tori_auricht', 'braids_by_lisa', 'mybraidings', 'ellaboag', 'Jada_autumn', 'mimi_floreani', 'saramccoy11', 'jovanoviclj', 'dulce_lo_', 'saraawegz', 'brunosaltor', 'nailp0lish_', 'natalieszenas', 'mia__chan', 'indieconnolly', 'zoerelf', 'tay.k.18', 'fatom_3sk', 'dyna_kd', 'meryemlaaraich', 'maryam_tariq', 'lujain_alesawy', '______555suzi__', 'xx_anoode', 'omneat', 'saragrammm', 'joslexispam']
elif (peopleNeeded == 0):
followerNames = []
else:
followerNames = followers['username'].tolist()
try:
followerNames.remove(primaryAccount)
except ValueError:
pass
followerNames = [name for name in followerNames if (not any([('follow' in name), ('golf' in name), ('shop' in name), ('app' in name), ('furniture' in name), ('free' in name), ('hack' in name), ('store' in name)]))]
try:
firstTagIx = random.randrange(0, ((len(followerNames) - 1) - peopleNeeded))
except:
firstTagIx = 0
followerNames = ([primaryAccount] + followerNames[firstTagIx:((firstTagIx + peopleNeeded) - 1)])
return followerNames | 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_cullenn', 'tara_sagexo', 'madisinw', 'jenny_filt', 'garymannwx', 'cam_raee', 'tori_auricht', 'braids_by_lisa', 'mybraidings', 'ellaboag', 'Jada_autumn', 'mimi_floreani', 'saramccoy11', 'jovanoviclj', 'dulce_lo_', 'saraawegz', 'brunosaltor', 'nailp0lish_', 'natalieszenas', 'mia__chan', 'indieconnolly', 'zoerelf', 'tay.k.18', 'fatom_3sk', 'dyna_kd', 'meryemlaaraich', 'maryam_tariq', 'lujain_alesawy', '______555suzi__', 'xx_anoode', 'omneat', 'saragrammm', 'joslexispam']
elif (peopleNeeded == 0):
followerNames = []
else:
followerNames = followers['username'].tolist()
try:
followerNames.remove(primaryAccount)
except ValueError:
pass
followerNames = [name for name in followerNames if (not any([('follow' in name), ('golf' in name), ('shop' in name), ('app' in name), ('furniture' in name), ('free' in name), ('hack' in name), ('store' in name)]))]
try:
firstTagIx = random.randrange(0, ((len(followerNames) - 1) - peopleNeeded))
except:
firstTagIx = 0
followerNames = ([primaryAccount] + followerNames[firstTagIx:((firstTagIx + peopleNeeded) - 1)])
return followerNames<|docstring|>returns List of n usernames from own followers<|endoftext|> |
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:
if (userId not in totalFollowingIdList):
instagram.follow(userId)
sleepCounter += randomSleepTimer(0, 2)
print('Successfully finished search')
return sleepCounter | 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 totalFollowingIdList):
instagram.follow(userId)
sleepCounter += randomSleepTimer(0, 2)
print('Successfully finished search')
return sleepCounter | 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 totalFollowingIdList):
instagram.follow(userId)
sleepCounter += randomSleepTimer(0, 2)
print('Successfully finished search')
return sleepCounter<|docstring|>search for new Users given list<|endoftext|> |
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:
if (user['username'].lower() == tag.lower()):
ids.append(user['pk'])
added = True
elif (user['username'].lower() == tag[1:].lower()):
ids.append(user['pk'])
added = True
elif (user['username'].lower() == ('@' + tag).lower()):
ids.append(user['pk'])
added = True
if (added == False):
try:
ids.append(userList[0]['pk'])
print((' Failed: finding %s. Following: %s' % (tag, instagram.LastJson['users'][0]['username'])))
except:
print(' Failed: Cannot recognize ID !!!')
print(ids)
return ids | 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()):
ids.append(user['pk'])
added = True
elif (user['username'].lower() == tag[1:].lower()):
ids.append(user['pk'])
added = True
elif (user['username'].lower() == ('@' + tag).lower()):
ids.append(user['pk'])
added = True
if (added == False):
try:
ids.append(userList[0]['pk'])
print((' Failed: finding %s. Following: %s' % (tag, instagram.LastJson['users'][0]['username'])))
except:
print(' Failed: Cannot recognize ID !!!')
print(ids)
return ids | 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()):
ids.append(user['pk'])
added = True
elif (user['username'].lower() == tag[1:].lower()):
ids.append(user['pk'])
added = True
elif (user['username'].lower() == ('@' + tag).lower()):
ids.append(user['pk'])
added = True
if (added == False):
try:
ids.append(userList[0]['pk'])
print((' Failed: finding %s. Following: %s' % (tag, instagram.LastJson['users'][0]['username'])))
except:
print(' Failed: Cannot recognize ID !!!')
print(ids)
return ids<|docstring|>given a list of userids, gets user tag by search and match<|endoftext|> |
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(userId)
newFollows.append(userId)
sleepCounter += randomSleepTimer(1, 2)
print((' [x] Followed: ' + ', '.join(toFollow)), '- already followed: ', ', '.join([str(item) for item in list((set(userIdList) - set(toFollow)))]))
return sleepCounter | 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)
sleepCounter += randomSleepTimer(1, 2)
print((' [x] Followed: ' + ', '.join(toFollow)), '- already followed: ', ', '.join([str(item) for item in list((set(userIdList) - set(toFollow)))]))
return sleepCounter | 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)
sleepCounter += randomSleepTimer(1, 2)
print((' [x] Followed: ' + ', '.join(toFollow)), '- already followed: ', ', '.join([str(item) for item in list((set(userIdList) - set(toFollow)))]))
return sleepCounter<|docstring|>follow a list of new users if not already followed<|endoftext|> |
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 (postsToCheck.iloc[i]['shareCaption'] == 'nan')):
continue
elif ((selfFeed[i]['caption'] == None) and (postsToCheck.iloc[i]['shareCaption'] != 'nan')):
print('Changing caption')
print(selfFeed[i]['pk'])
try:
print(postsToCheck.iloc[i]['shareCaption'])
if instagram.editMedia(mediaId=selfFeed[i]['pk'], captionText=postsToCheck.iloc[i]['shareCaption']):
changed = (changed + 1)
else:
print('Could not edit image')
except:
print('Unable to change. Deleting.')
instagram.deleteMedia(selfFeed[i]['pk'])
else:
continue
print('Changed items: ', changed) | 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'] == 'nan')):
continue
elif ((selfFeed[i]['caption'] == None) and (postsToCheck.iloc[i]['shareCaption'] != 'nan')):
print('Changing caption')
print(selfFeed[i]['pk'])
try:
print(postsToCheck.iloc[i]['shareCaption'])
if instagram.editMedia(mediaId=selfFeed[i]['pk'], captionText=postsToCheck.iloc[i]['shareCaption']):
changed = (changed + 1)
else:
print('Could not edit image')
except:
print('Unable to change. Deleting.')
instagram.deleteMedia(selfFeed[i]['pk'])
else:
continue
print('Changed items: ', changed) | 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'] == 'nan')):
continue
elif ((selfFeed[i]['caption'] == None) and (postsToCheck.iloc[i]['shareCaption'] != 'nan')):
print('Changing caption')
print(selfFeed[i]['pk'])
try:
print(postsToCheck.iloc[i]['shareCaption'])
if instagram.editMedia(mediaId=selfFeed[i]['pk'], captionText=postsToCheck.iloc[i]['shareCaption']):
changed = (changed + 1)
else:
print('Could not edit image')
except:
print('Unable to change. Deleting.')
instagram.deleteMedia(selfFeed[i]['pk'])
else:
continue
print('Changed items: ', changed)<|docstring|>Check and update captions of posts<|endoftext|> |
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(website)
with urllib.request.urlopen(req) as response:
pageHTML = response.read()
pattern = ((b'([^"$"]*' + checkWebsite) + b'*[a-zA-Z0-9_+/]*)')
results = re.findall(pattern, pageHTML)
return results | 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 response:
pageHTML = response.read()
pattern = ((b'([^"$"]*' + checkWebsite) + b'*[a-zA-Z0-9_+/]*)')
results = re.findall(pattern, pageHTML)
return results | 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 response:
pageHTML = response.read()
pattern = ((b'([^"$"]*' + checkWebsite) + b'*[a-zA-Z0-9_+/]*)')
results = re.findall(pattern, pageHTML)
return results<|docstring|>finds instagram (or other) account linked on website<|endoftext|> |
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 = MyModel()
assert (m.rid != m2.rid)
assert (m2.rid != m3.rid)
assert (m.rid != m3.rid) | 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 = MyModel()
assert (m.rid != m2.rid)
assert (m2.rid != m3.rid)
assert (m.rid != m3.rid) | 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 = MyModel()
assert (m.rid != m2.rid)
assert (m2.rid != m3.rid)
assert (m.rid != m3.rid)<|docstring|>Creating a ModelBase should create a new record id 'rid.' For each
instance, a new 'rid' should be created.<|endoftext|> |
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)
copied = copy_method(m)
assert (m.rid != copied.rid)
assert (copied.id is None) | 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)
assert (m.rid != copied.rid)
assert (copied.id is None) | @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)
assert (m.rid != copied.rid)
assert (copied.id is None)<|docstring|>Copy should anonymize models.<|endoftext|> |
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().__init__(id=id)
m = MyModel(1)
m2 = MyOtherModel(2)
m3 = MyModel(3)
m3.other = m2
m2.other = m
rid1 = m.rid
rid2 = m2.rid
rid3 = m3.rid
copied = m3.copy()
assert (copied.id is None)
assert (copied.other.id is None)
assert (copied.other.other.id is None)
assert (copied.rid != rid1)
assert (copied.other.rid != rid2)
assert (copied.other.other.rid != rid3)
assert (m3.rid == rid3)
assert (m3.other.rid == rid2)
assert (m3.other.other.rid == rid1) | 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 = MyOtherModel(2)
m3 = MyModel(3)
m3.other = m2
m2.other = m
rid1 = m.rid
rid2 = m2.rid
rid3 = m3.rid
copied = m3.copy()
assert (copied.id is None)
assert (copied.other.id is None)
assert (copied.other.other.id is None)
assert (copied.rid != rid1)
assert (copied.other.rid != rid2)
assert (copied.other.other.rid != rid3)
assert (m3.rid == rid3)
assert (m3.other.rid == rid2)
assert (m3.other.other.rid == rid1) | 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 = MyOtherModel(2)
m3 = MyModel(3)
m3.other = m2
m2.other = m
rid1 = m.rid
rid2 = m2.rid
rid3 = m3.rid
copied = m3.copy()
assert (copied.id is None)
assert (copied.other.id is None)
assert (copied.other.other.id is None)
assert (copied.rid != rid1)
assert (copied.other.rid != rid2)
assert (copied.other.other.rid != rid3)
assert (m3.rid == rid3)
assert (m3.other.rid == rid2)
assert (m3.other.other.rid == rid1)<|docstring|>Copy should recursively anonymize all models.<|endoftext|> |
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()
del mdump['rid']
assert (mdump == {'name': 'model', 'id': 5}) | 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()
del mdump['rid']
assert (mdump == {'name': 'model', 'id': 5}) | 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()
del mdump['rid']
assert (mdump == {'name': 'model', 'id': 5})<|docstring|>MyModel initializes should absorb kwargs into attributes.
With a schema, those attributes are also tracked and available for
dumping.<|endoftext|> |
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(Exception):
m.connect_to_session(fake_session2) | 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|>Connecting to other sessions afterward should not be allowed.<|endoftext|> |
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, _check_for_session should raise an
AttributeError.<|endoftext|> |
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.<|endoftext|> |
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 "
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
monkeypatch.setattr(AqSession, AqSession.model_interface.__name__, fake_model_interface)
m = mymodel()
ModelRegistry.models['FakeModel'] = ModelBase
m.connect_to_session(fake_session)
assert (m.where_callback('FakeModel', 5) == 5)
assert (m.find_callback('FakeModel', 6) == 6) | 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 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
monkeypatch.setattr(AqSession, AqSession.model_interface.__name__, fake_model_interface)
m = mymodel()
ModelRegistry.models['FakeModel'] = ModelBase
m.connect_to_session(fake_session)
assert (m.where_callback('FakeModel', 5) == 5)
assert (m.find_callback('FakeModel', 6) == 6) | 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 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
monkeypatch.setattr(AqSession, AqSession.model_interface.__name__, fake_model_interface)
m = mymodel()
ModelRegistry.models['FakeModel'] = ModelBase
m.connect_to_session(fake_session)
assert (m.where_callback('FakeModel', 5) == 5)
assert (m.find_callback('FakeModel', 6) == 6)<|docstring|>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<|endoftext|> |
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__' in with_uri)
assert (with_uri['__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_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.org/my_models/10') | 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.org/my_models/10')<|docstring|>Expect with with the `include_uri` key includes the default URI.<|endoftext|> |
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 ('__model__' in with_mt)
assert (with_mt['__model__'] == 'MyModel') | 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')<|docstring|>Expect with with the `include_uri` key includes the default URI.<|endoftext|> |
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 = model_response['conv{}'.format(l)]
losses.append(nn.functional.mse_loss(content_response, target_response))
return sum(losses) | 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 = model_response['conv{}'.format(l)]
losses.append(nn.functional.mse_loss(content_response, target_response))
return sum(losses) | 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 = model_response['conv{}'.format(l)]
losses.append(nn.functional.mse_loss(content_response, target_response))
return sum(losses)<|docstring|>Compute loss of given image w.r.t. initialized content.
Arguments:
model_response (tensor): Model response to target image.<|endoftext|> |
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(subset)
return subsets | 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<|docstring|>Get all subsets of the given set.<|endoftext|> |
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 (len(beta) == 0):
continue
tmpset.clear()
for gamma in beta:
if (gamma in tmp_dfa.delta_function[alpha]):
for item in tmp_dfa.delta_function[alpha][gamma]:
tmpset.add(item)
listset = list(tmpset)
listset.sort()
tmp_delta_function[alpha][str(beta)] = listset
tmp_dfa.delta_function = tmp_delta_function
terminal_set = set()
for item in tmp_dfa.states:
if (not set(tmp_dfa.terminal_states).isdisjoint(set(item))):
terminal_set.add(str(item))
tmp_dfa.terminal_states = list(terminal_set)
return tmp_dfa | 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):
continue
tmpset.clear()
for gamma in beta:
if (gamma in tmp_dfa.delta_function[alpha]):
for item in tmp_dfa.delta_function[alpha][gamma]:
tmpset.add(item)
listset = list(tmpset)
listset.sort()
tmp_delta_function[alpha][str(beta)] = listset
tmp_dfa.delta_function = tmp_delta_function
terminal_set = set()
for item in tmp_dfa.states:
if (not set(tmp_dfa.terminal_states).isdisjoint(set(item))):
terminal_set.add(str(item))
tmp_dfa.terminal_states = list(terminal_set)
return tmp_dfa | 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):
continue
tmpset.clear()
for gamma in beta:
if (gamma in tmp_dfa.delta_function[alpha]):
for item in tmp_dfa.delta_function[alpha][gamma]:
tmpset.add(item)
listset = list(tmpset)
listset.sort()
tmp_delta_function[alpha][str(beta)] = listset
tmp_dfa.delta_function = tmp_delta_function
terminal_set = set()
for item in tmp_dfa.states:
if (not set(tmp_dfa.terminal_states).isdisjoint(set(item))):
terminal_set.add(str(item))
tmp_dfa.terminal_states = list(terminal_set)
return tmp_dfa<|docstring|>Convert NFA to DFA<|endoftext|> |
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 Response(retailers, status=200, mimetype='application/json') | 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 Response(retailers, status=200, mimetype='application/json') | @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 Response(retailers, status=200, mimetype='application/json')<|docstring|>Get all retailer objects.
:return: [{
"id": "123",
"address": {Address}
}, {...}]<|endoftext|> |
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_input((retailer_id, 'retailer to retrieve'))
retailer = retailer_service.get_retailer(token=g.auth['loopback_token'], retailer_id=retailer_id)
return Response(retailer, status=200, mimetype='application/json') | 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_input((retailer_id, 'retailer to retrieve'))
retailer = retailer_service.get_retailer(token=g.auth['loopback_token'], retailer_id=retailer_id)
return Response(retailer, status=200, mimetype='application/json') | @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_input((retailer_id, 'retailer to retrieve'))
retailer = retailer_service.get_retailer(token=g.auth['loopback_token'], retailer_id=retailer_id)
return Response(retailer, status=200, mimetype='application/json')<|docstring|>Retrieve a single retailer object.
:param retailer_id: The retailer's id
:return: {
"id": "123",
"address": {Address}
}<|endoftext|> |
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": "SHIPPED",\n "createdAt": "2015-11-05T22:00:51.692765",\n "updatedAt": "2015-11-08T22:00:51.692765",\n "deliveredAt": "2015-11-08T22:00:51.692765",\n "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",\n "currentLocation": {Address},\n "fromId": "D2",\n "toId:": "123"\n }, {...}]\n\n '
check_null_input((retailer_id, 'retailer whose shipments you want to retrieve'))
status = request.args.get('status')
shipments = shipment_service.get_shipments(token=g.auth['loopback_token'], retailer_id=retailer_id, status=status)
return Response(shipments, status=200, mimetype='application/json') | 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",
"estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
"currentLocation": {Address},
"fromId": "D2",
"toId:": "123"
}, {...}] | 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": "SHIPPED",\n "createdAt": "2015-11-05T22:00:51.692765",\n "updatedAt": "2015-11-08T22:00:51.692765",\n "deliveredAt": "2015-11-08T22:00:51.692765",\n "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",\n "currentLocation": {Address},\n "fromId": "D2",\n "toId:": "123"\n }, {...}]\n\n '
check_null_input((retailer_id, 'retailer whose shipments you want to retrieve'))
status = request.args.get('status')
shipments = shipment_service.get_shipments(token=g.auth['loopback_token'], retailer_id=retailer_id, status=status)
return Response(shipments, status=200, mimetype='application/json') | @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": "SHIPPED",\n "createdAt": "2015-11-05T22:00:51.692765",\n "updatedAt": "2015-11-08T22:00:51.692765",\n "deliveredAt": "2015-11-08T22:00:51.692765",\n "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",\n "currentLocation": {Address},\n "fromId": "D2",\n "toId:": "123"\n }, {...}]\n\n '
check_null_input((retailer_id, 'retailer whose shipments you want to retrieve'))
status = request.args.get('status')
shipments = shipment_service.get_shipments(token=g.auth['loopback_token'], retailer_id=retailer_id, status=status)
return Response(shipments, status=200, mimetype='application/json')<|docstring|>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",
"estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
"currentLocation": {Address},
"fromId": "D2",
"toId:": "123"
}, {...}]<|endoftext|> |
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 "productId": "123",\n "locationId": "123",\n "locationType": "Retailer"\n }, {...}]\n '
check_null_input((retailer_id, 'retailer whose inventory you want to retrieve'))
inventory = retailer_service.get_retailer_inventory(token=g.auth['loopback_token'], retailer_id=retailer_id)
return Response(inventory, status=200, mimetype='application/json') | 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 "productId": "123",\n "locationId": "123",\n "locationType": "Retailer"\n }, {...}]\n '
check_null_input((retailer_id, 'retailer whose inventory you want to retrieve'))
inventory = retailer_service.get_retailer_inventory(token=g.auth['loopback_token'], retailer_id=retailer_id)
return Response(inventory, status=200, mimetype='application/json') | @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 "productId": "123",\n "locationId": "123",\n "locationType": "Retailer"\n }, {...}]\n '
check_null_input((retailer_id, 'retailer whose inventory you want to retrieve'))
inventory = retailer_service.get_retailer_inventory(token=g.auth['loopback_token'], retailer_id=retailer_id)
return Response(inventory, status=200, mimetype='application/json')<|docstring|>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"
}, {...}]<|endoftext|> |
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<|docstring|>只设置host content-type 还有x开头的头部.
:param data(dict): 所有的头部信息.
:return(dict): 计算进签名的头部.<|endoftext|> |
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:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('Error: can\'t find template "mailmerge_template.txt"' in stderr)
assert ('https://github.com/awdeorio/mailmerge' in stderr) | 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:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('Error: can\'t find template "mailmerge_template.txt"' in stderr)
assert ('https://github.com/awdeorio/mailmerge' in stderr) | 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:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('Error: can\'t find template "mailmerge_template.txt"' in stderr)
assert ('https://github.com/awdeorio/mailmerge' in stderr)<|docstring|>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.<|endoftext|> |
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')).exists()
assert (output.stderr.decode('utf-8') == '')
assert ('Created sample template' in output)
assert ('Created sample database' in output)
assert ('Created sample config' in output) | 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-8') == )
assert ('Created sample template' in output)
assert ('Created sample database' in output)
assert ('Created sample config' in output) | 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-8') == )
assert ('Created sample template' in output)
assert ('Created sample database' in output)
assert ('Created sample config' in output)<|docstring|>Verify --sample creates sample input files.<|endoftext|> |
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 = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('Error: file exists: mailmerge_template.txt' in 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 == )
assert ('Error: file exists: mailmerge_template.txt' in stderr) | 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 == )
assert ('Error: file exists: mailmerge_template.txt' in stderr)<|docstring|>Verify --sample won't clobber template if it already exists.<|endoftext|> |
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 = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('Error: file exists: mailmerge_database.csv' in 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 == )
assert ('Error: file exists: mailmerge_database.csv' in stderr) | 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 == )
assert ('Error: file exists: mailmerge_database.csv' in stderr)<|docstring|>Verify --sample won't clobber database if it already exists.<|endoftext|> |
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 = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('Error: file exists: mailmerge_server.conf' in stderr) | 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 == )
assert ('Error: file exists: mailmerge_server.conf' in stderr) | 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 == )
assert ('Error: file exists: mailmerge_server.conf' in stderr)<|docstring|>Verify --sample won't clobber config if it already exists.<|endoftext|> |
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)
assert ('This was a dry run' 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 options are provided, use default input file names.<|endoftext|> |
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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--dry-run', '--limit', '-1')
stderr = error.value.stderr.decode('utf-8')
assert ('Error: Invalid value' in stderr) | 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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--dry-run', '--limit', '-1')
stderr = error.value.stderr.decode('utf-8')
assert ('Error: Invalid value' in stderr) | def test_bad_limit(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--dry-run', '--limit', '-1')
stderr = error.value.stderr.decode('utf-8')
assert ('Error: Invalid value' in stderr)<|docstring|>Verify --limit with bad value.<|endoftext|> |
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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--no-limit', '--limit', '1')
assert (output.stderr.decode('utf-8') == '')
assert ('message 1 sent' in output)
assert ('message 2 sent' in output)
assert ('Limit was 1' not in output) | 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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--no-limit', '--limit', '1')
assert (output.stderr.decode('utf-8') == )
assert ('message 1 sent' in output)
assert ('message 2 sent' in output)
assert ('Limit was 1' not in output) | def test_limit_combo(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--no-limit', '--limit', '1')
assert (output.stderr.decode('utf-8') == )
assert ('message 1 sent' in output)
assert ('message 2 sent' in output)
assert ('Limit was 1' not in output)<|docstring|>Verify --limit 1 --no-limit results in no limit.<|endoftext|> |
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')
assert (stdout == '')
assert ("Error: can't find template" in stderr) | 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 template" in stderr) | 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 template" in stderr)<|docstring|>Verify error when template input file not found.<|endoftext|> |
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 = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ("Error: can't find database" in 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 (stdout == )
assert ("Error: can't find database" in stderr) | 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 (stdout == )
assert ("Error: can't find database" in stderr)<|docstring|>Verify error when database input file not found.<|endoftext|> |
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 = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ("Error: can't find config" in stderr) | 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 = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("Error: can't find config" in stderr) | 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 = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("Error: can't find config" in stderr)<|docstring|>Verify error when config input file not found.<|endoftext|> |
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 == output2) | 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 produces a help message.<|endoftext|> |
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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ("template.txt: 'error_not_in_database' is undefined" in stderr) | 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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("template.txt: 'error_not_in_database' is undefined" in stderr) | 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: [email protected]\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("template.txt: 'error_not_in_database' is undefined" in stderr)<|docstring|>Template mismatch with database header should produce an error.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n "hello world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('database.csv:1: unexpected end of data' in stderr) | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n "hello world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('database.csv:1: unexpected end of data' in stderr) | def test_bad_database(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n "hello world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('database.csv:1: unexpected end of data' in stderr)<|docstring|>Database read error should produce a sane error.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' dummy\n asdf\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ("server.conf: No option 'host' in section: 'smtp_server'" in stderr) | 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: [email protected]\n FROM: [email protected]\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' dummy\n asdf\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("server.conf: No option 'host' in section: 'smtp_server'" in stderr) | def test_bad_config(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' dummy\n asdf\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ("server.conf: No option 'host' in section: 'smtp_server'" in stderr)<|docstring|>Config containing an error should produce an error.<|endoftext|> |
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((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n ATTACHMENT: attachment1.txt\n ATTACHMENT: attachment2.txt\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--output-format', 'text')
assert (output.stderr.decode('utf-8') == '')
assert ('>>> message part: text/plain' in output)
assert ('Hello world' in output)
assert ('>>> message part: attachment attachment1.txt' in output)
assert ('>>> message part: attachment attachment2.txt' in output) | 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'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n ATTACHMENT: attachment1.txt\n ATTACHMENT: attachment2.txt\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--output-format', 'text')
assert (output.stderr.decode('utf-8') == )
assert ('>>> message part: text/plain' in output)
assert ('Hello world' in output)
assert ('>>> message part: attachment attachment1.txt' in output)
assert ('>>> message part: attachment attachment2.txt' in output) | 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'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n ATTACHMENT: attachment1.txt\n ATTACHMENT: attachment2.txt\n\n Hello world\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--output-format', 'text')
assert (output.stderr.decode('utf-8') == )
assert ('>>> message part: text/plain' in output)
assert ('Hello world' in output)
assert ('>>> message part: attachment attachment1.txt' in output)
assert ('>>> message part: attachment attachment2.txt' in output)<|docstring|>Verify attachments feature output.<|endoftext|> |
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: [email protected]\n\n Laȝamon 😀 klâwen\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
output = sh.mailmerge('--template', template_path, '--database', database_path, '--config', config_path, '--dry-run', '--output-format', 'text')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == '')
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n Laȝamon 😀 klâwen\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | 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: [email protected]\n\n Laȝamon 😀 klâwen\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
output = sh.mailmerge('--template', template_path, '--database', database_path, '--config', config_path, '--dry-run', '--output-format', 'text')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n Laȝamon 😀 klâwen\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | def test_utf8_template(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n\n Laȝamon 😀 klâwen\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
output = sh.mailmerge('--template', template_path, '--database', database_path, '--config', config_path, '--dry-run', '--output-format', 'text')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n Laȝamon 😀 klâwen\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n '))<|docstring|>Message is utf-8 encoded when only the template contains utf-8 chars.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n Laȝamon 😀 klâwen\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--output-format', 'text')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == '')
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n Laȝamon 😀 klâwen\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n Laȝamon 😀 klâwen\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--output-format', 'text')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n Laȝamon 😀 klâwen\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | def test_utf8_database(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n Laȝamon 😀 klâwen\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--output-format', 'text')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n Laȝamon 😀 klâwen\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n '))<|docstring|>Message is utf-8 encoded when only the databse contains utf-8 chars.<|endoftext|> |
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 <[email protected]>\n FROM: klâwen <[email protected]>\n SUBJECT: Laȝamon 😀 klâwen\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
output = sh.mailmerge('--template', template_path, '--database', database_path, '--config', config_path, '--dry-run', '--output-format', 'raw')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == '')
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: =?utf-8?b?TGHInWFtb24gPHRvQHRlc3QuY29tPg==?=\n FROM: =?utf-8?b?a2zDondlbiA8ZnJvbUB0ZXN0LmNvbT4=?=\n SUBJECT: =?utf-8?b?TGHInWFtb24g8J+YgCBrbMOid2Vu?=\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n aGVsbG8=\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | 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 <[email protected]>\n FROM: klâwen <[email protected]>\n SUBJECT: Laȝamon 😀 klâwen\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
output = sh.mailmerge('--template', template_path, '--database', database_path, '--config', config_path, '--dry-run', '--output-format', 'raw')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: =?utf-8?b?TGHInWFtb24gPHRvQHRlc3QuY29tPg==?=\n FROM: =?utf-8?b?a2zDondlbiA8ZnJvbUB0ZXN0LmNvbT4=?=\n SUBJECT: =?utf-8?b?TGHInWFtb24g8J+YgCBrbMOid2Vu?=\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n aGVsbG8=\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | def test_utf8_headers(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: Laȝamon <[email protected]>\n FROM: klâwen <[email protected]>\n SUBJECT: Laȝamon 😀 klâwen\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
output = sh.mailmerge('--template', template_path, '--database', database_path, '--config', config_path, '--dry-run', '--output-format', 'raw')
stdout = output.stdout.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (output.stderr.decode('utf-8') == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: =?utf-8?b?TGHInWFtb24gPHRvQHRlc3QuY29tPg==?=\n FROM: =?utf-8?b?a2zDondlbiA8ZnJvbUB0ZXN0LmNvbT4=?=\n SUBJECT: =?utf-8?b?TGHInWFtb24g8J+YgCBrbMOid2Vu?=\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n Date: REDACTED\n\n aGVsbG8=\n\n >>> message 1 sent\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n '))<|docstring|>Message is utf-8 encoded when headers contain utf-8 chars.<|endoftext|> |
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 / 'attachment1.txt'))
attachment1_path.write_text(u'Hello world\n')
attachment2_path = Path((tmpdir / 'attachment2.csv'))
attachment2_path.write_text(u'hello,mailmerge\n')
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n CC: [email protected], [email protected]\n BCC: [email protected], [email protected]\n ATTACHMENT: attachment1.txt\n ATTACHMENT: attachment2.csv\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n Content-Type: text/plain; charset=us-ascii\n\n {{message}}\n\n\n --boundary\n Content-Type: text/html; charset=us-ascii\n\n <html>\n <body>\n <p>{{message}}</p>\n </body>\n </html>\n\n\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email,message\n [email protected],"Hello, ""world"""\n Lazamon<[email protected]>,Laȝamon 😀 klâwen\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--no-limit', '--output-format', 'raw')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
stdout = stdout.replace('EXAMPLE_KEY', 'EXAMPLE_KEY')
stdout = stdout.replace('Pgo8L2h0bWw+Cgo=', 'Pgo8L2h0bWw+Cg==')
stdout = stdout.replace('Hello, "world"\n\n\n\n', 'Hello, "world"\n\n\n')
stdout = stdout.replace('</html>\n\n\n', '</html>\n\n')
assert (stderr == '')
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n CC: [email protected], [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/plain; charset="us-ascii"\n Content-Transfer-Encoding: 7bit\n\n Hello, "world"\n\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/html; charset="us-ascii"\n Content-Transfer-Encoding: 7bit\n\n <html>\n <body>\n <p>Hello, "world"</p>\n </body>\n </html>\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment1.txt"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment1.txt"\n\n SGVsbG8gd29ybGQK\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment2.csv"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment2.csv"\n\n aGVsbG8sbWFpbG1lcmdlCg==\n\n --boundary--\n >>> message 1 sent\n >>> message 2\n TO: Lazamon<[email protected]>\n FROM: [email protected]\n CC: [email protected], [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n\n EXAMPLE_KEY\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/html; charset="utf-8"\n Content-Transfer-Encoding: base64\n\n PGh0bWw+CiAgPGJvZHk+CiAgICA8cD5MYcidYW1vbiDwn5iAIGtsw6J3ZW48L3A+CiAgPC9ib2R5\n Pgo8L2h0bWw+Cg==\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment1.txt"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment1.txt"\n\n SGVsbG8gd29ybGQK\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment2.csv"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment2.csv"\n\n aGVsbG8sbWFpbG1lcmdlCg==\n\n --boundary--\n >>> message 2 sent\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | 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 / 'attachment1.txt'))
attachment1_path.write_text(u'Hello world\n')
attachment2_path = Path((tmpdir / 'attachment2.csv'))
attachment2_path.write_text(u'hello,mailmerge\n')
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n CC: [email protected], [email protected]\n BCC: [email protected], [email protected]\n ATTACHMENT: attachment1.txt\n ATTACHMENT: attachment2.csv\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n Content-Type: text/plain; charset=us-ascii\n\n {{message}}\n\n\n --boundary\n Content-Type: text/html; charset=us-ascii\n\n <html>\n <body>\n <p>{{message}}</p>\n </body>\n </html>\n\n\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email,message\n [email protected],"Hello, world"\n Lazamon<[email protected]>,Laȝamon 😀 klâwen\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--no-limit', '--output-format', 'raw')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
stdout = stdout.replace('EXAMPLE_KEY', 'EXAMPLE_KEY')
stdout = stdout.replace('Pgo8L2h0bWw+Cgo=', 'Pgo8L2h0bWw+Cg==')
stdout = stdout.replace('Hello, "world"\n\n\n\n', 'Hello, "world"\n\n\n')
stdout = stdout.replace('</html>\n\n\n', '</html>\n\n')
assert (stderr == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n CC: [email protected], [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/plain; charset="us-ascii"\n Content-Transfer-Encoding: 7bit\n\n Hello, "world"\n\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/html; charset="us-ascii"\n Content-Transfer-Encoding: 7bit\n\n <html>\n <body>\n <p>Hello, "world"</p>\n </body>\n </html>\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment1.txt"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment1.txt"\n\n SGVsbG8gd29ybGQK\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment2.csv"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment2.csv"\n\n aGVsbG8sbWFpbG1lcmdlCg==\n\n --boundary--\n >>> message 1 sent\n >>> message 2\n TO: Lazamon<[email protected]>\n FROM: [email protected]\n CC: [email protected], [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n\n EXAMPLE_KEY\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/html; charset="utf-8"\n Content-Transfer-Encoding: base64\n\n PGh0bWw+CiAgPGJvZHk+CiAgICA8cD5MYcidYW1vbiDwn5iAIGtsw6J3ZW48L3A+CiAgPC9ib2R5\n Pgo8L2h0bWw+Cg==\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment1.txt"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment1.txt"\n\n SGVsbG8gd29ybGQK\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment2.csv"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment2.csv"\n\n aGVsbG8sbWFpbG1lcmdlCg==\n\n --boundary--\n >>> message 2 sent\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | 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 / 'attachment1.txt'))
attachment1_path.write_text(u'Hello world\n')
attachment2_path = Path((tmpdir / 'attachment2.csv'))
attachment2_path.write_text(u'hello,mailmerge\n')
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n CC: [email protected], [email protected]\n BCC: [email protected], [email protected]\n ATTACHMENT: attachment1.txt\n ATTACHMENT: attachment2.csv\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n Content-Type: text/plain; charset=us-ascii\n\n {{message}}\n\n\n --boundary\n Content-Type: text/html; charset=us-ascii\n\n <html>\n <body>\n <p>{{message}}</p>\n </body>\n </html>\n\n\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email,message\n [email protected],"Hello, world"\n Lazamon<[email protected]>,Laȝamon 😀 klâwen\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--no-limit', '--output-format', 'raw')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
stdout = stdout.replace('EXAMPLE_KEY', 'EXAMPLE_KEY')
stdout = stdout.replace('Pgo8L2h0bWw+Cgo=', 'Pgo8L2h0bWw+Cg==')
stdout = stdout.replace('Hello, "world"\n\n\n\n', 'Hello, "world"\n\n\n')
stdout = stdout.replace('</html>\n\n\n', '</html>\n\n')
assert (stderr == )
assert (stdout == textwrap.dedent(u' >>> message 1\n TO: [email protected]\n FROM: [email protected]\n CC: [email protected], [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/plain; charset="us-ascii"\n Content-Transfer-Encoding: 7bit\n\n Hello, "world"\n\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/html; charset="us-ascii"\n Content-Transfer-Encoding: 7bit\n\n <html>\n <body>\n <p>Hello, "world"</p>\n </body>\n </html>\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment1.txt"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment1.txt"\n\n SGVsbG8gd29ybGQK\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment2.csv"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment2.csv"\n\n aGVsbG8sbWFpbG1lcmdlCg==\n\n --boundary--\n >>> message 1 sent\n >>> message 2\n TO: Lazamon<[email protected]>\n FROM: [email protected]\n CC: [email protected], [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n This is a MIME-encoded message. If you are seeing this, your mail\n reader is old.\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/plain; charset="utf-8"\n Content-Transfer-Encoding: base64\n\n EXAMPLE_KEY\n\n --boundary\n MIME-Version: 1.0\n Content-Type: text/html; charset="utf-8"\n Content-Transfer-Encoding: base64\n\n PGh0bWw+CiAgPGJvZHk+CiAgICA8cD5MYcidYW1vbiDwn5iAIGtsw6J3ZW48L3A+CiAgPC9ib2R5\n Pgo8L2h0bWw+Cg==\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment1.txt"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment1.txt"\n\n SGVsbG8gd29ybGQK\n\n --boundary\n Content-Type: application/octet-stream; Name="attachment2.csv"\n MIME-Version: 1.0\n Content-Transfer-Encoding: base64\n Content-Disposition: attachment; filename="attachment2.csv"\n\n aGVsbG8sbWFpbG1lcmdlCg==\n\n --boundary--\n >>> message 2 sent\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n '))<|docstring|>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.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--resume', '2', '--no-limit')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert (stderr == '')
assert ('hello' not in stdout)
assert ('message 1 sent' not in stdout)
assert ('world' in stdout)
assert ('message 2 sent' in stdout) | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--resume', '2', '--no-limit')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert (stderr == )
assert ('hello' not in stdout)
assert ('message 1 sent' not in stdout)
assert ('world' in stdout)
assert ('message 2 sent' in stdout) | def test_resume(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--resume', '2', '--no-limit')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert (stderr == )
assert ('hello' not in stdout)
assert ('message 1 sent' not in stdout)
assert ('world' in stdout)
assert ('message 2 sent' in stdout)<|docstring|>Verify --resume option starts "in the middle" of the database.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--resume', '0')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('Invalid value' in stderr)
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--resume', '-1')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('Invalid value' in stderr) | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--resume', '0')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('Invalid value' in stderr)
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--resume', '-1')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('Invalid value' in stderr) | def test_resume_too_small(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--resume', '0')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('Invalid value' in stderr)
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_2) as error:
sh.mailmerge('--resume', '-1')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('Invalid value' in stderr)<|docstring|>Verify --resume <= 0 prints an error message.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--resume', '3', '--no-limit')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert ('sent message' not in stdout)
assert (stderr == '') | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--resume', '3', '--no-limit')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert ('sent message' not in stdout)
assert (stderr == ) | def test_resume_too_big(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge('--resume', '3', '--no-limit')
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert ('sent message' not in stdout)
assert (stderr == )<|docstring|>Verify --resume > database does nothing.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n "world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('--resume 1' not in stderr) | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n "world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('--resume 1' not in stderr) | def test_resume_hint_on_config_error(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n "world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge()
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('--resume 1' not in stderr)<|docstring|>Verify *no* --resume hint when error is after first message.<|endoftext|> |
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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n "world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge('--resume', '2', '--no-limit')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == '')
assert ('--resume 2' in stderr) | 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: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n "world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge('--resume', '2', '--no-limit')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('--resume 2' in stderr) | def test_resume_hint_on_csv_error(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: [email protected]\n FROM: [email protected]\n\n {{message}}\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' message\n hello\n "world\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error:
sh.mailmerge('--resume', '2', '--no-limit')
stdout = error.value.stdout.decode('utf-8')
stderr = error.value.stderr.decode('utf-8')
assert (stdout == )
assert ('--resume 2' in stderr)<|docstring|>Verify --resume hint after CSV error.<|endoftext|> |
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: [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n --boundary\n Content-Type: text/plain; charset=us-ascii\n\n Hello world\n\n --boundary\n Content-Type: application/pdf\n\n DUMMY\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge()
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert (stderr == '')
stdout = stdout.replace('\n\n\n\n', '\n\n\n')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (stdout == textwrap.dedent(u' \x1b[7m\x1b[1m\x1b[36m>>> message 1\x1b(B\x1b[m\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n \x1b[36m>>> message part: text/plain\x1b(B\x1b[m\n Hello world\n\n\n \x1b[36m>>> message part: application/pdf\x1b(B\x1b[m\n \x1b[7m\x1b[1m\x1b[36m>>> message 1 sent\x1b(B\x1b[m\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | 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: [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n --boundary\n Content-Type: text/plain; charset=us-ascii\n\n Hello world\n\n --boundary\n Content-Type: application/pdf\n\n DUMMY\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge()
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert (stderr == )
stdout = stdout.replace('\n\n\n\n', '\n\n\n')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (stdout == textwrap.dedent(u' \x1b[7m\x1b[1m\x1b[36m>>> message 1\x1b(B\x1b[m\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n \x1b[36m>>> message part: text/plain\x1b(B\x1b[m\n Hello world\n\n\n \x1b[36m>>> message part: application/pdf\x1b(B\x1b[m\n \x1b[7m\x1b[1m\x1b[36m>>> message 1 sent\x1b(B\x1b[m\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n ')) | def test_other_mime_type(tmpdir):
template_path = Path((tmpdir / 'mailmerge_template.txt'))
template_path.write_text(textwrap.dedent(u' TO: {{email}}\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n\n --boundary\n Content-Type: text/plain; charset=us-ascii\n\n Hello world\n\n --boundary\n Content-Type: application/pdf\n\n DUMMY\n '))
database_path = Path((tmpdir / 'mailmerge_database.csv'))
database_path.write_text(textwrap.dedent(u' email\n [email protected]\n '))
config_path = Path((tmpdir / 'mailmerge_server.conf'))
config_path.write_text(textwrap.dedent(u' [smtp_server]\n host = open-smtp.example.com\n port = 25\n '))
with tmpdir.as_cwd():
output = sh.mailmerge()
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
assert (stderr == )
stdout = stdout.replace('\n\n\n\n', '\n\n\n')
stdout = re.sub('Date:.+', 'Date: REDACTED', stdout, re.MULTILINE)
assert (stdout == textwrap.dedent(u' \x1b[7m\x1b[1m\x1b[36m>>> message 1\x1b(B\x1b[m\n TO: [email protected]\n FROM: [email protected]\n MIME-Version: 1.0\n Content-Type: multipart/alternative; boundary="boundary"\n Date: REDACTED\n\n \x1b[36m>>> message part: text/plain\x1b(B\x1b[m\n Hello world\n\n\n \x1b[36m>>> message part: application/pdf\x1b(B\x1b[m\n \x1b[7m\x1b[1m\x1b[36m>>> message 1 sent\x1b(B\x1b[m\n >>> Limit was 1 message. To remove the limit, use the --no-limit option.\n >>> This was a dry run. To send messages, use the --no-dry-run option.\n '))<|docstring|>Verify output with a MIME type that's not text or an attachment.<|endoftext|> |
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 True if yes<|endoftext|> |
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 ('initial_spectra' in d[name]):
d[name].pop(root)
new_key = f'initial spectra: root {(number + 1)}'
if (new_key not in d[name]):
d[name][new_key] = {}
d[name][new_key]['peaks'] = {}
if (iteration not in d[name][new_key]['peaks']):
d[name][new_key]['peaks'][iteration] = []
if (intensity > cutoff):
d[name][new_key]['peaks'][iteration].append((transition_energy, wavelength, intensity))
return d | 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 "
if ('initial_spectra' in d[name]):
d[name].pop(root)
new_key = f'initial spectra: root {(number + 1)}'
if (new_key not in d[name]):
d[name][new_key] = {}
d[name][new_key]['peaks'] = {}
if (iteration not in d[name][new_key]['peaks']):
d[name][new_key]['peaks'][iteration] = []
if (intensity > cutoff):
d[name][new_key]['peaks'][iteration].append((transition_energy, wavelength, intensity))
return d | 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 ('initial_spectra' in d[name]):
d[name].pop(root)
new_key = f'initial spectra: root {(number + 1)}'
if (new_key not in d[name]):
d[name][new_key] = {}
d[name][new_key]['peaks'] = {}
if (iteration not in d[name][new_key]['peaks']):
d[name][new_key]['peaks'][iteration] = []
if (intensity > cutoff):
d[name][new_key]['peaks'][iteration].append((transition_energy, wavelength, intensity))
return d<|docstring|>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<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.