uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
0a02ee68d93c83e51b4466b1
train
class
@register_trait class TemperatureSettingTrait(_Trait): """Trait to offer handling both temperature point and modes functionality. https://developers.google.com/actions/smarthome/traits/temperaturesetting """ name = TRAIT_TEMPERATURE_SETTING commands = [ COMMAND_THERMOSTAT_TEMPERATURE_SETPO...
@register_trait class TemperatureSettingTrait(_Trait):
"""Trait to offer handling both temperature point and modes functionality. https://developers.google.com/actions/smarthome/traits/temperaturesetting """ name = TRAIT_TEMPERATURE_SETTING commands = [ COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE, ...
'isRunning': self.state.state == vacuum.STATE_CLEANING, 'isPaused': self.state.state == vacuum.STATE_PAUSED, } async def execute(self, command, data, params): """Execute a StartStop command.""" if command == COMMAND_STARTSTOP: if params['start']: ...
256
256
1,677
11
245
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
TemperatureSettingTrait
TemperatureSettingTrait
530
726
530
531
97e1f6707c4dd29d98087adf5003023261ad26ba
bigcode/the-stack
train
2a115727a5ec4971caa94280
train
class
@register_trait class BrightnessTrait(_Trait): """Trait to control brightness of a device. https://developers.google.com/actions/smarthome/traits/brightness """ name = TRAIT_BRIGHTNESS commands = [ COMMAND_BRIGHTNESS_ABSOLUTE ] @staticmethod def supported(domain, features): ...
@register_trait class BrightnessTrait(_Trait):
"""Trait to control brightness of a device. https://developers.google.com/actions/smarthome/traits/brightness """ name = TRAIT_BRIGHTNESS commands = [ COMMAND_BRIGHTNESS_ABSOLUTE ] @staticmethod def supported(domain, features): """Test if state is supported.""" ...
trait for a state.""" self.hass = hass self.state = state self.config = config def sync_attributes(self): """Return attributes for a sync request.""" raise NotImplementedError def query_attributes(self): """Return the attributes of this trait for this entity.""...
131
131
437
11
119
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
BrightnessTrait
BrightnessTrait
117
178
117
118
5357308f68e5cdc66b6ba8f2d5707ea2986967e3
bigcode/the-stack
train
3147f1107cd04055606a755e
train
class
@register_trait class CameraStreamTrait(_Trait): """Trait to stream from cameras. https://developers.google.com/actions/smarthome/traits/camerastream """ name = TRAIT_CAMERA_STREAM commands = [ COMMAND_GET_CAMERA_STREAM ] stream_info = None @staticmethod def supported(dom...
@register_trait class CameraStreamTrait(_Trait):
"""Trait to stream from cameras. https://developers.google.com/actions/smarthome/traits/camerastream """ name = TRAIT_CAMERA_STREAM commands = [ COMMAND_GET_CAMERA_STREAM ] stream_info = None @staticmethod def supported(domain, features): """Test if state is suppo...
_player.DOMAIN: await self.hass.services.async_call( media_player.DOMAIN, media_player.SERVICE_VOLUME_SET, { ATTR_ENTITY_ID: self.state.entity_id, media_player.ATTR_MEDIA_VOLUME_LEVEL: params['brightness'] / 100 }, b...
75
75
250
11
64
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
CameraStreamTrait
CameraStreamTrait
181
223
181
182
81f2717203b48aff6d85aa83a8843bd0b79e3560
bigcode/the-stack
train
f7862a67034ba9188e20aed6
train
class
@register_trait class ModesTrait(_Trait): """Trait to set modes. https://developers.google.com/actions/smarthome/traits/modes """ name = TRAIT_MODES commands = [ COMMAND_MODES ] # Google requires specific mode names and settings. Here is the full list. # https://developers.goo...
@register_trait class ModesTrait(_Trait):
"""Trait to set modes. https://developers.google.com/actions/smarthome/traits/modes """ name = TRAIT_MODES commands = [ COMMAND_MODES ] # Google requires specific mode names and settings. Here is the full list. # https://developers.google.com/actions/reference/smarthome/traits...
_name": mode, "speed_values": [{ "speed_synonym": self.speed_synonyms.get(mode), "lang": 'en' }] } speeds.append(speed) return { 'availableFanSpeeds': { 'speeds': speeds, ...
256
256
1,461
10
246
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
ModesTrait
ModesTrait
847
1,029
847
848
8a5e5f517c3a61c6ad2ff6a58530d97352f60b32
bigcode/the-stack
train
03a7c1f4d6e33bf58a2b5b86
train
class
@register_trait class OnOffTrait(_Trait): """Trait to offer basic on and off functionality. https://developers.google.com/actions/smarthome/traits/onoff """ name = TRAIT_ONOFF commands = [ COMMAND_ONOFF ] @staticmethod def supported(domain, features): """Test if state ...
@register_trait class OnOffTrait(_Trait):
"""Trait to offer basic on and off functionality. https://developers.google.com/actions/smarthome/traits/onoff """ name = TRAIT_ONOFF commands = [ COMMAND_ONOFF ] @staticmethod def supported(domain, features): """Test if state is supported.""" return domain in ...
.stream_info or {} async def execute(self, command, data, params): """Execute a get camera stream command.""" url = await self.hass.components.camera.async_request_stream( self.state.entity_id, 'hls') self.stream_info = { 'cameraStreamAccessUrl': self.hass.config.api...
84
84
283
11
73
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
OnOffTrait
OnOffTrait
226
272
226
227
06cc8337f7d87a1ec41edc0e52dcab924bf6c744
bigcode/the-stack
train
373fd5641bdf2af82a3e5600
train
class
class _Trait: """Represents a Trait inside Google Assistant skill.""" commands = [] def __init__(self, hass, state, config): """Initialize a trait for a state.""" self.hass = hass self.state = state self.config = config def sync_attributes(self): """Return attr...
class _Trait:
"""Represents a Trait inside Google Assistant skill.""" commands = [] def __init__(self, hass, state, config): """Initialize a trait for a state.""" self.hass = hass self.state = state self.config = config def sync_attributes(self): """Return attributes for a s...
ait): """Decorate a function to register a trait.""" TRAITS.append(trait) return trait def _google_temp_unit(units): """Return Google temperature unit.""" if units == TEMP_FAHRENHEIT: return 'F' return 'C' class _Trait:
64
64
156
4
60
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
_Trait
_Trait
89
114
89
89
144210e1066ff77b661c7a2fbd9c4cad862e1b5c
bigcode/the-stack
train
89469c764408b4f98ddeda53
train
function
def register_trait(trait): """Decorate a function to register a trait.""" TRAITS.append(trait) return trait
def register_trait(trait):
"""Decorate a function to register a trait.""" TRAITS.append(trait) return trait
' COMMAND_LOCKUNLOCK = PREFIX_COMMANDS + 'LockUnlock' COMMAND_FANSPEED = PREFIX_COMMANDS + 'SetFanSpeed' COMMAND_MODES = PREFIX_COMMANDS + 'SetModes' COMMAND_OPENCLOSE = PREFIX_COMMANDS + 'OpenClose' TRAITS = [] def register_trait(trait):
63
64
28
6
57
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
register_trait
register_trait
76
79
76
76
60c0c0d49814bd8180bb92e26700934658864d4f
bigcode/the-stack
train
6ea45c24545e4156328092ec
train
class
@register_trait class ColorTemperatureTrait(_Trait): """Trait to offer color temperature functionality. https://developers.google.com/actions/smarthome/traits/colortemperature """ name = TRAIT_COLOR_TEMP commands = [ COMMAND_COLOR_ABSOLUTE ] @staticmethod def supported(domain,...
@register_trait class ColorTemperatureTrait(_Trait):
"""Trait to offer color temperature functionality. https://developers.google.com/actions/smarthome/traits/colortemperature """ name = TRAIT_COLOR_TEMP commands = [ COMMAND_COLOR_ABSOLUTE ] @staticmethod def supported(domain, features): """Test if state is supported."""...
return (command in self.commands and 'spectrumRGB' in params.get('color', {})) async def execute(self, command, data, params): """Execute a color spectrum command.""" # Convert integer to hex format and left pad with 0's till length 6 hex_value = "{0:06x}".format(params['co...
161
161
538
11
150
markusressel/home-assistant
homeassistant/components/google_assistant/trait.py
Python
ColorTemperatureTrait
ColorTemperatureTrait
331
401
331
332
0bbf84ee6b412a2017bf180ebec344855c055b71
bigcode/the-stack
train
791f3c5f6db8fcc61ca163fe
train
function
def main( version: bool = typer.Option( None, "--version", "-v", callback=version_callback, is_eager=True ) ): pass
def main( version: bool = typer.Option( None, "--version", "-v", callback=version_callback, is_eager=True ) ):
pass
bool): if value: typer.echo(f"Mcanitexgen: {mcanitexgen.__version__}") raise typer.Exit() def main( version: bool = typer.Option( None, "--version", "-v", callback=version_callback, is_eager=True ) ):
64
64
36
33
31
OrangeUtan/MCMetagen
mcanitexgen/cli.py
Python
main
main
24
29
24
28
32f244855ce571dec245b949e9ed89416548a2dd
bigcode/the-stack
train
5b89212b3ecb89e8d5eb8ff3
train
function
@app.command(help="Create gifs for all animations in an animation file") def gif( file: Path = typer.Argument(..., exists=True, dir_okay=False, readable=True), out: Optional[Path] = typer.Option( None, "-o", "--out", help="The output directory of the generated gif", file_...
@app.command(help="Create gifs for all animations in an animation file") def gif( file: Path = typer.Argument(..., exists=True, dir_okay=False, readable=True), out: Optional[Path] = typer.Option( None, "-o", "--out", help="The output directory of the generated gif", file_...
out = out if out else file.parent out.mkdir(parents=True, exist_ok=True) for animation in load_animations_from_file(file).values(): texture_path = Path(file.parent, animation.texture) dest = Path(out, f"{os.path.splitext(animation.texture.name)[0]}.gif") texture = PIL.Image.open(tex...
@app.command(help="Create gifs for all animations in an animation file") def gif( file: Path = typer.Argument(..., exists=True, dir_okay=False, readable=True), out: Optional[Path] = typer.Option( None, "-o", "--out", help="The output directory of the generated gif", file_...
83
64
179
83
0
OrangeUtan/MCMetagen
mcanitexgen/cli.py
Python
gif
gif
67
86
67
78
3b6fde82930b14f80fdb6b3be0b9a654cd4cc430
bigcode/the-stack
train
970107b8569c0ea1981c2911
train
function
@app.command(help="Generate .mcmeta files for all animations in an animation file") def generate( src: Path = typer.Argument( ..., exists=True, readable=True, help="File or directory containing animations" ), out: Optional[Path] = typer.Option( None, "-o", "--out", he...
@app.command(help="Generate .mcmeta files for all animations in an animation file") def generate( src: Path = typer.Argument( ..., exists=True, readable=True, help="File or directory containing animations" ), out: Optional[Path] = typer.Option( None, "-o", "--out", he...
if out is None: out = src if src.is_dir() else src.parent texture_animations = load_animations(src) if not dry: out.mkdir(parents=True, exist_ok=True) write_mcmeta_files(texture_animations, out, indent if not minify else None)
@app.command(help="Generate .mcmeta files for all animations in an animation file") def generate( src: Path = typer.Argument( ..., exists=True, readable=True, help="File or directory containing animations" ), out: Optional[Path] = typer.Option( None, "-o", "--out", he...
187
75
251
187
0
OrangeUtan/MCMetagen
mcanitexgen/cli.py
Python
generate
generate
35
64
35
57
90c39f300b634c87e6780f66c2d1846c77bd1e7a
bigcode/the-stack
train
4bf8c43150ecece2e8a4f06d
train
function
def version_callback(value: bool): if value: typer.echo(f"Mcanitexgen: {mcanitexgen.__version__}") raise typer.Exit()
def version_callback(value: bool):
if value: typer.echo(f"Mcanitexgen: {mcanitexgen.__version__}") raise typer.Exit()
annotations import os from pathlib import Path from typing import Optional import PIL.Image import typer import mcanitexgen from mcanitexgen.animation import ( load_animations, load_animations_from_file, write_mcmeta_files, ) def version_callback(value: bool):
64
64
36
7
57
OrangeUtan/MCMetagen
mcanitexgen/cli.py
Python
version_callback
version_callback
18
21
18
18
7c6bc8786b0c3bd4ba52f6602d756059b52b126d
bigcode/the-stack
train
e8139247613a81bc6b6a1013
train
function
@has_request_variables def get_logo_backend(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse: url = get_realm_logo_url(user_profile.realm, night) # We can rely on the url already having query parameters. Because # our templates dep...
@has_request_variables def get_logo_backend(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse:
url = get_realm_logo_url(user_profile.realm, night) # We can rely on the url already having query parameters. Because # our templates depend on being able to use the ampersand to # add query parameters to our url, get_logo_url does '?version=version_number' # hacks to prevent us from having to jump...
do_change_logo_source(user_profile.realm, user_profile.realm.LOGO_DEFAULT, night, acting_user=user_profile) return json_success() @has_request_variables def get_logo_backend(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse:
64
64
139
36
28
kaustubh-nair/zulip
zerver/views/realm_logo.py
Python
get_logo_backend
get_logo_backend
44
54
44
46
95e2e6526bbc7fa8094f49d53f6c02b763f66477
bigcode/the-stack
train
81c8497b01ea87560aad932f
train
function
@require_realm_admin @has_request_variables def delete_logo_backend(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse: # We don't actually delete the logo because it might still # be needed if the URL was cached and it is rewritten ...
@require_realm_admin @has_request_variables def delete_logo_backend(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse: # We don't actually delete the logo because it might still # be needed if the URL was cached and it is rewritten ...
do_change_logo_source(user_profile.realm, user_profile.realm.LOGO_DEFAULT, night, acting_user=user_profile) return json_success()
@require_realm_admin @has_request_variables def delete_logo_backend(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse: # We don't actually delete the logo because it might still # be needed if the URL was cached and it is rewritten ...
78
64
106
78
0
kaustubh-nair/zulip
zerver/views/realm_logo.py
Python
delete_logo_backend
delete_logo_backend
34
42
34
40
d319d59319afbc03e831f8ee60aa8ce052ff83d4
bigcode/the-stack
train
271890846ed6d260749608ca
train
function
@require_realm_admin @has_request_variables def upload_logo(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse: user_profile.realm.ensure_not_on_limited_plan() if len(request.FILES) != 1: return json_error(_("You must upload exactly o...
@require_realm_admin @has_request_variables def upload_logo(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse:
user_profile.realm.ensure_not_on_limited_plan() if len(request.FILES) != 1: return json_error(_("You must upload exactly one logo.")) logo_file = list(request.FILES.values())[0] if ((settings.MAX_LOGO_FILE_SIZE * 1024 * 1024) < logo_file.size): return json_error(_("Uploaded file is larg...
_query_arg_to_redirect_url from zerver.lib.validator import check_bool from zerver.models import UserProfile @require_realm_admin @has_request_variables def upload_logo(request: HttpRequest, user_profile: UserProfile, night: bool=REQ(validator=check_bool)) -> HttpResponse:
64
64
184
41
22
kaustubh-nair/zulip
zerver/views/realm_logo.py
Python
upload_logo
upload_logo
17
32
17
20
bb683d3cf9b502f1be1605dcc8a352c14d3d9008
bigcode/the-stack
train
046adf574de5c2d829dc1605
train
function
def _choose_2k_samples(x, y, k): pos = np.random.choice(np.where(y > 0)[0], k, replace=False) neg = np.random.choice(np.where(y < 0)[0], k, replace=False) samples = np.hstack([pos, neg]) mask = np.zeros(y.shape, dtype=np.bool) mask[samples] = True return x[samples], y[samples], mask
def _choose_2k_samples(x, y, k):
pos = np.random.choice(np.where(y > 0)[0], k, replace=False) neg = np.random.choice(np.where(y < 0)[0], k, replace=False) samples = np.hstack([pos, neg]) mask = np.zeros(y.shape, dtype=np.bool) mask[samples] = True return x[samples], y[samples], mask
[0])) attrs.append(np.int8(tokens[1:])) if sigmoid: attrs = np.ceil((np.int8(attrs) + .5))//2 return np.array(fnames), np.int8(attrs), attrnames def _choose_2k_samples(x, y, k):
64
64
96
13
50
MatheusAD95/fg2020-faceunderstanding
deepface/datasets/celeba.py
Python
_choose_2k_samples
_choose_2k_samples
34
40
34
34
b8224212eaeeeac38ea7d760cb39605aa4510614
bigcode/the-stack
train
9363482cc20539ac2c7be39f
train
function
def create_generators(celeba_path, attr, input_reader, n_train, n_val): train_x, train_y, attrnames = _loadpaths(celeba_path, split='train') val_x, val_y, _ = _loadpaths(celeba_path, split='val') # we mix the train and validation sets to get enough samples for all attributes x = np.hstack([train_x, val_...
def create_generators(celeba_path, attr, input_reader, n_train, n_val):
train_x, train_y, attrnames = _loadpaths(celeba_path, split='train') val_x, val_y, _ = _loadpaths(celeba_path, split='val') # we mix the train and validation sets to get enough samples for all attributes x = np.hstack([train_x, val_x]) y = np.vstack([train_y, val_y])[:, attrnames == attr].ravel() ...
, replace=False) neg = np.random.choice(np.where(y < 0)[0], k, replace=False) samples = np.hstack([pos, neg]) mask = np.zeros(y.shape, dtype=np.bool) mask[samples] = True return x[samples], y[samples], mask def create_generators(celeba_path, attr, input_reader, n_train, n_val):
87
87
292
20
66
MatheusAD95/fg2020-faceunderstanding
deepface/datasets/celeba.py
Python
create_generators
create_generators
42
57
42
42
08a2b49b07b59532efa06051100b113179f3f924
bigcode/the-stack
train
cda6bcdb8936a80235f9452e
train
function
def _loadpaths(celeba_path, split='train', sigmoid=False): split_dict = {0: 'train', 1: 'val', 2: 'test'} split_file = os.path.join(celeba_path, 'Eval', 'list_eval_partition.txt') lines = open(split_file, 'r').read().splitlines() partition = {} for line in lines: tokens = re.split('[ ]+', li...
def _loadpaths(celeba_path, split='train', sigmoid=False):
split_dict = {0: 'train', 1: 'val', 2: 'test'} split_file = os.path.join(celeba_path, 'Eval', 'list_eval_partition.txt') lines = open(split_file, 'r').read().splitlines() partition = {} for line in lines: tokens = re.split('[ ]+', line.strip()) partition[tokens[0]] = split_dict[int(t...
import os import re from math import ceil import numpy as np from .batch_generator import BatchGenerator def loadpaths(*args, **kwargs): return _loadpaths(*args, **kwargs) def _loadpaths(celeba_path, split='train', sigmoid=False):
60
84
282
16
44
MatheusAD95/fg2020-faceunderstanding
deepface/datasets/celeba.py
Python
_loadpaths
_loadpaths
12
32
12
12
8206cf52d0290cac78e3ed0c47a856b74f0e637f
bigcode/the-stack
train
ec5118f8fd7db1924d594428
train
function
def loadpaths(*args, **kwargs): return _loadpaths(*args, **kwargs)
def loadpaths(*args, **kwargs):
return _loadpaths(*args, **kwargs)
import os import re from math import ceil import numpy as np from .batch_generator import BatchGenerator def loadpaths(*args, **kwargs):
33
64
20
9
23
MatheusAD95/fg2020-faceunderstanding
deepface/datasets/celeba.py
Python
loadpaths
loadpaths
9
10
9
9
e5ce203cee6da5f095c4d5ec7035424cee1a84a1
bigcode/the-stack
train
d9b62b45c29fb679a12d4121
train
function
def n_at_ph(jobs, ph): return sum([1 for j in jobs if j.progress() == ph])
def n_at_ph(jobs, ph):
return sum([1 for j in jobs if j.progress() == ph])
phases[:n_first]]) elided = " [+%d] " % n_elided last = " ".join(["%d:%d" % pair for pair in phases[n_first + n_elided :]]) return first + elided + last def n_at_ph(jobs, ph):
64
64
25
9
54
Gigatron/plotman
reporting.py
Python
n_at_ph
n_at_ph
33
34
33
33
2c25c376742a4032a5194a81de4285c39402b81b
bigcode/the-stack
train
6867ac88f18026a7406246b9
train
function
def dst_dir_report(jobs, dstdirs, width, prefix=""): tab = tt.Texttable() dir2oldphase = manager.dstdirs_to_furthest_phase(jobs) dir2newphase = manager.dstdirs_to_youngest_phase(jobs) headings = ["dst", "plots", "GBfree", "inbnd phases", "pri"] tab.header(headings) tab.set_cols_dtype("t" * len(h...
def dst_dir_report(jobs, dstdirs, width, prefix=""):
tab = tt.Texttable() dir2oldphase = manager.dstdirs_to_furthest_phase(jobs) dir2newphase = manager.dstdirs_to_youngest_phase(jobs) headings = ["dst", "plots", "GBfree", "inbnd phases", "pri"] tab.header(headings) tab.set_cols_dtype("t" * len(headings)) for d in sorted(dstdirs): # TO...
if job_age else "N/A", plot_util.time_format(max(job_age)) if job_age else "N/A", ] tab.add_row(row) tab.set_max_width(width) tab.set_deco(tt.Texttable.BORDER | tt.Texttable.HEADER) tab.set_deco(0) # No borders return tab.draw() def dst_dir_report(jobs, dstdirs, width, pre...
91
91
304
16
75
Gigatron/plotman
reporting.py
Python
dst_dir_report
dst_dir_report
173
196
173
173
e52b33a4e4cc5e766d55c1c2c0229db9bb4420bf
bigcode/the-stack
train
45d57b61140297a40ffc557c
train
function
def abbr_path(path, putative_prefix): if putative_prefix and path.startswith(putative_prefix): return os.path.relpath(path, putative_prefix) else: return path
def abbr_path(path, putative_prefix):
if putative_prefix and path.startswith(putative_prefix): return os.path.relpath(path, putative_prefix) else: return path
import texttable as tt # from somewhere? import os import psutil import archive import job import manager import math import plot_util def abbr_path(path, putative_prefix):
43
64
42
10
32
Gigatron/plotman
reporting.py
Python
abbr_path
abbr_path
12
16
12
12
5d95203050487171608508eadce240128d7ddda4
bigcode/the-stack
train
0167e99b1560d7983ae7d4aa
train
function
def n_to_char(n): n_to_char_map = dict(enumerate(" .:;!")) if n < 0: return "X" # Should never be negative elif n >= len(n_to_char_map): n = len(n_to_char_map) - 1 return n_to_char_map[n]
def n_to_char(n):
n_to_char_map = dict(enumerate(" .:;!")) if n < 0: return "X" # Should never be negative elif n >= len(n_to_char_map): n = len(n_to_char_map) - 1 return n_to_char_map[n]
= " ".join(["%d:%d" % pair for pair in phases[n_first + n_elided :]]) return first + elided + last def n_at_ph(jobs, ph): return sum([1 for j in jobs if j.progress() == ph]) def n_to_char(n):
64
64
72
6
58
Gigatron/plotman
reporting.py
Python
n_to_char
n_to_char
37
45
37
37
df50791dabcc753117fe1fd3cf3aee7e16a7991d
bigcode/the-stack
train
52660894435a97a434920b12
train
function
def status_report(jobs, width, height=None, tmp_prefix="", dst_prefix=""): """height, if provided, will limit the number of rows in the table, showing first and last rows, row numbers and an elipsis in the middle.""" abbreviate_jobs_list = False n_begin_rows = 0 n_end_rows = 0 if height and h...
def status_report(jobs, width, height=None, tmp_prefix="", dst_prefix=""):
"""height, if provided, will limit the number of rows in the table, showing first and last rows, row numbers and an elipsis in the middle.""" abbreviate_jobs_list = False n_begin_rows = 0 n_end_rows = 0 if height and height < len(jobs) + 1: # One row for header abbreviate_jobs_list =...
_viz(jobs): # TODO: Rewrite this in a way that ensures we count every job # even if the reported phases don't line up with expectations. result = "" result += "1" for i in range(0, 8): result += n_to_char(n_at_ph(jobs, (1, i))) result += "2" for i in range(0, 8): result += n_...
186
186
623
18
167
Gigatron/plotman
reporting.py
Python
status_report
status_report
66
140
66
66
d37eff55c5e4784231effb2765f74b9a04dd406b
bigcode/the-stack
train
6944f9f69047a2ca90f5e0ee
train
function
def dirs_report(jobs, dir_cfg, sched_cfg, width): tmpdirs = dir_cfg["tmp"] dstdirs = dir_cfg["dst"] arch_cfg = dir_cfg.get("archive") msg = ( tmp_dir_report(jobs, tmpdirs, sched_cfg, width) + "\n\n" + dst_dir_report(jobs, dstdirs, width) + "\n" ) if arch_cfg: ...
def dirs_report(jobs, dir_cfg, sched_cfg, width):
tmpdirs = dir_cfg["tmp"] dstdirs = dir_cfg["dst"] arch_cfg = dir_cfg.get("archive") msg = ( tmp_dir_report(jobs, tmpdirs, sched_cfg, width) + "\n\n" + dst_dir_report(jobs, dstdirs, width) + "\n" ) if arch_cfg: msg += ( "archive dirs free space:...
row in plot_util.column_wrap(cells, n_columns, filler=""): tab.add_row(row) tab.set_cols_align("r" * (n_columns)) tab.set_deco(tt.Texttable.VLINES) return tab.draw() def dirs_report(jobs, dir_cfg, sched_cfg, width):
64
64
136
14
50
Gigatron/plotman
reporting.py
Python
dirs_report
dirs_report
217
233
217
217
078ffce45560c226cd24e630459cffc9c61fc1f8
bigcode/the-stack
train
a36072b77c1bdbb563238349
train
function
def tmp_dir_report(jobs, tmpdirs, sched_cfg, width, start_row=None, end_row=None, prefix=""): """start_row, end_row let you split the table up if you want""" tab = tt.Texttable() headings = ["tmp", "count", "ready", "phases", "youngest", "eldest"] tab.header(headings) tab.set_cols_dtype("t" * len(he...
def tmp_dir_report(jobs, tmpdirs, sched_cfg, width, start_row=None, end_row=None, prefix=""):
"""start_row, end_row let you split the table up if you want""" tab = tt.Texttable() headings = ["tmp", "count", "ready", "phases", "youngest", "eldest"] tab.header(headings) tab.set_cols_dtype("t" * len(headings)) tab.set_cols_align("r" * (len(headings) - 1) + "l") for i, d in enumerate(sor...
height: row.insert(0, "%3d" % i) tab.add_row(row) tab.set_max_width(width) tab.set_deco(0) # No borders # return ('tmp dir prefix: %s ; dst dir prefix: %s\n' % (tmp_prefix, dst_prefix) return tab.draw() def tmp_dir_report(jobs, tmpdirs, sched_cfg, width, start_row=None, end_r...
99
99
331
26
73
Gigatron/plotman
reporting.py
Python
tmp_dir_report
tmp_dir_report
143
170
143
143
7c46f612fb9c212b99023dd5b8fd9200c9dafb6c
bigcode/the-stack
train
79a24c3af35126c33e2920e2
train
function
def phases_str(phases, max_num=None): """Take a list of phase-subphase pairs and return them as a compact string""" if not max_num or len(phases) <= max_num: return " ".join(["%d:%d" % pair for pair in phases]) else: n_first = math.floor(max_num / 2) n_last = max_num - n_first ...
def phases_str(phases, max_num=None):
"""Take a list of phase-subphase pairs and return them as a compact string""" if not max_num or len(phases) <= max_num: return " ".join(["%d:%d" % pair for pair in phases]) else: n_first = math.floor(max_num / 2) n_last = max_num - n_first n_elided = len(phases) - (n_first + ...
job import manager import math import plot_util def abbr_path(path, putative_prefix): if putative_prefix and path.startswith(putative_prefix): return os.path.relpath(path, putative_prefix) else: return path def phases_str(phases, max_num=None):
64
64
174
10
53
Gigatron/plotman
reporting.py
Python
phases_str
phases_str
19
30
19
19
b7a0b3b3d4daa0d2d071b713cd95c599e161da0a
bigcode/the-stack
train
5cef14c7e416f73e2375c882
train
function
def arch_dir_report(archdir_freebytes, width, prefix=""): cells = [ "%s:%5dGB" % (abbr_path(d, prefix), int(int(space) / plot_util.GB)) for (d, space) in sorted(archdir_freebytes.items()) ] if not cells: return "" n_columns = int(width / (len(max(cells, key=len)) + 3)) tab =...
def arch_dir_report(archdir_freebytes, width, prefix=""):
cells = [ "%s:%5dGB" % (abbr_path(d, prefix), int(int(space) / plot_util.GB)) for (d, space) in sorted(archdir_freebytes.items()) ] if not cells: return "" n_columns = int(width / (len(max(cells, key=len)) + 3)) tab = tt.Texttable() tab.set_max_width(width) for row i...
] tab.add_row(row) tab.set_max_width(width) tab.set_deco(tt.Texttable.BORDER | tt.Texttable.HEADER) tab.set_deco(0) # No borders return tab.draw() def arch_dir_report(archdir_freebytes, width, prefix=""):
64
64
157
15
49
Gigatron/plotman
reporting.py
Python
arch_dir_report
arch_dir_report
199
214
199
199
0313b919eb6f85bb00e797dc23a0506a3231515d
bigcode/the-stack
train
83a4675cec8bf77b6a276ed6
train
function
def job_viz(jobs): # TODO: Rewrite this in a way that ensures we count every job # even if the reported phases don't line up with expectations. result = "" result += "1" for i in range(0, 8): result += n_to_char(n_at_ph(jobs, (1, i))) result += "2" for i in range(0, 8): resul...
def job_viz(jobs): # TODO: Rewrite this in a way that ensures we count every job # even if the reported phases don't line up with expectations.
result = "" result += "1" for i in range(0, 8): result += n_to_char(n_at_ph(jobs, (1, i))) result += "2" for i in range(0, 8): result += n_to_char(n_at_ph(jobs, (2, i))) result += "3" for i in range(0, 7): result += n_to_char(n_at_ph(jobs, (3, i))) result += "4" ...
>= len(n_to_char_map): n = len(n_to_char_map) - 1 return n_to_char_map[n] def job_viz(jobs): # TODO: Rewrite this in a way that ensures we count every job # even if the reported phases don't line up with expectations.
64
64
170
36
28
Gigatron/plotman
reporting.py
Python
job_viz
job_viz
48
63
48
50
e0cfd4990b36551bd67aea5ad409930190f98b65
bigcode/the-stack
train
ca32e1958b81e9a00c72f6ed
train
class
class TestFeatureCorrelationVisualizer(VisualTestCase): """ FeatureCorrelation visualizer """ data = datasets.load_diabetes() X, y = data['data'], data['target'] labels = data['feature_names'] @pytest.mark.xfail( sys.platform == 'win32', reason="images not close on windows" ) ...
class TestFeatureCorrelationVisualizer(VisualTestCase):
""" FeatureCorrelation visualizer """ data = datasets.load_diabetes() X, y = data['data'], data['target'] labels = data['feature_names'] @pytest.mark.xfail( sys.platform == 'win32', reason="images not close on windows" ) def test_feature_correlation_integrated_pearson(self)...
# tests.test_features.test_feature_correlation # Test the feature correlation visualizers # # Author: Zijie (ZJ) Poh <poh.zijie@gmail.com> # Created: Tue Jul 31 20:21:32 2018 -0700 # # Copyright (C) 2018 District Data Labs # For license information, see LICENSE.txt # # ID: test_feature_correlation.py [] poh.zijie@gmai...
216
256
1,175
10
206
thisHermit/yellowbrick
tests/test_target/test_feature_correlation.py
Python
TestFeatureCorrelationVisualizer
TestFeatureCorrelationVisualizer
42
210
42
42
13a0c33a1fb9316b6067a8ab6b816936ff8b5880
bigcode/the-stack
train
368897f310fef4031170df83
train
function
def trim_silence(in_list, out_list, in_dimension, label_list, label_dimension, \ silence_feature_index, percent_to_keep=0): ''' Function to trim silence from binary label/speech files based on binary labels. in_list: list of binary label/speech files to trim ...
def trim_silence(in_list, out_list, in_dimension, label_list, label_dimension, \ silence_feature_index, percent_to_keep=0):
''' Function to trim silence from binary label/speech files based on binary labels. in_list: list of binary label/speech files to trim out_list: trimmed files in_dimension: dimension of data to trim label_list: list of binary labels which contain trimming criterion label_...
_frame_index + frame_index) base_frame_index = base_frame_index + frame_number elif self.subphone_feats == 'state_only': if label_binary_flag == 0: nonsilence_frame_index_list.append(base_frame_index) base_frame_index = base_frame_index + 1...
256
256
977
32
223
QimingFangS/merlin
src/frontend/silence_remover.py
Python
trim_silence
trim_silence
221
284
221
222
7f86ce50cb86662d21d5270899df492cfb64db4c
bigcode/the-stack
train
91ab569cf2b9ec9bcda05933
train
class
class SilenceRemover(object): def __init__(self, n_cmp, silence_pattern=['*-#+*'], label_type="state_align", remove_frame_features=True, subphone_feats="none"): self.silence_pattern = silence_pattern self.silence_pattern_size = len(silence_pattern) self.label_type = label_type self.r...
class SilenceRemover(object):
def __init__(self, n_cmp, silence_pattern=['*-#+*'], label_type="state_align", remove_frame_features=True, subphone_feats="none"): self.silence_pattern = silence_pattern self.silence_pattern_size = len(silence_pattern) self.label_type = label_type self.remove_frame_features = remove_...
source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials...
256
256
1,487
6
249
QimingFangS/merlin
src/frontend/silence_remover.py
Python
SilenceRemover
SilenceRemover
44
208
44
44
dd5c958dcc06ce0a4cc2bc88394e17a9a5fe3014
bigcode/the-stack
train
213d64c0d76c2931ee51f530
train
function
def _create_sites(basis_vectors, extent, site_offsets): basis_coords, positions = create_site_positions(basis_vectors, extent, site_offsets) sites = [ LatticeSite(id=idx, position=pos, basis_coord=coord) for idx, (coord, pos) in enumerate(zip(basis_coords, positions)) ] return sites, b...
def _create_sites(basis_vectors, extent, site_offsets):
basis_coords, positions = create_site_positions(basis_vectors, extent, site_offsets) sites = [ LatticeSite(id=idx, position=pos, basis_coord=coord) for idx, (coord, pos) in enumerate(zip(basis_coords, positions)) ] return sites, basis_coords, positions
""" basis_coord: CoordT """basis coordinates of this site""" def __repr__(self): s = ", ".join(map(str, (self.id, self.basis_coord))) return f"LatticeSite({s})" def _create_sites(basis_vectors, extent, site_offsets):
64
64
81
13
51
tobiaswiener/netket
netket/graph/lattice.py
Python
_create_sites
_create_sites
71
79
71
71
e23a7685292074d5834061462d79be3a6f0a5293
bigcode/the-stack
train
f909ad06d5623cdc2311c920
train
class
class InvalidSiteError(Exception): pass
class InvalidSiteError(Exception):
pass
._lattice_edge_logic import ( get_nn_edges, get_custom_edges, create_site_positions, CustomEdgeT, ) if TYPE_CHECKING: from .space_group import SpaceGroupBuilder PositionT = _np.ndarray CoordT = _np.ndarray class InvalidSiteError(Exception):
64
64
9
6
57
tobiaswiener/netket
netket/graph/lattice.py
Python
InvalidSiteError
InvalidSiteError
45
46
45
45
d6d47c3777e7b2072565f38c664295813d8c297a
bigcode/the-stack
train
529b464ed6d3d1bea62ec743
train
class
class InvalidWaveVectorError(Exception): pass
class InvalidWaveVectorError(Exception):
pass
_nn_edges, get_custom_edges, create_site_positions, CustomEdgeT, ) if TYPE_CHECKING: from .space_group import SpaceGroupBuilder PositionT = _np.ndarray CoordT = _np.ndarray class InvalidSiteError(Exception): pass class InvalidWaveVectorError(Exception):
64
64
10
7
56
tobiaswiener/netket
netket/graph/lattice.py
Python
InvalidWaveVectorError
InvalidWaveVectorError
49
50
49
49
5be175240ac14d9f4863b3a34693c27751534fdc
bigcode/the-stack
train
32d0abfd792f1bf4c9c7ba71
train
class
class Lattice(Graph): r""" A lattice built by periodic arrangement of a given unit cell. The lattice is represented as a Bravais lattice with (:code:`basis_vectors`) :math:`\{a_d\}_{d=1}^D` (where :math:`D = \mathtt{ndim}` is the dimension of the lattice) and a unit cell consisting of one or more s...
class Lattice(Graph):
r""" A lattice built by periodic arrangement of a given unit cell. The lattice is represented as a Bravais lattice with (:code:`basis_vectors`) :math:`\{a_d\}_{d=1}^D` (where :math:`D = \mathtt{ndim}` is the dimension of the lattice) and a unit cell consisting of one or more sites, The position...
: int """Integer ID of this site""" position: PositionT """Real-space position of this site""" basis_coord: CoordT """basis coordinates of this site""" def __repr__(self): s = ", ".join(map(str, (self.id, self.basis_coord))) return f"LatticeSite({s})" def _create_sites(basis_v...
256
256
5,636
5
251
tobiaswiener/netket
netket/graph/lattice.py
Python
Lattice
Lattice
105
744
105
105
4c8534214781c4e8c21b38164f6e8796fb72f4ea
bigcode/the-stack
train
9866c25126f2e9cc1f137e2f
train
class
@dataclass class LatticeSite: """ Contains information about a single :class:`~netket.graph.Lattice` site. """ id: int """Integer ID of this site""" position: PositionT """Real-space position of this site""" basis_coord: CoordT """basis coordinates of this site""" def __repr__(...
@dataclass class LatticeSite:
""" Contains information about a single :class:`~netket.graph.Lattice` site. """ id: int """Integer ID of this site""" position: PositionT """Real-space position of this site""" basis_coord: CoordT """basis coordinates of this site""" def __repr__(self): s = ", ".join(m...
_positions, CustomEdgeT, ) if TYPE_CHECKING: from .space_group import SpaceGroupBuilder PositionT = _np.ndarray CoordT = _np.ndarray class InvalidSiteError(Exception): pass class InvalidWaveVectorError(Exception): pass @dataclass class LatticeSite:
64
64
108
8
55
tobiaswiener/netket
netket/graph/lattice.py
Python
LatticeSite
LatticeSite
53
68
53
54
9364dc93402266756a8df8baa86d583b9c0a27e7
bigcode/the-stack
train
2ec2adf9d3a894d825fcbc8c
train
function
def deprecated(alternative): def wrapper(fn): msg = ( f"{fn.__name__} is deprecated and may be removed in the future. " f"You can use `{alternative}`` instead." ) f = _deprecated(msg)(fn) return f return wrapper
def deprecated(alternative):
def wrapper(fn): msg = ( f"{fn.__name__} is deprecated and may be removed in the future. " f"You can use `{alternative}`` instead." ) f = _deprecated(msg)(fn) return f return wrapper
(basis_vectors, extent, site_offsets) sites = [ LatticeSite(id=idx, position=pos, basis_coord=coord) for idx, (coord, pos) in enumerate(zip(basis_coords, positions)) ] return sites, basis_coords, positions def deprecated(alternative):
64
64
63
5
58
tobiaswiener/netket
netket/graph/lattice.py
Python
deprecated
deprecated
82
91
82
82
ab3da150279685c802455106f0018e9f0abd51e6
bigcode/the-stack
train
cc043eb2daab164a1ac2cbcb
train
function
def sort(tuples, allitems): """sort the given list of items by dependency. 'tuples' is a list of tuples representing a partial ordering. """ for set_ in sort_as_subsets(tuples, allitems): for s in set_: yield s
def sort(tuples, allitems):
"""sort the given list of items by dependency. 'tuples' is a list of tuples representing a partial ordering. """ for set_ in sort_as_subsets(tuples, allitems): for s in set_: yield s
todo.intersection(edges[node]): output.add(node) if not output: raise CircularDependencyError( "Circular dependency detected.", find_cycles(tuples, allitems), _gen_edges(edges) ) todo.difference_up...
64
64
62
8
55
banianlabs/Stash-Prototype
venv/lib/python2.7/site-packages/sqlalchemy/util/topological.py
Python
sort
sort
40
48
40
40
8b1f399933e3be651df74658595791033f4d4c82
bigcode/the-stack
train
2e577765d36b0ccca2978c89
train
function
def _gen_edges(edges): return set([ (right, left) for left in edges for right in edges[left] ])
def _gen_edges(edges):
return set([ (right, left) for left in edges for right in edges[left] ])
stack: cyc = stack[stack.index(node):] todo.difference_update(cyc) output.update(cyc) if node in todo: stack.append(node) todo.remove(node) break else: no...
64
64
31
6
57
banianlabs/Stash-Prototype
venv/lib/python2.7/site-packages/sqlalchemy/util/topological.py
Python
_gen_edges
_gen_edges
91
96
91
91
923337adaad000f7f99ad66a53d9938b1ab44228
bigcode/the-stack
train
2a58d826288631c4ec5d13a0
train
function
def sort_as_subsets(tuples, allitems): edges = util.defaultdict(set) for parent, child in tuples: edges[child].add(parent) todo = set(allitems) while todo: output = set() for node in list(todo): if not todo.intersection(edges[node]): output.add(node...
def sort_as_subsets(tuples, allitems):
edges = util.defaultdict(set) for parent, child in tuples: edges[child].add(parent) todo = set(allitems) while todo: output = set() for node in list(todo): if not todo.intersection(edges[node]): output.add(node) if not output: ra...
# the MIT License: http://www.opensource.org/licenses/mit-license.php """Topological sorting algorithms.""" from ..exc import CircularDependencyError from .. import util __all__ = ['sort', 'sort_as_subsets', 'find_cycles'] def sort_as_subsets(tuples, allitems):
64
64
117
11
53
banianlabs/Stash-Prototype
venv/lib/python2.7/site-packages/sqlalchemy/util/topological.py
Python
sort_as_subsets
sort_as_subsets
15
37
15
16
014aad7fca642f7dc5acbeb5bf0b953820f5ed29
bigcode/the-stack
train
8c19d64a06519924ad0b20dc
train
function
def find_cycles(tuples, allitems): # adapted from: # http://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html edges = util.defaultdict(set) for parent, child in tuples: edges[parent].add(child) nodes_to_test = set(edges) output = set() # we'd like to find al...
def find_cycles(tuples, allitems): # adapted from: # http://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html
edges = util.defaultdict(set) for parent, child in tuples: edges[parent].add(child) nodes_to_test = set(edges) output = set() # we'd like to find all nodes that are # involved in cycles, so we do the full # pass through the whole thing for each # node in the original list. ...
tuples' is a list of tuples representing a partial ordering. """ for set_ in sort_as_subsets(tuples, allitems): for s in set_: yield s def find_cycles(tuples, allitems): # adapted from: # http://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html
81
81
272
40
40
banianlabs/Stash-Prototype
venv/lib/python2.7/site-packages/sqlalchemy/util/topological.py
Python
find_cycles
find_cycles
51
88
51
54
4f8705e04b43a636afe1fe60b09453b95a00a9d6
bigcode/the-stack
train
1ebfbd8536a9d3ba17692881
train
function
def get_lr(lr_init, lr_decay_rate, num_epoch_per_decay, total_epochs, steps_per_epoch, is_stair=False): """ generate learning rate array Args: lr_init(float): init learning rate lr_decay_rate (float): total_epochs(int): total epoch of training steps_per_epoch(int): steps of one ...
def get_lr(lr_init, lr_decay_rate, num_epoch_per_decay, total_epochs, steps_per_epoch, is_stair=False):
""" generate learning rate array Args: lr_init(float): init learning rate lr_decay_rate (float): total_epochs(int): total epoch of training steps_per_epoch(int): steps of one epoch is_stair(bool): If `True` decay the learning rate at discrete intervals Returns: ...
# See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """learning rate exponential decay generator""" import math import numpy as np def get_lr(lr_init, lr_decay_rate, num_epoch_per_decay, tot...
64
64
206
28
35
leelige/mindspore
research/cv/pnasnet/src/lr_generator.py
Python
get_lr
get_lr
19
42
19
19
4dc7ddc62975a6ba3f5e22c5e9ca8b721e41b06d
bigcode/the-stack
train
460cc8f8e7885b51958f9c63
train
class
class Printer(BasePrinter): def __init__(self, args=None, variables=None): token = variables.get('slack_bot_token') if token is None: token = os.environ.get('SLACK_BOT_TOKEN') self.client = WebClient(token=token) self.args = args self.variables = variables d...
class Printer(BasePrinter):
def __init__(self, args=None, variables=None): token = variables.get('slack_bot_token') if token is None: token = os.environ.get('SLACK_BOT_TOKEN') self.client = WebClient(token=token) self.args = args self.variables = variables def print(self, title, message...
#!/usr/bin/python3 import os import sys import time from slack_sdk import WebClient from slack_sdk.errors import SlackClientError, SlackApiError from sitewatcher.interfaces.ifprinter import BasePrinter class Printer(BasePrinter):
51
80
268
5
45
mkyutani/sitewatcher
sitewatcher/interfaces/ifslack.py
Python
Printer
Printer
12
41
12
13
2108d12cebcda6231e6df4bf644041cb94061fb9
bigcode/the-stack
train
d6c632d61fc4e2585068c804
train
class
class SQLAlchemyBaseUoW(IUoW): def __init__(self, session: AsyncSession): self._session = session @exception_mapper async def commit(self) -> None: await self._session.commit() async def rollback(self) -> None: await self._session.rollback()
class SQLAlchemyBaseUoW(IUoW):
def __init__(self, session: AsyncSession): self._session = session @exception_mapper async def commit(self) -> None: await self._session.commit() async def rollback(self) -> None: await self._session.rollback()
UoW from app.domain.common.interfaces.uow import IUoW from app.domain.user.interfaces.persistence import IUserReader, IUserRepo from app.domain.user.interfaces.uow import IUserUoW from app.infrastructure.database.exception_mapper import exception_mapper class SQLAlchemyBaseUoW(IUoW):
64
64
68
12
51
AnViSe/cost_confirmation_bot
app/infrastructure/database/uow.py
Python
SQLAlchemyBaseUoW
SQLAlchemyBaseUoW
13
22
13
13
f5286ee7001afd812d375a551524c8bd6490170c
bigcode/the-stack
train
751f30f49eedd73d04719975
train
class
class SQLAlchemyUoW(SQLAlchemyBaseUoW, IUserUoW, IAccessLevelUoW): user: IUserRepo user_reader = IUserReader access_level_reader: IAccessLevelReader def __init__( self, session: AsyncSession, user_repo: Type[IUserRepo], user_reader: Type[IUserReader], access_leve...
class SQLAlchemyUoW(SQLAlchemyBaseUoW, IUserUoW, IAccessLevelUoW):
user: IUserRepo user_reader = IUserReader access_level_reader: IAccessLevelReader def __init__( self, session: AsyncSession, user_repo: Type[IUserRepo], user_reader: Type[IUserReader], access_level_reader: Type[IAccessLevelReader], ): self.user = user...
session @exception_mapper async def commit(self) -> None: await self._session.commit() async def rollback(self) -> None: await self._session.rollback() class SQLAlchemyUoW(SQLAlchemyBaseUoW, IUserUoW, IAccessLevelUoW):
64
64
129
25
39
AnViSe/cost_confirmation_bot
app/infrastructure/database/uow.py
Python
SQLAlchemyUoW
SQLAlchemyUoW
25
40
25
25
8a0bdccf5db8a38be3f2bbf36f280dc657c2e122
bigcode/the-stack
train
a78946399d60a41d49741218
train
function
def morphTriangle(img1, img2, img, t1, t2, t, alpha): # Find bounding rectangle for each triangle r1 = cv2.boundingRect(np.float32([t1])) r2 = cv2.boundingRect(np.float32([t2])) r = cv2.boundingRect(np.float32([t])) # Offset points by left top corner of the respective rectangles t1Rect = [] ...
def morphTriangle(img1, img2, img, t1, t2, t, alpha): # Find bounding rectangle for each triangle
r1 = cv2.boundingRect(np.float32([t1])) r2 = cv2.boundingRect(np.float32([t2])) r = cv2.boundingRect(np.float32([t])) # Offset points by left top corner of the respective rectangles t1Rect = [] t2Rect = [] tRect = [] for i in range(0, 3): tRect.append(((t[i][0] - r[0]), (t[i][1] ...
AffineTransform(src, srcTri, dstTri, size): # Given a pair of triangles, find the affine transform. warpMat = cv2.getAffineTransform(np.float32(srcTri), np.float32(dstTri)) # Apply the Affine Transform just found to the src image dst = cv2.warpAffine(src, warpMat, (size[0], size[1]), None, ...
154
154
515
30
123
anshul2807/Automation-scripts
face_morpher/facemorphing.py
Python
morphTriangle
morphTriangle
33
61
33
35
42c09d6b1f0dd8e25704ed7dd3d349295b60495e
bigcode/the-stack
train
d90ad3aa5c170a07d58087c4
train
function
def readPoints(path): # Create array of points points = [] # Read points with open(path) as file: for line in file: x, y = line.split() points.append((int(x), int(y))) return points
def readPoints(path): # Create array of points
points = [] # Read points with open(path) as file: for line in file: x, y = line.split() points.append((int(x), int(y))) return points
import numpy as np import cv2 # import sys # Read points from text file def readPoints(path): # Create array of points
32
64
57
12
19
anshul2807/Automation-scripts
face_morpher/facemorphing.py
Python
readPoints
readPoints
7
16
7
8
f7ac767bdfa75132bbdd776588f889a747c57ddb
bigcode/the-stack
train
0bb0c1b9c05ec72bd115fdbc
train
function
def applyAffineTransform(src, srcTri, dstTri, size): # Given a pair of triangles, find the affine transform. warpMat = cv2.getAffineTransform(np.float32(srcTri), np.float32(dstTri)) # Apply the Affine Transform just found to the src image dst = cv2.warpAffine(src, warpMat, (size[0], size[1]), None, ...
def applyAffineTransform(src, srcTri, dstTri, size): # Given a pair of triangles, find the affine transform.
warpMat = cv2.getAffineTransform(np.float32(srcTri), np.float32(dstTri)) # Apply the Affine Transform just found to the src image dst = cv2.warpAffine(src, warpMat, (size[0], size[1]), None, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101) retu...
() points.append((int(x), int(y))) return points # Apply affine transform calculated using srcTri and dstTri to src and # output an image of size. def applyAffineTransform(src, srcTri, dstTri, size): # Given a pair of triangles, find the affine transform.
64
64
109
27
37
anshul2807/Automation-scripts
face_morpher/facemorphing.py
Python
applyAffineTransform
applyAffineTransform
22
29
22
23
b01ccb62dcf573bc53684382e34ba273c5886a6e
bigcode/the-stack
train
2ede3f7238ed88dfc50000a8
train
class
class VpnSite(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, address_space: Optional[pulumi.Input[pulumi.InputType['AddressSpaceArgs']]] = None, bgp_properties: Option...
class VpnSite(pulumi.CustomResource): @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, address_space: Optional[pulumi.Input[pulumi.InputType['AddressSpaceArgs']]] = None, bgp_properties: Optional[pulumi.Input[pulumi.InputType['BgpSettingsArgs']]...
an(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "virtual_wan", value) @property @pulumi.getter(name="vpnSiteLinks") def vpn_site_links(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VpnSiteLinkArgs']]]]: """ List of all vpn site links """ ...
256
256
3,560
15
241
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/network/v20190601/vpn_site.py
Python
VpnSite
VpnSite
230
486
230
231
eabbca46743443fe8642b02e910267aa8b9aedba
bigcode/the-stack
train
ff0b48947a3468fb9703345b
train
class
@pulumi.input_type class VpnSiteArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], address_space: Optional[pulumi.Input['AddressSpaceArgs']] = None, bgp_properties: Optional[pulumi.Input['BgpSettingsArgs']] = None, device_prope...
@pulumi.input_type class VpnSiteArgs:
def __init__(__self__, *, resource_group_name: pulumi.Input[str], address_space: Optional[pulumi.Input['AddressSpaceArgs']] = None, bgp_properties: Optional[pulumi.Input['BgpSettingsArgs']] = None, device_properties: Optional[pulumi.Input['DevicePr...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
110
256
2,008
12
98
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/network/v20190601/vpn_site.py
Python
VpnSiteArgs
VpnSiteArgs
15
227
15
16
220f9e55a7d9641bec9e9c6ca499e90047df0176
bigcode/the-stack
train
93bcae9555650db1e6d1e78c
train
class
class LSCDefaultTest(zeit.content.article.testing.FunctionalTestCase): def setUp(self): super(LSCDefaultTest, self).setUp() self.repository[ 'article'] = zeit.content.article.testing.create_article() with checked_out(self.repository['article']) as co: co.body.create_...
class LSCDefaultTest(zeit.content.article.testing.FunctionalTestCase):
def setUp(self): super(LSCDefaultTest, self).setUp() self.repository[ 'article'] = zeit.content.article.testing.create_article() with checked_out(self.repository['article']) as co: co.body.create_item('liveblog') self.assertFalse(ISemanticChange(co).has_se...
from zeit.cms.checkout.helper import checked_out from zeit.cms.content.interfaces import ISemanticChange import zeit.content.article.testing import zeit.edit.interfaces class LSCDefaultTest(zeit.content.article.testing.FunctionalTestCase):
46
64
207
15
30
rickdg/vivi
core/src/zeit/content/article/edit/tests/test_liveblog.py
Python
LSCDefaultTest
LSCDefaultTest
7
26
7
8
4a9aefc89d3c95dd81dc0f66cb0460cc45df80f4
bigcode/the-stack
train
9862148c5862086e6ccba03a
train
class
class LiveblogTest(zeit.content.article.testing.FunctionalTestCase): def get_liveblog(self): from zeit.content.article.edit.liveblog import Liveblog import lxml.objectify liveblog = Liveblog(None, lxml.objectify.E.liveblog()) return liveblog def test_liveblog_should_be_set(self...
class LiveblogTest(zeit.content.article.testing.FunctionalTestCase):
def get_liveblog(self): from zeit.content.article.edit.liveblog import Liveblog import lxml.objectify liveblog = Liveblog(None, lxml.objectify.E.liveblog()) return liveblog def test_liveblog_should_be_set(self): liveblog = self.get_liveblog() liveblog.blog_id = u...
'] lsc = ISemanticChange(article).last_semantic_change zeit.cms.workflow.interfaces.IPublishInfo(article).urgent = True zeit.cms.workflow.interfaces.IPublish(article).publish() self.assertEqual(lsc, ISemanticChange(article).last_semantic_change) class LiveblogTest(zeit.content.article.te...
73
73
245
14
59
rickdg/vivi
core/src/zeit/content/article/edit/tests/test_liveblog.py
Python
LiveblogTest
LiveblogTest
29
52
29
30
1b7ddee83bdf6a26e1fe72b11c7217188c476666
bigcode/the-stack
train
4bac651643cbc3840f400de3
train
class
class FilteredQueryTestCase(TestCase): """ Unit tests ported from Java Lucene """ def setUp(self): self.directory = RAMDirectory() writer = IndexWriter(self.directory, WhitespaceAnalyzer(), True, IndexWriter.MaxFieldLength.LIMITED) doc = Document()...
class FilteredQueryTestCase(TestCase):
""" Unit tests ported from Java Lucene """ def setUp(self): self.directory = RAMDirectory() writer = IndexWriter(self.directory, WhitespaceAnalyzer(), True, IndexWriter.MaxFieldLength.LIMITED) doc = Document() doc.add(Field("field", "one tw...
# ==================================================================== # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
156
230
767
9
147
fnp/pylucene
test/test_FilteredQuery.py
Python
FilteredQueryTestCase
FilteredQueryTestCase
19
119
19
19
009f2d3fca2f939c6f0e7e10849047e56ce70613
bigcode/the-stack
train
ee1310cbedbf1930ba72698f
train
class
class MerkleBlockTest(ShitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 self.setup_clean_chain = True # Nodes 0/1 are "wallet" nodes, Nodes 2/3 are used for testing self.extra_args = [[], [], [], ["-txindex"]] def skip_test_if_missing_module(self): se...
class MerkleBlockTest(ShitcoinTestFramework):
def set_test_params(self): self.num_nodes = 4 self.setup_clean_chain = True # Nodes 0/1 are "wallet" nodes, Nodes 2/3 are used for testing self.extra_args = [[], [], [], ["-txindex"]] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def setup_network(...
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test gettxoutproof and verifytxoutproof RPCs.""" from test_framework.messages import CMerkleBlock, Fro...
121
256
1,349
12
108
Shitcoin-beta/shitcoin-sc
test/functional/rpc_txoutproof.py
Python
MerkleBlockTest
MerkleBlockTest
11
102
11
11
c584fe964a731d1cfd33f87c227882d44f942d9f
bigcode/the-stack
train
f8a267e75e8817f1e25c4e46
train
function
def mouse_callback(event, x, y, flags, param): global size global image global line if event == 1: image = cv2.circle(image, (x, y), 12, (0, 255, 0), -1) line = line + ' {0:.7f} {1:.7f}'.format(x / size, y / size) cv2.imshow('ROI selector', image)
def mouse_callback(event, x, y, flags, param):
global size global image global line if event == 1: image = cv2.circle(image, (x, y), 12, (0, 255, 0), -1) line = line + ' {0:.7f} {1:.7f}'.format(x / size, y / size) cv2.imshow('ROI selector', image)
import cv2 size = 0 def mouse_callback(event, x, y, flags, param):
22
64
97
13
8
vsskarthik/TI1K-Dataset
scripts/annotate_video.py
Python
mouse_callback
mouse_callback
6
13
6
6
dfce030b2d6a385f91a75d8d8127ac8c1f5e4b28
bigcode/the-stack
train
3b94fbf204c24cb32f48a2c7
train
function
@socketio.on("send question") def generate_message(body, methods=["POST"]): question = body["message"] twitter_handle = body["username"] # Call get_user_tweets() from twitter_scraper_fetcher.py to scrape some tweets tweets = get_user_tweets(twitter_handle) try: bot_answer = generate_bot_answer(twitter_ha...
@socketio.on("send question") def generate_message(body, methods=["POST"]):
question = body["message"] twitter_handle = body["username"] # Call get_user_tweets() from twitter_scraper_fetcher.py to scrape some tweets tweets = get_user_tweets(twitter_handle) try: bot_answer = generate_bot_answer(twitter_handle, question) moderated_answer = moderate(bot_answer) # Send the a...
random from markov import * app = Flask(__name__) socketio = SocketIO(app) # Renders UI @app.route("/") def home(): return render_template("homepage.html") # Chat API - WebSocket @socketio.on("send question") def generate_message(body, methods=["POST"]):
64
64
166
18
45
RadCon/Part-3
main.py
Python
generate_message
generate_message
19
34
19
20
dd81197482906f77fe69a8b49c88c3abab769e16
bigcode/the-stack
train
65f6c85183631639c51b7955
train
function
@app.route("/") def home(): return render_template("homepage.html")
@app.route("/") def home():
return render_template("homepage.html")
from flask_socketio import SocketIO from twitter_scraper_fetcher import * from mlh_twitter_api import moderate import json import config import random from markov import * app = Flask(__name__) socketio = SocketIO(app) # Renders UI @app.route("/") def home():
64
64
14
6
57
RadCon/Part-3
main.py
Python
home
home
14
16
14
15
a04f32f3d1ee95fe2649d1481db7888be7418cc7
bigcode/the-stack
train
220fb1367c4eee61d564ce03
train
function
@jsonresolver.hookimpl def jsonresolver_loader(url_map): """Resolve the referred Document for an Item record.""" from flask import current_app @get_pid_or_default(default_value=dict()) def get_document(document_pid): """Return the Document record.""" Document = current_app_ils.document_...
@jsonresolver.hookimpl def jsonresolver_loader(url_map):
"""Resolve the referred Document for an Item record.""" from flask import current_app @get_pid_or_default(default_value=dict()) def get_document(document_pid): """Return the Document record.""" Document = current_app_ils.document_record_cls document = Document.get_record_by_pid(...
get_field_value_for_record as get_field_value from invenio_app_ils.records.jsonresolvers.api import get_pid_or_default, pick # Note: there must be only one resolver per file, # otherwise only the last one is registered @jsonresolver.hookimpl def jsonresolver_loader(url_map):
64
64
200
14
49
jrcastro2/invenio-app-ils
invenio_app_ils/items/jsonresolvers/item_document.py
Python
jsonresolver_loader
jsonresolver_loader
23
54
23
24
6367cc67a386165e3a458af23849a0c710f730d2
bigcode/the-stack
train
61eb016a1d43aeef456ba815
train
function
def login_request(request): context = {} if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return render(...
def login_request(request):
context = {} if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return render(request, 'djangoapp/index.ht...
): return render(request, 'djangoapp/about.html', {}) # Create a `contact` view to return a static contact page def contact(request): return render(request, 'djangoapp/contact.html', {}) # Create a `login_request` view to handle sign in request def login_request(request):
64
64
83
5
58
gowtham2910r/agfzb-CloudAppDevelopment_Capstone
server/djangoapp/views.py
Python
login_request
login_request
28
38
28
28
405e11b941e88a1e5b107c4a47077766a38702f7
bigcode/the-stack
train
118a437cad0af5459d16d8e0
train
function
def get_dealerships(request): context = {} if request.method == "GET": return render(request, 'djangoapp/index.html', context)
def get_dealerships(request):
context = {} if request.method == "GET": return render(request, 'djangoapp/index.html', context)
login(request, user) return render(request, "djangoapp/index.html", {}) else: return render(request, 'djangoapp/registration.html', context) # Update the `get_dealerships` view to render the index page with a list of dealerships def get_dealerships(request):
64
64
33
8
55
gowtham2910r/agfzb-CloudAppDevelopment_Capstone
server/djangoapp/views.py
Python
get_dealerships
get_dealerships
69
72
69
69
67e2d4158caf8288d49b3f17e40d228404e025f0
bigcode/the-stack
train
c9e624676ee61fb317557e35
train
function
def about(request): return render(request, 'djangoapp/about.html', {})
def about(request):
return render(request, 'djangoapp/about.html', {})
import login, logout, authenticate from django.contrib import messages from datetime import datetime import logging import json # Get an instance of a logger logger = logging.getLogger(__name__) # Create your views here. # Create an `about` view to render a static about page def about(request):
64
64
16
4
59
gowtham2910r/agfzb-CloudAppDevelopment_Capstone
server/djangoapp/views.py
Python
about
about
20
21
20
20
edbe46fa8c4cd2b4f6b8a4c5dcae9aa18d28e75c
bigcode/the-stack
train
b762027c7302a95c948048bf
train
function
def registration_request(request): context = {} if request.method == 'GET': return render(request, 'djangoapp/registration.html', context) elif request.method == 'POST': username = request.POST['username'] password = request.POST['password'] first_name = request.POST['fname']...
def registration_request(request):
context = {} if request.method == 'GET': return render(request, 'djangoapp/registration.html', context) elif request.method == 'POST': username = request.POST['username'] password = request.POST['password'] first_name = request.POST['fname'] last_name = request.POST['...
, 'djangoapp/index.html', {}) # Create a `logout_request` view to handle sign out request def logout_request(request): logout(request) return render(request, 'djangoapp/index.html', {}) # Create a `registration_request` view to handle sign up request def registration_request(request):
64
64
175
5
58
gowtham2910r/agfzb-CloudAppDevelopment_Capstone
server/djangoapp/views.py
Python
registration_request
registration_request
46
66
46
46
494214a38f652a01aa36da439bc786bcae5e9140
bigcode/the-stack
train
2f0ea935b09a889523964cb7
train
function
def logout_request(request): logout(request) return render(request, 'djangoapp/index.html', {})
def logout_request(request):
logout(request) return render(request, 'djangoapp/index.html', {})
, password=password) if user is not None: login(request, user) return render(request, 'djangoapp/index.html', {}) else: return render(request, 'djangoapp/index.html', {}) # Create a `logout_request` view to handle sign out request def logout_request(request):
64
64
21
5
58
gowtham2910r/agfzb-CloudAppDevelopment_Capstone
server/djangoapp/views.py
Python
logout_request
logout_request
41
43
41
41
730c9e2a1911712c32b0e13419747648e34d7610
bigcode/the-stack
train
01e57c996e70d34effd7092b
train
function
def contact(request): return render(request, 'djangoapp/contact.html', {})
def contact(request):
return render(request, 'djangoapp/contact.html', {})
logger = logging.getLogger(__name__) # Create your views here. # Create an `about` view to render a static about page def about(request): return render(request, 'djangoapp/about.html', {}) # Create a `contact` view to return a static contact page def contact(request):
64
64
16
4
59
gowtham2910r/agfzb-CloudAppDevelopment_Capstone
server/djangoapp/views.py
Python
contact
contact
24
25
24
24
502b7108f974c3f8f83c1d353c010c70dd4fe6e8
bigcode/the-stack
train
86315e3a6e1bbc66f4c70308
train
function
def test_service_appinfo(): appinfos = [x for x in windows.system.services if x.name == b"Appinfo"] assert len(appinfos) == 1 appinfo = appinfos[0] assert appinfo.status.type & gdef.SERVICE_WIN32_OWN_PROCESS # Check other fields assert appinfo.name == b"Appinfo" assert appinfo.description ==...
def test_service_appinfo():
appinfos = [x for x in windows.system.services if x.name == b"Appinfo"] assert len(appinfos) == 1 appinfo = appinfos[0] assert appinfo.status.type & gdef.SERVICE_WIN32_OWN_PROCESS # Check other fields assert appinfo.name == b"Appinfo" assert appinfo.description == b"Application Information"
windows.generated_def as gdef def test_services_process(): services_with_process = [s for s in windows.system.services if s.status.dwProcessId] service = services_with_process[0] proc = service.process assert proc.pid == service.status.dwProcessId def test_service_appinfo():
64
64
91
6
57
lucasg/PythonForWindows
tests/test_service.py
Python
test_service_appinfo
test_service_appinfo
14
21
14
14
e301c88eb46527c1eff38504871f86d7d9164c3f
bigcode/the-stack
train
0adcc62c247008bc3c9e565d
train
function
def test_services_process(): services_with_process = [s for s in windows.system.services if s.status.dwProcessId] service = services_with_process[0] proc = service.process assert proc.pid == service.status.dwProcessId
def test_services_process():
services_with_process = [s for s in windows.system.services if s.status.dwProcessId] service = services_with_process[0] proc = service.process assert proc.pid == service.status.dwProcessId
import pytest import windows import windows.generated_def as gdef def test_services_process():
19
64
51
5
13
lucasg/PythonForWindows
tests/test_service.py
Python
test_services_process
test_services_process
7
11
7
7
93187c7d91e2d3a07fe5b514e8e9b058ef556bd9
bigcode/the-stack
train
6550740afe8b6ef9bccb6566
train
class
class FastTextEmbedding(WordEmbedding): def load_embedding(self, progbar=None): self.fasttext_model = fastText.load_model(self.embedding_path) return None, None, None def add_word_embedding(self, matrix, word_index, word): self.embedding_matrix.append( self.fasttext_model....
class FastTextEmbedding(WordEmbedding):
def load_embedding(self, progbar=None): self.fasttext_model = fastText.load_model(self.embedding_path) return None, None, None def add_word_embedding(self, matrix, word_index, word): self.embedding_matrix.append( self.fasttext_model.get_word_vector(word).tolist()) ...
+ 1, []) return word_index, embedding_matrix, vocab def add_word_embedding(self, matrix, word_index, word): if word in word_index: self.embedding_matrix.append( matrix[word_index[word]]) return True return False class FastTextEmbedding(WordEmbeddi...
64
64
76
8
55
LIAMF-USP/deep_active_learning
word_embedding/word_embedding.py
Python
FastTextEmbedding
FastTextEmbedding
170
181
170
171
15b0471f38777da5e69cb1a2d3d7c39082ea63c1
bigcode/the-stack
train
23d027c55c65431a9df588c1
train
class
class GloVeEmbedding(WordEmbedding): def load_embedding(self, progbar=None): word_index = dict() embedding_matrix = [] vocab = [] self.add_zero_rows(embedding_matrix) with open(self.embedding_path, 'r') as glove_file: for index, glove_line in enumerate(glove_fi...
class GloVeEmbedding(WordEmbedding):
def load_embedding(self, progbar=None): word_index = dict() embedding_matrix = [] vocab = [] self.add_zero_rows(embedding_matrix) with open(self.embedding_path, 'r') as glove_file: for index, glove_line in enumerate(glove_file.readlines()): glove...
1 self.vocab.append(word) return self.word_index, self.embedding_matrix, self.vocab def load_embedding(self): raise NotImplementedError def add_word_embedding(self, matrix, word_index, word): raise NotImplementedError class GloVeEmbedding(WordEmbedding):
64
64
188
9
54
LIAMF-USP/deep_active_learning
word_embedding/word_embedding.py
Python
GloVeEmbedding
GloVeEmbedding
139
167
139
140
27d96face4b3abff821e38d3d31b2543e8ab3222
bigcode/the-stack
train
ec7dda7b32bd4e3fee8a28bd
train
class
class Word2VecEmbedding(WordEmbedding): def load_embedding(self, progbar=None): self.word2vec_model = gensim.models.KeyedVectors.load_word2vec_format( self.embedding_path, binary=True) return None, None, None def add_word_embedding(self, matrix, word_index, word): if word ...
class Word2VecEmbedding(WordEmbedding):
def load_embedding(self, progbar=None): self.word2vec_model = gensim.models.KeyedVectors.load_word2vec_format( self.embedding_path, binary=True) return None, None, None def add_word_embedding(self, matrix, word_index, word): if word in self.word2vec_model: self....
text_model = fastText.load_model(self.embedding_path) return None, None, None def add_word_embedding(self, matrix, word_index, word): self.embedding_matrix.append( self.fasttext_model.get_word_vector(word).tolist()) return True class Word2VecEmbedding(WordEmbedding):
64
64
102
9
54
LIAMF-USP/deep_active_learning
word_embedding/word_embedding.py
Python
Word2VecEmbedding
Word2VecEmbedding
184
199
184
185
9d0f4bfce69413c07450b94ae221f055a7baa5f9
bigcode/the-stack
train
3c7536fd551f3868dd4aa17f
train
class
class WordEmbedding: def __init__(self, embedding_path, embed_size, word_vocab, embedding_save_path, word_index_save_path): self.embedding_path = embedding_path self.embed_size = embed_size self.word_vocab = word_vocab self.embedding_save_path = embedding_save_path...
class WordEmbedding:
def __init__(self, embedding_path, embed_size, word_vocab, embedding_save_path, word_index_save_path): self.embedding_path = embedding_path self.embed_size = embed_size self.word_vocab = word_vocab self.embedding_save_path = embedding_save_path self.word_ind...
import fastText import os import pickle import gensim import numpy as np WORD_POS = 0 UNK_TOKEN = '<unk>' GLOVE_STR = 'glove' FASTTEXT_STR = 'wiki' WORD2VEC_STR = 'Google' def get_embedding(embedding_path, embed_size, vocab, embedding_save_path=None, word_index_save_path=None, progbar=None): ...
207
218
729
4
202
LIAMF-USP/deep_active_learning
word_embedding/word_embedding.py
Python
WordEmbedding
WordEmbedding
33
136
33
34
7606639fad6653528cacf34fcb482b78d84337a7
bigcode/the-stack
train
feeb608b49901769dd2a6128
train
function
def get_embedding(embedding_path, embed_size, vocab, embedding_save_path=None, word_index_save_path=None, progbar=None): word_embedding = None if GLOVE_STR in embedding_path: word_embedding = GloVeEmbedding(embedding_path, embed_size, vocab, emb...
def get_embedding(embedding_path, embed_size, vocab, embedding_save_path=None, word_index_save_path=None, progbar=None):
word_embedding = None if GLOVE_STR in embedding_path: word_embedding = GloVeEmbedding(embedding_path, embed_size, vocab, embedding_save_path, word_index_save_path) elif FASTTEXT_STR in embedding_path: word_embedding = FastTextEmbedding(embedding_path,...
WORD_POS = 0 UNK_TOKEN = '<unk>' GLOVE_STR = 'glove' FASTTEXT_STR = 'wiki' WORD2VEC_STR = 'Google' def get_embedding(embedding_path, embed_size, vocab, embedding_save_path=None, word_index_save_path=None, progbar=None):
64
64
148
28
36
LIAMF-USP/deep_active_learning
word_embedding/word_embedding.py
Python
get_embedding
get_embedding
16
30
16
17
43cfe84b3d2980a47ae1cc51796cdff3ddc59904
bigcode/the-stack
train
099a1a2b8b092c081e217c88
train
function
def _http_archive_repo_impl(name, **kwargs): # `existing_rule_keys` contains the names of repositories that have already # been defined in the Bazel workspace. By skipping repos with existing keys, # users can override dependency versions by using standard Bazel repository # rules in their WORKSPACE fil...
def _http_archive_repo_impl(name, **kwargs): # `existing_rule_keys` contains the names of repositories that have already # been defined in the Bazel workspace. By skipping repos with existing keys, # users can override dependency versions by using standard Bazel repository # rules in their WORKSPACE fil...
existing_rule_keys = native.existing_rules().keys() if name in existing_rule_keys: # This repository has already been defined, probably because the user # wants to override the version. Do nothing. return location = REPOSITORY_LOCATIONS[name] # HTTP tarball at a given URL. Add ...
def _http_archive_repo_impl(name, **kwargs): # `existing_rule_keys` contains the names of repositories that have already # been defined in the Bazel workspace. By skipping repos with existing keys, # users can override dependency versions by using standard Bazel repository # rules in their WORKSPACE fil...
67
64
184
67
0
jundizhou/pixie
bazel/repositories.bzl
Python
_http_archive_repo_impl
_http_archive_repo_impl
25
45
25
29
9eb042e5e89ce1b54e57ebb17d1c5a10614f566c
bigcode/the-stack
train
f7501d9037e62c9a9df1e7bb
train
function
def _git_repo_impl(name, **kwargs): # `existing_rule_keys` contains the names of repositories that have already # been defined in the Bazel workspace. By skipping repos with existing keys, # users can override dependency versions by using standard Bazel repository # rules in their WORKSPACE files. e...
def _git_repo_impl(name, **kwargs): # `existing_rule_keys` contains the names of repositories that have already # been defined in the Bazel workspace. By skipping repos with existing keys, # users can override dependency versions by using standard Bazel repository # rules in their WORKSPACE files.
existing_rule_keys = native.existing_rules().keys() if name in existing_rule_keys: # This repository has already been defined, probably because the user # wants to override the version. Do nothing. return location = GIT_REPOSITORY_LOCATIONS[name] # HTTP tarball at a given URL. ...
def _git_repo_impl(name, **kwargs): # `existing_rule_keys` contains the names of repositories that have already # been defined in the Bazel workspace. By skipping repos with existing keys, # users can override dependency versions by using standard Bazel repository # rules in their WORKSPACE files.
66
64
200
66
0
jundizhou/pixie
bazel/repositories.bzl
Python
_git_repo_impl
_git_repo_impl
47
69
47
51
02c26a4414d1c711dbfedfb84b6e5b8de4fa7bac
bigcode/the-stack
train
32830e8c3aa1185f146f071f
train
function
def _cc_deps(): # Dependencies with native bazel build files. _bazel_repo("com_google_protobuf", patches = ["//bazel/external:protobuf.patch", "//bazel/external:protobuf_text_format.patch"], patch_args = ["-p1"]) _bazel_repo("com_github_grpc_grpc", patches = ["//bazel/external:grpc.patch"], patch_args = ["-...
def _cc_deps(): # Dependencies with native bazel build files.
_bazel_repo("com_google_protobuf", patches = ["//bazel/external:protobuf.patch", "//bazel/external:protobuf_text_format.patch"], patch_args = ["-p1"]) _bazel_repo("com_github_grpc_grpc", patches = ["//bazel/external:grpc.patch"], patch_args = ["-p1"]) _bazel_repo("com_google_benchmark") _bazel_repo("com...
"], commit = location["commit"], init_submodules = True, recursive_init_submodules = True, shallow_since = location.get("shallow_since", ""), **kwargs ) def _git_repo(name, **kwargs): _git_repo_impl(name, **kwargs) # For bazel repos do not require customization. def _ba...
256
256
1,353
16
240
jundizhou/pixie
bazel/repositories.bzl
Python
_cc_deps
_cc_deps
96
152
96
97
438900ea07a7f93385d7519f0be65517f3d80ef2
bigcode/the-stack
train
4d4b051fa4317d167e6bcb77
train
function
def _include_all_repo(name, **kwargs): kwargs["build_file_content"] = BUILD_ALL_CONTENT _http_archive_repo_impl(name, **kwargs)
def _include_all_repo(name, **kwargs):
kwargs["build_file_content"] = BUILD_ALL_CONTENT _http_archive_repo_impl(name, **kwargs)
(name, **kwargs) # For bazel repos do not require customization. def _bazel_repo(name, **kwargs): _http_archive_repo_impl(name, **kwargs) # With a predefined "include all files" BUILD file for a non-Bazel repo. def _include_all_repo(name, **kwargs):
64
64
33
10
54
jundizhou/pixie
bazel/repositories.bzl
Python
_include_all_repo
_include_all_repo
79
81
79
79
1764de0b14febb7f504aa9de0a65f10d32ce2e3c
bigcode/the-stack
train
dae9a7ed33cdd5b6f9e170c0
train
function
def _bazel_repo(name, **kwargs): _http_archive_repo_impl(name, **kwargs)
def _bazel_repo(name, **kwargs):
_http_archive_repo_impl(name, **kwargs)
recursive_init_submodules = True, shallow_since = location.get("shallow_since", ""), **kwargs ) def _git_repo(name, **kwargs): _git_repo_impl(name, **kwargs) # For bazel repos do not require customization. def _bazel_repo(name, **kwargs):
64
64
21
10
54
jundizhou/pixie
bazel/repositories.bzl
Python
_bazel_repo
_bazel_repo
75
76
75
75
206c3f14aa8f8d90b512f495998d1ff42b19ac63
bigcode/the-stack
train
b5052f5f45afc5e5d8597963
train
function
def _git_repo(name, **kwargs): _git_repo_impl(name, **kwargs)
def _git_repo(name, **kwargs):
_git_repo_impl(name, **kwargs)
_git_repository( name = name, remote = location["remote"], commit = location["commit"], init_submodules = True, recursive_init_submodules = True, shallow_since = location.get("shallow_since", ""), **kwargs ) def _git_repo(name, **kwargs):
64
64
19
9
55
jundizhou/pixie
bazel/repositories.bzl
Python
_git_repo
_git_repo
71
72
71
71
9c438586994f34693d96926cb9e819b2baf6467e
bigcode/the-stack
train
418eac9ffab6e293a7390718
train
function
def list_pl_deps(name): repo_urls = list() for repo_name, repo_config in REPOSITORY_LOCATIONS.items(): urls = repo_config["urls"] best_url = None for url in urls: if url.startswith("https://github.com") or best_url == None: best_url = url repo_urls.app...
def list_pl_deps(name):
repo_urls = list() for repo_name, repo_config in REPOSITORY_LOCATIONS.items(): urls = repo_config["urls"] best_url = None for url in urls: if url.startswith("https://github.com") or best_url == None: best_url = url repo_urls.append(best_url) for r...
patch_args = ["-p1"]) _include_all_repo("com_github_libuv_libuv", patches = ["//bazel/external:libuv.patch"], patch_args = ["-p1"]) _include_all_repo("com_github_libarchive_libarchive") def list_pl_deps(name):
64
64
174
7
57
jundizhou/pixie
bazel/repositories.bzl
Python
list_pl_deps
list_pl_deps
154
175
154
154
24766d832a0f71136a2147ca4718336f63a9dfe3
bigcode/the-stack
train
21f4174b6b900b6ec7458a16
train
function
def _com_llvm_lib(): native.new_local_repository( name = "com_llvm_lib", build_file = "bazel/external/llvm.BUILD", path = "/opt/clang-11.1", ) native.new_local_repository( name = "com_llvm_lib_libcpp", build_file = "bazel/external/llvm.BUILD", path = "/opt/cl...
def _com_llvm_lib():
native.new_local_repository( name = "com_llvm_lib", build_file = "bazel/external/llvm.BUILD", path = "/opt/clang-11.1", ) native.new_local_repository( name = "com_llvm_lib_libcpp", build_file = "bazel/external/llvm.BUILD", path = "/opt/clang-11.1-libc++", ...
_impl(name, **kwargs) # With a predefined "include all files" BUILD file for a non-Bazel repo. def _include_all_repo(name, **kwargs): kwargs["build_file_content"] = BUILD_ALL_CONTENT _http_archive_repo_impl(name, **kwargs) def _com_llvm_lib():
64
64
98
7
57
jundizhou/pixie
bazel/repositories.bzl
Python
_com_llvm_lib
_com_llvm_lib
83
94
83
83
8c24f6ac930cf531440d2a41a89f538b1f01aa63
bigcode/the-stack
train
c24a2efd29d9ede1aad283dd
train
function
def pl_deps(): _bazel_repo("bazel_skylib") _bazel_repo("bazel_gazelle") _bazel_repo("distroless") _bazel_repo("io_bazel_rules_go") _bazel_repo("io_bazel_rules_scala") _bazel_repo("rules_jvm_external") _bazel_repo("io_bazel_toolchains") _bazel_repo("rules_foreign_cc") _bazel_repo("io_...
def pl_deps():
_bazel_repo("bazel_skylib") _bazel_repo("bazel_gazelle") _bazel_repo("distroless") _bazel_repo("io_bazel_rules_go") _bazel_repo("io_bazel_rules_scala") _bazel_repo("rules_jvm_external") _bazel_repo("io_bazel_toolchains") _bazel_repo("rules_foreign_cc") _bazel_repo("io_bazel_rules_k8s...
(".git")] repo_urls.append(remote) native.genrule( name = name, outs = ["{}.out".format(name)], cmd = 'echo "{}" > $@'.format("\n".join(repo_urls)), visibility = ["//visibility:public"], ) def pl_deps():
64
64
175
5
59
jundizhou/pixie
bazel/repositories.bzl
Python
pl_deps
pl_deps
177
193
177
177
50d3dec3c35343354f2a76025a95cfab66aaa0c2
bigcode/the-stack
train
a2ee92dc8a439ce6ab01e3b3
train
function
@application.route('/check', methods=['GET', 'HEAD']) def check(): """ HAproxy check """ # Only GET is implemented if request.method not in ['GET', 'HEAD']: abort(501) return 'ok'
@application.route('/check', methods=['GET', 'HEAD']) def check():
""" HAproxy check """ # Only GET is implemented if request.method not in ['GET', 'HEAD']: abort(501) return 'ok'
config.get('return_scripts_info', False) if not info: return dumps({'status': 'done'}) output = dumps(ran, sort_keys=True, indent=4) logging.info(output) return output @application.route('/check', methods=['GET', 'HEAD']) def check():
64
64
54
16
47
aander07/python-github-webhooks
webhooks.py
Python
check
check
251
260
251
252
fbc14b1032fce0e99cfb1a095e5f44fa3bd5bd50
bigcode/the-stack
train
a035b120ac82dd81125bb104
train
class
class GithubMeta(object): """ Cache the Github Meta data """ def __init__(self): self._ips = [] self._etag = '' @property def ips(self): """Return the IP list""" return self._ips @ips.setter def ips(self, val): self._ips = val @property ...
class GithubMeta(object):
""" Cache the Github Meta data """ def __init__(self): self._ips = [] self._etag = '' @property def ips(self): """Return the IP list""" return self._ips @ips.setter def ips(self, val): self._ips = val @property def etag(self): "...
import isfile, abspath, normpath, dirname, join, basename import requests from ipaddress import ip_address, ip_network from flask import Flask, request, abort logging.basicConfig(stream=stderr) application = Flask(__name__) # pylint: disable=invalid-name class GithubMeta(object):
64
64
119
5
58
aander07/python-github-webhooks
webhooks.py
Python
GithubMeta
GithubMeta
42
67
42
42
ef8435fb57f81192823946b8071eea101ce4cf77
bigcode/the-stack
train
e71699b7ad6b80a0c0cb7d8b
train
function
@application.route('/', methods=['GET', 'POST']) def index(): """ Main WSGI application entry. """ path = normpath(abspath(dirname(__file__))) # Only POST is implemented if request.method != 'POST': abort(501) # Load config with open(join(path, 'config.json'), 'r') as cfg: ...
@application.route('/', methods=['GET', 'POST']) def index():
""" Main WSGI application entry. """ path = normpath(abspath(dirname(__file__))) # Only POST is implemented if request.method != 'POST': abort(501) # Load config with open(join(path, 'config.json'), 'r') as cfg: config = loads(cfg.read()) hooks = config.get('hooks...
kins/python-github-webhooks """ import logging from sys import stderr, hexversion import hmac import hashlib from json import loads, dumps from subprocess import Popen, PIPE from tempfile import mkstemp from os import access, X_OK, remove, fdopen from os.path import isfile, abspath, normpath, dirname, join, basename ...
256
256
1,330
14
241
aander07/python-github-webhooks
webhooks.py
Python
index
index
70
249
70
71
23a12dd98bc62ab49461b3b94d19a4f58f9970e7
bigcode/the-stack
train
04eab2b6b33a4eaa43a91a01
train
class
class _TestFactory(MarkerFactory): # Only used for testing import from module. pass
class _TestFactory(MarkerFactory): # Only used for testing import from module.
pass
.MPLMarkerSpec() def legend(self, map, parameters, colormaps): """ :param map: :param parameters: :param colormaps: :return: """ return class _TestFactory(MarkerFactory): # Only used for testing import from module.
64
64
21
18
45
cldf/cldfviz
src/cldfviz/map/__init__.py
Python
_TestFactory
_TestFactory
65
66
65
65
15aa4a974eac8f9bd0336b9a84e9a6715b04dfc6
bigcode/the-stack
train
53bd4e5e7be82615247b977a
train
class
class MarkerFactory: """ If the capabilities of standard `Map` implementations are not sufficient, custom plotting code can be provided as subclass of `MarkerFactory`. Note: It's the responsibility of the `MarkerFactory` to figure out what map format is requested. This can be done by inspecting...
class MarkerFactory:
""" If the capabilities of standard `Map` implementations are not sufficient, custom plotting code can be provided as subclass of `MarkerFactory`. Note: It's the responsibility of the `MarkerFactory` to figure out what map format is requested. This can be done by inspecting `self.args.format`, ...
import argparse import pycldf from . import leaflet # noqa: F401 try: from . import mpl # noqa: F401 WITH_CARTOPY = True except ImportError: # pragma: no cover WITH_CARTOPY = False mpl = None from .base import Map # noqa: F401 class MarkerFactory:
79
115
384
4
74
cldf/cldfviz
src/cldfviz/map/__init__.py
Python
MarkerFactory
MarkerFactory
15
62
15
15
9db82ca5ea040b4c76159e9ea18a6c1e821a5407
bigcode/the-stack
train
a0883e8b54b8149e570a33a4
train
class
@push_notification.apply class LiveAgents(Document): agent_type = StringField(required=True, choices=Utility.get_live_agents) config = DictField(required=True) override_bot = BooleanField(default=False) trigger_on_intents = ListField(StringField(), default=[]) trigger_on_actions = ListField(StringFi...
@push_notification.apply class LiveAgents(Document):
agent_type = StringField(required=True, choices=Utility.get_live_agents) config = DictField(required=True) override_bot = BooleanField(default=False) trigger_on_intents = ListField(StringField(), default=[]) trigger_on_actions = ListField(StringField(), default=[]) bot = StringField(required=Tru...
from mongoengine import Document, StringField, DictField, DateTimeField, ValidationError, ListField, BooleanField from datetime import datetime from kairon.shared.account.processor import AccountProcessor from kairon.shared.data.signals import push_notification from kairon.shared.utils import Utility @push_notificatio...
72
84
280
10
61
rit1200/kairon
kairon/shared/live_agent/data_objects.py
Python
LiveAgents
LiveAgents
9
36
9
10
0a44ff5328cc02cc1927ae0385154cb7d4ad61cb
bigcode/the-stack
train
2c9ab513b087005cf9f98e0f
train
class
class LiveAgentMetadata(Document): agent_type = StringField(required=True, choices=Utility.get_live_agents()) sender_id = StringField(required=True) metadata = DictField(required=True) bot = StringField(required=True) timestamp = DateTimeField(default=datetime.utcnow)
class LiveAgentMetadata(Document):
agent_type = StringField(required=True, choices=Utility.get_live_agents()) sender_id = StringField(required=True) metadata = DictField(required=True) bot = StringField(required=True) timestamp = DateTimeField(default=datetime.utcnow)
metadata = agent.complete_prerequisites(**bot_info) if metadata: document.config.update(metadata) for required_field in Utility.system_metadata['live_agents'][document.agent_type]['required_fields']: document.config[required_field] = Utility.encrypt_message(document.confi...
64
64
57
6
58
rit1200/kairon
kairon/shared/live_agent/data_objects.py
Python
LiveAgentMetadata
LiveAgentMetadata
39
44
39
39
a0d0deaad295dd6da4dee652e476f9db8199f6c0
bigcode/the-stack
train
fb79955a911d146b2a89bf3d
train
function
@pytest.fixture def permission_edit_properties(): return Permission.objects.get(codename='edit_properties')
@pytest.fixture def permission_edit_properties():
return Permission.objects.get(codename='edit_properties')
permission_view_group(): return Permission.objects.get(codename='view_group') @pytest.fixture def permission_edit_group(): return Permission.objects.get(codename='edit_group') @pytest.fixture def permission_view_properties(): return Permission.objects.get(codename='view_properties') @pytest.fixture def...
64
64
20
8
56
VanilleBid/weekly-saleor
tests/conftest.py
Python
permission_edit_properties
permission_edit_properties
619
621
619
620
31170453c0cd6c0dd399340c0b637d5a00b496a2
bigcode/the-stack
train
5fef6b40e7431e6d755d45c3
train
function
@pytest.fixture def order(billing_address): return Order.objects.create(billing_address=billing_address)
@pytest.fixture def order(billing_address):
return Order.objects.create(billing_address=billing_address)
return request_cart @pytest.fixture def request_checkout(checkout): import saleor.checkout.core def _override(*args, **kwargs): return checkout return set_value( saleor.checkout.core.Checkout, 'from_storage', _override) @pytest.fixture def order(billing_address):
64
64
21
9
55
VanilleBid/weekly-saleor
tests/conftest.py
Python
order
order
86
88
86
87
e500189ea2700fb2f01da833f18732979ff7b840
bigcode/the-stack
train
50ad884e33259aa905f48975
train
function
@pytest.fixture def product_type(color_attribute, size_attribute): product_type = ProductType.objects.create( name='Default Type', has_variants=False, is_shipping_required=True) product_type.product_attributes.add(color_attribute) product_type.variant_attributes.add(size_attribute) return produc...
@pytest.fixture def product_type(color_attribute, size_attribute):
product_type = ProductType.objects.create( name='Default Type', has_variants=False, is_shipping_required=True) product_type.product_attributes.add(color_attribute) product_type.variant_attributes.add(size_attribute) return product_type
return Permission.objects.get(codename='edit_voucher') @pytest.fixture def permission_view_order(): return Permission.objects.get(codename='view_order') @pytest.fixture def permission_edit_order(): return Permission.objects.get(codename='edit_order') @pytest.fixture def product_type(color_attribute, size_a...
64
64
60
12
52
VanilleBid/weekly-saleor
tests/conftest.py
Python
product_type
product_type
263
269
263
264
0031d7333c43abb9386b9d8bb6ab0e229eccddb6
bigcode/the-stack
train
3a77a8d148d4fbe23270eaa5
train
function
@pytest.fixture def unavailable_product(product_type, default_category): product = Product.objects.create( name='Test product', price=Decimal('10.00'), product_type=product_type, is_published=False, category=default_category) return product
@pytest.fixture def unavailable_product(product_type, default_category):
product = Product.objects.create( name='Test product', price=Decimal('10.00'), product_type=product_type, is_published=False, category=default_category) return product
return SimpleUploadedFile('product.jpg', img_data.getvalue()) @pytest.fixture def product_with_image(product_in_stock, product_image): product = product_in_stock ProductImage.objects.create(product=product, image=product_image) return product @pytest.fixture def unavailable_product(product_type, default_...
64
64
55
12
51
VanilleBid/weekly-saleor
tests/conftest.py
Python
unavailable_product
unavailable_product
392
398
392
393
538f05c9ac7db29fd0e32428fe88d0190dbbb18a
bigcode/the-stack
train
385c65c1c11ee4a87e4421d2
train
function
@pytest.fixture def permission_view_product(): return Permission.objects.get(codename='view_product')
@pytest.fixture def permission_view_product():
return Permission.objects.get(codename='view_product')
: disable=W0613 return Category.objects.create(name='Default', slug='default') @pytest.fixture def default_stock_location(db): return StockLocation.objects.create(name='Warehouse 1') @pytest.fixture def staff_group(): return Group.objects.create(name='test') @pytest.fixture def permission_view_product()...
64
64
20
8
56
VanilleBid/weekly-saleor
tests/conftest.py
Python
permission_view_product
permission_view_product
203
205
203
204
2408ba9d03b6d59b3446f9481120bfa81b1228a3
bigcode/the-stack
train
ce687b8fb830097e2f45b8ee
train
function
@pytest.fixture def product_without_shipping(default_category): product_type = ProductType.objects.create( name='Type with no shipping', has_variants=False, is_shipping_required=False) product = Product.objects.create( name='Test product', price=Decimal('10.00'), product_type=pro...
@pytest.fixture def product_without_shipping(default_category):
product_type = ProductType.objects.create( name='Type with no shipping', has_variants=False, is_shipping_required=False) product = Product.objects.create( name='Test product', price=Decimal('10.00'), product_type=product_type, category=default_category) ProductVariant.objects...
, quantity=5, quantity_allocated=5, location=warehouse_2) Stock.objects.create( variant=variant, cost_price=10, quantity=5, quantity_allocated=0, location=warehouse_3) return product @pytest.fixture def product_without_shipping(default_category):
64
64
89
10
53
VanilleBid/weekly-saleor
tests/conftest.py
Python
product_without_shipping
product_without_shipping
305
314
305
306
56bb23a85f1c85f79d546a7907c0ab0d7caedab3
bigcode/the-stack
train
c1b6a3ada67e2ee622d75288
train
function
@pytest.fixture def permission_view_properties(): return Permission.objects.get(codename='view_properties')
@pytest.fixture def permission_view_properties():
return Permission.objects.get(codename='view_properties')
permission_edit_staff(): return Permission.objects.get(codename='edit_staff') @pytest.fixture def permission_view_group(): return Permission.objects.get(codename='view_group') @pytest.fixture def permission_edit_group(): return Permission.objects.get(codename='edit_group') @pytest.fixture def permissio...
64
64
20
8
56
VanilleBid/weekly-saleor
tests/conftest.py
Python
permission_view_properties
permission_view_properties
614
616
614
615
53d9e9ef3ee0b2d8acf1e7fccd0198ff40198357
bigcode/the-stack
train
cc0b94971f07419df655826f
train
function
@pytest.fixture def cart(db): # pylint: disable=W0613 return Cart.objects.create()
@pytest.fixture def cart(db): # pylint: disable=W0613
return Cart.objects.create()
_or_create( name="mirumee.com", domain="mirumee.com")[0] obj = SiteSettings.objects.get_or_create(site=site)[0] settings.SITE_ID = site.pk return obj @pytest.fixture def cart(db): # pylint: disable=W0613
64
64
22
16
47
VanilleBid/weekly-saleor
tests/conftest.py
Python
cart
cart
47
49
47
48
5d3bf1172cd759165c9dd221d88e3a186ecec68d
bigcode/the-stack
train
bc8c39c366beb4350a06d417
train
function
@pytest.fixture def product_image(): img_data = BytesIO() image = Image.new('RGB', size=(1, 1)) image.save(img_data, format='JPEG') return SimpleUploadedFile('product.jpg', img_data.getvalue())
@pytest.fixture def product_image():
img_data = BytesIO() image = Image.new('RGB', size=(1, 1)) image.save(img_data, format='JPEG') return SimpleUploadedFile('product.jpg', img_data.getvalue())
1 = Order.objects.create(**data) order2 = Order.objects.create(**data) return [order, order1, order2] @pytest.fixture def stock_location(): warehouse_1 = StockLocation.objects.create(name='Warehouse 1') return warehouse_1 @pytest.fixture def product_image():
64
64
53
7
56
VanilleBid/weekly-saleor
tests/conftest.py
Python
product_image
product_image
377
382
377
378
5ad7152d8f6ff4a23d2f92c9ff2676720a484a79
bigcode/the-stack
train
10d2effaa78ff71801d8f76c
train
function
@pytest.fixture def request_cart_with_item(product_in_stock, request_cart): variant = product_in_stock.variants.get() # Prepare some data request_cart.add(variant) return request_cart
@pytest.fixture def request_cart_with_item(product_in_stock, request_cart):
variant = product_in_stock.variants.get() # Prepare some data request_cart.add(variant) return request_cart
# FIXME: Fixtures should not have any side effects monkeypatch.setattr( utils, 'get_cart_from_request', lambda request, cart_queryset=None: cart) cart.discounts = Sale.objects.all() return cart @pytest.fixture def request_cart_with_item(product_in_stock, request_cart):
64
64
43
15
48
VanilleBid/weekly-saleor
tests/conftest.py
Python
request_cart_with_item
request_cart_with_item
67
72
67
68
f6f3a2bb8b3d2dd18672de7fe7579608b1ad1fa1
bigcode/the-stack
train
97c4d34f751c585029550f6e
train
function
@pytest.fixture() def staff_user(db): """Return a staff member.""" return User.objects.create_user( email='staff_test@example.com', password='password', is_staff=True, is_active=True)
@pytest.fixture() def staff_user(db):
"""Return a staff member.""" return User.objects.create_user( email='staff_test@example.com', password='password', is_staff=True, is_active=True)
'password') @pytest.fixture() def admin_client(admin_user): """Return a Django test client logged in as an admin user.""" from django.test.client import Client client = Client() client.login(username=admin_user.email, password='password') return client @pytest.fixture() def staff_user(db):
64
64
43
8
55
VanilleBid/weekly-saleor
tests/conftest.py
Python
staff_user
staff_user
106
111
106
107
441cc09315d8b516ae6802cda769eab13c74dfb8
bigcode/the-stack
train
b74bf6584cfeead90e0b4d35
train
function
@pytest.fixture def billing_address(db): # pylint: disable=W0613 return Address.objects.create( first_name='John', last_name='Doe', company_name='Mirumee Software', street_address_1='Tęczowa 7', city='Wrocław', postal_code='53-601', country='PL', phone='+4871...
@pytest.fixture def billing_address(db): # pylint: disable=W0613
return Address.objects.create( first_name='John', last_name='Doe', company_name='Mirumee Software', street_address_1='Tęczowa 7', city='Wrocław', postal_code='53-601', country='PL', phone='+48713988102')
member.""" client.login(username=staff_user.email, password='password') return client @pytest.fixture() def authorized_client(client, customer_user): client.login(username=customer_user.email, password='password') return client @pytest.fixture def billing_address(db): # pylint: disable=W0613
64
64
84
17
46
VanilleBid/weekly-saleor
tests/conftest.py
Python
billing_address
billing_address
127
136
127
128
184855554841b2043db4a7c02ec32f5d115c6e70
bigcode/the-stack
train