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 |
|---|---|---|---|---|---|---|---|---|---|
5ee7ba1d97ac3fe64f0c22feecf3e691c7939c7ee3f80cd252da7cdece66c51b | def build_inputs(parameters, sess, inputs, outputs):
'Builds the inputs for expand_dims.'
input_values = []
input_values.append(create_tensor_data(parameters['input_type'], parameters['input_shape'], min_value=(- 1), max_value=1))
if (not parameters['constant_axis']):
input_values.append(np.array([parameters['axis_value']], dtype=np.int32))
return (input_values, sess.run(outputs, feed_dict=dict(zip(inputs, input_values)))) | Builds the inputs for expand_dims. | tensorflow/lite/testing/op_tests/expand_dims.py | build_inputs | K4S4B4/tensorflow | 190,993 | python | def build_inputs(parameters, sess, inputs, outputs):
input_values = []
input_values.append(create_tensor_data(parameters['input_type'], parameters['input_shape'], min_value=(- 1), max_value=1))
if (not parameters['constant_axis']):
input_values.append(np.array([parameters['axis_value']], dtype=np.int32))
return (input_values, sess.run(outputs, feed_dict=dict(zip(inputs, input_values)))) | def build_inputs(parameters, sess, inputs, outputs):
input_values = []
input_values.append(create_tensor_data(parameters['input_type'], parameters['input_shape'], min_value=(- 1), max_value=1))
if (not parameters['constant_axis']):
input_values.append(np.array([parameters['axis_value']], dtype=np.int32))
return (input_values, sess.run(outputs, feed_dict=dict(zip(inputs, input_values))))<|docstring|>Builds the inputs for expand_dims.<|endoftext|> |
818eddb1e1d06ab3c8d10cab375acf27c0e70b21b6bf827b14ad4a3d115f68c7 | def load(reward_scale: float, seed: int):
'Load a mountain_car experiment with the prescribed settings.'
env = wrappers.RewardScale(env=mountain_car.MountainCar(seed=seed), reward_scale=reward_scale, seed=seed)
env.bsuite_num_episodes = sweep.NUM_EPISODES
return env | Load a mountain_car experiment with the prescribed settings. | bsuite/experiments/mountain_car_scale/mountain_car_scale.py | load | RobvanGastel/bsuite | 1,337 | python | def load(reward_scale: float, seed: int):
env = wrappers.RewardScale(env=mountain_car.MountainCar(seed=seed), reward_scale=reward_scale, seed=seed)
env.bsuite_num_episodes = sweep.NUM_EPISODES
return env | def load(reward_scale: float, seed: int):
env = wrappers.RewardScale(env=mountain_car.MountainCar(seed=seed), reward_scale=reward_scale, seed=seed)
env.bsuite_num_episodes = sweep.NUM_EPISODES
return env<|docstring|>Load a mountain_car experiment with the prescribed settings.<|endoftext|> |
1febd7298240348521c3cd3397d073f6f21a32012e94a6d23b4c51182fcf496f | def parse(self, response):
'\n `parse` should always `yield` Meeting items.\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n '
sel_id = 'ctl00_PlaceHolderMain_PageContent__ControlWrapper_RichHtmlField'
sel_path = '/blockquote[1]/font/text()'
select_txt = ((("//*[@id='" + sel_id) + "']") + sel_path)
meetings = response.xpath(select_txt).extract()
for item in meetings:
meeting = Meeting(title=self._parse_title(item), description=self._parse_description(item), classification=self._parse_classification(item), start=self._parse_start(item), end=self._parse_end(item), all_day=self._parse_all_day(item), time_notes=self._parse_time_notes(item), location=self._parse_location(item), links=self._parse_links(item), source=self._parse_source(response))
(yield meeting) | `parse` should always `yield` Meeting items.
Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping
needs. | city_scrapers/spiders/pa_liquorboard.py | parse | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def parse(self, response):
'\n `parse` should always `yield` Meeting items.\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n '
sel_id = 'ctl00_PlaceHolderMain_PageContent__ControlWrapper_RichHtmlField'
sel_path = '/blockquote[1]/font/text()'
select_txt = ((("//*[@id='" + sel_id) + "']") + sel_path)
meetings = response.xpath(select_txt).extract()
for item in meetings:
meeting = Meeting(title=self._parse_title(item), description=self._parse_description(item), classification=self._parse_classification(item), start=self._parse_start(item), end=self._parse_end(item), all_day=self._parse_all_day(item), time_notes=self._parse_time_notes(item), location=self._parse_location(item), links=self._parse_links(item), source=self._parse_source(response))
(yield meeting) | def parse(self, response):
'\n `parse` should always `yield` Meeting items.\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n '
sel_id = 'ctl00_PlaceHolderMain_PageContent__ControlWrapper_RichHtmlField'
sel_path = '/blockquote[1]/font/text()'
select_txt = ((("//*[@id='" + sel_id) + "']") + sel_path)
meetings = response.xpath(select_txt).extract()
for item in meetings:
meeting = Meeting(title=self._parse_title(item), description=self._parse_description(item), classification=self._parse_classification(item), start=self._parse_start(item), end=self._parse_end(item), all_day=self._parse_all_day(item), time_notes=self._parse_time_notes(item), location=self._parse_location(item), links=self._parse_links(item), source=self._parse_source(response))
(yield meeting)<|docstring|>`parse` should always `yield` Meeting items.
Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping
needs.<|endoftext|> |
e4e9c1fc47af758e52cf23db86050b24a45385d03aab54ac95d96494086f0a00 | def _parse_title(self, item):
'Parse or generate meeting title.'
return '' | Parse or generate meeting title. | city_scrapers/spiders/pa_liquorboard.py | _parse_title | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_title(self, item):
return | def _parse_title(self, item):
return <|docstring|>Parse or generate meeting title.<|endoftext|> |
5a4ec446ae824d71279729cc9e880c73c151ee06014b6431921e20316a3b43be | def _parse_description(self, item):
'Parse or generate meeting description.'
return '' | Parse or generate meeting description. | city_scrapers/spiders/pa_liquorboard.py | _parse_description | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_description(self, item):
return | def _parse_description(self, item):
return <|docstring|>Parse or generate meeting description.<|endoftext|> |
7c70f016effcf525615fb009fc642291447b04d10a32b54d382736631d280a9f | def _parse_classification(self, item):
'Parse or generate classification from allowed options.'
return BOARD | Parse or generate classification from allowed options. | city_scrapers/spiders/pa_liquorboard.py | _parse_classification | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_classification(self, item):
return BOARD | def _parse_classification(self, item):
return BOARD<|docstring|>Parse or generate classification from allowed options.<|endoftext|> |
1fbbd91281e582bbd885699610423d15321e830781f785f9d7558a27663f4eec | def _parse_start(self, item):
'Parse start datetime as a naive datetime object.'
date_object = datetime.date(datetime.strptime(' '.join(item.split()[(- 3):]), '%B %d, %Y'))
return date_object | Parse start datetime as a naive datetime object. | city_scrapers/spiders/pa_liquorboard.py | _parse_start | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_start(self, item):
date_object = datetime.date(datetime.strptime(' '.join(item.split()[(- 3):]), '%B %d, %Y'))
return date_object | def _parse_start(self, item):
date_object = datetime.date(datetime.strptime(' '.join(item.split()[(- 3):]), '%B %d, %Y'))
return date_object<|docstring|>Parse start datetime as a naive datetime object.<|endoftext|> |
e82f36107f95a73af141d22b25e9bd36af423d2efe5ceb59933d6b4836659cc9 | def _parse_end(self, item):
'Parse end datetime as a naive datetime object. Added by pipeline if None'
return None | Parse end datetime as a naive datetime object. Added by pipeline if None | city_scrapers/spiders/pa_liquorboard.py | _parse_end | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_end(self, item):
return None | def _parse_end(self, item):
return None<|docstring|>Parse end datetime as a naive datetime object. Added by pipeline if None<|endoftext|> |
ffc031b7ed935e34d5b4c64aeffcceba2c29c1826ad1114a4d6c8dadf5298d39 | def _parse_time_notes(self, item):
'Parse any additional notes on the timing of the meeting'
return '' | Parse any additional notes on the timing of the meeting | city_scrapers/spiders/pa_liquorboard.py | _parse_time_notes | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_time_notes(self, item):
return | def _parse_time_notes(self, item):
return <|docstring|>Parse any additional notes on the timing of the meeting<|endoftext|> |
c27f5e8affb266214cd84946f92a2fa5e12a464c16a4400ba819d8130342e0a3 | def _parse_all_day(self, item):
'Parse or generate all-day status. Defaults to False.'
return False | Parse or generate all-day status. Defaults to False. | city_scrapers/spiders/pa_liquorboard.py | _parse_all_day | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_all_day(self, item):
return False | def _parse_all_day(self, item):
return False<|docstring|>Parse or generate all-day status. Defaults to False.<|endoftext|> |
bf052e1bddb9084a63bd96ab9677d59621bf6e97322a4179d6322b88651b6dbc | def _parse_location(self, item):
'Parse or generate location.'
return {'address': 'Room 117, 604 Northwest Office Building, Harrisburg, PA 17124', 'name': 'Pennsylvania Liquor Control Board Headquarters'} | Parse or generate location. | city_scrapers/spiders/pa_liquorboard.py | _parse_location | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_location(self, item):
return {'address': 'Room 117, 604 Northwest Office Building, Harrisburg, PA 17124', 'name': 'Pennsylvania Liquor Control Board Headquarters'} | def _parse_location(self, item):
return {'address': 'Room 117, 604 Northwest Office Building, Harrisburg, PA 17124', 'name': 'Pennsylvania Liquor Control Board Headquarters'}<|docstring|>Parse or generate location.<|endoftext|> |
ba51b7e1353733aebea3eab3ec2f0a96578c66500bf3d33e07f800131643201a | def _parse_links(self, item):
'Parse or generate links.'
return [{'href': '', 'title': ''}] | Parse or generate links. | city_scrapers/spiders/pa_liquorboard.py | _parse_links | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_links(self, item):
return [{'href': , 'title': }] | def _parse_links(self, item):
return [{'href': , 'title': }]<|docstring|>Parse or generate links.<|endoftext|> |
845990b6d6eda732f11ca8016d857e2e6fc5986c492231b62b4decbb3a8125df | def _parse_source(self, response):
'Parse or generate source.'
return response.url | Parse or generate source. | city_scrapers/spiders/pa_liquorboard.py | _parse_source | tochukwuokafor/city-scrapers-tochukwu | 0 | python | def _parse_source(self, response):
return response.url | def _parse_source(self, response):
return response.url<|docstring|>Parse or generate source.<|endoftext|> |
3ffe939e0010c7efa7ca27296dca110d73a6b1459ccdf0cb2f5c1b7e95328be3 | def main():
'Entrypoint for magproc-prepfiles command defined in setup.py.\n\n Runs prepfiles() with typer for argument parsing and usage.\n '
typer.run(prepfiles) | Entrypoint for magproc-prepfiles command defined in setup.py.
Runs prepfiles() with typer for argument parsing and usage. | geomagio/processing/magproc.py | main | usgs/geomag-algorithms | 49 | python | def main():
'Entrypoint for magproc-prepfiles command defined in setup.py.\n\n Runs prepfiles() with typer for argument parsing and usage.\n '
typer.run(prepfiles) | def main():
'Entrypoint for magproc-prepfiles command defined in setup.py.\n\n Runs prepfiles() with typer for argument parsing and usage.\n '
typer.run(prepfiles)<|docstring|>Entrypoint for magproc-prepfiles command defined in setup.py.
Runs prepfiles() with typer for argument parsing and usage.<|endoftext|> |
250771cf683031a1d89d423aed7289976ac9b07df3279c3b84d45f8aee38b518 | def denoise(im, U_init, tolerance=0.1, tau=0.125, tv_weight=100):
'\n ROFノイズ除去モデルの実装\n\n Args:\n im: ノイズのあるグレースケール画像\n U_init: Uの初期ガウス分布\n tolerance: 終了判定基準の許容誤差\n tau: ステップ長\n tv_weight: TV正規化項の重み\n\n Returns:\n U: ノイズ除去された画像\n im-U: 残余テクスチャ\n '
(m, n) = im.shape
U = U_init
Px = im
Py = im
'\n 双対領域\n \u3000例えば色の塗分けにおいて隣り合う色が別の色になるときの、そのお互いの領域のこと\n '
error = 1
while (error > tolerance):
U_old = U
GrandUx = (np.roll(U, (- 1), axis=1) - U)
GrandUy = (np.roll(U, (- 1), axis=0) - U)
'\n 双対問題:\n \u3000主問題の対となる問題のこと\n\n 双対変数:\n \u3000双対問題、特にラグランジュ双対問題の変数のこと\n '
Px_new = (Px + ((tau / tv_weight) * GrandUx))
Py_new = (Py + ((tau / tv_weight) * GrandUy))
Norm_new = np.maximum(1, np.sqrt(((Px_new ** 2) + (Py_new ** 2))))
Px = (Px_new / Norm_new)
Py = (Py_new / Norm_new)
RxPx = np.roll(Px, 1, axis=1)
RyPy = np.roll(Py, 1, axis=0)
DivP = ((Px - RxPx) + (Py - RyPy))
U = (im + (tv_weight * DivP))
error = (np.linalg.norm((U - U_old)) / np.sqrt((n * m)))
return (U, (im - U)) | ROFノイズ除去モデルの実装
Args:
im: ノイズのあるグレースケール画像
U_init: Uの初期ガウス分布
tolerance: 終了判定基準の許容誤差
tau: ステップ長
tv_weight: TV正規化項の重み
Returns:
U: ノイズ除去された画像
im-U: 残余テクスチャ | rof.py | denoise | KindledKindred/python | 0 | python | def denoise(im, U_init, tolerance=0.1, tau=0.125, tv_weight=100):
'\n ROFノイズ除去モデルの実装\n\n Args:\n im: ノイズのあるグレースケール画像\n U_init: Uの初期ガウス分布\n tolerance: 終了判定基準の許容誤差\n tau: ステップ長\n tv_weight: TV正規化項の重み\n\n Returns:\n U: ノイズ除去された画像\n im-U: 残余テクスチャ\n '
(m, n) = im.shape
U = U_init
Px = im
Py = im
'\n 双対領域\n \u3000例えば色の塗分けにおいて隣り合う色が別の色になるときの、そのお互いの領域のこと\n '
error = 1
while (error > tolerance):
U_old = U
GrandUx = (np.roll(U, (- 1), axis=1) - U)
GrandUy = (np.roll(U, (- 1), axis=0) - U)
'\n 双対問題:\n \u3000主問題の対となる問題のこと\n\n 双対変数:\n \u3000双対問題、特にラグランジュ双対問題の変数のこと\n '
Px_new = (Px + ((tau / tv_weight) * GrandUx))
Py_new = (Py + ((tau / tv_weight) * GrandUy))
Norm_new = np.maximum(1, np.sqrt(((Px_new ** 2) + (Py_new ** 2))))
Px = (Px_new / Norm_new)
Py = (Py_new / Norm_new)
RxPx = np.roll(Px, 1, axis=1)
RyPy = np.roll(Py, 1, axis=0)
DivP = ((Px - RxPx) + (Py - RyPy))
U = (im + (tv_weight * DivP))
error = (np.linalg.norm((U - U_old)) / np.sqrt((n * m)))
return (U, (im - U)) | def denoise(im, U_init, tolerance=0.1, tau=0.125, tv_weight=100):
'\n ROFノイズ除去モデルの実装\n\n Args:\n im: ノイズのあるグレースケール画像\n U_init: Uの初期ガウス分布\n tolerance: 終了判定基準の許容誤差\n tau: ステップ長\n tv_weight: TV正規化項の重み\n\n Returns:\n U: ノイズ除去された画像\n im-U: 残余テクスチャ\n '
(m, n) = im.shape
U = U_init
Px = im
Py = im
'\n 双対領域\n \u3000例えば色の塗分けにおいて隣り合う色が別の色になるときの、そのお互いの領域のこと\n '
error = 1
while (error > tolerance):
U_old = U
GrandUx = (np.roll(U, (- 1), axis=1) - U)
GrandUy = (np.roll(U, (- 1), axis=0) - U)
'\n 双対問題:\n \u3000主問題の対となる問題のこと\n\n 双対変数:\n \u3000双対問題、特にラグランジュ双対問題の変数のこと\n '
Px_new = (Px + ((tau / tv_weight) * GrandUx))
Py_new = (Py + ((tau / tv_weight) * GrandUy))
Norm_new = np.maximum(1, np.sqrt(((Px_new ** 2) + (Py_new ** 2))))
Px = (Px_new / Norm_new)
Py = (Py_new / Norm_new)
RxPx = np.roll(Px, 1, axis=1)
RyPy = np.roll(Py, 1, axis=0)
DivP = ((Px - RxPx) + (Py - RyPy))
U = (im + (tv_weight * DivP))
error = (np.linalg.norm((U - U_old)) / np.sqrt((n * m)))
return (U, (im - U))<|docstring|>ROFノイズ除去モデルの実装
Args:
im: ノイズのあるグレースケール画像
U_init: Uの初期ガウス分布
tolerance: 終了判定基準の許容誤差
tau: ステップ長
tv_weight: TV正規化項の重み
Returns:
U: ノイズ除去された画像
im-U: 残余テクスチャ<|endoftext|> |
2bc533cf18dd6c30d6c425fd114d1485ea559d3fbb423bf201551282d2384d78 | def test_init_wrong_spotify_credentials():
'\n Tests if exception is raised if no spotify credentials are given.\n '
with pytest.raises(TypeError):
Spotdl()
with pytest.raises(SpotifyOauthError):
Spotdl(None, None) | Tests if exception is raised if no spotify credentials are given. | tests/test_init.py | test_init_wrong_spotify_credentials | spotDL/spotdl-v4 | 10 | python | def test_init_wrong_spotify_credentials():
'\n \n '
with pytest.raises(TypeError):
Spotdl()
with pytest.raises(SpotifyOauthError):
Spotdl(None, None) | def test_init_wrong_spotify_credentials():
'\n \n '
with pytest.raises(TypeError):
Spotdl()
with pytest.raises(SpotifyOauthError):
Spotdl(None, None)<|docstring|>Tests if exception is raised if no spotify credentials are given.<|endoftext|> |
4163607a4b9846093d46079ad0a70d205378b24fb330df543b1bac3ca17a21d2 | @pytest.mark.vcr()
def test_get_urls():
'\n Tests if spotdl can be initialized correctly.\n '
spotdl = Spotdl(client_id=DEFAULT_CONFIG['client_id'], client_secret=DEFAULT_CONFIG['client_secret'], user_auth=DEFAULT_CONFIG['user_auth'], cache_path=DEFAULT_CONFIG['cache_path'], no_cache=True, headless=DEFAULT_CONFIG['headless'], audio_providers=DEFAULT_CONFIG['audio_providers'], lyrics_providers=DEFAULT_CONFIG['lyrics_providers'], ffmpeg=DEFAULT_CONFIG['ffmpeg'], bitrate=DEFAULT_CONFIG['bitrate'], ffmpeg_args=DEFAULT_CONFIG['ffmpeg_args'], output_format=DEFAULT_CONFIG['format'], threads=DEFAULT_CONFIG['threads'], output=DEFAULT_CONFIG['output'], save_file=DEFAULT_CONFIG['save_file'], overwrite=DEFAULT_CONFIG['overwrite'], cookie_file=DEFAULT_CONFIG['cookie_file'], filter_results=DEFAULT_CONFIG['filter_results'], search_query=DEFAULT_CONFIG['search_query'], log_level='DEBUG', simple_tui=True, restrict=DEFAULT_CONFIG['restrict'], print_errors=DEFAULT_CONFIG['print_errors'])
urls = spotdl.get_download_urls([Song.from_url('https://open.spotify.com/track/0kx3ml8bdAYrQtcIwvkhp8')])
assert (len(urls) == 1) | Tests if spotdl can be initialized correctly. | tests/test_init.py | test_get_urls | spotDL/spotdl-v4 | 10 | python | @pytest.mark.vcr()
def test_get_urls():
'\n \n '
spotdl = Spotdl(client_id=DEFAULT_CONFIG['client_id'], client_secret=DEFAULT_CONFIG['client_secret'], user_auth=DEFAULT_CONFIG['user_auth'], cache_path=DEFAULT_CONFIG['cache_path'], no_cache=True, headless=DEFAULT_CONFIG['headless'], audio_providers=DEFAULT_CONFIG['audio_providers'], lyrics_providers=DEFAULT_CONFIG['lyrics_providers'], ffmpeg=DEFAULT_CONFIG['ffmpeg'], bitrate=DEFAULT_CONFIG['bitrate'], ffmpeg_args=DEFAULT_CONFIG['ffmpeg_args'], output_format=DEFAULT_CONFIG['format'], threads=DEFAULT_CONFIG['threads'], output=DEFAULT_CONFIG['output'], save_file=DEFAULT_CONFIG['save_file'], overwrite=DEFAULT_CONFIG['overwrite'], cookie_file=DEFAULT_CONFIG['cookie_file'], filter_results=DEFAULT_CONFIG['filter_results'], search_query=DEFAULT_CONFIG['search_query'], log_level='DEBUG', simple_tui=True, restrict=DEFAULT_CONFIG['restrict'], print_errors=DEFAULT_CONFIG['print_errors'])
urls = spotdl.get_download_urls([Song.from_url('https://open.spotify.com/track/0kx3ml8bdAYrQtcIwvkhp8')])
assert (len(urls) == 1) | @pytest.mark.vcr()
def test_get_urls():
'\n \n '
spotdl = Spotdl(client_id=DEFAULT_CONFIG['client_id'], client_secret=DEFAULT_CONFIG['client_secret'], user_auth=DEFAULT_CONFIG['user_auth'], cache_path=DEFAULT_CONFIG['cache_path'], no_cache=True, headless=DEFAULT_CONFIG['headless'], audio_providers=DEFAULT_CONFIG['audio_providers'], lyrics_providers=DEFAULT_CONFIG['lyrics_providers'], ffmpeg=DEFAULT_CONFIG['ffmpeg'], bitrate=DEFAULT_CONFIG['bitrate'], ffmpeg_args=DEFAULT_CONFIG['ffmpeg_args'], output_format=DEFAULT_CONFIG['format'], threads=DEFAULT_CONFIG['threads'], output=DEFAULT_CONFIG['output'], save_file=DEFAULT_CONFIG['save_file'], overwrite=DEFAULT_CONFIG['overwrite'], cookie_file=DEFAULT_CONFIG['cookie_file'], filter_results=DEFAULT_CONFIG['filter_results'], search_query=DEFAULT_CONFIG['search_query'], log_level='DEBUG', simple_tui=True, restrict=DEFAULT_CONFIG['restrict'], print_errors=DEFAULT_CONFIG['print_errors'])
urls = spotdl.get_download_urls([Song.from_url('https://open.spotify.com/track/0kx3ml8bdAYrQtcIwvkhp8')])
assert (len(urls) == 1)<|docstring|>Tests if spotdl can be initialized correctly.<|endoftext|> |
4427910abd80ef3ccfb7205ba2a7b235379e653b5bb82e3f46b6badf52414f1f | @pytest.mark.vcr()
def test_download(setup, monkeypatch):
'\n Tests if spotdl can be initialized correctly.\n '
monkeypatch.setattr(SpotifyClient, 'init', new_initialize)
spotdl = Spotdl(client_id=DEFAULT_CONFIG['client_id'], client_secret=DEFAULT_CONFIG['client_secret'], user_auth=DEFAULT_CONFIG['user_auth'], cache_path=DEFAULT_CONFIG['cache_path'], no_cache=True, headless=DEFAULT_CONFIG['headless'], audio_providers=DEFAULT_CONFIG['audio_providers'], lyrics_providers=DEFAULT_CONFIG['lyrics_providers'], ffmpeg=DEFAULT_CONFIG['ffmpeg'], bitrate=DEFAULT_CONFIG['bitrate'], ffmpeg_args=DEFAULT_CONFIG['ffmpeg_args'], output_format=DEFAULT_CONFIG['format'], threads=DEFAULT_CONFIG['threads'], output=str(setup.directory.absolute()), save_file=DEFAULT_CONFIG['save_file'], overwrite=DEFAULT_CONFIG['overwrite'], cookie_file=DEFAULT_CONFIG['cookie_file'], filter_results=DEFAULT_CONFIG['filter_results'], search_query=DEFAULT_CONFIG['search_query'], log_level='DEBUG', simple_tui=True, restrict=DEFAULT_CONFIG['restrict'], print_errors=DEFAULT_CONFIG['print_errors'])
song = {'name': 'Nobody Else', 'artists': ['Abstrakt'], 'artist': 'Abstrakt', 'album_name': 'Nobody Else', 'album_artist': 'Abstrakt', 'genres': [], 'disc_number': 1, 'disc_count': 1, 'duration': 162.406, 'year': 2022, 'date': '2022-03-17', 'track_number': 1, 'tracks_count': 1, 'isrc': 'GB2LD2210007', 'song_id': '0kx3ml8bdAYrQtcIwvkhp8', 'cover_url': 'https://i.scdn.co/image/ab67616d0000b27345f5ba253b9825efc88bc236', 'explicit': False, 'publisher': 'NCS', 'url': 'https://open.spotify.com/track/0kx3ml8bdAYrQtcIwvkhp8', 'copyright_text': '2022 NCS', 'download_url': 'https://www.youtube.com/watch?v=nfyk-V5CoIE', 'song_list': None}
assert (None not in spotdl.download(Song.from_dict(song))) | Tests if spotdl can be initialized correctly. | tests/test_init.py | test_download | spotDL/spotdl-v4 | 10 | python | @pytest.mark.vcr()
def test_download(setup, monkeypatch):
'\n \n '
monkeypatch.setattr(SpotifyClient, 'init', new_initialize)
spotdl = Spotdl(client_id=DEFAULT_CONFIG['client_id'], client_secret=DEFAULT_CONFIG['client_secret'], user_auth=DEFAULT_CONFIG['user_auth'], cache_path=DEFAULT_CONFIG['cache_path'], no_cache=True, headless=DEFAULT_CONFIG['headless'], audio_providers=DEFAULT_CONFIG['audio_providers'], lyrics_providers=DEFAULT_CONFIG['lyrics_providers'], ffmpeg=DEFAULT_CONFIG['ffmpeg'], bitrate=DEFAULT_CONFIG['bitrate'], ffmpeg_args=DEFAULT_CONFIG['ffmpeg_args'], output_format=DEFAULT_CONFIG['format'], threads=DEFAULT_CONFIG['threads'], output=str(setup.directory.absolute()), save_file=DEFAULT_CONFIG['save_file'], overwrite=DEFAULT_CONFIG['overwrite'], cookie_file=DEFAULT_CONFIG['cookie_file'], filter_results=DEFAULT_CONFIG['filter_results'], search_query=DEFAULT_CONFIG['search_query'], log_level='DEBUG', simple_tui=True, restrict=DEFAULT_CONFIG['restrict'], print_errors=DEFAULT_CONFIG['print_errors'])
song = {'name': 'Nobody Else', 'artists': ['Abstrakt'], 'artist': 'Abstrakt', 'album_name': 'Nobody Else', 'album_artist': 'Abstrakt', 'genres': [], 'disc_number': 1, 'disc_count': 1, 'duration': 162.406, 'year': 2022, 'date': '2022-03-17', 'track_number': 1, 'tracks_count': 1, 'isrc': 'GB2LD2210007', 'song_id': '0kx3ml8bdAYrQtcIwvkhp8', 'cover_url': 'https://i.scdn.co/image/ab67616d0000b27345f5ba253b9825efc88bc236', 'explicit': False, 'publisher': 'NCS', 'url': 'https://open.spotify.com/track/0kx3ml8bdAYrQtcIwvkhp8', 'copyright_text': '2022 NCS', 'download_url': 'https://www.youtube.com/watch?v=nfyk-V5CoIE', 'song_list': None}
assert (None not in spotdl.download(Song.from_dict(song))) | @pytest.mark.vcr()
def test_download(setup, monkeypatch):
'\n \n '
monkeypatch.setattr(SpotifyClient, 'init', new_initialize)
spotdl = Spotdl(client_id=DEFAULT_CONFIG['client_id'], client_secret=DEFAULT_CONFIG['client_secret'], user_auth=DEFAULT_CONFIG['user_auth'], cache_path=DEFAULT_CONFIG['cache_path'], no_cache=True, headless=DEFAULT_CONFIG['headless'], audio_providers=DEFAULT_CONFIG['audio_providers'], lyrics_providers=DEFAULT_CONFIG['lyrics_providers'], ffmpeg=DEFAULT_CONFIG['ffmpeg'], bitrate=DEFAULT_CONFIG['bitrate'], ffmpeg_args=DEFAULT_CONFIG['ffmpeg_args'], output_format=DEFAULT_CONFIG['format'], threads=DEFAULT_CONFIG['threads'], output=str(setup.directory.absolute()), save_file=DEFAULT_CONFIG['save_file'], overwrite=DEFAULT_CONFIG['overwrite'], cookie_file=DEFAULT_CONFIG['cookie_file'], filter_results=DEFAULT_CONFIG['filter_results'], search_query=DEFAULT_CONFIG['search_query'], log_level='DEBUG', simple_tui=True, restrict=DEFAULT_CONFIG['restrict'], print_errors=DEFAULT_CONFIG['print_errors'])
song = {'name': 'Nobody Else', 'artists': ['Abstrakt'], 'artist': 'Abstrakt', 'album_name': 'Nobody Else', 'album_artist': 'Abstrakt', 'genres': [], 'disc_number': 1, 'disc_count': 1, 'duration': 162.406, 'year': 2022, 'date': '2022-03-17', 'track_number': 1, 'tracks_count': 1, 'isrc': 'GB2LD2210007', 'song_id': '0kx3ml8bdAYrQtcIwvkhp8', 'cover_url': 'https://i.scdn.co/image/ab67616d0000b27345f5ba253b9825efc88bc236', 'explicit': False, 'publisher': 'NCS', 'url': 'https://open.spotify.com/track/0kx3ml8bdAYrQtcIwvkhp8', 'copyright_text': '2022 NCS', 'download_url': 'https://www.youtube.com/watch?v=nfyk-V5CoIE', 'song_list': None}
assert (None not in spotdl.download(Song.from_dict(song)))<|docstring|>Tests if spotdl can be initialized correctly.<|endoftext|> |
8bdf49b857f938963eba7115fded72499087242ee8958335d73314c181d233f8 | def __init__(self, idempotency_key=None, amount_money=None, card_nonce=None, customer_card_id=None, delay_capture=None, reference_id=None, note=None, customer_id=None, billing_address=None, shipping_address=None, buyer_email_address=None, order_id=None, additional_recipients=None, verification_token=None):
'\n ChargeRequest - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n '
self.swagger_types = {'idempotency_key': 'str', 'amount_money': 'Money', 'card_nonce': 'str', 'customer_card_id': 'str', 'delay_capture': 'bool', 'reference_id': 'str', 'note': 'str', 'customer_id': 'str', 'billing_address': 'Address', 'shipping_address': 'Address', 'buyer_email_address': 'str', 'order_id': 'str', 'additional_recipients': 'list[AdditionalRecipient]', 'verification_token': 'str'}
self.attribute_map = {'idempotency_key': 'idempotency_key', 'amount_money': 'amount_money', 'card_nonce': 'card_nonce', 'customer_card_id': 'customer_card_id', 'delay_capture': 'delay_capture', 'reference_id': 'reference_id', 'note': 'note', 'customer_id': 'customer_id', 'billing_address': 'billing_address', 'shipping_address': 'shipping_address', 'buyer_email_address': 'buyer_email_address', 'order_id': 'order_id', 'additional_recipients': 'additional_recipients', 'verification_token': 'verification_token'}
self._idempotency_key = idempotency_key
self._amount_money = amount_money
self._card_nonce = card_nonce
self._customer_card_id = customer_card_id
self._delay_capture = delay_capture
self._reference_id = reference_id
self._note = note
self._customer_id = customer_id
self._billing_address = billing_address
self._shipping_address = shipping_address
self._buyer_email_address = buyer_email_address
self._order_id = order_id
self._additional_recipients = additional_recipients
self._verification_token = verification_token | ChargeRequest - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | squareconnect/models/charge_request.py | __init__ | sanketsaurav/connect-python-sdk | 53 | python | def __init__(self, idempotency_key=None, amount_money=None, card_nonce=None, customer_card_id=None, delay_capture=None, reference_id=None, note=None, customer_id=None, billing_address=None, shipping_address=None, buyer_email_address=None, order_id=None, additional_recipients=None, verification_token=None):
'\n ChargeRequest - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n '
self.swagger_types = {'idempotency_key': 'str', 'amount_money': 'Money', 'card_nonce': 'str', 'customer_card_id': 'str', 'delay_capture': 'bool', 'reference_id': 'str', 'note': 'str', 'customer_id': 'str', 'billing_address': 'Address', 'shipping_address': 'Address', 'buyer_email_address': 'str', 'order_id': 'str', 'additional_recipients': 'list[AdditionalRecipient]', 'verification_token': 'str'}
self.attribute_map = {'idempotency_key': 'idempotency_key', 'amount_money': 'amount_money', 'card_nonce': 'card_nonce', 'customer_card_id': 'customer_card_id', 'delay_capture': 'delay_capture', 'reference_id': 'reference_id', 'note': 'note', 'customer_id': 'customer_id', 'billing_address': 'billing_address', 'shipping_address': 'shipping_address', 'buyer_email_address': 'buyer_email_address', 'order_id': 'order_id', 'additional_recipients': 'additional_recipients', 'verification_token': 'verification_token'}
self._idempotency_key = idempotency_key
self._amount_money = amount_money
self._card_nonce = card_nonce
self._customer_card_id = customer_card_id
self._delay_capture = delay_capture
self._reference_id = reference_id
self._note = note
self._customer_id = customer_id
self._billing_address = billing_address
self._shipping_address = shipping_address
self._buyer_email_address = buyer_email_address
self._order_id = order_id
self._additional_recipients = additional_recipients
self._verification_token = verification_token | def __init__(self, idempotency_key=None, amount_money=None, card_nonce=None, customer_card_id=None, delay_capture=None, reference_id=None, note=None, customer_id=None, billing_address=None, shipping_address=None, buyer_email_address=None, order_id=None, additional_recipients=None, verification_token=None):
'\n ChargeRequest - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n '
self.swagger_types = {'idempotency_key': 'str', 'amount_money': 'Money', 'card_nonce': 'str', 'customer_card_id': 'str', 'delay_capture': 'bool', 'reference_id': 'str', 'note': 'str', 'customer_id': 'str', 'billing_address': 'Address', 'shipping_address': 'Address', 'buyer_email_address': 'str', 'order_id': 'str', 'additional_recipients': 'list[AdditionalRecipient]', 'verification_token': 'str'}
self.attribute_map = {'idempotency_key': 'idempotency_key', 'amount_money': 'amount_money', 'card_nonce': 'card_nonce', 'customer_card_id': 'customer_card_id', 'delay_capture': 'delay_capture', 'reference_id': 'reference_id', 'note': 'note', 'customer_id': 'customer_id', 'billing_address': 'billing_address', 'shipping_address': 'shipping_address', 'buyer_email_address': 'buyer_email_address', 'order_id': 'order_id', 'additional_recipients': 'additional_recipients', 'verification_token': 'verification_token'}
self._idempotency_key = idempotency_key
self._amount_money = amount_money
self._card_nonce = card_nonce
self._customer_card_id = customer_card_id
self._delay_capture = delay_capture
self._reference_id = reference_id
self._note = note
self._customer_id = customer_id
self._billing_address = billing_address
self._shipping_address = shipping_address
self._buyer_email_address = buyer_email_address
self._order_id = order_id
self._additional_recipients = additional_recipients
self._verification_token = verification_token<|docstring|>ChargeRequest - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.<|endoftext|> |
ae2af8c10c8bb69ec8c5361b75659926668192043201743543527de54e133fc2 | @property
def idempotency_key(self):
"\n Gets the idempotency_key of this ChargeRequest.\n A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.\n\n :return: The idempotency_key of this ChargeRequest.\n :rtype: str\n "
return self._idempotency_key | Gets the idempotency_key of this ChargeRequest.
A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.
:return: The idempotency_key of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | idempotency_key | sanketsaurav/connect-python-sdk | 53 | python | @property
def idempotency_key(self):
"\n Gets the idempotency_key of this ChargeRequest.\n A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.\n\n :return: The idempotency_key of this ChargeRequest.\n :rtype: str\n "
return self._idempotency_key | @property
def idempotency_key(self):
"\n Gets the idempotency_key of this ChargeRequest.\n A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.\n\n :return: The idempotency_key of this ChargeRequest.\n :rtype: str\n "
return self._idempotency_key<|docstring|>Gets the idempotency_key of this ChargeRequest.
A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.
:return: The idempotency_key of this ChargeRequest.
:rtype: str<|endoftext|> |
3c875d2f7479b1308eed88f610767d59394dfa91f604ff93b580fb8d415253c9 | @idempotency_key.setter
def idempotency_key(self, idempotency_key):
"\n Sets the idempotency_key of this ChargeRequest.\n A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.\n\n :param idempotency_key: The idempotency_key of this ChargeRequest.\n :type: str\n "
if (idempotency_key is None):
raise ValueError('Invalid value for `idempotency_key`, must not be `None`')
if (len(idempotency_key) > 192):
raise ValueError('Invalid value for `idempotency_key`, length must be less than `192`')
if (len(idempotency_key) < 1):
raise ValueError('Invalid value for `idempotency_key`, length must be greater than or equal to `1`')
self._idempotency_key = idempotency_key | Sets the idempotency_key of this ChargeRequest.
A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.
:param idempotency_key: The idempotency_key of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | idempotency_key | sanketsaurav/connect-python-sdk | 53 | python | @idempotency_key.setter
def idempotency_key(self, idempotency_key):
"\n Sets the idempotency_key of this ChargeRequest.\n A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.\n\n :param idempotency_key: The idempotency_key of this ChargeRequest.\n :type: str\n "
if (idempotency_key is None):
raise ValueError('Invalid value for `idempotency_key`, must not be `None`')
if (len(idempotency_key) > 192):
raise ValueError('Invalid value for `idempotency_key`, length must be less than `192`')
if (len(idempotency_key) < 1):
raise ValueError('Invalid value for `idempotency_key`, length must be greater than or equal to `1`')
self._idempotency_key = idempotency_key | @idempotency_key.setter
def idempotency_key(self, idempotency_key):
"\n Sets the idempotency_key of this ChargeRequest.\n A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.\n\n :param idempotency_key: The idempotency_key of this ChargeRequest.\n :type: str\n "
if (idempotency_key is None):
raise ValueError('Invalid value for `idempotency_key`, must not be `None`')
if (len(idempotency_key) > 192):
raise ValueError('Invalid value for `idempotency_key`, length must be less than `192`')
if (len(idempotency_key) < 1):
raise ValueError('Invalid value for `idempotency_key`, length must be greater than or equal to `1`')
self._idempotency_key = idempotency_key<|docstring|>Sets the idempotency_key of this ChargeRequest.
A value you specify that uniquely identifies this transaction among transactions you've created. If you're unsure whether a particular transaction succeeded, you can reattempt it with the same idempotency key without worrying about double-charging the buyer. See [Idempotency](/basics/api101/idempotency) for more information.
:param idempotency_key: The idempotency_key of this ChargeRequest.
:type: str<|endoftext|> |
137a20c1fe1e2b7ba2ed98296868b435088d77986dcf2ce8b2276a39ff13e431 | @property
def amount_money(self):
'\n Gets the amount_money of this ChargeRequest.\n The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.\n\n :return: The amount_money of this ChargeRequest.\n :rtype: Money\n '
return self._amount_money | Gets the amount_money of this ChargeRequest.
The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.
:return: The amount_money of this ChargeRequest.
:rtype: Money | squareconnect/models/charge_request.py | amount_money | sanketsaurav/connect-python-sdk | 53 | python | @property
def amount_money(self):
'\n Gets the amount_money of this ChargeRequest.\n The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.\n\n :return: The amount_money of this ChargeRequest.\n :rtype: Money\n '
return self._amount_money | @property
def amount_money(self):
'\n Gets the amount_money of this ChargeRequest.\n The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.\n\n :return: The amount_money of this ChargeRequest.\n :rtype: Money\n '
return self._amount_money<|docstring|>Gets the amount_money of this ChargeRequest.
The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.
:return: The amount_money of this ChargeRequest.
:rtype: Money<|endoftext|> |
35bcd95a6612aa9aac6e0a32b25a449948aeeb165371278ae456c8ba1a59e475 | @amount_money.setter
def amount_money(self, amount_money):
'\n Sets the amount_money of this ChargeRequest.\n The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.\n\n :param amount_money: The amount_money of this ChargeRequest.\n :type: Money\n '
self._amount_money = amount_money | Sets the amount_money of this ChargeRequest.
The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.
:param amount_money: The amount_money of this ChargeRequest.
:type: Money | squareconnect/models/charge_request.py | amount_money | sanketsaurav/connect-python-sdk | 53 | python | @amount_money.setter
def amount_money(self, amount_money):
'\n Sets the amount_money of this ChargeRequest.\n The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.\n\n :param amount_money: The amount_money of this ChargeRequest.\n :type: Money\n '
self._amount_money = amount_money | @amount_money.setter
def amount_money(self, amount_money):
'\n Sets the amount_money of this ChargeRequest.\n The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.\n\n :param amount_money: The amount_money of this ChargeRequest.\n :type: Money\n '
self._amount_money = amount_money<|docstring|>Sets the amount_money of this ChargeRequest.
The amount of money to charge. Note that you specify the amount in the __smallest denomination of the applicable currency__. For example, US dollar amounts are specified in cents. See [Working with monetary amounts](#workingwithmonetaryamounts) for details. The value of `currency` must match the currency associated with the business that is charging the card.
:param amount_money: The amount_money of this ChargeRequest.
:type: Money<|endoftext|> |
bfd3e373e027431b522cb6cb92f9d51404aff746e6e22b2b9d6b69f5a19cdc6c | @property
def card_nonce(self):
'\n Gets the card_nonce of this ChargeRequest.\n A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.\n\n :return: The card_nonce of this ChargeRequest.\n :rtype: str\n '
return self._card_nonce | Gets the card_nonce of this ChargeRequest.
A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.
:return: The card_nonce of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | card_nonce | sanketsaurav/connect-python-sdk | 53 | python | @property
def card_nonce(self):
'\n Gets the card_nonce of this ChargeRequest.\n A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.\n\n :return: The card_nonce of this ChargeRequest.\n :rtype: str\n '
return self._card_nonce | @property
def card_nonce(self):
'\n Gets the card_nonce of this ChargeRequest.\n A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.\n\n :return: The card_nonce of this ChargeRequest.\n :rtype: str\n '
return self._card_nonce<|docstring|>Gets the card_nonce of this ChargeRequest.
A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.
:return: The card_nonce of this ChargeRequest.
:rtype: str<|endoftext|> |
d1b7164f011b87106a1158245186f0e7f09baf870caff3c7cfcc1bfec7ed8387 | @card_nonce.setter
def card_nonce(self, card_nonce):
'\n Sets the card_nonce of this ChargeRequest.\n A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.\n\n :param card_nonce: The card_nonce of this ChargeRequest.\n :type: str\n '
if (card_nonce is None):
raise ValueError('Invalid value for `card_nonce`, must not be `None`')
if (len(card_nonce) > 192):
raise ValueError('Invalid value for `card_nonce`, length must be less than `192`')
self._card_nonce = card_nonce | Sets the card_nonce of this ChargeRequest.
A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.
:param card_nonce: The card_nonce of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | card_nonce | sanketsaurav/connect-python-sdk | 53 | python | @card_nonce.setter
def card_nonce(self, card_nonce):
'\n Sets the card_nonce of this ChargeRequest.\n A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.\n\n :param card_nonce: The card_nonce of this ChargeRequest.\n :type: str\n '
if (card_nonce is None):
raise ValueError('Invalid value for `card_nonce`, must not be `None`')
if (len(card_nonce) > 192):
raise ValueError('Invalid value for `card_nonce`, length must be less than `192`')
self._card_nonce = card_nonce | @card_nonce.setter
def card_nonce(self, card_nonce):
'\n Sets the card_nonce of this ChargeRequest.\n A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.\n\n :param card_nonce: The card_nonce of this ChargeRequest.\n :type: str\n '
if (card_nonce is None):
raise ValueError('Invalid value for `card_nonce`, must not be `None`')
if (len(card_nonce) > 192):
raise ValueError('Invalid value for `card_nonce`, length must be less than `192`')
self._card_nonce = card_nonce<|docstring|>Sets the card_nonce of this ChargeRequest.
A nonce generated from the `SqPaymentForm` that represents the card to charge. The application that provides a nonce to this endpoint must be the _same application_ that generated the nonce with the `SqPaymentForm`. Otherwise, the nonce is invalid. Do not provide a value for this field if you provide a value for `customer_card_id`.
:param card_nonce: The card_nonce of this ChargeRequest.
:type: str<|endoftext|> |
319b87e6b685864faa5b8f2fff7a51cdc880ef9426e0348713c33ff43e44c6a0 | @property
def customer_card_id(self):
'\n Gets the customer_card_id of this ChargeRequest.\n The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.\n\n :return: The customer_card_id of this ChargeRequest.\n :rtype: str\n '
return self._customer_card_id | Gets the customer_card_id of this ChargeRequest.
The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.
:return: The customer_card_id of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | customer_card_id | sanketsaurav/connect-python-sdk | 53 | python | @property
def customer_card_id(self):
'\n Gets the customer_card_id of this ChargeRequest.\n The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.\n\n :return: The customer_card_id of this ChargeRequest.\n :rtype: str\n '
return self._customer_card_id | @property
def customer_card_id(self):
'\n Gets the customer_card_id of this ChargeRequest.\n The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.\n\n :return: The customer_card_id of this ChargeRequest.\n :rtype: str\n '
return self._customer_card_id<|docstring|>Gets the customer_card_id of this ChargeRequest.
The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.
:return: The customer_card_id of this ChargeRequest.
:rtype: str<|endoftext|> |
917e7574b7e1008d7ee6aa405c87903a321b78cb5cac21ce659149a59fa700f6 | @customer_card_id.setter
def customer_card_id(self, customer_card_id):
'\n Sets the customer_card_id of this ChargeRequest.\n The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.\n\n :param customer_card_id: The customer_card_id of this ChargeRequest.\n :type: str\n '
if (customer_card_id is None):
raise ValueError('Invalid value for `customer_card_id`, must not be `None`')
if (len(customer_card_id) > 192):
raise ValueError('Invalid value for `customer_card_id`, length must be less than `192`')
self._customer_card_id = customer_card_id | Sets the customer_card_id of this ChargeRequest.
The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.
:param customer_card_id: The customer_card_id of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | customer_card_id | sanketsaurav/connect-python-sdk | 53 | python | @customer_card_id.setter
def customer_card_id(self, customer_card_id):
'\n Sets the customer_card_id of this ChargeRequest.\n The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.\n\n :param customer_card_id: The customer_card_id of this ChargeRequest.\n :type: str\n '
if (customer_card_id is None):
raise ValueError('Invalid value for `customer_card_id`, must not be `None`')
if (len(customer_card_id) > 192):
raise ValueError('Invalid value for `customer_card_id`, length must be less than `192`')
self._customer_card_id = customer_card_id | @customer_card_id.setter
def customer_card_id(self, customer_card_id):
'\n Sets the customer_card_id of this ChargeRequest.\n The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.\n\n :param customer_card_id: The customer_card_id of this ChargeRequest.\n :type: str\n '
if (customer_card_id is None):
raise ValueError('Invalid value for `customer_card_id`, must not be `None`')
if (len(customer_card_id) > 192):
raise ValueError('Invalid value for `customer_card_id`, length must be less than `192`')
self._customer_card_id = customer_card_id<|docstring|>Sets the customer_card_id of this ChargeRequest.
The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `customer_id`.
:param customer_card_id: The customer_card_id of this ChargeRequest.
:type: str<|endoftext|> |
2278a21d3340ed142593df8bd188edcc96c067247b18781d519579415dbc0fbb | @property
def delay_capture(self):
'\n Gets the delay_capture of this ChargeRequest.\n If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`\n\n :return: The delay_capture of this ChargeRequest.\n :rtype: bool\n '
return self._delay_capture | Gets the delay_capture of this ChargeRequest.
If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`
:return: The delay_capture of this ChargeRequest.
:rtype: bool | squareconnect/models/charge_request.py | delay_capture | sanketsaurav/connect-python-sdk | 53 | python | @property
def delay_capture(self):
'\n Gets the delay_capture of this ChargeRequest.\n If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`\n\n :return: The delay_capture of this ChargeRequest.\n :rtype: bool\n '
return self._delay_capture | @property
def delay_capture(self):
'\n Gets the delay_capture of this ChargeRequest.\n If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`\n\n :return: The delay_capture of this ChargeRequest.\n :rtype: bool\n '
return self._delay_capture<|docstring|>Gets the delay_capture of this ChargeRequest.
If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`
:return: The delay_capture of this ChargeRequest.
:rtype: bool<|endoftext|> |
170bbe04b62e96e89a2d1c810f7874480c1170dba086df176604ef06466fa83f | @delay_capture.setter
def delay_capture(self, delay_capture):
'\n Sets the delay_capture of this ChargeRequest.\n If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`\n\n :param delay_capture: The delay_capture of this ChargeRequest.\n :type: bool\n '
self._delay_capture = delay_capture | Sets the delay_capture of this ChargeRequest.
If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`
:param delay_capture: The delay_capture of this ChargeRequest.
:type: bool | squareconnect/models/charge_request.py | delay_capture | sanketsaurav/connect-python-sdk | 53 | python | @delay_capture.setter
def delay_capture(self, delay_capture):
'\n Sets the delay_capture of this ChargeRequest.\n If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`\n\n :param delay_capture: The delay_capture of this ChargeRequest.\n :type: bool\n '
self._delay_capture = delay_capture | @delay_capture.setter
def delay_capture(self, delay_capture):
'\n Sets the delay_capture of this ChargeRequest.\n If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`\n\n :param delay_capture: The delay_capture of this ChargeRequest.\n :type: bool\n '
self._delay_capture = delay_capture<|docstring|>Sets the delay_capture of this ChargeRequest.
If `true`, the request will only perform an Auth on the provided card. You can then later perform either a Capture (with the [CaptureTransaction](#endpoint-capturetransaction) endpoint) or a Void (with the [VoidTransaction](#endpoint-voidtransaction) endpoint). Default value: `false`
:param delay_capture: The delay_capture of this ChargeRequest.
:type: bool<|endoftext|> |
e9113c3263a5115c5fabd3a53abab550405d6b1236aa858bbdc47524152c4db9 | @property
def reference_id(self):
'\n Gets the reference_id of this ChargeRequest.\n An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.\n\n :return: The reference_id of this ChargeRequest.\n :rtype: str\n '
return self._reference_id | Gets the reference_id of this ChargeRequest.
An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.
:return: The reference_id of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | reference_id | sanketsaurav/connect-python-sdk | 53 | python | @property
def reference_id(self):
'\n Gets the reference_id of this ChargeRequest.\n An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.\n\n :return: The reference_id of this ChargeRequest.\n :rtype: str\n '
return self._reference_id | @property
def reference_id(self):
'\n Gets the reference_id of this ChargeRequest.\n An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.\n\n :return: The reference_id of this ChargeRequest.\n :rtype: str\n '
return self._reference_id<|docstring|>Gets the reference_id of this ChargeRequest.
An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.
:return: The reference_id of this ChargeRequest.
:rtype: str<|endoftext|> |
a06b5b4184e4ff9c720615f3d572b3c36ab2866982c6000d3a900f20ee89154a | @reference_id.setter
def reference_id(self, reference_id):
'\n Sets the reference_id of this ChargeRequest.\n An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.\n\n :param reference_id: The reference_id of this ChargeRequest.\n :type: str\n '
if (reference_id is None):
raise ValueError('Invalid value for `reference_id`, must not be `None`')
if (len(reference_id) > 40):
raise ValueError('Invalid value for `reference_id`, length must be less than `40`')
self._reference_id = reference_id | Sets the reference_id of this ChargeRequest.
An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.
:param reference_id: The reference_id of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | reference_id | sanketsaurav/connect-python-sdk | 53 | python | @reference_id.setter
def reference_id(self, reference_id):
'\n Sets the reference_id of this ChargeRequest.\n An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.\n\n :param reference_id: The reference_id of this ChargeRequest.\n :type: str\n '
if (reference_id is None):
raise ValueError('Invalid value for `reference_id`, must not be `None`')
if (len(reference_id) > 40):
raise ValueError('Invalid value for `reference_id`, length must be less than `40`')
self._reference_id = reference_id | @reference_id.setter
def reference_id(self, reference_id):
'\n Sets the reference_id of this ChargeRequest.\n An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.\n\n :param reference_id: The reference_id of this ChargeRequest.\n :type: str\n '
if (reference_id is None):
raise ValueError('Invalid value for `reference_id`, must not be `None`')
if (len(reference_id) > 40):
raise ValueError('Invalid value for `reference_id`, length must be less than `40`')
self._reference_id = reference_id<|docstring|>Sets the reference_id of this ChargeRequest.
An optional ID you can associate with the transaction for your own purposes (such as to associate the transaction with an entity ID in your own database). This value cannot exceed 40 characters.
:param reference_id: The reference_id of this ChargeRequest.
:type: str<|endoftext|> |
82ea3e7a3348f4c7efcb279b3374fb0e93a36314baca3e78352b245bee6f2f28 | @property
def note(self):
'\n Gets the note of this ChargeRequest.\n An optional note to associate with the transaction. This value cannot exceed 60 characters.\n\n :return: The note of this ChargeRequest.\n :rtype: str\n '
return self._note | Gets the note of this ChargeRequest.
An optional note to associate with the transaction. This value cannot exceed 60 characters.
:return: The note of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | note | sanketsaurav/connect-python-sdk | 53 | python | @property
def note(self):
'\n Gets the note of this ChargeRequest.\n An optional note to associate with the transaction. This value cannot exceed 60 characters.\n\n :return: The note of this ChargeRequest.\n :rtype: str\n '
return self._note | @property
def note(self):
'\n Gets the note of this ChargeRequest.\n An optional note to associate with the transaction. This value cannot exceed 60 characters.\n\n :return: The note of this ChargeRequest.\n :rtype: str\n '
return self._note<|docstring|>Gets the note of this ChargeRequest.
An optional note to associate with the transaction. This value cannot exceed 60 characters.
:return: The note of this ChargeRequest.
:rtype: str<|endoftext|> |
65f8ced6f4f085466d2c58948b99f3e7b490de4be23f8cc5e453a00f6dfc129b | @note.setter
def note(self, note):
'\n Sets the note of this ChargeRequest.\n An optional note to associate with the transaction. This value cannot exceed 60 characters.\n\n :param note: The note of this ChargeRequest.\n :type: str\n '
if (note is None):
raise ValueError('Invalid value for `note`, must not be `None`')
if (len(note) > 60):
raise ValueError('Invalid value for `note`, length must be less than `60`')
self._note = note | Sets the note of this ChargeRequest.
An optional note to associate with the transaction. This value cannot exceed 60 characters.
:param note: The note of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | note | sanketsaurav/connect-python-sdk | 53 | python | @note.setter
def note(self, note):
'\n Sets the note of this ChargeRequest.\n An optional note to associate with the transaction. This value cannot exceed 60 characters.\n\n :param note: The note of this ChargeRequest.\n :type: str\n '
if (note is None):
raise ValueError('Invalid value for `note`, must not be `None`')
if (len(note) > 60):
raise ValueError('Invalid value for `note`, length must be less than `60`')
self._note = note | @note.setter
def note(self, note):
'\n Sets the note of this ChargeRequest.\n An optional note to associate with the transaction. This value cannot exceed 60 characters.\n\n :param note: The note of this ChargeRequest.\n :type: str\n '
if (note is None):
raise ValueError('Invalid value for `note`, must not be `None`')
if (len(note) > 60):
raise ValueError('Invalid value for `note`, length must be less than `60`')
self._note = note<|docstring|>Sets the note of this ChargeRequest.
An optional note to associate with the transaction. This value cannot exceed 60 characters.
:param note: The note of this ChargeRequest.
:type: str<|endoftext|> |
67df62e3ebbf125bdb639f1c1ab1bdf8127c50df3f555852b6b559da4fd03bb2 | @property
def customer_id(self):
'\n Gets the customer_id of this ChargeRequest.\n The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.\n\n :return: The customer_id of this ChargeRequest.\n :rtype: str\n '
return self._customer_id | Gets the customer_id of this ChargeRequest.
The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.
:return: The customer_id of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | customer_id | sanketsaurav/connect-python-sdk | 53 | python | @property
def customer_id(self):
'\n Gets the customer_id of this ChargeRequest.\n The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.\n\n :return: The customer_id of this ChargeRequest.\n :rtype: str\n '
return self._customer_id | @property
def customer_id(self):
'\n Gets the customer_id of this ChargeRequest.\n The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.\n\n :return: The customer_id of this ChargeRequest.\n :rtype: str\n '
return self._customer_id<|docstring|>Gets the customer_id of this ChargeRequest.
The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.
:return: The customer_id of this ChargeRequest.
:rtype: str<|endoftext|> |
2147e6e9e4d3159c37857bc214a5e9103a5e0109bb897627bff11e5de3d91882 | @customer_id.setter
def customer_id(self, customer_id):
'\n Sets the customer_id of this ChargeRequest.\n The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.\n\n :param customer_id: The customer_id of this ChargeRequest.\n :type: str\n '
if (customer_id is None):
raise ValueError('Invalid value for `customer_id`, must not be `None`')
if (len(customer_id) > 50):
raise ValueError('Invalid value for `customer_id`, length must be less than `50`')
self._customer_id = customer_id | Sets the customer_id of this ChargeRequest.
The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.
:param customer_id: The customer_id of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | customer_id | sanketsaurav/connect-python-sdk | 53 | python | @customer_id.setter
def customer_id(self, customer_id):
'\n Sets the customer_id of this ChargeRequest.\n The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.\n\n :param customer_id: The customer_id of this ChargeRequest.\n :type: str\n '
if (customer_id is None):
raise ValueError('Invalid value for `customer_id`, must not be `None`')
if (len(customer_id) > 50):
raise ValueError('Invalid value for `customer_id`, length must be less than `50`')
self._customer_id = customer_id | @customer_id.setter
def customer_id(self, customer_id):
'\n Sets the customer_id of this ChargeRequest.\n The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.\n\n :param customer_id: The customer_id of this ChargeRequest.\n :type: str\n '
if (customer_id is None):
raise ValueError('Invalid value for `customer_id`, must not be `None`')
if (len(customer_id) > 50):
raise ValueError('Invalid value for `customer_id`, length must be less than `50`')
self._customer_id = customer_id<|docstring|>Sets the customer_id of this ChargeRequest.
The ID of the customer to associate this transaction with. This field is required if you provide a value for `customer_card_id`, and optional otherwise.
:param customer_id: The customer_id of this ChargeRequest.
:type: str<|endoftext|> |
b631e4ce65ba52990825445d9f64d1ae9ee83faf4b13058e3b8e50485fda226c | @property
def billing_address(self):
"\n Gets the billing_address of this ChargeRequest.\n The buyer's billing address.\n\n :return: The billing_address of this ChargeRequest.\n :rtype: Address\n "
return self._billing_address | Gets the billing_address of this ChargeRequest.
The buyer's billing address.
:return: The billing_address of this ChargeRequest.
:rtype: Address | squareconnect/models/charge_request.py | billing_address | sanketsaurav/connect-python-sdk | 53 | python | @property
def billing_address(self):
"\n Gets the billing_address of this ChargeRequest.\n The buyer's billing address.\n\n :return: The billing_address of this ChargeRequest.\n :rtype: Address\n "
return self._billing_address | @property
def billing_address(self):
"\n Gets the billing_address of this ChargeRequest.\n The buyer's billing address.\n\n :return: The billing_address of this ChargeRequest.\n :rtype: Address\n "
return self._billing_address<|docstring|>Gets the billing_address of this ChargeRequest.
The buyer's billing address.
:return: The billing_address of this ChargeRequest.
:rtype: Address<|endoftext|> |
39ad953fe926211cb734446629bc3558ee2dbe8d31c94b53f832d59315d402eb | @billing_address.setter
def billing_address(self, billing_address):
"\n Sets the billing_address of this ChargeRequest.\n The buyer's billing address.\n\n :param billing_address: The billing_address of this ChargeRequest.\n :type: Address\n "
self._billing_address = billing_address | Sets the billing_address of this ChargeRequest.
The buyer's billing address.
:param billing_address: The billing_address of this ChargeRequest.
:type: Address | squareconnect/models/charge_request.py | billing_address | sanketsaurav/connect-python-sdk | 53 | python | @billing_address.setter
def billing_address(self, billing_address):
"\n Sets the billing_address of this ChargeRequest.\n The buyer's billing address.\n\n :param billing_address: The billing_address of this ChargeRequest.\n :type: Address\n "
self._billing_address = billing_address | @billing_address.setter
def billing_address(self, billing_address):
"\n Sets the billing_address of this ChargeRequest.\n The buyer's billing address.\n\n :param billing_address: The billing_address of this ChargeRequest.\n :type: Address\n "
self._billing_address = billing_address<|docstring|>Sets the billing_address of this ChargeRequest.
The buyer's billing address.
:param billing_address: The billing_address of this ChargeRequest.
:type: Address<|endoftext|> |
d75edf89ea7f4d14f272d21ca17f4b6a5edcb35b7e5f32a6b1b81bc2c17821c1 | @property
def shipping_address(self):
"\n Gets the shipping_address of this ChargeRequest.\n The buyer's shipping address, if available.\n\n :return: The shipping_address of this ChargeRequest.\n :rtype: Address\n "
return self._shipping_address | Gets the shipping_address of this ChargeRequest.
The buyer's shipping address, if available.
:return: The shipping_address of this ChargeRequest.
:rtype: Address | squareconnect/models/charge_request.py | shipping_address | sanketsaurav/connect-python-sdk | 53 | python | @property
def shipping_address(self):
"\n Gets the shipping_address of this ChargeRequest.\n The buyer's shipping address, if available.\n\n :return: The shipping_address of this ChargeRequest.\n :rtype: Address\n "
return self._shipping_address | @property
def shipping_address(self):
"\n Gets the shipping_address of this ChargeRequest.\n The buyer's shipping address, if available.\n\n :return: The shipping_address of this ChargeRequest.\n :rtype: Address\n "
return self._shipping_address<|docstring|>Gets the shipping_address of this ChargeRequest.
The buyer's shipping address, if available.
:return: The shipping_address of this ChargeRequest.
:rtype: Address<|endoftext|> |
0d8977c41ae39ffe8138af6624c276a4b567cdb723eb65635f07313497aa5ee4 | @shipping_address.setter
def shipping_address(self, shipping_address):
"\n Sets the shipping_address of this ChargeRequest.\n The buyer's shipping address, if available.\n\n :param shipping_address: The shipping_address of this ChargeRequest.\n :type: Address\n "
self._shipping_address = shipping_address | Sets the shipping_address of this ChargeRequest.
The buyer's shipping address, if available.
:param shipping_address: The shipping_address of this ChargeRequest.
:type: Address | squareconnect/models/charge_request.py | shipping_address | sanketsaurav/connect-python-sdk | 53 | python | @shipping_address.setter
def shipping_address(self, shipping_address):
"\n Sets the shipping_address of this ChargeRequest.\n The buyer's shipping address, if available.\n\n :param shipping_address: The shipping_address of this ChargeRequest.\n :type: Address\n "
self._shipping_address = shipping_address | @shipping_address.setter
def shipping_address(self, shipping_address):
"\n Sets the shipping_address of this ChargeRequest.\n The buyer's shipping address, if available.\n\n :param shipping_address: The shipping_address of this ChargeRequest.\n :type: Address\n "
self._shipping_address = shipping_address<|docstring|>Sets the shipping_address of this ChargeRequest.
The buyer's shipping address, if available.
:param shipping_address: The shipping_address of this ChargeRequest.
:type: Address<|endoftext|> |
146927786d99437d94a4c6e5dd3b225d07cc7415864667993ec4534d0edd2cef | @property
def buyer_email_address(self):
"\n Gets the buyer_email_address of this ChargeRequest.\n The buyer's email address, if available.\n\n :return: The buyer_email_address of this ChargeRequest.\n :rtype: str\n "
return self._buyer_email_address | Gets the buyer_email_address of this ChargeRequest.
The buyer's email address, if available.
:return: The buyer_email_address of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | buyer_email_address | sanketsaurav/connect-python-sdk | 53 | python | @property
def buyer_email_address(self):
"\n Gets the buyer_email_address of this ChargeRequest.\n The buyer's email address, if available.\n\n :return: The buyer_email_address of this ChargeRequest.\n :rtype: str\n "
return self._buyer_email_address | @property
def buyer_email_address(self):
"\n Gets the buyer_email_address of this ChargeRequest.\n The buyer's email address, if available.\n\n :return: The buyer_email_address of this ChargeRequest.\n :rtype: str\n "
return self._buyer_email_address<|docstring|>Gets the buyer_email_address of this ChargeRequest.
The buyer's email address, if available.
:return: The buyer_email_address of this ChargeRequest.
:rtype: str<|endoftext|> |
d057fcbd503a87674245c575e59a6f8e8ce6e0e2d1020e4e16efb1d0c399db48 | @buyer_email_address.setter
def buyer_email_address(self, buyer_email_address):
"\n Sets the buyer_email_address of this ChargeRequest.\n The buyer's email address, if available.\n\n :param buyer_email_address: The buyer_email_address of this ChargeRequest.\n :type: str\n "
self._buyer_email_address = buyer_email_address | Sets the buyer_email_address of this ChargeRequest.
The buyer's email address, if available.
:param buyer_email_address: The buyer_email_address of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | buyer_email_address | sanketsaurav/connect-python-sdk | 53 | python | @buyer_email_address.setter
def buyer_email_address(self, buyer_email_address):
"\n Sets the buyer_email_address of this ChargeRequest.\n The buyer's email address, if available.\n\n :param buyer_email_address: The buyer_email_address of this ChargeRequest.\n :type: str\n "
self._buyer_email_address = buyer_email_address | @buyer_email_address.setter
def buyer_email_address(self, buyer_email_address):
"\n Sets the buyer_email_address of this ChargeRequest.\n The buyer's email address, if available.\n\n :param buyer_email_address: The buyer_email_address of this ChargeRequest.\n :type: str\n "
self._buyer_email_address = buyer_email_address<|docstring|>Sets the buyer_email_address of this ChargeRequest.
The buyer's email address, if available.
:param buyer_email_address: The buyer_email_address of this ChargeRequest.
:type: str<|endoftext|> |
7084f9a7f754a1a269938197ba2102a7347433c20d3b62981a7498e79014ad0b | @property
def order_id(self):
"\n Gets the order_id of this ChargeRequest.\n The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.\n\n :return: The order_id of this ChargeRequest.\n :rtype: str\n "
return self._order_id | Gets the order_id of this ChargeRequest.
The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.
:return: The order_id of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | order_id | sanketsaurav/connect-python-sdk | 53 | python | @property
def order_id(self):
"\n Gets the order_id of this ChargeRequest.\n The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.\n\n :return: The order_id of this ChargeRequest.\n :rtype: str\n "
return self._order_id | @property
def order_id(self):
"\n Gets the order_id of this ChargeRequest.\n The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.\n\n :return: The order_id of this ChargeRequest.\n :rtype: str\n "
return self._order_id<|docstring|>Gets the order_id of this ChargeRequest.
The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.
:return: The order_id of this ChargeRequest.
:rtype: str<|endoftext|> |
021a23f700bb7e8b673a33b2822e83321fbabd98db7389662e3376de252eada7 | @order_id.setter
def order_id(self, order_id):
"\n Sets the order_id of this ChargeRequest.\n The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.\n\n :param order_id: The order_id of this ChargeRequest.\n :type: str\n "
if (order_id is None):
raise ValueError('Invalid value for `order_id`, must not be `None`')
if (len(order_id) > 192):
raise ValueError('Invalid value for `order_id`, length must be less than `192`')
self._order_id = order_id | Sets the order_id of this ChargeRequest.
The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.
:param order_id: The order_id of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | order_id | sanketsaurav/connect-python-sdk | 53 | python | @order_id.setter
def order_id(self, order_id):
"\n Sets the order_id of this ChargeRequest.\n The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.\n\n :param order_id: The order_id of this ChargeRequest.\n :type: str\n "
if (order_id is None):
raise ValueError('Invalid value for `order_id`, must not be `None`')
if (len(order_id) > 192):
raise ValueError('Invalid value for `order_id`, length must be less than `192`')
self._order_id = order_id | @order_id.setter
def order_id(self, order_id):
"\n Sets the order_id of this ChargeRequest.\n The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.\n\n :param order_id: The order_id of this ChargeRequest.\n :type: str\n "
if (order_id is None):
raise ValueError('Invalid value for `order_id`, must not be `None`')
if (len(order_id) > 192):
raise ValueError('Invalid value for `order_id`, length must be less than `192`')
self._order_id = order_id<|docstring|>Sets the order_id of this ChargeRequest.
The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field.
:param order_id: The order_id of this ChargeRequest.
:type: str<|endoftext|> |
373a6241ccbb941460a23f34a92423fb01390437e8b71c6c73a83ea01e026ab7 | @property
def additional_recipients(self):
'\n Gets the additional_recipients of this ChargeRequest.\n The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.\n\n :return: The additional_recipients of this ChargeRequest.\n :rtype: list[AdditionalRecipient]\n '
return self._additional_recipients | Gets the additional_recipients of this ChargeRequest.
The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.
:return: The additional_recipients of this ChargeRequest.
:rtype: list[AdditionalRecipient] | squareconnect/models/charge_request.py | additional_recipients | sanketsaurav/connect-python-sdk | 53 | python | @property
def additional_recipients(self):
'\n Gets the additional_recipients of this ChargeRequest.\n The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.\n\n :return: The additional_recipients of this ChargeRequest.\n :rtype: list[AdditionalRecipient]\n '
return self._additional_recipients | @property
def additional_recipients(self):
'\n Gets the additional_recipients of this ChargeRequest.\n The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.\n\n :return: The additional_recipients of this ChargeRequest.\n :rtype: list[AdditionalRecipient]\n '
return self._additional_recipients<|docstring|>Gets the additional_recipients of this ChargeRequest.
The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.
:return: The additional_recipients of this ChargeRequest.
:rtype: list[AdditionalRecipient]<|endoftext|> |
567dca5ab4daa9d17f3666523460bf895ceec8b1cb49d2378c5aa40d5ea4e023 | @additional_recipients.setter
def additional_recipients(self, additional_recipients):
'\n Sets the additional_recipients of this ChargeRequest.\n The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.\n\n :param additional_recipients: The additional_recipients of this ChargeRequest.\n :type: list[AdditionalRecipient]\n '
self._additional_recipients = additional_recipients | Sets the additional_recipients of this ChargeRequest.
The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.
:param additional_recipients: The additional_recipients of this ChargeRequest.
:type: list[AdditionalRecipient] | squareconnect/models/charge_request.py | additional_recipients | sanketsaurav/connect-python-sdk | 53 | python | @additional_recipients.setter
def additional_recipients(self, additional_recipients):
'\n Sets the additional_recipients of this ChargeRequest.\n The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.\n\n :param additional_recipients: The additional_recipients of this ChargeRequest.\n :type: list[AdditionalRecipient]\n '
self._additional_recipients = additional_recipients | @additional_recipients.setter
def additional_recipients(self, additional_recipients):
'\n Sets the additional_recipients of this ChargeRequest.\n The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.\n\n :param additional_recipients: The additional_recipients of this ChargeRequest.\n :type: list[AdditionalRecipient]\n '
self._additional_recipients = additional_recipients<|docstring|>Sets the additional_recipients of this ChargeRequest.
The basic primitive of multi-party transaction. The value is optional. The transaction facilitated by you can be split from here. If you provide this value, the `amount_money` value in your additional_recipients must not be more than 90% of the `amount_money` value in the charge request. The `location_id` must be the valid location of the app owner merchant. This field requires the `PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS` OAuth permission. This field is currently not supported in sandbox.
:param additional_recipients: The additional_recipients of this ChargeRequest.
:type: list[AdditionalRecipient]<|endoftext|> |
870b56e5d7e23a02850a3b59411a2e40818288c035fec28f0f6f72cbe68367fb | @property
def verification_token(self):
'\n Gets the verification_token of this ChargeRequest.\n An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.\n\n :return: The verification_token of this ChargeRequest.\n :rtype: str\n '
return self._verification_token | Gets the verification_token of this ChargeRequest.
An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.
:return: The verification_token of this ChargeRequest.
:rtype: str | squareconnect/models/charge_request.py | verification_token | sanketsaurav/connect-python-sdk | 53 | python | @property
def verification_token(self):
'\n Gets the verification_token of this ChargeRequest.\n An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.\n\n :return: The verification_token of this ChargeRequest.\n :rtype: str\n '
return self._verification_token | @property
def verification_token(self):
'\n Gets the verification_token of this ChargeRequest.\n An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.\n\n :return: The verification_token of this ChargeRequest.\n :rtype: str\n '
return self._verification_token<|docstring|>Gets the verification_token of this ChargeRequest.
An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.
:return: The verification_token of this ChargeRequest.
:rtype: str<|endoftext|> |
4b8428c9de08302ae70a0123d2364e43a328be087795bcd26f76bc8450773188 | @verification_token.setter
def verification_token(self, verification_token):
'\n Sets the verification_token of this ChargeRequest.\n An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.\n\n :param verification_token: The verification_token of this ChargeRequest.\n :type: str\n '
self._verification_token = verification_token | Sets the verification_token of this ChargeRequest.
An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.
:param verification_token: The verification_token of this ChargeRequest.
:type: str | squareconnect/models/charge_request.py | verification_token | sanketsaurav/connect-python-sdk | 53 | python | @verification_token.setter
def verification_token(self, verification_token):
'\n Sets the verification_token of this ChargeRequest.\n An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.\n\n :param verification_token: The verification_token of this ChargeRequest.\n :type: str\n '
self._verification_token = verification_token | @verification_token.setter
def verification_token(self, verification_token):
'\n Sets the verification_token of this ChargeRequest.\n An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.\n\n :param verification_token: The verification_token of this ChargeRequest.\n :type: str\n '
self._verification_token = verification_token<|docstring|>Sets the verification_token of this ChargeRequest.
An identifying token generated by `SqPaymentForm.verifyBuyer()`. Verification tokens encapsulate customer device information and 3-D Secure challenge results to indicate that Square has verified the buyer identity.
:param verification_token: The verification_token of this ChargeRequest.
:type: str<|endoftext|> |
f92515cd38effc7eee4069f2288d78a0f0836df932fb36a84e3b4f7e14233415 | def to_dict(self):
'\n Returns the model properties as a dict\n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result | Returns the model properties as a dict | squareconnect/models/charge_request.py | to_dict | sanketsaurav/connect-python-sdk | 53 | python | def to_dict(self):
'\n \n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result | def to_dict(self):
'\n \n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result<|docstring|>Returns the model properties as a dict<|endoftext|> |
c373d87dd29c1e96dce460ab571bff86e58edb298ba83c85d8cc7603a6505de4 | def to_str(self):
'\n Returns the string representation of the model\n '
return pformat(self.to_dict()) | Returns the string representation of the model | squareconnect/models/charge_request.py | to_str | sanketsaurav/connect-python-sdk | 53 | python | def to_str(self):
'\n \n '
return pformat(self.to_dict()) | def to_str(self):
'\n \n '
return pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|> |
1034ff7dd2eef24d21e3c2fa7409b793ab5cbb8cd75a2eb0ab3e62604b26264d | def __repr__(self):
'\n For `print` and `pprint`\n '
return self.to_str() | For `print` and `pprint` | squareconnect/models/charge_request.py | __repr__ | sanketsaurav/connect-python-sdk | 53 | python | def __repr__(self):
'\n \n '
return self.to_str() | def __repr__(self):
'\n \n '
return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|> |
a43b3ce7478646f0122f200e4de04f4f5ed99329a4b75930eecef4ff54a23351 | def __eq__(self, other):
'\n Returns true if both objects are equal\n '
return (self.__dict__ == other.__dict__) | Returns true if both objects are equal | squareconnect/models/charge_request.py | __eq__ | sanketsaurav/connect-python-sdk | 53 | python | def __eq__(self, other):
'\n \n '
return (self.__dict__ == other.__dict__) | def __eq__(self, other):
'\n \n '
return (self.__dict__ == other.__dict__)<|docstring|>Returns true if both objects are equal<|endoftext|> |
e5050f8e1402e3a4c90d6c6e229c4c9e2b8ec61e0be457915ea9d976f7e6b0b4 | def __ne__(self, other):
'\n Returns true if both objects are not equal\n '
return (not (self == other)) | Returns true if both objects are not equal | squareconnect/models/charge_request.py | __ne__ | sanketsaurav/connect-python-sdk | 53 | python | def __ne__(self, other):
'\n \n '
return (not (self == other)) | def __ne__(self, other):
'\n \n '
return (not (self == other))<|docstring|>Returns true if both objects are not equal<|endoftext|> |
8b37450608ea67380e4cab382c2e9d5530f48ab2d37e2bb1dc5e4798053c6812 | def __init__(self, p1_starts: bool) -> None:
'\n Initialize this Game, using p1_starts to find who the first player is.\n '
raise NotImplementedError | Initialize this Game, using p1_starts to find who the first player is. | game.py | __init__ | PenPenMark06/Stonehenge-MiniMax | 1 | python | def __init__(self, p1_starts: bool) -> None:
'\n \n '
raise NotImplementedError | def __init__(self, p1_starts: bool) -> None:
'\n \n '
raise NotImplementedError<|docstring|>Initialize this Game, using p1_starts to find who the first player is.<|endoftext|> |
8303418bde73043d44ae65e65c53c6c590e9d8fe779d5e9fafb26eb27d90239d | def get_instructions(self) -> str:
'\n Return the instructions for this Game.\n '
raise NotImplementedError | Return the instructions for this Game. | game.py | get_instructions | PenPenMark06/Stonehenge-MiniMax | 1 | python | def get_instructions(self) -> str:
'\n \n '
raise NotImplementedError | def get_instructions(self) -> str:
'\n \n '
raise NotImplementedError<|docstring|>Return the instructions for this Game.<|endoftext|> |
b3c871a070f355e985061a971b477cb3cd1582fab889223359b77774d7169bfe | def is_over(self, state: GameState) -> bool:
'\n Return whether or not this game is over at state.\n '
raise NotImplementedError | Return whether or not this game is over at state. | game.py | is_over | PenPenMark06/Stonehenge-MiniMax | 1 | python | def is_over(self, state: GameState) -> bool:
'\n \n '
raise NotImplementedError | def is_over(self, state: GameState) -> bool:
'\n \n '
raise NotImplementedError<|docstring|>Return whether or not this game is over at state.<|endoftext|> |
422fad3dd9d4b3ddbb900fd0b24c85b911ebcaa24d96bc9e3aa4eaa0876c2408 | def is_winner(self, player: str) -> bool:
"\n Return whether player has won the game.\n\n Precondition: player is 'p1' or 'p2'.\n "
raise NotImplementedError | Return whether player has won the game.
Precondition: player is 'p1' or 'p2'. | game.py | is_winner | PenPenMark06/Stonehenge-MiniMax | 1 | python | def is_winner(self, player: str) -> bool:
"\n Return whether player has won the game.\n\n Precondition: player is 'p1' or 'p2'.\n "
raise NotImplementedError | def is_winner(self, player: str) -> bool:
"\n Return whether player has won the game.\n\n Precondition: player is 'p1' or 'p2'.\n "
raise NotImplementedError<|docstring|>Return whether player has won the game.
Precondition: player is 'p1' or 'p2'.<|endoftext|> |
bf9dbd23ac60e07d3362768daefba51995c2e6f6a5a929c921ab7f5c1460fa6a | def str_to_move(self, string: str) -> Any:
'\n Return the move that string represents. If string is not a move,\n return some invalid move.\n '
raise NotImplementedError | Return the move that string represents. If string is not a move,
return some invalid move. | game.py | str_to_move | PenPenMark06/Stonehenge-MiniMax | 1 | python | def str_to_move(self, string: str) -> Any:
'\n Return the move that string represents. If string is not a move,\n return some invalid move.\n '
raise NotImplementedError | def str_to_move(self, string: str) -> Any:
'\n Return the move that string represents. If string is not a move,\n return some invalid move.\n '
raise NotImplementedError<|docstring|>Return the move that string represents. If string is not a move,
return some invalid move.<|endoftext|> |
caca8a3b85a1ff86f02367a8a7fe5c5b4dc9c45e083366200285b60595f32528 | def t_DOUBLE_CONST(self, t):
'\\d+\\.\\d*'
t.value = float(t.value)
return t | \d+\.\d* | src/lz_lexer.py | t_DOUBLE_CONST | jeremystevens/Lay-Z-Lang | 0 | python | def t_DOUBLE_CONST(self, t):
'\\d+\\.\\d*'
t.value = float(t.value)
return t | def t_DOUBLE_CONST(self, t):
'\\d+\\.\\d*'
t.value = float(t.value)
return t<|docstring|>\d+\.\d*<|endoftext|> |
d5c4757f37233b439ca6500dacdfe63b7e0526192a5fe0badca3bb7523b2c1d9 | def t_INT_CONST(self, t):
'\\d+'
t.value = int(t.value)
return t | \d+ | src/lz_lexer.py | t_INT_CONST | jeremystevens/Lay-Z-Lang | 0 | python | def t_INT_CONST(self, t):
'\'
t.value = int(t.value)
return t | def t_INT_CONST(self, t):
'\'
t.value = int(t.value)
return t<|docstring|>\d+<|endoftext|> |
34528df9b621221cd8cac3c3f4ff8dd3855b29245291e02d59816d2f14de11b7 | def t_STRING_CONST(self, t):
'".*?"'
t.value = t.value[1:(len(t.value) - 1)]
return t | ".*?" | src/lz_lexer.py | t_STRING_CONST | jeremystevens/Lay-Z-Lang | 0 | python | def t_STRING_CONST(self, t):
t.value = t.value[1:(len(t.value) - 1)]
return t | def t_STRING_CONST(self, t):
t.value = t.value[1:(len(t.value) - 1)]
return t<|docstring|>".*?"<|endoftext|> |
f4538498318af12deefe78055b27d312fa83a6f6f515167218625e09b14717d7 | def t_NEWLINE(self, t):
'\\n+'
t.lexer.lineno += t.value.count('\n')
return t | \n+ | src/lz_lexer.py | t_NEWLINE | jeremystevens/Lay-Z-Lang | 0 | python | def t_NEWLINE(self, t):
'\'
t.lexer.lineno += t.value.count('\n')
return t | def t_NEWLINE(self, t):
'\'
t.lexer.lineno += t.value.count('\n')
return t<|docstring|>\n+<|endoftext|> |
843e60633316b3453b6a99f1aad669f835c248473320e69dd6d2f0ba17332dcb | def test_governance_message_headers(self):
'\n This test is used to make sure the ION endpoint code is properly setting the\n '
old_send = BidirClientChannel._send
def patched_send(*args, **kwargs):
msg_headers = kwargs['headers']
if ((self.resource_id_header_value == '') and ('resource-id' in msg_headers)):
self.resource_id_header_value = msg_headers['resource-id']
return old_send(*args, **kwargs)
patcher = patch('pyon.net.endpoint.BidirClientChannel._send', patched_send)
patcher.start()
self.addCleanup(patcher.stop)
obj = IonObject('ActorIdentity', name='name')
with self.assertRaises(BadRequest) as cm:
self.rr_client.update(obj)
self.resource_id_header_value = ''
(obj_id, obj_rev) = self.rr_client.create(obj)
log.debug('The id of the created object is %s', obj_id)
self.assertEqual(self.resource_id_header_value, '')
self.resource_id_header_value = ''
read_obj = self.rr_client.read(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value = ''
with self.assertRaises(BadRequest) as cm:
self.rr_client.create(read_obj)
self.assertEqual(self.resource_id_header_value, '')
read_obj.name = 'John Doe'
self.resource_id_header_value = ''
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value = ''
with self.assertRaises(Conflict) as cm:
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value = ''
read_obj = self.rr_client.read(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value = ''
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
obj = IonObject('ActorIdentity', name='Babs Smith')
self.resource_id_header_value = ''
(obj2_id, obj2_rev) = self.rr_client.create(obj)
log.debug('The id of the created object is %s', obj_id)
self.assertEqual(self.resource_id_header_value, '')
self.resource_id_header_value = ''
objs = self.rr_client.read_mult([obj_id, obj2_id])
self.assertAlmostEquals(self.resource_id_header_value, [obj_id, obj2_id])
self.assertEqual(len(objs), 2)
self.resource_id_header_value = ''
self.rr_client.delete(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value = ''
self.rr_client.delete(obj2_id)
self.assertEqual(self.resource_id_header_value, obj2_id) | This test is used to make sure the ION endpoint code is properly setting the | src/ion/service/test/test_governance.py | test_governance_message_headers | klawande-cci/scioncc | 2 | python | def test_governance_message_headers(self):
'\n \n '
old_send = BidirClientChannel._send
def patched_send(*args, **kwargs):
msg_headers = kwargs['headers']
if ((self.resource_id_header_value == ) and ('resource-id' in msg_headers)):
self.resource_id_header_value = msg_headers['resource-id']
return old_send(*args, **kwargs)
patcher = patch('pyon.net.endpoint.BidirClientChannel._send', patched_send)
patcher.start()
self.addCleanup(patcher.stop)
obj = IonObject('ActorIdentity', name='name')
with self.assertRaises(BadRequest) as cm:
self.rr_client.update(obj)
self.resource_id_header_value =
(obj_id, obj_rev) = self.rr_client.create(obj)
log.debug('The id of the created object is %s', obj_id)
self.assertEqual(self.resource_id_header_value, )
self.resource_id_header_value =
read_obj = self.rr_client.read(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
with self.assertRaises(BadRequest) as cm:
self.rr_client.create(read_obj)
self.assertEqual(self.resource_id_header_value, )
read_obj.name = 'John Doe'
self.resource_id_header_value =
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
with self.assertRaises(Conflict) as cm:
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
read_obj = self.rr_client.read(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
obj = IonObject('ActorIdentity', name='Babs Smith')
self.resource_id_header_value =
(obj2_id, obj2_rev) = self.rr_client.create(obj)
log.debug('The id of the created object is %s', obj_id)
self.assertEqual(self.resource_id_header_value, )
self.resource_id_header_value =
objs = self.rr_client.read_mult([obj_id, obj2_id])
self.assertAlmostEquals(self.resource_id_header_value, [obj_id, obj2_id])
self.assertEqual(len(objs), 2)
self.resource_id_header_value =
self.rr_client.delete(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
self.rr_client.delete(obj2_id)
self.assertEqual(self.resource_id_header_value, obj2_id) | def test_governance_message_headers(self):
'\n \n '
old_send = BidirClientChannel._send
def patched_send(*args, **kwargs):
msg_headers = kwargs['headers']
if ((self.resource_id_header_value == ) and ('resource-id' in msg_headers)):
self.resource_id_header_value = msg_headers['resource-id']
return old_send(*args, **kwargs)
patcher = patch('pyon.net.endpoint.BidirClientChannel._send', patched_send)
patcher.start()
self.addCleanup(patcher.stop)
obj = IonObject('ActorIdentity', name='name')
with self.assertRaises(BadRequest) as cm:
self.rr_client.update(obj)
self.resource_id_header_value =
(obj_id, obj_rev) = self.rr_client.create(obj)
log.debug('The id of the created object is %s', obj_id)
self.assertEqual(self.resource_id_header_value, )
self.resource_id_header_value =
read_obj = self.rr_client.read(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
with self.assertRaises(BadRequest) as cm:
self.rr_client.create(read_obj)
self.assertEqual(self.resource_id_header_value, )
read_obj.name = 'John Doe'
self.resource_id_header_value =
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
with self.assertRaises(Conflict) as cm:
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
read_obj = self.rr_client.read(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
self.rr_client.update(read_obj)
self.assertEqual(self.resource_id_header_value, obj_id)
obj = IonObject('ActorIdentity', name='Babs Smith')
self.resource_id_header_value =
(obj2_id, obj2_rev) = self.rr_client.create(obj)
log.debug('The id of the created object is %s', obj_id)
self.assertEqual(self.resource_id_header_value, )
self.resource_id_header_value =
objs = self.rr_client.read_mult([obj_id, obj2_id])
self.assertAlmostEquals(self.resource_id_header_value, [obj_id, obj2_id])
self.assertEqual(len(objs), 2)
self.resource_id_header_value =
self.rr_client.delete(obj_id)
self.assertEqual(self.resource_id_header_value, obj_id)
self.resource_id_header_value =
self.rr_client.delete(obj2_id)
self.assertEqual(self.resource_id_header_value, obj2_id)<|docstring|>This test is used to make sure the ION endpoint code is properly setting the<|endoftext|> |
648073ba74019d7d88fe9e5336fe0edf2c5d82c26b14f79745aa02dcab4e1e77 | def test_add(self):
' Add two registers into a third '
self.feed('add r2, r5, r7')
self.check('00 45 38 00') | Add two registers into a third | test/arch/test_microblaze.py | test_add | tstreiff/ppci-mirror | 161 | python | def test_add(self):
' '
self.feed('add r2, r5, r7')
self.check('00 45 38 00') | def test_add(self):
' '
self.feed('add r2, r5, r7')
self.check('00 45 38 00')<|docstring|>Add two registers into a third<|endoftext|> |
2b2947d81b8a352769d9bb1ead6687f1f2e86e8730dc942bef2059af1283d96a | def test_addik(self):
' Test add immediate '
self.feed('addik r5, r0, 65')
self.check('30 a0 00 41') | Test add immediate | test/arch/test_microblaze.py | test_addik | tstreiff/ppci-mirror | 161 | python | def test_addik(self):
' '
self.feed('addik r5, r0, 65')
self.check('30 a0 00 41') | def test_addik(self):
' '
self.feed('addik r5, r0, 65')
self.check('30 a0 00 41')<|docstring|>Test add immediate<|endoftext|> |
9f73e475366c3d07b396ae03d2f35e52fabc6946a6ddca9b98b352099bc0d127 | @summarization_featurizing(name='get_oracle_summary', contributor='datalab', task='summarization', description='This function extract the oracle summaries for text summarization')
def get_oracle_summary(sample: dict) -> Dict:
'\n Input:\n SummarizationDataset: dict\n Output:\n return {"source":src,\n "reference":ref,\n "oracle_summary":oracle,\n "oracle_labels":labels,\n "oracle_score":max_score}\n '
document = sent_tokenize(sample['text'])
summary = sample['summary']
oracle_info = _ext_oracle(document, summary, _compute_rouge, max_sent=3)
return oracle_info | Input:
SummarizationDataset: dict
Output:
return {"source":src,
"reference":ref,
"oracle_summary":oracle,
"oracle_labels":labels,
"oracle_score":max_score} | datalabs/operations/featurize/summarization.py | get_oracle_summary | ExpressAI/DataLab | 54 | python | @summarization_featurizing(name='get_oracle_summary', contributor='datalab', task='summarization', description='This function extract the oracle summaries for text summarization')
def get_oracle_summary(sample: dict) -> Dict:
'\n Input:\n SummarizationDataset: dict\n Output:\n return {"source":src,\n "reference":ref,\n "oracle_summary":oracle,\n "oracle_labels":labels,\n "oracle_score":max_score}\n '
document = sent_tokenize(sample['text'])
summary = sample['summary']
oracle_info = _ext_oracle(document, summary, _compute_rouge, max_sent=3)
return oracle_info | @summarization_featurizing(name='get_oracle_summary', contributor='datalab', task='summarization', description='This function extract the oracle summaries for text summarization')
def get_oracle_summary(sample: dict) -> Dict:
'\n Input:\n SummarizationDataset: dict\n Output:\n return {"source":src,\n "reference":ref,\n "oracle_summary":oracle,\n "oracle_labels":labels,\n "oracle_score":max_score}\n '
document = sent_tokenize(sample['text'])
summary = sample['summary']
oracle_info = _ext_oracle(document, summary, _compute_rouge, max_sent=3)
return oracle_info<|docstring|>Input:
SummarizationDataset: dict
Output:
return {"source":src,
"reference":ref,
"oracle_summary":oracle,
"oracle_labels":labels,
"oracle_score":max_score}<|endoftext|> |
8fc70994e5caf09c79d0850cfbb1a7faba6bf27638b43626ecc3a754371061f7 | @summarization_featurizing(name='get_lead_k_summary', contributor='datalab', task='summarization', description='This function extract the lead k summary for text summarization datasets')
def get_lead_k_summary(sample: dict) -> Dict:
'\n Input:\n SummarizationDataset: dict\n Output:\n return {"source":src,\n "reference":ref,\n "lead_k_summary":src,\n "lead_k_score":score}\n '
document = sent_tokenize(sample['text'])
summary = sample['summary']
lead_k_info = _lead_k(document, summary, _compute_rouge, k=3)
return lead_k_info | Input:
SummarizationDataset: dict
Output:
return {"source":src,
"reference":ref,
"lead_k_summary":src,
"lead_k_score":score} | datalabs/operations/featurize/summarization.py | get_lead_k_summary | ExpressAI/DataLab | 54 | python | @summarization_featurizing(name='get_lead_k_summary', contributor='datalab', task='summarization', description='This function extract the lead k summary for text summarization datasets')
def get_lead_k_summary(sample: dict) -> Dict:
'\n Input:\n SummarizationDataset: dict\n Output:\n return {"source":src,\n "reference":ref,\n "lead_k_summary":src,\n "lead_k_score":score}\n '
document = sent_tokenize(sample['text'])
summary = sample['summary']
lead_k_info = _lead_k(document, summary, _compute_rouge, k=3)
return lead_k_info | @summarization_featurizing(name='get_lead_k_summary', contributor='datalab', task='summarization', description='This function extract the lead k summary for text summarization datasets')
def get_lead_k_summary(sample: dict) -> Dict:
'\n Input:\n SummarizationDataset: dict\n Output:\n return {"source":src,\n "reference":ref,\n "lead_k_summary":src,\n "lead_k_score":score}\n '
document = sent_tokenize(sample['text'])
summary = sample['summary']
lead_k_info = _lead_k(document, summary, _compute_rouge, k=3)
return lead_k_info<|docstring|>Input:
SummarizationDataset: dict
Output:
return {"source":src,
"reference":ref,
"lead_k_summary":src,
"lead_k_score":score}<|endoftext|> |
cbfaa83bf7dec4e382ba2bd9b4858a1936a704ce29e693d8f9db706a6302304d | @command(aliases=['Manual', 'manual', 'fm'])
async def fieldmanual(self, ctx: Context):
'\n Returns a link to the field manual\n '
(await ctx.send('https://game.joincyberdiscovery.com/manual')) | Returns a link to the field manual | cdbot/cogs/cyber.py | fieldmanual | joker314/cyberdisc-bot | 0 | python | @command(aliases=['Manual', 'manual', 'fm'])
async def fieldmanual(self, ctx: Context):
'\n \n '
(await ctx.send('https://game.joincyberdiscovery.com/manual')) | @command(aliases=['Manual', 'manual', 'fm'])
async def fieldmanual(self, ctx: Context):
'\n \n '
(await ctx.send('https://game.joincyberdiscovery.com/manual'))<|docstring|>Returns a link to the field manual<|endoftext|> |
e8218185219a0ab83b96eb47ad96f37adef23a258ebc58691481054a86c60acd | @command(aliases=['l', 'lc'])
async def level(self, ctx: Context, base: str, level_num: int, challenge_num: int=0):
'\n Gets information about a specific CyberStart Game level and challenge.\n If the date is before the start date of game (15th January 2019) it will redirect to game() instead\n '
if (datetime.date.today() < datetime.date(2019, 1, 15)):
(await self.game.callback(self, ctx))
return
with open('cdbot/data/game.json') as f:
game_docs = load(f)
if base.isnumeric():
challenge_num = level_num
level_num = int(base)
base = 'hq'
elif (challenge_num == 0):
(await ctx.send('Invalid challenge number!'))
return
for area in BASE_ALIASES.keys():
if (base.lower() in BASE_ALIASES[area]):
base = area
break
else:
(await ctx.send('Unknown base.'))
return
if (not (0 < level_num <= len(game_docs[base]))):
(await ctx.send('Invalid level number!'))
elif (challenge_num not in range((len(game_docs[base][(level_num - 1)]) + 1))):
(await ctx.send('Invalid challenge number!'))
else:
challenge_raw = game_docs[base][(level_num - 1)][(challenge_num - 1)]
challenge_title = challenge_raw['title']
challenge_tip = challenge_raw['tips']
challenge_text = challenge_raw['description']
embed = Embed(title=f'{base} - Level {level_num} Challenge {challenge_num} - {challenge_title}', description=challenge_text, colour=4350708)
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=' | '.join(challenge_tip))
(await ctx.send(embed=embed)) | Gets information about a specific CyberStart Game level and challenge.
If the date is before the start date of game (15th January 2019) it will redirect to game() instead | cdbot/cogs/cyber.py | level | joker314/cyberdisc-bot | 0 | python | @command(aliases=['l', 'lc'])
async def level(self, ctx: Context, base: str, level_num: int, challenge_num: int=0):
'\n Gets information about a specific CyberStart Game level and challenge.\n If the date is before the start date of game (15th January 2019) it will redirect to game() instead\n '
if (datetime.date.today() < datetime.date(2019, 1, 15)):
(await self.game.callback(self, ctx))
return
with open('cdbot/data/game.json') as f:
game_docs = load(f)
if base.isnumeric():
challenge_num = level_num
level_num = int(base)
base = 'hq'
elif (challenge_num == 0):
(await ctx.send('Invalid challenge number!'))
return
for area in BASE_ALIASES.keys():
if (base.lower() in BASE_ALIASES[area]):
base = area
break
else:
(await ctx.send('Unknown base.'))
return
if (not (0 < level_num <= len(game_docs[base]))):
(await ctx.send('Invalid level number!'))
elif (challenge_num not in range((len(game_docs[base][(level_num - 1)]) + 1))):
(await ctx.send('Invalid challenge number!'))
else:
challenge_raw = game_docs[base][(level_num - 1)][(challenge_num - 1)]
challenge_title = challenge_raw['title']
challenge_tip = challenge_raw['tips']
challenge_text = challenge_raw['description']
embed = Embed(title=f'{base} - Level {level_num} Challenge {challenge_num} - {challenge_title}', description=challenge_text, colour=4350708)
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=' | '.join(challenge_tip))
(await ctx.send(embed=embed)) | @command(aliases=['l', 'lc'])
async def level(self, ctx: Context, base: str, level_num: int, challenge_num: int=0):
'\n Gets information about a specific CyberStart Game level and challenge.\n If the date is before the start date of game (15th January 2019) it will redirect to game() instead\n '
if (datetime.date.today() < datetime.date(2019, 1, 15)):
(await self.game.callback(self, ctx))
return
with open('cdbot/data/game.json') as f:
game_docs = load(f)
if base.isnumeric():
challenge_num = level_num
level_num = int(base)
base = 'hq'
elif (challenge_num == 0):
(await ctx.send('Invalid challenge number!'))
return
for area in BASE_ALIASES.keys():
if (base.lower() in BASE_ALIASES[area]):
base = area
break
else:
(await ctx.send('Unknown base.'))
return
if (not (0 < level_num <= len(game_docs[base]))):
(await ctx.send('Invalid level number!'))
elif (challenge_num not in range((len(game_docs[base][(level_num - 1)]) + 1))):
(await ctx.send('Invalid challenge number!'))
else:
challenge_raw = game_docs[base][(level_num - 1)][(challenge_num - 1)]
challenge_title = challenge_raw['title']
challenge_tip = challenge_raw['tips']
challenge_text = challenge_raw['description']
embed = Embed(title=f'{base} - Level {level_num} Challenge {challenge_num} - {challenge_title}', description=challenge_text, colour=4350708)
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=' | '.join(challenge_tip))
(await ctx.send(embed=embed))<|docstring|>Gets information about a specific CyberStart Game level and challenge.
If the date is before the start date of game (15th January 2019) it will redirect to game() instead<|endoftext|> |
6bfc37592ff997e3d911a7e7b327ad9ee125881930b03583aee24d5855bd9cb6 | @command()
async def flag(self, ctx: Context, base: str, level_num: int, challenge_num: int=0):
'Generate a flag for the specified base, level and challenge.'
if (challenge_num == 0):
challenge_num = level_num
level_num = int(base)
base = 'Headquarters'
if ((level_num == 13) and (challenge_num == 1)):
content = '13.1 is a No Flag Zone™ 🙅⛔⚔️'
else:
content = (('The flag is: ||' + (await generatebase64(((ord(base[0]) + level_num) + challenge_num)))) + '||')
embed = Embed(title=f'{base} - Level {level_num} Challenge {challenge_num}', description=content, colour=4350708)
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
(await ctx.send(embed=embed)) | Generate a flag for the specified base, level and challenge. | cdbot/cogs/cyber.py | flag | joker314/cyberdisc-bot | 0 | python | @command()
async def flag(self, ctx: Context, base: str, level_num: int, challenge_num: int=0):
if (challenge_num == 0):
challenge_num = level_num
level_num = int(base)
base = 'Headquarters'
if ((level_num == 13) and (challenge_num == 1)):
content = '13.1 is a No Flag Zone™ 🙅⛔⚔️'
else:
content = (('The flag is: ||' + (await generatebase64(((ord(base[0]) + level_num) + challenge_num)))) + '||')
embed = Embed(title=f'{base} - Level {level_num} Challenge {challenge_num}', description=content, colour=4350708)
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
(await ctx.send(embed=embed)) | @command()
async def flag(self, ctx: Context, base: str, level_num: int, challenge_num: int=0):
if (challenge_num == 0):
challenge_num = level_num
level_num = int(base)
base = 'Headquarters'
if ((level_num == 13) and (challenge_num == 1)):
content = '13.1 is a No Flag Zone™ 🙅⛔⚔️'
else:
content = (('The flag is: ||' + (await generatebase64(((ord(base[0]) + level_num) + challenge_num)))) + '||')
embed = Embed(title=f'{base} - Level {level_num} Challenge {challenge_num}', description=content, colour=4350708)
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
(await ctx.send(embed=embed))<|docstring|>Generate a flag for the specified base, level and challenge.<|endoftext|> |
9e66b21e47a335e1774388c6660017cd00912a974ae5e49cf684519116b775e7 | @command()
@has_role(ROOT_ROLE_ID)
async def readme(self, ctx: Context, operand: str='', channel_id: int=0, msg_send_interval: int=0):
'\n Allows generating, sending and manipulation of JSON file containing the info needed\n to create and send the embeds for the #readme channel. Only ROOT_ROLE_ID users have\n the permissions need to use this command.\n '
README_SEND_ALIASES = ['create', 'push', 'generate', 'send', 'make', 'build', 'upload']
README_RECV_ALIASES = ['fetch', 'get', 'pull', 'download', 'retrieve', 'dm', 'dl']
operand = operand.lower()
if (not (operand in (README_SEND_ALIASES + README_RECV_ALIASES))):
incorrect_operand_embed = Embed(colour=6765239, description=':shrug: **Invalid readme operand supplied.**')
(await ctx.message.delete())
(await ctx.send(embed=incorrect_operand_embed))
elif ((channel_id == 0) and (operand in README_SEND_ALIASES)):
misssing_channel_embed = Embed(colour=16733986, description=':facepalm: **Whoops, you missed out the channel ID! Try again.**')
(await ctx.message.delete())
(await ctx.send(embed=misssing_channel_embed))
elif (operand in README_SEND_ALIASES):
try:
usr_confirmation_embed = Embed(colour=5025616, description=':white_check_mark: **Creating readme using uploaded config file.**')
if (ctx.message.attachments != []):
json_file_location = [_.url for _ in ctx.message.attachments][0]
async with ClientSession() as session:
async with session.get(json_file_location) as response:
if (response.status == 200):
resp_text = (await response.text())
json_config = load(StringIO(resp_text))
(await ctx.send(embed=usr_confirmation_embed))
else:
with open('cdbot/data/readme.json', 'rb') as default_json:
json_config = load(default_json)
usr_confirmation_embed.description = ':ballot_box_with_check: **Creating readme using default config file.**'
(await ctx.send(embed=usr_confirmation_embed))
(await ctx.message.delete())
for section in json_config:
(msg_content, current_embed) = (None, None)
if ('content' in json_config[section]):
msg_content = json_config[section]['content']
if ('embed' in json_config[section]):
current_embed = Embed()
msg_embed = json_config[section]['embed']
if ('title' in msg_embed):
current_embed.title = msg_embed['title']
if ('text' in msg_embed):
current_embed.description = msg_embed['text']
if ('color' in msg_embed):
current_embed.colour = Colour(int(msg_embed['color'], 16))
if ('fields' in msg_embed):
for current_field in msg_embed['fields']:
current_embed.add_field(name=current_field['name'], value=current_field['value'])
requested_channel = self.bot.get_channel(channel_id)
if ((msg_content is not None) and (current_embed is None)):
(await requested_channel.send(content=msg_content))
elif ((current_embed is not None) and (msg_content is None)):
(await requested_channel.send(embed=current_embed))
else:
(await requested_channel.send(content=msg_content, embed=current_embed))
if (0 < msg_send_interval < 901):
(await sleep(msg_send_interval))
(await requested_channel.send(content=END_README_MESSAGE))
except Exception:
parse_fail_embed = Embed(colour=6765239, description=':x: **Error parsing JSON file, please ensure its valid!**')
(await ctx.message.delete())
(await ctx.send(embed=parse_fail_embed))
elif (operand in README_RECV_ALIASES):
with open('cdbot/data/readme_raw.json', 'rb') as readme_json:
raw_json = readme_json.read()
requesting_user = (await self.bot.get_user_info(ctx.message.author.id))
(await requesting_user.send(content="Hey, here's your readme config file!", file=File(raw_json, 'readme_raw.json')))
msg_confirmation = Embed(colour=38536, description=':airplane: **Flying in, check your DMs!**')
(await ctx.message.delete())
(await ctx.send(embed=msg_confirmation)) | Allows generating, sending and manipulation of JSON file containing the info needed
to create and send the embeds for the #readme channel. Only ROOT_ROLE_ID users have
the permissions need to use this command. | cdbot/cogs/cyber.py | readme | joker314/cyberdisc-bot | 0 | python | @command()
@has_role(ROOT_ROLE_ID)
async def readme(self, ctx: Context, operand: str=, channel_id: int=0, msg_send_interval: int=0):
'\n Allows generating, sending and manipulation of JSON file containing the info needed\n to create and send the embeds for the #readme channel. Only ROOT_ROLE_ID users have\n the permissions need to use this command.\n '
README_SEND_ALIASES = ['create', 'push', 'generate', 'send', 'make', 'build', 'upload']
README_RECV_ALIASES = ['fetch', 'get', 'pull', 'download', 'retrieve', 'dm', 'dl']
operand = operand.lower()
if (not (operand in (README_SEND_ALIASES + README_RECV_ALIASES))):
incorrect_operand_embed = Embed(colour=6765239, description=':shrug: **Invalid readme operand supplied.**')
(await ctx.message.delete())
(await ctx.send(embed=incorrect_operand_embed))
elif ((channel_id == 0) and (operand in README_SEND_ALIASES)):
misssing_channel_embed = Embed(colour=16733986, description=':facepalm: **Whoops, you missed out the channel ID! Try again.**')
(await ctx.message.delete())
(await ctx.send(embed=misssing_channel_embed))
elif (operand in README_SEND_ALIASES):
try:
usr_confirmation_embed = Embed(colour=5025616, description=':white_check_mark: **Creating readme using uploaded config file.**')
if (ctx.message.attachments != []):
json_file_location = [_.url for _ in ctx.message.attachments][0]
async with ClientSession() as session:
async with session.get(json_file_location) as response:
if (response.status == 200):
resp_text = (await response.text())
json_config = load(StringIO(resp_text))
(await ctx.send(embed=usr_confirmation_embed))
else:
with open('cdbot/data/readme.json', 'rb') as default_json:
json_config = load(default_json)
usr_confirmation_embed.description = ':ballot_box_with_check: **Creating readme using default config file.**'
(await ctx.send(embed=usr_confirmation_embed))
(await ctx.message.delete())
for section in json_config:
(msg_content, current_embed) = (None, None)
if ('content' in json_config[section]):
msg_content = json_config[section]['content']
if ('embed' in json_config[section]):
current_embed = Embed()
msg_embed = json_config[section]['embed']
if ('title' in msg_embed):
current_embed.title = msg_embed['title']
if ('text' in msg_embed):
current_embed.description = msg_embed['text']
if ('color' in msg_embed):
current_embed.colour = Colour(int(msg_embed['color'], 16))
if ('fields' in msg_embed):
for current_field in msg_embed['fields']:
current_embed.add_field(name=current_field['name'], value=current_field['value'])
requested_channel = self.bot.get_channel(channel_id)
if ((msg_content is not None) and (current_embed is None)):
(await requested_channel.send(content=msg_content))
elif ((current_embed is not None) and (msg_content is None)):
(await requested_channel.send(embed=current_embed))
else:
(await requested_channel.send(content=msg_content, embed=current_embed))
if (0 < msg_send_interval < 901):
(await sleep(msg_send_interval))
(await requested_channel.send(content=END_README_MESSAGE))
except Exception:
parse_fail_embed = Embed(colour=6765239, description=':x: **Error parsing JSON file, please ensure its valid!**')
(await ctx.message.delete())
(await ctx.send(embed=parse_fail_embed))
elif (operand in README_RECV_ALIASES):
with open('cdbot/data/readme_raw.json', 'rb') as readme_json:
raw_json = readme_json.read()
requesting_user = (await self.bot.get_user_info(ctx.message.author.id))
(await requesting_user.send(content="Hey, here's your readme config file!", file=File(raw_json, 'readme_raw.json')))
msg_confirmation = Embed(colour=38536, description=':airplane: **Flying in, check your DMs!**')
(await ctx.message.delete())
(await ctx.send(embed=msg_confirmation)) | @command()
@has_role(ROOT_ROLE_ID)
async def readme(self, ctx: Context, operand: str=, channel_id: int=0, msg_send_interval: int=0):
'\n Allows generating, sending and manipulation of JSON file containing the info needed\n to create and send the embeds for the #readme channel. Only ROOT_ROLE_ID users have\n the permissions need to use this command.\n '
README_SEND_ALIASES = ['create', 'push', 'generate', 'send', 'make', 'build', 'upload']
README_RECV_ALIASES = ['fetch', 'get', 'pull', 'download', 'retrieve', 'dm', 'dl']
operand = operand.lower()
if (not (operand in (README_SEND_ALIASES + README_RECV_ALIASES))):
incorrect_operand_embed = Embed(colour=6765239, description=':shrug: **Invalid readme operand supplied.**')
(await ctx.message.delete())
(await ctx.send(embed=incorrect_operand_embed))
elif ((channel_id == 0) and (operand in README_SEND_ALIASES)):
misssing_channel_embed = Embed(colour=16733986, description=':facepalm: **Whoops, you missed out the channel ID! Try again.**')
(await ctx.message.delete())
(await ctx.send(embed=misssing_channel_embed))
elif (operand in README_SEND_ALIASES):
try:
usr_confirmation_embed = Embed(colour=5025616, description=':white_check_mark: **Creating readme using uploaded config file.**')
if (ctx.message.attachments != []):
json_file_location = [_.url for _ in ctx.message.attachments][0]
async with ClientSession() as session:
async with session.get(json_file_location) as response:
if (response.status == 200):
resp_text = (await response.text())
json_config = load(StringIO(resp_text))
(await ctx.send(embed=usr_confirmation_embed))
else:
with open('cdbot/data/readme.json', 'rb') as default_json:
json_config = load(default_json)
usr_confirmation_embed.description = ':ballot_box_with_check: **Creating readme using default config file.**'
(await ctx.send(embed=usr_confirmation_embed))
(await ctx.message.delete())
for section in json_config:
(msg_content, current_embed) = (None, None)
if ('content' in json_config[section]):
msg_content = json_config[section]['content']
if ('embed' in json_config[section]):
current_embed = Embed()
msg_embed = json_config[section]['embed']
if ('title' in msg_embed):
current_embed.title = msg_embed['title']
if ('text' in msg_embed):
current_embed.description = msg_embed['text']
if ('color' in msg_embed):
current_embed.colour = Colour(int(msg_embed['color'], 16))
if ('fields' in msg_embed):
for current_field in msg_embed['fields']:
current_embed.add_field(name=current_field['name'], value=current_field['value'])
requested_channel = self.bot.get_channel(channel_id)
if ((msg_content is not None) and (current_embed is None)):
(await requested_channel.send(content=msg_content))
elif ((current_embed is not None) and (msg_content is None)):
(await requested_channel.send(embed=current_embed))
else:
(await requested_channel.send(content=msg_content, embed=current_embed))
if (0 < msg_send_interval < 901):
(await sleep(msg_send_interval))
(await requested_channel.send(content=END_README_MESSAGE))
except Exception:
parse_fail_embed = Embed(colour=6765239, description=':x: **Error parsing JSON file, please ensure its valid!**')
(await ctx.message.delete())
(await ctx.send(embed=parse_fail_embed))
elif (operand in README_RECV_ALIASES):
with open('cdbot/data/readme_raw.json', 'rb') as readme_json:
raw_json = readme_json.read()
requesting_user = (await self.bot.get_user_info(ctx.message.author.id))
(await requesting_user.send(content="Hey, here's your readme config file!", file=File(raw_json, 'readme_raw.json')))
msg_confirmation = Embed(colour=38536, description=':airplane: **Flying in, check your DMs!**')
(await ctx.message.delete())
(await ctx.send(embed=msg_confirmation))<|docstring|>Allows generating, sending and manipulation of JSON file containing the info needed
to create and send the embeds for the #readme channel. Only ROOT_ROLE_ID users have
the permissions need to use this command.<|endoftext|> |
fd7352272406a7c02a2b1fe1de1f3ad26a7d931521f327009e078a2071c0db4a | @command(aliases=['a', 'al'])
async def assess(self, ctx: Context, challenge_num: int):
'\n Gets information about a specific CyberStart Assess level and challenge.\n '
NO_HINTS_MSG = f"**:warning: Remember, other people can't give hints after challenge {HINTS_LIMIT}**"
with open('cdbot/data/assess.json') as f:
assess_docs = load(f)
if (not (0 < challenge_num <= len(assess_docs))):
(await ctx.send('Invalid challenge number!'))
else:
challenge_raw = assess_docs[(challenge_num - 1)]
challenge_title = challenge_raw['title']
challenge_difficulty = challenge_raw['difficulty']
challenge_text = challenge_raw['description']
if (challenge_num > HINTS_LIMIT):
challenge_text = ((NO_HINTS_MSG + '\n') + challenge_text)
embed = Embed(title=f'CyberStart Assess Challenge {challenge_num} - {challenge_title}', description=challenge_text, colour=4350708, url=f'https://assess.joincyberdiscovery.com/challenge-{challenge_num:02d}')
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=f'Difficulty: {challenge_difficulty}')
(await ctx.send(embed=embed)) | Gets information about a specific CyberStart Assess level and challenge. | cdbot/cogs/cyber.py | assess | joker314/cyberdisc-bot | 0 | python | @command(aliases=['a', 'al'])
async def assess(self, ctx: Context, challenge_num: int):
'\n \n '
NO_HINTS_MSG = f"**:warning: Remember, other people can't give hints after challenge {HINTS_LIMIT}**"
with open('cdbot/data/assess.json') as f:
assess_docs = load(f)
if (not (0 < challenge_num <= len(assess_docs))):
(await ctx.send('Invalid challenge number!'))
else:
challenge_raw = assess_docs[(challenge_num - 1)]
challenge_title = challenge_raw['title']
challenge_difficulty = challenge_raw['difficulty']
challenge_text = challenge_raw['description']
if (challenge_num > HINTS_LIMIT):
challenge_text = ((NO_HINTS_MSG + '\n') + challenge_text)
embed = Embed(title=f'CyberStart Assess Challenge {challenge_num} - {challenge_title}', description=challenge_text, colour=4350708, url=f'https://assess.joincyberdiscovery.com/challenge-{challenge_num:02d}')
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=f'Difficulty: {challenge_difficulty}')
(await ctx.send(embed=embed)) | @command(aliases=['a', 'al'])
async def assess(self, ctx: Context, challenge_num: int):
'\n \n '
NO_HINTS_MSG = f"**:warning: Remember, other people can't give hints after challenge {HINTS_LIMIT}**"
with open('cdbot/data/assess.json') as f:
assess_docs = load(f)
if (not (0 < challenge_num <= len(assess_docs))):
(await ctx.send('Invalid challenge number!'))
else:
challenge_raw = assess_docs[(challenge_num - 1)]
challenge_title = challenge_raw['title']
challenge_difficulty = challenge_raw['difficulty']
challenge_text = challenge_raw['description']
if (challenge_num > HINTS_LIMIT):
challenge_text = ((NO_HINTS_MSG + '\n') + challenge_text)
embed = Embed(title=f'CyberStart Assess Challenge {challenge_num} - {challenge_title}', description=challenge_text, colour=4350708, url=f'https://assess.joincyberdiscovery.com/challenge-{challenge_num:02d}')
embed.set_author(name='Cyber Discovery', icon_url=CYBERDISC_ICON_URL)
embed.set_footer(text=f'Difficulty: {challenge_difficulty}')
(await ctx.send(embed=embed))<|docstring|>Gets information about a specific CyberStart Assess level and challenge.<|endoftext|> |
05a3c291a2065fab2eb5bb3f03f00e8eece8ed2be12c6e5f34dcc8e5463578d0 | @command()
async def game(self, ctx: Context):
'\n Gets the date of, and days and months until, CyberStart Game\n '
(await self.countdown('15th January 2019', 'CyberStart Game', ctx)) | Gets the date of, and days and months until, CyberStart Game | cdbot/cogs/cyber.py | game | joker314/cyberdisc-bot | 0 | python | @command()
async def game(self, ctx: Context):
'\n \n '
(await self.countdown('15th January 2019', 'CyberStart Game', ctx)) | @command()
async def game(self, ctx: Context):
'\n \n '
(await self.countdown('15th January 2019', 'CyberStart Game', ctx))<|docstring|>Gets the date of, and days and months until, CyberStart Game<|endoftext|> |
97e8c5955cb8bddacc971458989b8e0045b28a48f3133b0bb91517b7b2cb4657 | @command()
async def essentials(self, ctx: Context):
'\n Gets the date of, and days and months until, CyberStart Essentials\n '
(await self.countdown('5th March 2019', 'CyberStart Essentials', ctx)) | Gets the date of, and days and months until, CyberStart Essentials | cdbot/cogs/cyber.py | essentials | joker314/cyberdisc-bot | 0 | python | @command()
async def essentials(self, ctx: Context):
'\n \n '
(await self.countdown('5th March 2019', 'CyberStart Essentials', ctx)) | @command()
async def essentials(self, ctx: Context):
'\n \n '
(await self.countdown('5th March 2019', 'CyberStart Essentials', ctx))<|docstring|>Gets the date of, and days and months until, CyberStart Essentials<|endoftext|> |
506b14c3073f54a022e45a174ac870a70b8e206e56e2398f6811897c6d3237a8 | @command()
async def hundred(self, ctx: Context):
'\n Gets the number of 100% and true 100% users\n '
game_r = ctx.guild.get_role(HUNDRED_PERCENT_ROLE_ID)
true_r = ctx.guild.get_role(TRUE_HUNDRED_PERCENT_ROLE_ID)
(await ctx.send(f'There are {len(game_r.members)} that have completed Cyberstart Game. Out of them, {len(true_r.members)} have also completed Essentials and Assess.')) | Gets the number of 100% and true 100% users | cdbot/cogs/cyber.py | hundred | joker314/cyberdisc-bot | 0 | python | @command()
async def hundred(self, ctx: Context):
'\n \n '
game_r = ctx.guild.get_role(HUNDRED_PERCENT_ROLE_ID)
true_r = ctx.guild.get_role(TRUE_HUNDRED_PERCENT_ROLE_ID)
(await ctx.send(f'There are {len(game_r.members)} that have completed Cyberstart Game. Out of them, {len(true_r.members)} have also completed Essentials and Assess.')) | @command()
async def hundred(self, ctx: Context):
'\n \n '
game_r = ctx.guild.get_role(HUNDRED_PERCENT_ROLE_ID)
true_r = ctx.guild.get_role(TRUE_HUNDRED_PERCENT_ROLE_ID)
(await ctx.send(f'There are {len(game_r.members)} that have completed Cyberstart Game. Out of them, {len(true_r.members)} have also completed Essentials and Assess.'))<|docstring|>Gets the number of 100% and true 100% users<|endoftext|> |
8cd255e725eef69fff43038252b44834838a80fc238f5a8ec8211ec087e15948 | @command()
async def elitecount(self, ctx: Context):
'\n Gets the number of elite users\n '
elite_r = ctx.guild.get_role(ELITE_ROLE_ID)
ldn_y_r = ctx.guild.get_role(ELITE_LDN_YNG_ROLE_ID)
ldn_o_r = ctx.guild.get_role(ELITE_LDN_OLD_ROLE_ID)
brm_y_r = ctx.guild.get_role(ELITE_BRM_YNG_ROLE_ID)
brm_o_r = ctx.guild.get_role(ELITE_BRM_OLD_ROLE_ID)
lan_y_r = ctx.guild.get_role(ELITE_LAN_YNG_ROLE_ID)
lan_o_r = ctx.guild.get_role(ELITE_LAN_OLD_ROLE_ID)
exch_l_r = ctx.guild.get_role(ELITE_EXCH_LIST_ROLE_ID)
exch_c_r = ctx.guild.get_role(ELITE_EXCH_CONF_ROLE_ID)
(await ctx.send(f'''There are {len(elite_r.members)} server members that have qualified for CyberStart Elite.
{len(exch_l_r.members)} members have qualified for Exchange ({len(exch_c_r.members)} confirmed).
Of those who didn't, preferences have been expressed as follows:
London - Younger: {len(ldn_y_r.members)}
London - Older: {len(ldn_o_r.members)}
Birmingham - Younger: {len(brm_y_r.members)}
Birmingham - Older: {len(brm_o_r.members)}
Lancaster - Younger: {len(lan_y_r.members)}
Lancaster - Older: {len(lan_o_r.members)}
''')) | Gets the number of elite users | cdbot/cogs/cyber.py | elitecount | joker314/cyberdisc-bot | 0 | python | @command()
async def elitecount(self, ctx: Context):
'\n \n '
elite_r = ctx.guild.get_role(ELITE_ROLE_ID)
ldn_y_r = ctx.guild.get_role(ELITE_LDN_YNG_ROLE_ID)
ldn_o_r = ctx.guild.get_role(ELITE_LDN_OLD_ROLE_ID)
brm_y_r = ctx.guild.get_role(ELITE_BRM_YNG_ROLE_ID)
brm_o_r = ctx.guild.get_role(ELITE_BRM_OLD_ROLE_ID)
lan_y_r = ctx.guild.get_role(ELITE_LAN_YNG_ROLE_ID)
lan_o_r = ctx.guild.get_role(ELITE_LAN_OLD_ROLE_ID)
exch_l_r = ctx.guild.get_role(ELITE_EXCH_LIST_ROLE_ID)
exch_c_r = ctx.guild.get_role(ELITE_EXCH_CONF_ROLE_ID)
(await ctx.send(f'There are {len(elite_r.members)} server members that have qualified for CyberStart Elite.
{len(exch_l_r.members)} members have qualified for Exchange ({len(exch_c_r.members)} confirmed).
Of those who didn't, preferences have been expressed as follows:
London - Younger: {len(ldn_y_r.members)}
London - Older: {len(ldn_o_r.members)}
Birmingham - Younger: {len(brm_y_r.members)}
Birmingham - Older: {len(brm_o_r.members)}
Lancaster - Younger: {len(lan_y_r.members)}
Lancaster - Older: {len(lan_o_r.members)}
')) | @command()
async def elitecount(self, ctx: Context):
'\n \n '
elite_r = ctx.guild.get_role(ELITE_ROLE_ID)
ldn_y_r = ctx.guild.get_role(ELITE_LDN_YNG_ROLE_ID)
ldn_o_r = ctx.guild.get_role(ELITE_LDN_OLD_ROLE_ID)
brm_y_r = ctx.guild.get_role(ELITE_BRM_YNG_ROLE_ID)
brm_o_r = ctx.guild.get_role(ELITE_BRM_OLD_ROLE_ID)
lan_y_r = ctx.guild.get_role(ELITE_LAN_YNG_ROLE_ID)
lan_o_r = ctx.guild.get_role(ELITE_LAN_OLD_ROLE_ID)
exch_l_r = ctx.guild.get_role(ELITE_EXCH_LIST_ROLE_ID)
exch_c_r = ctx.guild.get_role(ELITE_EXCH_CONF_ROLE_ID)
(await ctx.send(f'There are {len(elite_r.members)} server members that have qualified for CyberStart Elite.
{len(exch_l_r.members)} members have qualified for Exchange ({len(exch_c_r.members)} confirmed).
Of those who didn't, preferences have been expressed as follows:
London - Younger: {len(ldn_y_r.members)}
London - Older: {len(ldn_o_r.members)}
Birmingham - Younger: {len(brm_y_r.members)}
Birmingham - Older: {len(brm_o_r.members)}
Lancaster - Younger: {len(lan_y_r.members)}
Lancaster - Older: {len(lan_o_r.members)}
'))<|docstring|>Gets the number of elite users<|endoftext|> |
99d9aa3ba33b461a172eb90ab4a92710d94585c4dfc3e70e2eaa8dea094e5764 | @trace.traceable
def TransformedRandomVariable(rv, reversible_layer, name=None, sample_shape=(), value=None):
'Random variable for f(x), where x ~ p(x) and f is reversible.'
return random_variable.RandomVariable(distribution=TransformedDistribution(rv.distribution, reversible_layer, name=name), sample_shape=sample_shape, value=value) | Random variable for f(x), where x ~ p(x) and f is reversible. | edward2/tensorflow/transformed_random_variable.py | TransformedRandomVariable | google/edward2 | 591 | python | @trace.traceable
def TransformedRandomVariable(rv, reversible_layer, name=None, sample_shape=(), value=None):
return random_variable.RandomVariable(distribution=TransformedDistribution(rv.distribution, reversible_layer, name=name), sample_shape=sample_shape, value=value) | @trace.traceable
def TransformedRandomVariable(rv, reversible_layer, name=None, sample_shape=(), value=None):
return random_variable.RandomVariable(distribution=TransformedDistribution(rv.distribution, reversible_layer, name=name), sample_shape=sample_shape, value=value)<|docstring|>Random variable for f(x), where x ~ p(x) and f is reversible.<|endoftext|> |
3f41fa566f02150a445e0b3ea0b09d7b2f62dce6c186e1d1a6ed084792ed47c5 | def __init__(self, base, reversible_layer, name=None):
'Constructs a transformed distribution.\n\n Args:\n base: Base distribution.\n reversible_layer: Callable with methods `reverse` and `log_det_jacobian`.\n name: Name for scoping operations in the class.\n '
self.base = base
self.reversible_layer = reversible_layer
if (name is None):
name = (reversible_layer.name + base.name)
super(TransformedDistribution, self).__init__(base.dtype, base.reparameterization_type, base.validate_args, base.allow_nan_stats, parameters=dict(locals()), name=name) | Constructs a transformed distribution.
Args:
base: Base distribution.
reversible_layer: Callable with methods `reverse` and `log_det_jacobian`.
name: Name for scoping operations in the class. | edward2/tensorflow/transformed_random_variable.py | __init__ | google/edward2 | 591 | python | def __init__(self, base, reversible_layer, name=None):
'Constructs a transformed distribution.\n\n Args:\n base: Base distribution.\n reversible_layer: Callable with methods `reverse` and `log_det_jacobian`.\n name: Name for scoping operations in the class.\n '
self.base = base
self.reversible_layer = reversible_layer
if (name is None):
name = (reversible_layer.name + base.name)
super(TransformedDistribution, self).__init__(base.dtype, base.reparameterization_type, base.validate_args, base.allow_nan_stats, parameters=dict(locals()), name=name) | def __init__(self, base, reversible_layer, name=None):
'Constructs a transformed distribution.\n\n Args:\n base: Base distribution.\n reversible_layer: Callable with methods `reverse` and `log_det_jacobian`.\n name: Name for scoping operations in the class.\n '
self.base = base
self.reversible_layer = reversible_layer
if (name is None):
name = (reversible_layer.name + base.name)
super(TransformedDistribution, self).__init__(base.dtype, base.reparameterization_type, base.validate_args, base.allow_nan_stats, parameters=dict(locals()), name=name)<|docstring|>Constructs a transformed distribution.
Args:
base: Base distribution.
reversible_layer: Callable with methods `reverse` and `log_det_jacobian`.
name: Name for scoping operations in the class.<|endoftext|> |
2b522838e4f512b15bb06d1c5f97b8fcb41acd8ef5d65a8f65775686479bc5b8 | def _flush(self):
'Overloaded by Shelve implementation.'
pass | Overloaded by Shelve implementation. | wsgidav/lock_storage.py | _flush | kalemas/wsgidav | 547 | python | def _flush(self):
pass | def _flush(self):
pass<|docstring|>Overloaded by Shelve implementation.<|endoftext|> |
3dcbab1fdae85840a194a297795b93c280df551ead433742e6d288026120a021 | def open(self):
'Called before first use.\n\n May be implemented to initialize a storage.\n '
assert (self._dict is None)
self._dict = {} | Called before first use.
May be implemented to initialize a storage. | wsgidav/lock_storage.py | open | kalemas/wsgidav | 547 | python | def open(self):
'Called before first use.\n\n May be implemented to initialize a storage.\n '
assert (self._dict is None)
self._dict = {} | def open(self):
'Called before first use.\n\n May be implemented to initialize a storage.\n '
assert (self._dict is None)
self._dict = {}<|docstring|>Called before first use.
May be implemented to initialize a storage.<|endoftext|> |
9c0cf24447ab66a1931b3284411c43919190b1097917fc454a767c235f717d90 | def close(self):
'Called on shutdown.'
self._dict = None | Called on shutdown. | wsgidav/lock_storage.py | close | kalemas/wsgidav | 547 | python | def close(self):
self._dict = None | def close(self):
self._dict = None<|docstring|>Called on shutdown.<|endoftext|> |
15e41b754184e3b62148b9b32a38c5899e73e98cf952fb0c71a44a28e2ff1e5c | def cleanup(self):
'Purge expired locks (optional).'
pass | Purge expired locks (optional). | wsgidav/lock_storage.py | cleanup | kalemas/wsgidav | 547 | python | def cleanup(self):
pass | def cleanup(self):
pass<|docstring|>Purge expired locks (optional).<|endoftext|> |
04c0e03b260edb6cbb6bfd9a25d307c031b9e03c8205e04d4b4fa787a7a802c1 | def clear(self):
'Delete all entries.'
if (self._dict is not None):
self._dict.clear() | Delete all entries. | wsgidav/lock_storage.py | clear | kalemas/wsgidav | 547 | python | def clear(self):
if (self._dict is not None):
self._dict.clear() | def clear(self):
if (self._dict is not None):
self._dict.clear()<|docstring|>Delete all entries.<|endoftext|> |
90870515571cd44690de9605a8552d942c332133479d1b228e663b067dbabb97 | def get(self, token):
'Return a lock dictionary for a token.\n\n If the lock does not exist or is expired, None is returned.\n\n token:\n lock token\n Returns:\n Lock dictionary or <None>\n\n Side effect: if lock is expired, it will be purged and None is returned.\n '
self._lock.acquire_read()
try:
lock = self._dict.get(token)
if (lock is None):
_logger.debug('Lock purged dangling: {}'.format(token))
self.delete(token)
return None
expire = float(lock['expire'])
if ((expire >= 0) and (expire < time.time())):
_logger.debug('Lock timed-out({}): {}'.format(expire, lock_string(lock)))
self.delete(token)
return None
return lock
finally:
self._lock.release() | Return a lock dictionary for a token.
If the lock does not exist or is expired, None is returned.
token:
lock token
Returns:
Lock dictionary or <None>
Side effect: if lock is expired, it will be purged and None is returned. | wsgidav/lock_storage.py | get | kalemas/wsgidav | 547 | python | def get(self, token):
'Return a lock dictionary for a token.\n\n If the lock does not exist or is expired, None is returned.\n\n token:\n lock token\n Returns:\n Lock dictionary or <None>\n\n Side effect: if lock is expired, it will be purged and None is returned.\n '
self._lock.acquire_read()
try:
lock = self._dict.get(token)
if (lock is None):
_logger.debug('Lock purged dangling: {}'.format(token))
self.delete(token)
return None
expire = float(lock['expire'])
if ((expire >= 0) and (expire < time.time())):
_logger.debug('Lock timed-out({}): {}'.format(expire, lock_string(lock)))
self.delete(token)
return None
return lock
finally:
self._lock.release() | def get(self, token):
'Return a lock dictionary for a token.\n\n If the lock does not exist or is expired, None is returned.\n\n token:\n lock token\n Returns:\n Lock dictionary or <None>\n\n Side effect: if lock is expired, it will be purged and None is returned.\n '
self._lock.acquire_read()
try:
lock = self._dict.get(token)
if (lock is None):
_logger.debug('Lock purged dangling: {}'.format(token))
self.delete(token)
return None
expire = float(lock['expire'])
if ((expire >= 0) and (expire < time.time())):
_logger.debug('Lock timed-out({}): {}'.format(expire, lock_string(lock)))
self.delete(token)
return None
return lock
finally:
self._lock.release()<|docstring|>Return a lock dictionary for a token.
If the lock does not exist or is expired, None is returned.
token:
lock token
Returns:
Lock dictionary or <None>
Side effect: if lock is expired, it will be purged and None is returned.<|endoftext|> |
b228bc898c8d398bb5cea016ff164db888684de4b4654599172c6b8e6128bfbd | def create(self, path, lock):
"Create a direct lock for a resource path.\n\n path:\n Normalized path (utf8 encoded string, no trailing '/')\n lock:\n lock dictionary, without a token entry\n Returns:\n New unique lock token.: <lock\n\n **Note:** the lock dictionary may be modified on return:\n\n - lock['root'] is ignored and set to the normalized <path>\n - lock['timeout'] may be normalized and shorter than requested\n - lock['token'] is added\n "
self._lock.acquire_write()
try:
assert (lock.get('token') is None)
assert (lock.get('expire') is None), 'Use timeout instead of expire'
assert (path and ('/' in path))
org_path = path
path = normalize_lock_root(path)
lock['root'] = path
timeout = float(lock.get('timeout'))
if (timeout is None):
timeout = LockStorageDict.LOCK_TIME_OUT_DEFAULT
elif ((timeout < 0) or (timeout > LockStorageDict.LOCK_TIME_OUT_MAX)):
timeout = LockStorageDict.LOCK_TIME_OUT_MAX
lock['timeout'] = timeout
lock['expire'] = (time.time() + timeout)
validate_lock(lock)
token = generate_lock_token()
lock['token'] = token
self._dict[token] = lock
key = 'URL2TOKEN:{}'.format(path)
if (key not in self._dict):
self._dict[key] = [token]
else:
tokList = self._dict[key]
tokList.append(token)
self._dict[key] = tokList
self._flush()
_logger.debug('LockStorageDict.set({!r}): {}'.format(org_path, lock_string(lock)))
return lock
finally:
self._lock.release() | Create a direct lock for a resource path.
path:
Normalized path (utf8 encoded string, no trailing '/')
lock:
lock dictionary, without a token entry
Returns:
New unique lock token.: <lock
**Note:** the lock dictionary may be modified on return:
- lock['root'] is ignored and set to the normalized <path>
- lock['timeout'] may be normalized and shorter than requested
- lock['token'] is added | wsgidav/lock_storage.py | create | kalemas/wsgidav | 547 | python | def create(self, path, lock):
"Create a direct lock for a resource path.\n\n path:\n Normalized path (utf8 encoded string, no trailing '/')\n lock:\n lock dictionary, without a token entry\n Returns:\n New unique lock token.: <lock\n\n **Note:** the lock dictionary may be modified on return:\n\n - lock['root'] is ignored and set to the normalized <path>\n - lock['timeout'] may be normalized and shorter than requested\n - lock['token'] is added\n "
self._lock.acquire_write()
try:
assert (lock.get('token') is None)
assert (lock.get('expire') is None), 'Use timeout instead of expire'
assert (path and ('/' in path))
org_path = path
path = normalize_lock_root(path)
lock['root'] = path
timeout = float(lock.get('timeout'))
if (timeout is None):
timeout = LockStorageDict.LOCK_TIME_OUT_DEFAULT
elif ((timeout < 0) or (timeout > LockStorageDict.LOCK_TIME_OUT_MAX)):
timeout = LockStorageDict.LOCK_TIME_OUT_MAX
lock['timeout'] = timeout
lock['expire'] = (time.time() + timeout)
validate_lock(lock)
token = generate_lock_token()
lock['token'] = token
self._dict[token] = lock
key = 'URL2TOKEN:{}'.format(path)
if (key not in self._dict):
self._dict[key] = [token]
else:
tokList = self._dict[key]
tokList.append(token)
self._dict[key] = tokList
self._flush()
_logger.debug('LockStorageDict.set({!r}): {}'.format(org_path, lock_string(lock)))
return lock
finally:
self._lock.release() | def create(self, path, lock):
"Create a direct lock for a resource path.\n\n path:\n Normalized path (utf8 encoded string, no trailing '/')\n lock:\n lock dictionary, without a token entry\n Returns:\n New unique lock token.: <lock\n\n **Note:** the lock dictionary may be modified on return:\n\n - lock['root'] is ignored and set to the normalized <path>\n - lock['timeout'] may be normalized and shorter than requested\n - lock['token'] is added\n "
self._lock.acquire_write()
try:
assert (lock.get('token') is None)
assert (lock.get('expire') is None), 'Use timeout instead of expire'
assert (path and ('/' in path))
org_path = path
path = normalize_lock_root(path)
lock['root'] = path
timeout = float(lock.get('timeout'))
if (timeout is None):
timeout = LockStorageDict.LOCK_TIME_OUT_DEFAULT
elif ((timeout < 0) or (timeout > LockStorageDict.LOCK_TIME_OUT_MAX)):
timeout = LockStorageDict.LOCK_TIME_OUT_MAX
lock['timeout'] = timeout
lock['expire'] = (time.time() + timeout)
validate_lock(lock)
token = generate_lock_token()
lock['token'] = token
self._dict[token] = lock
key = 'URL2TOKEN:{}'.format(path)
if (key not in self._dict):
self._dict[key] = [token]
else:
tokList = self._dict[key]
tokList.append(token)
self._dict[key] = tokList
self._flush()
_logger.debug('LockStorageDict.set({!r}): {}'.format(org_path, lock_string(lock)))
return lock
finally:
self._lock.release()<|docstring|>Create a direct lock for a resource path.
path:
Normalized path (utf8 encoded string, no trailing '/')
lock:
lock dictionary, without a token entry
Returns:
New unique lock token.: <lock
**Note:** the lock dictionary may be modified on return:
- lock['root'] is ignored and set to the normalized <path>
- lock['timeout'] may be normalized and shorter than requested
- lock['token'] is added<|endoftext|> |
e5f522136a51784baa4222a3f43f50d09de4fafbe6c091df6b2f56ffd9b5f585 | def refresh(self, token, timeout):
"Modify an existing lock's timeout.\n\n token:\n Valid lock token.\n timeout:\n Suggested lifetime in seconds (-1 for infinite).\n The real expiration time may be shorter than requested!\n Returns:\n Lock dictionary.\n Raises ValueError, if token is invalid.\n "
assert (token in self._dict), 'Lock must exist'
assert ((timeout == (- 1)) or (timeout > 0))
if ((timeout < 0) or (timeout > LockStorageDict.LOCK_TIME_OUT_MAX)):
timeout = LockStorageDict.LOCK_TIME_OUT_MAX
self._lock.acquire_write()
try:
lock = self._dict[token]
lock['timeout'] = timeout
lock['expire'] = (time.time() + timeout)
self._dict[token] = lock
self._flush()
finally:
self._lock.release()
return lock | Modify an existing lock's timeout.
token:
Valid lock token.
timeout:
Suggested lifetime in seconds (-1 for infinite).
The real expiration time may be shorter than requested!
Returns:
Lock dictionary.
Raises ValueError, if token is invalid. | wsgidav/lock_storage.py | refresh | kalemas/wsgidav | 547 | python | def refresh(self, token, timeout):
"Modify an existing lock's timeout.\n\n token:\n Valid lock token.\n timeout:\n Suggested lifetime in seconds (-1 for infinite).\n The real expiration time may be shorter than requested!\n Returns:\n Lock dictionary.\n Raises ValueError, if token is invalid.\n "
assert (token in self._dict), 'Lock must exist'
assert ((timeout == (- 1)) or (timeout > 0))
if ((timeout < 0) or (timeout > LockStorageDict.LOCK_TIME_OUT_MAX)):
timeout = LockStorageDict.LOCK_TIME_OUT_MAX
self._lock.acquire_write()
try:
lock = self._dict[token]
lock['timeout'] = timeout
lock['expire'] = (time.time() + timeout)
self._dict[token] = lock
self._flush()
finally:
self._lock.release()
return lock | def refresh(self, token, timeout):
"Modify an existing lock's timeout.\n\n token:\n Valid lock token.\n timeout:\n Suggested lifetime in seconds (-1 for infinite).\n The real expiration time may be shorter than requested!\n Returns:\n Lock dictionary.\n Raises ValueError, if token is invalid.\n "
assert (token in self._dict), 'Lock must exist'
assert ((timeout == (- 1)) or (timeout > 0))
if ((timeout < 0) or (timeout > LockStorageDict.LOCK_TIME_OUT_MAX)):
timeout = LockStorageDict.LOCK_TIME_OUT_MAX
self._lock.acquire_write()
try:
lock = self._dict[token]
lock['timeout'] = timeout
lock['expire'] = (time.time() + timeout)
self._dict[token] = lock
self._flush()
finally:
self._lock.release()
return lock<|docstring|>Modify an existing lock's timeout.
token:
Valid lock token.
timeout:
Suggested lifetime in seconds (-1 for infinite).
The real expiration time may be shorter than requested!
Returns:
Lock dictionary.
Raises ValueError, if token is invalid.<|endoftext|> |
08b80d182bd2b05d4d25485accab21452db9803787667e84ea3cd66677738d61 | def delete(self, token):
'Delete lock.\n\n Returns True on success. False, if token does not exist, or is expired.\n '
self._lock.acquire_write()
try:
lock = self._dict.get(token)
_logger.debug('delete {}'.format(lock_string(lock)))
if (lock is None):
return False
key = 'URL2TOKEN:{}'.format(lock.get('root'))
if (key in self._dict):
tokList = self._dict[key]
if (len(tokList) > 1):
tokList.remove(token)
self._dict[key] = tokList
else:
del self._dict[key]
del self._dict[token]
self._flush()
finally:
self._lock.release()
return True | Delete lock.
Returns True on success. False, if token does not exist, or is expired. | wsgidav/lock_storage.py | delete | kalemas/wsgidav | 547 | python | def delete(self, token):
'Delete lock.\n\n Returns True on success. False, if token does not exist, or is expired.\n '
self._lock.acquire_write()
try:
lock = self._dict.get(token)
_logger.debug('delete {}'.format(lock_string(lock)))
if (lock is None):
return False
key = 'URL2TOKEN:{}'.format(lock.get('root'))
if (key in self._dict):
tokList = self._dict[key]
if (len(tokList) > 1):
tokList.remove(token)
self._dict[key] = tokList
else:
del self._dict[key]
del self._dict[token]
self._flush()
finally:
self._lock.release()
return True | def delete(self, token):
'Delete lock.\n\n Returns True on success. False, if token does not exist, or is expired.\n '
self._lock.acquire_write()
try:
lock = self._dict.get(token)
_logger.debug('delete {}'.format(lock_string(lock)))
if (lock is None):
return False
key = 'URL2TOKEN:{}'.format(lock.get('root'))
if (key in self._dict):
tokList = self._dict[key]
if (len(tokList) > 1):
tokList.remove(token)
self._dict[key] = tokList
else:
del self._dict[key]
del self._dict[token]
self._flush()
finally:
self._lock.release()
return True<|docstring|>Delete lock.
Returns True on success. False, if token does not exist, or is expired.<|endoftext|> |
8c0b439e0f24f6f98d98836a9ce63c9f433a167ea119646f83598118b4216eff | def get_lock_list(self, path, include_root, include_children, token_only):
"Return a list of direct locks for <path>.\n\n Expired locks are *not* returned (but may be purged).\n\n path:\n Normalized path (utf8 encoded string, no trailing '/')\n include_root:\n False: don't add <path> lock (only makes sense, when include_children\n is True).\n include_children:\n True: Also check all sub-paths for existing locks.\n token_only:\n True: only a list of token is returned. This may be implemented\n more efficiently by some providers.\n Returns:\n List of valid lock dictionaries (may be empty).\n "
assert compat.is_native(path)
assert (path and path.startswith('/'))
assert (include_root or include_children)
def __appendLocks(toklist):
for token in toklist:
lock = self.get(token)
if lock:
if token_only:
lockList.append(lock['token'])
else:
lockList.append(lock)
path = normalize_lock_root(path)
self._lock.acquire_read()
try:
key = 'URL2TOKEN:{}'.format(path)
tokList = self._dict.get(key, [])
lockList = []
if include_root:
__appendLocks(tokList)
if include_children:
for (u, ltoks) in self._dict.items():
if util.is_child_uri(key, u):
__appendLocks(ltoks)
return lockList
finally:
self._lock.release() | Return a list of direct locks for <path>.
Expired locks are *not* returned (but may be purged).
path:
Normalized path (utf8 encoded string, no trailing '/')
include_root:
False: don't add <path> lock (only makes sense, when include_children
is True).
include_children:
True: Also check all sub-paths for existing locks.
token_only:
True: only a list of token is returned. This may be implemented
more efficiently by some providers.
Returns:
List of valid lock dictionaries (may be empty). | wsgidav/lock_storage.py | get_lock_list | kalemas/wsgidav | 547 | python | def get_lock_list(self, path, include_root, include_children, token_only):
"Return a list of direct locks for <path>.\n\n Expired locks are *not* returned (but may be purged).\n\n path:\n Normalized path (utf8 encoded string, no trailing '/')\n include_root:\n False: don't add <path> lock (only makes sense, when include_children\n is True).\n include_children:\n True: Also check all sub-paths for existing locks.\n token_only:\n True: only a list of token is returned. This may be implemented\n more efficiently by some providers.\n Returns:\n List of valid lock dictionaries (may be empty).\n "
assert compat.is_native(path)
assert (path and path.startswith('/'))
assert (include_root or include_children)
def __appendLocks(toklist):
for token in toklist:
lock = self.get(token)
if lock:
if token_only:
lockList.append(lock['token'])
else:
lockList.append(lock)
path = normalize_lock_root(path)
self._lock.acquire_read()
try:
key = 'URL2TOKEN:{}'.format(path)
tokList = self._dict.get(key, [])
lockList = []
if include_root:
__appendLocks(tokList)
if include_children:
for (u, ltoks) in self._dict.items():
if util.is_child_uri(key, u):
__appendLocks(ltoks)
return lockList
finally:
self._lock.release() | def get_lock_list(self, path, include_root, include_children, token_only):
"Return a list of direct locks for <path>.\n\n Expired locks are *not* returned (but may be purged).\n\n path:\n Normalized path (utf8 encoded string, no trailing '/')\n include_root:\n False: don't add <path> lock (only makes sense, when include_children\n is True).\n include_children:\n True: Also check all sub-paths for existing locks.\n token_only:\n True: only a list of token is returned. This may be implemented\n more efficiently by some providers.\n Returns:\n List of valid lock dictionaries (may be empty).\n "
assert compat.is_native(path)
assert (path and path.startswith('/'))
assert (include_root or include_children)
def __appendLocks(toklist):
for token in toklist:
lock = self.get(token)
if lock:
if token_only:
lockList.append(lock['token'])
else:
lockList.append(lock)
path = normalize_lock_root(path)
self._lock.acquire_read()
try:
key = 'URL2TOKEN:{}'.format(path)
tokList = self._dict.get(key, [])
lockList = []
if include_root:
__appendLocks(tokList)
if include_children:
for (u, ltoks) in self._dict.items():
if util.is_child_uri(key, u):
__appendLocks(ltoks)
return lockList
finally:
self._lock.release()<|docstring|>Return a list of direct locks for <path>.
Expired locks are *not* returned (but may be purged).
path:
Normalized path (utf8 encoded string, no trailing '/')
include_root:
False: don't add <path> lock (only makes sense, when include_children
is True).
include_children:
True: Also check all sub-paths for existing locks.
token_only:
True: only a list of token is returned. This may be implemented
more efficiently by some providers.
Returns:
List of valid lock dictionaries (may be empty).<|endoftext|> |
2ba2f6609959a598b45f23acfab8d942d027cdc021dc0da134ed9b69f9b0bde1 | def _flush(self):
'Write persistent dictionary to disc.'
_logger.debug('_flush()')
self._lock.acquire_write()
try:
self._dict.sync()
finally:
self._lock.release() | Write persistent dictionary to disc. | wsgidav/lock_storage.py | _flush | kalemas/wsgidav | 547 | python | def _flush(self):
_logger.debug('_flush()')
self._lock.acquire_write()
try:
self._dict.sync()
finally:
self._lock.release() | def _flush(self):
_logger.debug('_flush()')
self._lock.acquire_write()
try:
self._dict.sync()
finally:
self._lock.release()<|docstring|>Write persistent dictionary to disc.<|endoftext|> |
3c72fc796a31200a96d737a4de44c0f97656731955a3569982b2cf3ea7d80dfd | def clear(self):
'Delete all entries.'
self._lock.acquire_write()
try:
was_closed = (self._dict is None)
if was_closed:
self.open()
if len(self._dict):
self._dict.clear()
self._dict.sync()
if was_closed:
self.close()
finally:
self._lock.release() | Delete all entries. | wsgidav/lock_storage.py | clear | kalemas/wsgidav | 547 | python | def clear(self):
self._lock.acquire_write()
try:
was_closed = (self._dict is None)
if was_closed:
self.open()
if len(self._dict):
self._dict.clear()
self._dict.sync()
if was_closed:
self.close()
finally:
self._lock.release() | def clear(self):
self._lock.acquire_write()
try:
was_closed = (self._dict is None)
if was_closed:
self.open()
if len(self._dict):
self._dict.clear()
self._dict.sync()
if was_closed:
self.close()
finally:
self._lock.release()<|docstring|>Delete all entries.<|endoftext|> |
ed82d19c715156c8dcba69cd13ae129c4f4652f734e6b4ed8c0c4b0c35ff918b | def print_miles_report():
'\n Complexity: Big O(n)\n Print a report which lists the amount of miles driven by each truck\n '
(truck1_miles, truck2_miles, truck3_miles) = [truck.route.get_miles() for truck in cfg.trucks]
print(f'Truck1 Miles: {truck1_miles}')
print(f'Truck2 Miles: {truck2_miles}')
print(f'Truck3 Miles: {truck3_miles}')
print(((truck1_miles + truck2_miles) + truck3_miles)) | Complexity: Big O(n)
Print a report which lists the amount of miles driven by each truck | debug.py | print_miles_report | cohenpts/traveling_salesman | 0 | python | def print_miles_report():
'\n Complexity: Big O(n)\n Print a report which lists the amount of miles driven by each truck\n '
(truck1_miles, truck2_miles, truck3_miles) = [truck.route.get_miles() for truck in cfg.trucks]
print(f'Truck1 Miles: {truck1_miles}')
print(f'Truck2 Miles: {truck2_miles}')
print(f'Truck3 Miles: {truck3_miles}')
print(((truck1_miles + truck2_miles) + truck3_miles)) | def print_miles_report():
'\n Complexity: Big O(n)\n Print a report which lists the amount of miles driven by each truck\n '
(truck1_miles, truck2_miles, truck3_miles) = [truck.route.get_miles() for truck in cfg.trucks]
print(f'Truck1 Miles: {truck1_miles}')
print(f'Truck2 Miles: {truck2_miles}')
print(f'Truck3 Miles: {truck3_miles}')
print(((truck1_miles + truck2_miles) + truck3_miles))<|docstring|>Complexity: Big O(n)
Print a report which lists the amount of miles driven by each truck<|endoftext|> |
3a4b4050e44b14cc9698e72129488f0a67259ba10fa6e8f2931296ef41a5c353 | def print_delivery_count_by_truck():
'\n Complexity: Big O(n)\n Print a report which lists the deliveries delivered by truck.\n The total assigned and unassigned deliveries\n '
(truck1_deliveries, truck2_deliveries, truck3_deliveries) = [len(truck.get_deliveries()) for truck in cfg.trucks]
print(f'Truck1 Deliveries: {truck1_deliveries}')
print(f'Truck2 Deliveries: {truck2_deliveries}')
print(f'Truck3 Deliveries: {truck3_deliveries}')
print(f'Total Deliveries Assigned: {((truck1_deliveries + truck2_deliveries) + truck3_deliveries)}')
print(f'unassigned deliveries: {len(get_deliveries_with_unassigned_trucks())}') | Complexity: Big O(n)
Print a report which lists the deliveries delivered by truck.
The total assigned and unassigned deliveries | debug.py | print_delivery_count_by_truck | cohenpts/traveling_salesman | 0 | python | def print_delivery_count_by_truck():
'\n Complexity: Big O(n)\n Print a report which lists the deliveries delivered by truck.\n The total assigned and unassigned deliveries\n '
(truck1_deliveries, truck2_deliveries, truck3_deliveries) = [len(truck.get_deliveries()) for truck in cfg.trucks]
print(f'Truck1 Deliveries: {truck1_deliveries}')
print(f'Truck2 Deliveries: {truck2_deliveries}')
print(f'Truck3 Deliveries: {truck3_deliveries}')
print(f'Total Deliveries Assigned: {((truck1_deliveries + truck2_deliveries) + truck3_deliveries)}')
print(f'unassigned deliveries: {len(get_deliveries_with_unassigned_trucks())}') | def print_delivery_count_by_truck():
'\n Complexity: Big O(n)\n Print a report which lists the deliveries delivered by truck.\n The total assigned and unassigned deliveries\n '
(truck1_deliveries, truck2_deliveries, truck3_deliveries) = [len(truck.get_deliveries()) for truck in cfg.trucks]
print(f'Truck1 Deliveries: {truck1_deliveries}')
print(f'Truck2 Deliveries: {truck2_deliveries}')
print(f'Truck3 Deliveries: {truck3_deliveries}')
print(f'Total Deliveries Assigned: {((truck1_deliveries + truck2_deliveries) + truck3_deliveries)}')
print(f'unassigned deliveries: {len(get_deliveries_with_unassigned_trucks())}')<|docstring|>Complexity: Big O(n)
Print a report which lists the deliveries delivered by truck.
The total assigned and unassigned deliveries<|endoftext|> |
5af14a57ad88b605eb21cfcceeaf344874af3b413a23f751fa6d972ee3b6c4a7 | def print_package_count_by_truck():
'\n Complexity: Big O(n)\n Print a report which lists the amount packages assigned to each truck\n The total assigned and unassigned packages\n '
(truck1_packages, truck2_packages, truck3_packages) = [len(truck.get_packages()) for truck in cfg.trucks]
print(f'Truck1 packages: {truck1_packages}')
print(f'Truck2 packages: {truck2_packages}')
print(f'Truck3 packages: {truck3_packages}')
print(f'Total packages Assigned: {((truck1_packages + truck2_packages) + truck3_packages)}')
print(f'unassigned packages: {len(get_packages_with_unassigned_trucks())}') | Complexity: Big O(n)
Print a report which lists the amount packages assigned to each truck
The total assigned and unassigned packages | debug.py | print_package_count_by_truck | cohenpts/traveling_salesman | 0 | python | def print_package_count_by_truck():
'\n Complexity: Big O(n)\n Print a report which lists the amount packages assigned to each truck\n The total assigned and unassigned packages\n '
(truck1_packages, truck2_packages, truck3_packages) = [len(truck.get_packages()) for truck in cfg.trucks]
print(f'Truck1 packages: {truck1_packages}')
print(f'Truck2 packages: {truck2_packages}')
print(f'Truck3 packages: {truck3_packages}')
print(f'Total packages Assigned: {((truck1_packages + truck2_packages) + truck3_packages)}')
print(f'unassigned packages: {len(get_packages_with_unassigned_trucks())}') | def print_package_count_by_truck():
'\n Complexity: Big O(n)\n Print a report which lists the amount packages assigned to each truck\n The total assigned and unassigned packages\n '
(truck1_packages, truck2_packages, truck3_packages) = [len(truck.get_packages()) for truck in cfg.trucks]
print(f'Truck1 packages: {truck1_packages}')
print(f'Truck2 packages: {truck2_packages}')
print(f'Truck3 packages: {truck3_packages}')
print(f'Total packages Assigned: {((truck1_packages + truck2_packages) + truck3_packages)}')
print(f'unassigned packages: {len(get_packages_with_unassigned_trucks())}')<|docstring|>Complexity: Big O(n)
Print a report which lists the amount packages assigned to each truck
The total assigned and unassigned packages<|endoftext|> |
c21748eac892e90ac566b4f7698afb5c27f93e5cff08144a7dac77119caac5c8 | def print_package_table():
'\n Complexity: Big O(n)\n Print a Table which lists the id, address, truck assigned, deadline and any notes of each package\n '
print('___________________________________________________________________')
print('____________________________PACKAGES_______________________________')
print('id | Address | Truck | Deadline | Notes | Time Delivered ')
for package in cfg.packages:
package_id = '{:<2}'.format(package.id)
package_address = '{:<38}'.format(package.location.address)
package_truck = ('{:<10}'.format(package.assigned_truck) if (package.assigned_truck is not None) else 'unassigned')
package_deadline = package.deadline.strftime('%H:%M %p')
package_notes = ('{:<20}'.format(package.notes) if (package.notes is not False) else '{:<20}'.format('N/A'))
delivery = get_delivery_from_package_id(package.id)
if (delivery is not None):
delivery_time = (delivery.delivered_time if (delivery.delivered_time is not None) else 'undelivered')
else:
delivery_time = 'undelivered'
print(f'{package_id} | {package_address} | {package_truck} | {package_deadline} | {package_notes} | {delivery_time} ') | Complexity: Big O(n)
Print a Table which lists the id, address, truck assigned, deadline and any notes of each package | debug.py | print_package_table | cohenpts/traveling_salesman | 0 | python | def print_package_table():
'\n Complexity: Big O(n)\n Print a Table which lists the id, address, truck assigned, deadline and any notes of each package\n '
print('___________________________________________________________________')
print('____________________________PACKAGES_______________________________')
print('id | Address | Truck | Deadline | Notes | Time Delivered ')
for package in cfg.packages:
package_id = '{:<2}'.format(package.id)
package_address = '{:<38}'.format(package.location.address)
package_truck = ('{:<10}'.format(package.assigned_truck) if (package.assigned_truck is not None) else 'unassigned')
package_deadline = package.deadline.strftime('%H:%M %p')
package_notes = ('{:<20}'.format(package.notes) if (package.notes is not False) else '{:<20}'.format('N/A'))
delivery = get_delivery_from_package_id(package.id)
if (delivery is not None):
delivery_time = (delivery.delivered_time if (delivery.delivered_time is not None) else 'undelivered')
else:
delivery_time = 'undelivered'
print(f'{package_id} | {package_address} | {package_truck} | {package_deadline} | {package_notes} | {delivery_time} ') | def print_package_table():
'\n Complexity: Big O(n)\n Print a Table which lists the id, address, truck assigned, deadline and any notes of each package\n '
print('___________________________________________________________________')
print('____________________________PACKAGES_______________________________')
print('id | Address | Truck | Deadline | Notes | Time Delivered ')
for package in cfg.packages:
package_id = '{:<2}'.format(package.id)
package_address = '{:<38}'.format(package.location.address)
package_truck = ('{:<10}'.format(package.assigned_truck) if (package.assigned_truck is not None) else 'unassigned')
package_deadline = package.deadline.strftime('%H:%M %p')
package_notes = ('{:<20}'.format(package.notes) if (package.notes is not False) else '{:<20}'.format('N/A'))
delivery = get_delivery_from_package_id(package.id)
if (delivery is not None):
delivery_time = (delivery.delivered_time if (delivery.delivered_time is not None) else 'undelivered')
else:
delivery_time = 'undelivered'
print(f'{package_id} | {package_address} | {package_truck} | {package_deadline} | {package_notes} | {delivery_time} ')<|docstring|>Complexity: Big O(n)
Print a Table which lists the id, address, truck assigned, deadline and any notes of each package<|endoftext|> |
4bb98e012c382b5c431a0b2cece56cc0e1232db493a805355105d8adee498f1d | def print_delivery_table(deliveries_list):
'\n Complexity: Big O(n^2)\n Print a Table which lists the id, address, truck assigned, packages, and deadline of each delivery\n '
print('__________________________________________________________________________________________')
print('____________________________DELIVERIES____________________________________________________')
print('id | Address | Truck | packages | deadline | ETA ')
for delivery in deliveries_list:
delivery_id = '{:<2}'.format(delivery.id)
delivery_address = '{:<38}'.format(delivery.location.address)
delivery_truck = ('{:<10}'.format(delivery.assigned_truck) if (delivery.assigned_truck is not None) else 'unassigned')
packages = '{:<8}'.format(','.join([str(package.id) for package in delivery.packages]))
delivery_deadline = delivery.earliest_deadline()
delivery_ETA = '{:<8}'.format(str(delivery.ETA))
print(f'{delivery_id} | {delivery_address} | {delivery_truck} | {packages} | {delivery_deadline} | {delivery_ETA}')
print('_____________________________________________________________________') | Complexity: Big O(n^2)
Print a Table which lists the id, address, truck assigned, packages, and deadline of each delivery | debug.py | print_delivery_table | cohenpts/traveling_salesman | 0 | python | def print_delivery_table(deliveries_list):
'\n Complexity: Big O(n^2)\n Print a Table which lists the id, address, truck assigned, packages, and deadline of each delivery\n '
print('__________________________________________________________________________________________')
print('____________________________DELIVERIES____________________________________________________')
print('id | Address | Truck | packages | deadline | ETA ')
for delivery in deliveries_list:
delivery_id = '{:<2}'.format(delivery.id)
delivery_address = '{:<38}'.format(delivery.location.address)
delivery_truck = ('{:<10}'.format(delivery.assigned_truck) if (delivery.assigned_truck is not None) else 'unassigned')
packages = '{:<8}'.format(','.join([str(package.id) for package in delivery.packages]))
delivery_deadline = delivery.earliest_deadline()
delivery_ETA = '{:<8}'.format(str(delivery.ETA))
print(f'{delivery_id} | {delivery_address} | {delivery_truck} | {packages} | {delivery_deadline} | {delivery_ETA}')
print('_____________________________________________________________________') | def print_delivery_table(deliveries_list):
'\n Complexity: Big O(n^2)\n Print a Table which lists the id, address, truck assigned, packages, and deadline of each delivery\n '
print('__________________________________________________________________________________________')
print('____________________________DELIVERIES____________________________________________________')
print('id | Address | Truck | packages | deadline | ETA ')
for delivery in deliveries_list:
delivery_id = '{:<2}'.format(delivery.id)
delivery_address = '{:<38}'.format(delivery.location.address)
delivery_truck = ('{:<10}'.format(delivery.assigned_truck) if (delivery.assigned_truck is not None) else 'unassigned')
packages = '{:<8}'.format(','.join([str(package.id) for package in delivery.packages]))
delivery_deadline = delivery.earliest_deadline()
delivery_ETA = '{:<8}'.format(str(delivery.ETA))
print(f'{delivery_id} | {delivery_address} | {delivery_truck} | {packages} | {delivery_deadline} | {delivery_ETA}')
print('_____________________________________________________________________')<|docstring|>Complexity: Big O(n^2)
Print a Table which lists the id, address, truck assigned, packages, and deadline of each delivery<|endoftext|> |
aca75fcd281f639e189a6d2d8ff8f9ed7d5a58067cfdc541393ba7dc4074caa2 | def print_truck_table():
'\n Complexity: Big O(n^2)\n Print a Table which lists the id, current location, deliveries, packages of each truck\n '
print('____________________________________________________________________________')
print('___________________________________Trucks___________________________________')
print('id | Current Location | Deliveries | Packages | Miles|')
total_miles = 0
for truck in cfg.trucks:
truck_id = '{:<2}'.format(truck.id)
truck_location = '{:<38}'.format(truck.route._current_location.address)
deliveries_assigned = '{:<10}'.format(len(truck.route.deliveries))
packages_assigned = '{:<8}'.format(sum((len(delivery.packages) for delivery in truck.route.deliveries)))
miles = round(truck.route.get_miles(), 2)
if (truck.id == 2):
miles += get_distance(truck.route._route[(- 1)].address, cfg.starting_location.address)
total_miles += miles
print(f'{truck_id} | {truck_location} | {deliveries_assigned} | {packages_assigned} | {miles} |')
print(f'_________________________________________________________Total Miles: {round(total_miles, 2)} |')
print('____________________________________________________________________________') | Complexity: Big O(n^2)
Print a Table which lists the id, current location, deliveries, packages of each truck | debug.py | print_truck_table | cohenpts/traveling_salesman | 0 | python | def print_truck_table():
'\n Complexity: Big O(n^2)\n Print a Table which lists the id, current location, deliveries, packages of each truck\n '
print('____________________________________________________________________________')
print('___________________________________Trucks___________________________________')
print('id | Current Location | Deliveries | Packages | Miles|')
total_miles = 0
for truck in cfg.trucks:
truck_id = '{:<2}'.format(truck.id)
truck_location = '{:<38}'.format(truck.route._current_location.address)
deliveries_assigned = '{:<10}'.format(len(truck.route.deliveries))
packages_assigned = '{:<8}'.format(sum((len(delivery.packages) for delivery in truck.route.deliveries)))
miles = round(truck.route.get_miles(), 2)
if (truck.id == 2):
miles += get_distance(truck.route._route[(- 1)].address, cfg.starting_location.address)
total_miles += miles
print(f'{truck_id} | {truck_location} | {deliveries_assigned} | {packages_assigned} | {miles} |')
print(f'_________________________________________________________Total Miles: {round(total_miles, 2)} |')
print('____________________________________________________________________________') | def print_truck_table():
'\n Complexity: Big O(n^2)\n Print a Table which lists the id, current location, deliveries, packages of each truck\n '
print('____________________________________________________________________________')
print('___________________________________Trucks___________________________________')
print('id | Current Location | Deliveries | Packages | Miles|')
total_miles = 0
for truck in cfg.trucks:
truck_id = '{:<2}'.format(truck.id)
truck_location = '{:<38}'.format(truck.route._current_location.address)
deliveries_assigned = '{:<10}'.format(len(truck.route.deliveries))
packages_assigned = '{:<8}'.format(sum((len(delivery.packages) for delivery in truck.route.deliveries)))
miles = round(truck.route.get_miles(), 2)
if (truck.id == 2):
miles += get_distance(truck.route._route[(- 1)].address, cfg.starting_location.address)
total_miles += miles
print(f'{truck_id} | {truck_location} | {deliveries_assigned} | {packages_assigned} | {miles} |')
print(f'_________________________________________________________Total Miles: {round(total_miles, 2)} |')
print('____________________________________________________________________________')<|docstring|>Complexity: Big O(n^2)
Print a Table which lists the id, current location, deliveries, packages of each truck<|endoftext|> |
0a1bf16788c605e2470949687cda8c37c1f2ec479aed58ac9d2008c06a1bfd7c | def print_route_table():
'\n Complexity: Big O(n^2)\n Print list of addresses in the route assigned to each truck\n '
print('_____________________________________________________________________')
print('______________________________Routes_________________________________')
for truck in cfg.trucks:
print(f'Route assigned to truck {truck.id}')
for delivery in truck.route.deliveries:
print(f' |- {delivery.location.address}') | Complexity: Big O(n^2)
Print list of addresses in the route assigned to each truck | debug.py | print_route_table | cohenpts/traveling_salesman | 0 | python | def print_route_table():
'\n Complexity: Big O(n^2)\n Print list of addresses in the route assigned to each truck\n '
print('_____________________________________________________________________')
print('______________________________Routes_________________________________')
for truck in cfg.trucks:
print(f'Route assigned to truck {truck.id}')
for delivery in truck.route.deliveries:
print(f' |- {delivery.location.address}') | def print_route_table():
'\n Complexity: Big O(n^2)\n Print list of addresses in the route assigned to each truck\n '
print('_____________________________________________________________________')
print('______________________________Routes_________________________________')
for truck in cfg.trucks:
print(f'Route assigned to truck {truck.id}')
for delivery in truck.route.deliveries:
print(f' |- {delivery.location.address}')<|docstring|>Complexity: Big O(n^2)
Print list of addresses in the route assigned to each truck<|endoftext|> |
eb57d347f880379a52b64a3e0ee8727b0c6c49a6da6efcaaefdb4e7d69d94e27 | def print_current_time():
'\n Complexity: Big O(n^2)\n print the global simulated time of the app\n '
print('________________________________\nThe current time is:', cfg.app_time, '\n________________________________\n') | Complexity: Big O(n^2)
print the global simulated time of the app | debug.py | print_current_time | cohenpts/traveling_salesman | 0 | python | def print_current_time():
'\n Complexity: Big O(n^2)\n print the global simulated time of the app\n '
print('________________________________\nThe current time is:', cfg.app_time, '\n________________________________\n') | def print_current_time():
'\n Complexity: Big O(n^2)\n print the global simulated time of the app\n '
print('________________________________\nThe current time is:', cfg.app_time, '\n________________________________\n')<|docstring|>Complexity: Big O(n^2)
print the global simulated time of the app<|endoftext|> |
fea5c869d776627ba66212d63ccc1620a45af58cf9f43f5c3dff6989462db6b4 | @pytest.fixture(params=[bool, 'uint8', 'int32', 'uint64', 'float32', 'float64', 'complex64', 'complex128', 'M8[ns]', 'm8[ns]', str, bytes, object])
def any_numpy_dtype_reduced(request):
"\n Parameterized fixture for numpy dtypes, reduced from any_numpy_dtype.\n\n * bool\n * 'int32'\n * 'uint64'\n * 'float32'\n * 'float64'\n * 'complex64'\n * 'complex128'\n * 'M8[ns]'\n * 'M8[ns]'\n * str\n * bytes\n * object\n "
return request.param | Parameterized fixture for numpy dtypes, reduced from any_numpy_dtype.
* bool
* 'int32'
* 'uint64'
* 'float32'
* 'float64'
* 'complex64'
* 'complex128'
* 'M8[ns]'
* 'M8[ns]'
* str
* bytes
* object | pandas/tests/dtypes/cast/test_promote.py | any_numpy_dtype_reduced | ZhihuiChen0903/pandas | 603 | python | @pytest.fixture(params=[bool, 'uint8', 'int32', 'uint64', 'float32', 'float64', 'complex64', 'complex128', 'M8[ns]', 'm8[ns]', str, bytes, object])
def any_numpy_dtype_reduced(request):
"\n Parameterized fixture for numpy dtypes, reduced from any_numpy_dtype.\n\n * bool\n * 'int32'\n * 'uint64'\n * 'float32'\n * 'float64'\n * 'complex64'\n * 'complex128'\n * 'M8[ns]'\n * 'M8[ns]'\n * str\n * bytes\n * object\n "
return request.param | @pytest.fixture(params=[bool, 'uint8', 'int32', 'uint64', 'float32', 'float64', 'complex64', 'complex128', 'M8[ns]', 'm8[ns]', str, bytes, object])
def any_numpy_dtype_reduced(request):
"\n Parameterized fixture for numpy dtypes, reduced from any_numpy_dtype.\n\n * bool\n * 'int32'\n * 'uint64'\n * 'float32'\n * 'float64'\n * 'complex64'\n * 'complex128'\n * 'M8[ns]'\n * 'M8[ns]'\n * str\n * bytes\n * object\n "
return request.param<|docstring|>Parameterized fixture for numpy dtypes, reduced from any_numpy_dtype.
* bool
* 'int32'
* 'uint64'
* 'float32'
* 'float64'
* 'complex64'
* 'complex128'
* 'M8[ns]'
* 'M8[ns]'
* str
* bytes
* object<|endoftext|> |
8adcb1994959184c296da6e7b49505044b732a5d8b738099601ddab362f44170 | def _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar=None):
'\n Auxiliary function to unify testing of scalar/array promotion.\n\n Parameters\n ----------\n dtype : dtype\n The value to pass on as the first argument to maybe_promote.\n fill_value : scalar\n The value to pass on as the second argument to maybe_promote as\n a scalar.\n expected_dtype : dtype\n The expected dtype returned by maybe_promote (by design this is the\n same regardless of whether fill_value was passed as a scalar or in an\n array!).\n exp_val_for_scalar : scalar\n The expected value for the (potentially upcast) fill_value returned by\n maybe_promote.\n '
assert is_scalar(fill_value)
(result_dtype, result_fill_value) = maybe_promote(dtype, fill_value)
expected_fill_value = exp_val_for_scalar
assert (result_dtype == expected_dtype)
_assert_match(result_fill_value, expected_fill_value) | Auxiliary function to unify testing of scalar/array promotion.
Parameters
----------
dtype : dtype
The value to pass on as the first argument to maybe_promote.
fill_value : scalar
The value to pass on as the second argument to maybe_promote as
a scalar.
expected_dtype : dtype
The expected dtype returned by maybe_promote (by design this is the
same regardless of whether fill_value was passed as a scalar or in an
array!).
exp_val_for_scalar : scalar
The expected value for the (potentially upcast) fill_value returned by
maybe_promote. | pandas/tests/dtypes/cast/test_promote.py | _check_promote | ZhihuiChen0903/pandas | 603 | python | def _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar=None):
'\n Auxiliary function to unify testing of scalar/array promotion.\n\n Parameters\n ----------\n dtype : dtype\n The value to pass on as the first argument to maybe_promote.\n fill_value : scalar\n The value to pass on as the second argument to maybe_promote as\n a scalar.\n expected_dtype : dtype\n The expected dtype returned by maybe_promote (by design this is the\n same regardless of whether fill_value was passed as a scalar or in an\n array!).\n exp_val_for_scalar : scalar\n The expected value for the (potentially upcast) fill_value returned by\n maybe_promote.\n '
assert is_scalar(fill_value)
(result_dtype, result_fill_value) = maybe_promote(dtype, fill_value)
expected_fill_value = exp_val_for_scalar
assert (result_dtype == expected_dtype)
_assert_match(result_fill_value, expected_fill_value) | def _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar=None):
'\n Auxiliary function to unify testing of scalar/array promotion.\n\n Parameters\n ----------\n dtype : dtype\n The value to pass on as the first argument to maybe_promote.\n fill_value : scalar\n The value to pass on as the second argument to maybe_promote as\n a scalar.\n expected_dtype : dtype\n The expected dtype returned by maybe_promote (by design this is the\n same regardless of whether fill_value was passed as a scalar or in an\n array!).\n exp_val_for_scalar : scalar\n The expected value for the (potentially upcast) fill_value returned by\n maybe_promote.\n '
assert is_scalar(fill_value)
(result_dtype, result_fill_value) = maybe_promote(dtype, fill_value)
expected_fill_value = exp_val_for_scalar
assert (result_dtype == expected_dtype)
_assert_match(result_fill_value, expected_fill_value)<|docstring|>Auxiliary function to unify testing of scalar/array promotion.
Parameters
----------
dtype : dtype
The value to pass on as the first argument to maybe_promote.
fill_value : scalar
The value to pass on as the second argument to maybe_promote as
a scalar.
expected_dtype : dtype
The expected dtype returned by maybe_promote (by design this is the
same regardless of whether fill_value was passed as a scalar or in an
array!).
exp_val_for_scalar : scalar
The expected value for the (potentially upcast) fill_value returned by
maybe_promote.<|endoftext|> |
ec530118e5502b1cc5720dee4bc1addf6adbb74409179f287a2a04caf6c31050 | def __init__(self, queue: Queue, **kwargs):
'Create new logger handler with the specified queue and kwargs for the `LokiHandler`.'
super().__init__(queue)
self.handler = LokiHandler(**kwargs)
self.listener = QueueListener(self.queue, self.handler)
self.listener.start() | Create new logger handler with the specified queue and kwargs for the `LokiHandler`. | logging_loki/handlers.py | __init__ | muze-app/python-logging-loki | 71 | python | def __init__(self, queue: Queue, **kwargs):
super().__init__(queue)
self.handler = LokiHandler(**kwargs)
self.listener = QueueListener(self.queue, self.handler)
self.listener.start() | def __init__(self, queue: Queue, **kwargs):
super().__init__(queue)
self.handler = LokiHandler(**kwargs)
self.listener = QueueListener(self.queue, self.handler)
self.listener.start()<|docstring|>Create new logger handler with the specified queue and kwargs for the `LokiHandler`.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.