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
addfe167800bd09af63a85da
train
function
def load_yaml(filename, encoding=None, binary=True): try: with io.open(filename, 'rb' if binary else 'r', encoding=encoding) as fh: return yaml.safe_load(fh) except (IOError, yaml.YAMLError, UnicodeDecodeError) as e: if encoding is None: # Sometimes the user's locale sets...
def load_yaml(filename, encoding=None, binary=True):
try: with io.open(filename, 'rb' if binary else 'r', encoding=encoding) as fh: return yaml.safe_load(fh) except (IOError, yaml.YAMLError, UnicodeDecodeError) as e: if encoding is None: # Sometimes the user's locale sets an encoding that doesn't match # the YAM...
] else: return value def to_mapping(sequence, key_field): return {getattr(item, key_field): item for item in sequence} def has_uppercase(name): return any(char in string.ascii_uppercase for char in name) def load_yaml(filename, encoding=None, binary=True):
64
64
158
11
53
jovobe/compose
compose/config/config.py
Python
load_yaml
load_yaml
1,448
1,459
1,448
1,448
c6eee91986eb9d0fdf43ec507595b0842739e671
bigcode/the-stack
train
9f97a91997c6777969101b5b
train
function
def find_candidates_in_parent_dirs(filenames, path): """ Given a directory path to start, looks for filenames in the directory, and then each parent directory successively, until found. Returns tuple (candidates, path). """ candidates = [filename for filename in filenames ...
def find_candidates_in_parent_dirs(filenames, path):
""" Given a directory path to start, looks for filenames in the directory, and then each parent directory successively, until found. Returns tuple (candidates, path). """ candidates = [filename for filename in filenames if os.path.exists(os.path.join(path, filename))] ...
in DEFAULT_OVERRIDE_FILENAMES if os.path.exists(os.path.join(path, override_filename))] if len(override_files_in_path) > 1: raise DuplicateOverrideFileFound(override_files_in_path) return override_files_in_path def find_candidates_in_parent_dir...
64
64
127
11
52
jovobe/compose
compose/config/config.py
Python
find_candidates_in_parent_dirs
find_candidates_in_parent_dirs
333
349
333
333
1c2d8c9818458a905cdb71bd790ddf3cff76623a
bigcode/the-stack
train
9163383e9c1a01b4d21818d4
train
function
def parse_dict_or_list(split_func, type_name, arguments): if not arguments: return {} if isinstance(arguments, list): return dict(split_func(e) for e in arguments) if isinstance(arguments, dict): return dict(arguments) raise ConfigurationError( "%s \"%s\" must be a lis...
def parse_dict_or_list(split_func, type_name, arguments):
if not arguments: return {} if isinstance(arguments, list): return dict(split_func(e) for e in arguments) if isinstance(arguments, dict): return dict(arguments) raise ConfigurationError( "%s \"%s\" must be a list or mapping," % (type_name, arguments) )
def merge_override_items_lists(base, override): return sorted(set(override)) def split_kv(kvpair): if '=' in kvpair: return kvpair.split('=', 1) else: return kvpair, '' def parse_dict_or_list(split_func, type_name, arguments):
63
64
80
13
50
jovobe/compose
compose/config/config.py
Python
parse_dict_or_list
parse_dict_or_list
1,239
1,252
1,239
1,239
955852d99c25a8e1622c7ad769d81e52e038c3d1
bigcode/the-stack
train
7f19f986e86a0da6abfb1403
train
function
def merge_ports(md, base, override): def parse_sequence_func(seq): acc = [] for item in seq: acc.extend(ServicePort.parse(item)) return to_mapping(acc, 'merge_field') field = 'ports' if not md.needs_merge(field): return merged = parse_sequence_func(md.base....
def merge_ports(md, base, override):
def parse_sequence_func(seq): acc = [] for item in seq: acc.extend(ServicePort.parse(item)) return to_mapping(acc, 'merge_field') field = 'ports' if not md.needs_merge(field): return merged = parse_sequence_func(md.base.get(field, [])) merged.update(par...
(b) for b in base] return sorted(set().union(base, override)) def merge_healthchecks(base, override): if override.get('disabled') is True: return override result = base.copy() result.update(override) return result def merge_ports(md, base, override):
64
64
110
9
54
jovobe/compose
compose/config/config.py
Python
merge_ports
merge_ports
1,099
1,113
1,099
1,099
356359e0329402c675e15e2423532ab16645919a
bigcode/the-stack
train
c706ad1de1c6039bc678641a
train
function
def load(config_details, compatibility=False): """Load the configuration from a working directory and a list of configuration files. Files are loaded in order, and merged on top of each other to create the final configuration. Return a fully interpolated, extended and validated configuration. """ ...
def load(config_details, compatibility=False):
"""Load the configuration from a working directory and a list of configuration files. Files are loaded in order, and merged on top of each other to create the final configuration. Return a fully interpolated, extended and validated configuration. """ validate_config_version(config_details.conf...
if s.get(key)] if services: log.warn( warning_template.format( services=", ".join(sorted(s['name'] for s in services)), key=key ) ) if not compatibility: check_swarm_only_key(service_dicts, 'deploy') ...
95
95
318
8
87
jovobe/compose
compose/config/config.py
Python
load
load
374
412
374
374
037c22c85bbe52dfd47512c481837f4d02b7434f
bigcode/the-stack
train
d07e550e3911d91ad75a8435
train
function
def merge_override_items_lists(base, override): return sorted(set(override))
def merge_override_items_lists(base, override):
return sorted(set(override))
['build'] def merge_environment(base, override): env = parse_environment(base) env.update(parse_environment(override)) return env def merge_labels(base, override): labels = parse_labels(base) labels.update(parse_labels(override)) return labels def merge_override_items_lists(base, override):
64
64
16
9
54
jovobe/compose
compose/config/config.py
Python
merge_override_items_lists
merge_override_items_lists
1,228
1,229
1,228
1,228
ddc11be619f9a65f665b46e94b4ebe82365bed36
bigcode/the-stack
train
31c99e68f919fded6ccd6907
train
class
class Config(namedtuple('_Config', 'version services volumes networks secrets configs')): """ :param version: configuration version :type version: int :param services: List of service description dictionaries :type services: :class:`list` :param volumes: Dictionary mapping volume names to desc...
class Config(namedtuple('_Config', 'version services volumes networks secrets configs')):
""" :param version: configuration version :type version: int :param services: List of service description dictionaries :type services: :class:`list` :param volumes: Dictionary mapping volume names to description dictionaries :type volumes: :class:`dict` :param networks: Dictionary map...
< const.COMPOSEFILE_V3_1 else self.config.get('secrets', {}) def get_configs(self): return {} if self.version < const.COMPOSEFILE_V3_3 else self.config.get('configs', {}) class Config(namedtuple('_Config', 'version services volumes networks secrets configs')):
63
64
151
15
48
jovobe/compose
compose/config/config.py
Python
Config
Config
241
255
241
241
00d102f86dd342e70e8e7eb7509791d9cc912289
bigcode/the-stack
train
3e08e9293526017fc98d2512
train
function
def split_path_mapping(volume_path): """ Ascertain if the volume_path contains a host path as well as a container path. Using splitdrive so windows absolute paths won't cause issues with splitting on ':'. """ if isinstance(volume_path, dict): return (volume_path.get('target'), volume_pat...
def split_path_mapping(volume_path):
""" Ascertain if the volume_path contains a host path as well as a container path. Using splitdrive so windows absolute paths won't cause issues with splitting on ':'. """ if isinstance(volume_path, dict): return (volume_path.get('target'), volume_path) drive, volume_config = splitdr...
appings(path_mappings): if path_mappings: return dict(split_path_mapping(v) for v in path_mappings) else: return {} def path_mappings_from_dict(d): return [join_path_mapping(v) for v in sorted(d.items())] def split_path_mapping(volume_path):
64
64
166
7
57
jovobe/compose
compose/config/config.py
Python
split_path_mapping
split_path_mapping
1,377
1,396
1,377
1,377
5127f3f16748138c5feb456c4f5e537a75ed72b8
bigcode/the-stack
train
2635337378ab79f2144f3498
train
function
def validate_service(service_config, service_names, config_file): service_dict, service_name = service_config.config, service_config.name validate_service_constraints(service_dict, service_name, config_file) validate_paths(service_dict) validate_cpu(service_config) validate_ulimits(service_config) ...
def validate_service(service_config, service_names, config_file):
service_dict, service_name = service_config.config, service_config.name validate_service_constraints(service_dict, service_name, config_file) validate_paths(service_dict) validate_cpu(service_config) validate_ulimits(service_config) validate_network_mode(service_config, service_names) valid...
( "%s services with 'network_mode: service' cannot be extended" % error_prefix) if 'depends_on' in service_dict: raise ConfigurationError( "%s services with 'depends_on' cannot be extended" % error_prefix) def validate_service(service_config, service_names, config_file):
64
64
184
12
52
jovobe/compose
compose/config/config.py
Python
validate_service
validate_service
695
713
695
695
79e9045620584eb6e8166c7530901d442b179507
bigcode/the-stack
train
fde006a9029b8a8f1f8fa487
train
function
def merge_list_or_string(base, override): return to_list(base) + to_list(override)
def merge_list_or_string(base, override):
return to_list(base) + to_list(override)
result = ":".join((host, container)) if mode: result += ":" + mode return result def expand_path(working_dir, path): return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path))) def merge_list_or_string(base, override):
63
64
21
9
54
jovobe/compose
compose/config/config.py
Python
merge_list_or_string
merge_list_or_string
1,427
1,428
1,427
1,427
51ec984634b10b4c0d643b4177a36a7682b2a9f8
bigcode/the-stack
train
5c024b9b626c5ae2c9fc02e2
train
function
def merge_build(output, base, override): def to_dict(service): build_config = service.get('build', {}) if isinstance(build_config, six.string_types): return {'context': build_config} return build_config md = MergeDict(to_dict(base), to_dict(override)) md.merge_scalar('co...
def merge_build(output, base, override):
def to_dict(service): build_config = service.get('build', {}) if isinstance(build_config, six.string_types): return {'context': build_config} return build_config md = MergeDict(to_dict(base), to_dict(override)) md.merge_scalar('context') md.merge_scalar('dockerfile')...
_merge(field): return merged = parse_sequence_func(md.base.get(field, [])) merged.update(parse_sequence_func(md.override.get(field, []))) md[field] = [item for item in sorted(merged.values(), key=lambda x: x.target)] def merge_build(output, base, override):
63
64
162
9
54
jovobe/compose
compose/config/config.py
Python
merge_build
merge_build
1,116
1,134
1,116
1,116
336a81171a856a1ecd4b4353b935c53dfbe0ed31
bigcode/the-stack
train
6f170e194a7c1bd9feab794d
train
function
def merge_reservations(base, override): md = MergeDict(base, override) md.merge_scalar('cpus') md.merge_scalar('memory') md.merge_sequence('generic_resources', types.GenericResource.parse) return dict(md)
def merge_reservations(base, override):
md = MergeDict(base, override) md.merge_scalar('cpus') md.merge_scalar('memory') md.merge_sequence('generic_resources', types.GenericResource.parse) return dict(md)
.override.get('placement') or {}) placement_md.merge_field('constraints', merge_unique_items_lists, default=[]) placement_md.merge_field('preferences', merge_unique_objects_lists, default=[]) md['placement'] = dict(placement_md) return dict(md) def merge_reservations(base, override):
64
64
51
9
55
jovobe/compose
compose/config/config.py
Python
merge_reservations
merge_reservations
1,160
1,165
1,160
1,160
af2cc3ba91ec0322a511fd2a736474520a411602
bigcode/the-stack
train
4ecc31341502eeee8e840cba
train
function
def has_uppercase(name): return any(char in string.ascii_uppercase for char in name)
def has_uppercase(name):
return any(char in string.ascii_uppercase for char in name)
to_list(value): if value is None: return [] elif isinstance(value, six.string_types): return [value] else: return value def to_mapping(sequence, key_field): return {getattr(item, key_field): item for item in sequence} def has_uppercase(name):
64
64
21
6
58
jovobe/compose
compose/config/config.py
Python
has_uppercase
has_uppercase
1,444
1,445
1,444
1,444
3434a38c28198a4c23f477617ff3929cd0c7aa86
bigcode/the-stack
train
3f8634aeb7f82cfb501c9117
train
function
def process_ports(service_dict): if 'ports' not in service_dict: return service_dict ports = [] for port_definition in service_dict['ports']: if isinstance(port_definition, ServicePort): ports.append(port_definition) else: ports.extend(ServicePort.parse(port_...
def process_ports(service_dict):
if 'ports' not in service_dict: return service_dict ports = [] for port_definition in service_dict['ports']: if isinstance(port_definition, ServicePort): ports.append(port_definition) else: ports.extend(ServicePort.parse(port_definition)) service_dict['po...
path = service_dict['build']['context'] service_dict['build']['context'] = resolve_build_path(working_dir, path) if 'labels' in service_dict['build']: service_dict['build']['labels'] = parse_labels(service_dict['build']['labels']) def process_ports(service_dict):
63
64
76
6
57
jovobe/compose
compose/config/config.py
Python
process_ports
process_ports
762
773
762
762
1240b50bb061812beed267dbc60dc34df99d5fb7
bigcode/the-stack
train
1c82882a3b4c98aaf6da4406
train
function
def movieRatingPair(record_line): MovieID, UserID, Rating = record_line.split(',') return (MovieID, Rating)
def movieRatingPair(record_line):
MovieID, UserID, Rating = record_line.split(',') return (MovieID, Rating)
pyspark import SparkContext sc = SparkContext() testingFile = "file:/home/cloudera/Desktop/cse427s/final_project/TestingRatings.txt" trainingFile = "file:/home/cloudera/Desktop/cse427s/final_project/TrainingRatings.txt" def movieRatingPair(record_line):
64
64
27
7
57
PQMeng/RecommendationSystemOnSpark
netflix/milestone2/problem_2d.py
Python
movieRatingPair
movieRatingPair
11
13
11
11
b7aa0d676b9fc1ae6e82aa439396b692de0f8908
bigcode/the-stack
train
52cdd457f7af870c1cb220e6
train
class
@reversion.register() class Hint(models.Model): id = models.AutoField(primary_key=True) problem = models.ForeignKey( Problem, on_delete=models.CASCADE, help_text=r"The container of the current hint." ) keywords = models.CharField( max_length=255, default='', blank=True, help_text=r"A comma-separated list ...
@reversion.register() class Hint(models.Model):
id = models.AutoField(primary_key=True) problem = models.ForeignKey( Problem, on_delete=models.CASCADE, help_text=r"The container of the current hint." ) keywords = models.CharField( max_length=255, default='', blank=True, help_text=r"A comma-separated list of keywords that a solver could look at " "to ...
PS URL", ) def __str__(self) -> str: return self.puid def get_absolute_url(self): return reverse_lazy("hint-list", args=(self.puid, )) def get_statement(self) -> Optional[str]: if settings.PATH_STATEMENT_ON_DISK is None: return None statement_path = Path(settings.PATH_STATEMENT_ON_DISK) / (self.puid +...
135
135
453
10
125
theMetaHack/otis-web
arch/models.py
Python
Hint
Hint
51
99
51
52
4af0fdec54bcb5d542e2580d36705aaece70fc8f
bigcode/the-stack
train
13ebcb2a3850bff54131a611
train
class
@reversion.register() class Problem(models.Model): id = models.AutoField(primary_key=True) puid = models.CharField( max_length=24, help_text="Unique problem identifier, as printed in OTIS handout.", unique=True, verbose_name="PUID", validators=[ RegexValidator( regex=r'^[A-Z0-9]+$', message="Only upp...
@reversion.register() class Problem(models.Model):
id = models.AutoField(primary_key=True) puid = models.CharField( max_length=24, help_text="Unique problem identifier, as printed in OTIS handout.", unique=True, verbose_name="PUID", validators=[ RegexValidator( regex=r'^[A-Z0-9]+$', message="Only uppercase letters and digits appear in PUID's." ) ...
from pathlib import Path from typing import Optional import reversion from django.conf import settings from django.core.validators import RegexValidator from django.db import models from django.urls import reverse_lazy # Create your models here. @reversion.register() class Problem(models.Model):
57
81
270
10
47
theMetaHack/otis-web
arch/models.py
Python
Problem
Problem
12
48
12
13
641cf0df142d068f7214b97204dc40e54fe1e0c5
bigcode/the-stack
train
8a463842c7895e31895de365
train
function
def test_num_clients(init_and_serve_lazy): # Tests num clients reporting; useful if you want to build an app that # load balances clients between Ray client servers. def get_job_id(api): return api.get_runtime_context().worker.current_job_id api1 = _ClientContext() info1 = api1.connect("lo...
def test_num_clients(init_and_serve_lazy): # Tests num clients reporting; useful if you want to build an app that # load balances clients between Ray client servers.
def get_job_id(api): return api.get_runtime_context().worker.current_job_id api1 = _ClientContext() info1 = api1.connect("localhost:50051") job_id_1 = get_job_id(api1) assert info1["num_clients"] == 1, info1 api2 = _ClientContext() info2 = api2.connect("localhost:50051") job_id_...
.get.remote()) assert val == 12 ray.disconnect() def test_idempotent_disconnect(init_and_serve): from ray.util.client import ray ray.disconnect() ray.disconnect() ray.connect("localhost:50051") ray.disconnect() ray.disconnect() def test_num_clients(init_and_serve_lazy): # T...
95
95
319
37
58
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_num_clients
test_num_clients
105
139
105
108
cccfa9293ac4734808dce64902fcc660857e7849
bigcode/the-stack
train
d552e9576e838435c2591c1f
train
class
@ray.remote class C: def __init__(self, x): self.val = x def double(self): self.val += self.val def get(self): return self.val
@ray.remote class C:
def __init__(self, x): self.val = x def double(self): self.val += self.val def get(self): return self.val
.randint(1, 10)) c2 = complex_task.remote(random.randint(1, 10)) return sum(ray.get([c1, c2])) @ray.remote def complex_task(value): time.sleep(1) return value * 10 @ray.remote class C:
64
64
44
7
56
jamesliu/ray
python/ray/tests/test_client_init.py
Python
C
C
32
41
32
33
0e14d2a2f0bf373d94430057ffabd641d6cdd342
bigcode/the-stack
train
f74511f3eb41dffd25bf5c0e
train
function
def test_basic_preregister(init_and_serve): """Tests conversion of Ray actors and remote functions to client actors and client remote functions. Checks that the conversion works when disconnecting and reconnecting client sessions. """ from ray.util.client import ray for _ in range(2): ...
def test_basic_preregister(init_and_serve):
"""Tests conversion of Ray actors and remote functions to client actors and client remote functions. Checks that the conversion works when disconnecting and reconnecting client sessions. """ from ray.util.client import ray for _ in range(2): ray.connect("localhost:50051") va...
", "start", "--head", "--num-cpus", "8", "--ray-client-server-port", f"{port}" ]) assert "ValueError" in str(excinfo.traceback) assert "65535" in str(excinfo.traceback) def test_basic_preregister(init_and_serve):
64
64
152
10
54
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_basic_preregister
test_basic_preregister
73
93
73
73
36cb41acb930744d42df6130849b6c3b6e8f5f7f
bigcode/the-stack
train
eae2dd971a82eb5b2ebd7e83
train
function
@ray.remote def complex_task(value): time.sleep(1) return value * 10
@ray.remote def complex_task(value):
time.sleep(1) return value * 10
import ray @ray.remote def hello_world(): c1 = complex_task.remote(random.randint(1, 10)) c2 = complex_task.remote(random.randint(1, 10)) return sum(ray.get([c1, c2])) @ray.remote def complex_task(value):
63
64
22
9
54
jamesliu/ray
python/ray/tests/test_client_init.py
Python
complex_task
complex_task
26
29
26
27
e43a333555fcf03eef37ebb00bddc00a29d3a709
bigcode/the-stack
train
a4a32247e4b4b690775c6746
train
function
def test_python_version(init_and_serve): server_handle = init_and_serve ray = _ClientContext() info1 = ray.connect("localhost:50051") assert info1["python_version"] == ".".join( [str(x) for x in list(sys.version_info)[:3]]) ray.disconnect() time.sleep(1) def mock_connection_response...
def test_python_version(init_and_serve):
server_handle = init_and_serve ray = _ClientContext() info1 = ray.connect("localhost:50051") assert info1["python_version"] == ".".join( [str(x) for x in list(sys.version_info)[:3]]) ray.disconnect() time.sleep(1) def mock_connection_response(): return ray_client_pb2.Connect...
["ray_version"], str), info3 assert isinstance(info3["ray_commit"], str), info3 assert isinstance(info3["python_version"], str), info3 assert isinstance(info3["protocol_version"], str), info3 api3.disconnect() def test_python_version(init_and_serve):
65
65
219
9
56
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_python_version
test_python_version
142
171
142
142
989667fd23dba80f32099e158b1c7f9fc8e18f20
bigcode/the-stack
train
e801ac1ea28b8d601dcba93d
train
function
def test_idempotent_disconnect(init_and_serve): from ray.util.client import ray ray.disconnect() ray.disconnect() ray.connect("localhost:50051") ray.disconnect() ray.disconnect()
def test_idempotent_disconnect(init_and_serve):
from ray.util.client import ray ray.disconnect() ray.disconnect() ray.connect("localhost:50051") ray.disconnect() ray.disconnect()
200 c = C.remote(3) x = c.double.remote() y = c.double.remote() ray.wait([x, y]) val = ray.get(c.get.remote()) assert val == 12 ray.disconnect() def test_idempotent_disconnect(init_and_serve):
64
64
44
11
53
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_idempotent_disconnect
test_idempotent_disconnect
96
102
96
96
774a0af08143a9960d0df61b3be647cf71262ed2
bigcode/the-stack
train
54fc4dd3094ff5d13f15bed0
train
function
@pytest.mark.xfail(cluster_not_supported, reason="cluster not supported") @pytest.fixture def init_and_serve_lazy(): cluster = ray.cluster_utils.Cluster() cluster.add_node(num_cpus=1, num_gpus=0) cluster.wait_for_nodes(1) address = cluster.address def connect(job_config=None): ray.init(addr...
@pytest.mark.xfail(cluster_not_supported, reason="cluster not supported") @pytest.fixture def init_and_serve_lazy():
cluster = ray.cluster_utils.Cluster() cluster.add_node(num_cpus=1, num_gpus=0) cluster.wait_for_nodes(1) address = cluster.address def connect(job_config=None): ray.init(address=address, job_config=job_config) server_handle = ray_client_server.serve("localhost:50051", connect) yiel...
class C: def __init__(self, x): self.val = x def double(self): self.val += self.val def get(self): return self.val @pytest.mark.xfail(cluster_not_supported, reason="cluster not supported") @pytest.fixture def init_and_serve_lazy():
64
64
122
24
39
jamesliu/ray
python/ray/tests/test_client_init.py
Python
init_and_serve_lazy
init_and_serve_lazy
44
58
44
46
1aba01dc00ffb2647b59e3bebe7bc34543ceaa23
bigcode/the-stack
train
de5db2ec8f33be76832c2e02
train
function
@ray.remote def hello_world(): c1 = complex_task.remote(random.randint(1, 10)) c2 = complex_task.remote(random.randint(1, 10)) return sum(ray.get([c1, c2]))
@ray.remote def hello_world():
c1 = complex_task.remote(random.randint(1, 10)) c2 = complex_task.remote(random.randint(1, 10)) return sum(ray.get([c1, c2]))
unittest.mock import patch import ray.util.client.server.server as ray_client_server import ray.core.generated.ray_client_pb2 as ray_client_pb2 from ray.util.client import _ClientContext, CURRENT_PROTOCOL_VERSION from ray.cluster_utils import cluster_not_supported import ray @ray.remote def hello_world():
64
64
50
8
55
jamesliu/ray
python/ray/tests/test_client_init.py
Python
hello_world
hello_world
19
23
19
20
cce55f850b4c50a6ad76b3c960d21ce858b60fc9
bigcode/the-stack
train
5cfa4c2df541974339ab274f
train
function
@patch("ray.util.client.server.dataservicer.CLIENT_SERVER_MAX_THREADS", 6) @patch("ray.util.client.server.logservicer.CLIENT_SERVER_MAX_THREADS", 6) def test_max_clients(init_and_serve): # Tests max clients. Should support up to CLIENT_SERVER_MAX_THREADS / 2. def get_job_id(api): return api.get_runtime_...
@patch("ray.util.client.server.dataservicer.CLIENT_SERVER_MAX_THREADS", 6) @patch("ray.util.client.server.logservicer.CLIENT_SERVER_MAX_THREADS", 6) def test_max_clients(init_and_serve): # Tests max clients. Should support up to CLIENT_SERVER_MAX_THREADS / 2.
def get_job_id(api): return api.get_runtime_context().worker.current_job_id for i in range(3): api1 = _ClientContext() info1 = api1.connect("localhost:50051") assert info1["num_clients"] == i + 1, info1 with pytest.raises(ConnectionError): api = _ClientContext() ...
() @patch("ray.util.client.server.dataservicer.CLIENT_SERVER_MAX_THREADS", 6) @patch("ray.util.client.server.logservicer.CLIENT_SERVER_MAX_THREADS", 6) def test_max_clients(init_and_serve): # Tests max clients. Should support up to CLIENT_SERVER_MAX_THREADS / 2.
64
64
153
63
1
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_max_clients
test_max_clients
206
221
206
209
9afcbdd0375f58a9f5cbe61e0b7480c620869546
bigcode/the-stack
train
b6d448657a6c8e727f42ba7f
train
function
def test_protocol_version(init_and_serve): server_handle = init_and_serve ray = _ClientContext() info1 = ray.connect("localhost:50051") local_py_version = ".".join([str(x) for x in list(sys.version_info)[:3]]) assert info1["protocol_version"] == CURRENT_PROTOCOL_VERSION, info1 ray.disconnect() ...
def test_protocol_version(init_and_serve):
server_handle = init_and_serve ray = _ClientContext() info1 = ray.connect("localhost:50051") local_py_version = ".".join([str(x) for x in list(sys.version_info)[:3]]) assert info1["protocol_version"] == CURRENT_PROTOCOL_VERSION, info1 ray.disconnect() time.sleep(1) def mock_connection_r...
() with pytest.raises(RuntimeError): _ = ray.connect("localhost:50051") ray = _ClientContext() info3 = ray.connect("localhost:50051", ignore_version=True) assert info3["num_clients"] == 1, info3 ray.disconnect() def test_protocol_version(init_and_serve):
70
70
236
9
61
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_protocol_version
test_protocol_version
174
203
174
174
f65d37b4b22d8bc72fb14d06f7756d968802246b
bigcode/the-stack
train
3685145d0871d6ca0e5d2b7f
train
function
def test_validate_port(): """Check that ports outside of 1024-65535 are rejected.""" for port in [1000, 1023, 65536, 700000]: with pytest.raises(subprocess.CalledProcessError) as excinfo: subprocess.check_output([ "ray", "start", "--head", "--num-cpus", "8", "...
def test_validate_port():
"""Check that ports outside of 1024-65535 are rejected.""" for port in [1000, 1023, 65536, 700000]: with pytest.raises(subprocess.CalledProcessError) as excinfo: subprocess.check_output([ "ray", "start", "--head", "--num-cpus", "8", "--ray-client-server-port",...
def connect(job_config=None): ray.init(address=address, job_config=job_config) server_handle = ray_client_server.serve("localhost:50051", connect) yield server_handle ray_client_server.shutdown_with_server(server_handle.grpc_server) time.sleep(2) def test_validate_port():
64
64
118
5
59
jamesliu/ray
python/ray/tests/test_client_init.py
Python
test_validate_port
test_validate_port
61
70
61
61
2a2d2ffbf83015c97dcce05b9b2cb34613f90285
bigcode/the-stack
train
6b155df7f0e5a2f874ab6c7a
train
function
def write_text_proto(path, message): write_proto(path, message, as_text=True)
def write_text_proto(path, message):
write_proto(path, message, as_text=True)
.makedirs(dir_name, exist_ok=True) if as_text: with open(path, "w") as f: f.write(text_format.MessageToString(message)) else: with open(path, "wb") as f: f.write(message.SerializeToString()) def write_text_proto(path, message):
64
64
19
8
56
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
write_text_proto
write_text_proto
62
63
62
62
1f66d8a1cacd5fd0535c92bae2664da73d69b4d8
bigcode/the-stack
train
4fb9e222b55fc4ad50bc6b03
train
function
def write_proto(path, message, as_text=False): dir_name = os.path.dirname(path) generic_utils.mkdir_if_not_exist(dir_name) if dir_name: os.makedirs(dir_name, exist_ok=True) if as_text: with open(path, "w") as f: f.write(text_format.MessageToString(message)) else: with open(path, "wb") as f: ...
def write_proto(path, message, as_text=False):
dir_name = os.path.dirname(path) generic_utils.mkdir_if_not_exist(dir_name) if dir_name: os.makedirs(dir_name, exist_ok=True) if as_text: with open(path, "w") as f: f.write(text_format.MessageToString(message)) else: with open(path, "wb") as f: f.write(message.SerializeToString())
_def() write_binary_proto(path, graph) elif isinstance(graph, graph_pb2.GraphDef): write_binary_proto(path, graph) elif isinstance(graph, ops.Graph): viz.export_to_netron(path, graph) else: pass def write_proto(path, message, as_text=False):
64
64
93
11
52
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
write_proto
write_proto
50
60
50
50
939a7333349010d07d09ff96c985fa6b33344204
bigcode/the-stack
train
a6b681133f0b99cb4ecd6a3c
train
function
def topological_sort(graph): # Kahn's algorithm. # See https://en.wikipedia.org/wiki/Topological_sorting num_ready_inputs = {} for node in graph.nodes: num_ready_inputs[node.name] = 0 ready_nodes = [] for node in graph.inputs: ready_nodes.append(node) reordered_nodes = [] while ready_nodes: ...
def topological_sort(graph): # Kahn's algorithm. # See https://en.wikipedia.org/wiki/Topological_sorting
num_ready_inputs = {} for node in graph.nodes: num_ready_inputs[node.name] = 0 ready_nodes = [] for node in graph.inputs: ready_nodes.append(node) reordered_nodes = [] while ready_nodes: node = ready_nodes.pop(0) reordered_nodes.append(node) for node_name in node.out_nodes: out_n...
as_text=True) def write_binary_proto(path, message): write_proto(path, message, as_text=False) def op_param_by_name(op, name): for param in op.ParamName: if param.value == name: return param return None def topological_sort(graph): # Kahn's algorithm. # See https://en.wikipedia.org/wiki/Topologic...
83
83
278
28
54
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
topological_sort
topological_sort
74
106
74
76
7fba7a261ab68459b83f73d1ff1cb07a96889fa7
bigcode/the-stack
train
dbc5dc2287f5d330d1e0703e
train
function
def maybe_export_graph(path, graph): if not os.environ.get('EXPORT_NNDCT_TF_PARSER_INTERNAL', ''): return dir_name = os.path.dirname(path) generic_utils.mkdir_if_not_exist(dir_name) if isinstance(graph, tf.Graph): graph = graph.as_graph_def() write_binary_proto(path, graph) elif isinstance(graph,...
def maybe_export_graph(path, graph):
if not os.environ.get('EXPORT_NNDCT_TF_PARSER_INTERNAL', ''): return dir_name = os.path.dirname(path) generic_utils.mkdir_if_not_exist(dir_name) if isinstance(graph, tf.Graph): graph = graph.as_graph_def() write_binary_proto(path, graph) elif isinstance(graph, graph_pb2.GraphDef): write_binar...
import print_function import os import tensorflow as tf from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tf_nndct.graph import ops from tf_nndct.utils import generic_utils from tf_nndct.utils import viz def maybe_export_graph(path, graph):
64
64
116
8
55
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
maybe_export_graph
maybe_export_graph
34
48
34
34
1e01f17a179d7e783037c736c0e3a00012e9eded
bigcode/the-stack
train
a24d419a4356051df8188328
train
function
def stringfy_to_write(x): if isinstance(x, str): x = "'{}'".format(x) return '{}'.format(x)
def stringfy_to_write(x):
if isinstance(x, str): x = "'{}'".format(x) return '{}'.format(x)
there is at least one cycle in the graph. There is {} not-ready' 'nodes: {}'.format(len(not_ready_nodes), not_ready_nodes))) topo_graph = ops.Graph() for node in reordered_nodes: topo_graph.add_node(node) return topo_graph def stringfy_to_write(x):
64
64
31
7
56
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
stringfy_to_write
stringfy_to_write
108
111
108
108
e72330d19b72f405324d7e75b8aa03d382542bba
bigcode/the-stack
train
7a5ae99380d090693bff9f66
train
function
def op_param_by_name(op, name): for param in op.ParamName: if param.value == name: return param return None
def op_param_by_name(op, name):
for param in op.ParamName: if param.value == name: return param return None
open(path, "wb") as f: f.write(message.SerializeToString()) def write_text_proto(path, message): write_proto(path, message, as_text=True) def write_binary_proto(path, message): write_proto(path, message, as_text=False) def op_param_by_name(op, name):
64
64
32
9
55
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
op_param_by_name
op_param_by_name
68
72
68
68
aa233ae9eb2578c707e12215f23f4121daa5f687
bigcode/the-stack
train
6b4d8dbbab297094d3f21f4f
train
function
def write_binary_proto(path, message): write_proto(path, message, as_text=False)
def write_binary_proto(path, message):
write_proto(path, message, as_text=False)
w") as f: f.write(text_format.MessageToString(message)) else: with open(path, "wb") as f: f.write(message.SerializeToString()) def write_text_proto(path, message): write_proto(path, message, as_text=True) def write_binary_proto(path, message):
64
64
19
8
56
Carles-Figuerola/Vitis-AI
tools/RNN/rnn_quantizer/tensorflow/tf_nndct/graph/utils.py
Python
write_binary_proto
write_binary_proto
65
66
65
65
3b99e2c2778d1145c72f2fd78e34f7af30cada82
bigcode/the-stack
train
6d8788cbd0c16117a3ba657c
train
class
class TestMessageLog(unittest.TestCase): pass
class TestMessageLog(unittest.TestCase):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2019, Novo and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest class TestMessageLog(unittest.TestCase):
48
64
10
8
39
erpnextdeveloper/novo
novo/novo/doctype/message_log/test_message_log.py
Python
TestMessageLog
TestMessageLog
9
10
9
9
eca058b5e0aa895de9fcea229c65245012e56c30
bigcode/the-stack
train
d2f7c08161c8c45d5e8ffdee
train
function
async def _async_create_entities(hass, config): """Create the Template cover.""" covers = [] for device, device_config in config[CONF_COVERS].items(): state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) availability_template ...
async def _async_create_entities(hass, config):
"""Create the Template cover.""" covers = [] for device, device_config in config[CONF_COVERS].items(): state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) ...
, default=DEFAULT_TRAVEL_TIME): cv.positive_int, vol.Optional(CONF_TRAVELLING_TIME_UP, default=DEFAULT_TRAVEL_TIME): cv.positive_int, } ), ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_COVERS): cv.schema_with_slug_keys(COVER_SCHEMA)} ) async def _async_create_entities(hass,...
81
81
272
11
70
pfandrade/ha-custom-components
custom_components/pcc/cover.py
Python
_async_create_entities
_async_create_entities
83
121
83
83
301232fe30f169f2e8e28bf76d58c5448a6a6898
bigcode/the-stack
train
408bf48bca68455813d8c4ec
train
class
class PCCCover(TemplateEntity, CoverEntity): """Representation of a Template cover.""" def __init__( self, hass, device_id, friendly_name, device_class, state_template, icon_template, entity_picture_template, availability_template, ...
class PCCCover(TemplateEntity, CoverEntity):
"""Representation of a Template cover.""" def __init__( self, hass, device_id, friendly_name, device_class, state_template, icon_template, entity_picture_template, availability_template, open_action, close_action, s...
_config.get(CONF_ENTITY_PICTURE_TEMPLATE) friendly_name = device_config.get(CONF_FRIENDLY_NAME, device) device_class = device_config.get(CONF_DEVICE_CLASS) open_action = device_config.get(OPEN_ACTION) close_action = device_config.get(CLOSE_ACTION) stop_action = device_config.get...
256
256
1,175
10
246
pfandrade/ha-custom-components
custom_components/pcc/cover.py
Python
PCCCover
PCCCover
131
305
131
131
701aa31c88ee8c81df6994e7b516d3076fa5f8e7
bigcode/the-stack
train
55ce300622c8e79727f901c5
train
function
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Template cover.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config))
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Template cover.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config))
icon_template, entity_picture_template, availability_template, open_action, close_action, stop_action, travel_time_down, travel_time_up, unique_id, ) ) return covers ...
64
64
56
18
45
pfandrade/ha-custom-components
custom_components/pcc/cover.py
Python
async_setup_platform
async_setup_platform
124
128
124
124
90ba8918fb37abfdeb8f828befa7ed153f04e4ff
bigcode/the-stack
train
94de6d548e15eb7c50e12a83
train
function
@app.route("/api/data") def get_data(): return app.send_static_file("data.json")
@app.route("/api/data") def get_data():
return app.send_static_file("data.json")
About", content="Some neat tricks with Flask", subcontent="Date and time right now: " + datetime.now().strftime("%A, %d %B, %Y at %X") ) # "/api/data" Route (renders json file) @app.route("/api/data") def get_data():
64
64
20
10
54
bcha92/Python-HTML
app.py
Python
get_data
get_data
27
29
27
28
16216794ebb37afa02f5045f6524afeddeb9ae8e
bigcode/the-stack
train
bdd651d108a8a8ea5c8a0c41
train
function
@app.route("/raw") def raw(): return """ <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>RAW</title> <link rel="stylesheet" type="text/css" href="/static/styles.css"> </head> <body> <header class="flex"> <a h...
@app.route("/raw") def raw():
return """ <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>RAW</title> <link rel="stylesheet" type="text/css" href="/static/styles.css"> </head> <body> <header class="flex"> <a href="/" class="nav title">FLAS...
subcontent="Date and time right now: " + datetime.now().strftime("%A, %d %B, %Y at %X") ) # "/api/data" Route (renders json file) @app.route("/api/data") def get_data(): return app.send_static_file("data.json") # "/raw" RAW (renders html raw format) @app.route("/raw") def raw():
81
81
273
8
73
bcha92/Python-HTML
app.py
Python
raw
raw
32
61
32
33
582842464ea1329a03fd224512aa261d12ab15fa
bigcode/the-stack
train
057a79b647776bce50ebb215
train
function
@app.route("/") def home(): return render_template("extend.html", title="FLASK HOME", subtitle="Home Page", content="This site was generated using VSCode Python FLASK Library" )
@app.route("/") def home():
return render_template("extend.html", title="FLASK HOME", subtitle="Home Page", content="This site was generated using VSCode Python FLASK Library" )
from flask import Flask, render_template from datetime import datetime # Main Flask App app = Flask(__name__) # Homepage "/" @app.route("/") def home():
34
64
44
6
27
bcha92/Python-HTML
app.py
Python
home
home
8
14
8
9
d9973281b1b84a10efba7135f9732af844782809
bigcode/the-stack
train
0eb6518dedd0715b3e501412
train
function
@app.route("/about") def about(): return render_template("extend.html", title="FLASK ABOUT", subtitle="About", content="Some neat tricks with Flask", subcontent="Date and time right now: " + datetime.now().strftime("%A, %d %B, %Y at %X") )
@app.route("/about") def about():
return render_template("extend.html", title="FLASK ABOUT", subtitle="About", content="Some neat tricks with Flask", subcontent="Date and time right now: " + datetime.now().strftime("%A, %d %B, %Y at %X") )
name__) # Homepage "/" @app.route("/") def home(): return render_template("extend.html", title="FLASK HOME", subtitle="Home Page", content="This site was generated using VSCode Python FLASK Library" ) # "/about/" Route @app.route("/about") def about():
64
64
69
8
55
bcha92/Python-HTML
app.py
Python
about
about
17
24
17
18
4a8358238e0b75dab207a5760b4f997f0ff4bebd
bigcode/the-stack
train
dc6c9b81676bcccb7aa5e2be
train
class
class KeyWListTest(unittest.TestCase): def test_parse(self): "Parsing keywlist.txt" filename = os.path.join("SwissProt", "keywlist.txt") handle = open(filename) records = KeyWList.parse(handle) # Testing the first record record = next(records) self.assertEq...
class KeyWListTest(unittest.TestCase):
def test_parse(self): "Parsing keywlist.txt" filename = os.path.join("SwissProt", "keywlist.txt") handle = open(filename) records = KeyWList.parse(handle) # Testing the first record record = next(records) self.assertEqual(record["ID"], "2Fe-2S.") sel...
# Copyright 1999 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import unittest import os.path from Bio.SwissProt import KeyWList class KeyWListTest(unittest....
78
256
1,223
9
68
rwst/biopython
Tests/test_KeyWList.py
Python
KeyWListTest
KeyWListTest
11
93
11
12
9fd9cd28d65cbcd7393abbd306d376a8f04bb75f
bigcode/the-stack
train
f92de96f94cfafa89e2c103a
train
class
@dataclass class Bungalow(Property): name: str = "Bungalow" min_area: int = 600 max_area: int = 1_500 min_price: int = 70_000 max_price: int = 400_000 min_rooms: int = 3 max_rooms: int = 6
@dataclass class Bungalow(Property):
name: str = "Bungalow" min_area: int = 600 max_area: int = 1_500 min_price: int = 70_000 max_price: int = 400_000 min_rooms: int = 3 max_rooms: int = 6
1_000 max_area: int = 2_000 min_price: int = 150_000 max_price: int = 900_000 min_rooms: int = 5 max_rooms: int = 10 @dataclass class Bungalow(Property):
64
64
77
8
55
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
Bungalow
Bungalow
82
90
82
83
3db30875ff9da572d23b91c0aa70792fc199febd
bigcode/the-stack
train
aac6df53c3cd7e4d69e164b4
train
class
@dataclass class SemiDetachedHouse(Property): name: str = "Semi Detached" min_area: int = 1_000 max_area: int = 2_000 min_price: int = 150_000 max_price: int = 900_000 min_rooms: int = 5 max_rooms: int = 10
@dataclass class SemiDetachedHouse(Property):
name: str = "Semi Detached" min_area: int = 1_000 max_area: int = 2_000 min_price: int = 150_000 max_price: int = 900_000 min_rooms: int = 5 max_rooms: int = 10
= 100 max_area: int = 1_000 min_price: int = 70_000 max_price: int = 500_000 min_rooms: int = 1 max_rooms: int = 5 @dataclass class SemiDetachedHouse(Property):
64
64
80
9
54
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
SemiDetachedHouse
SemiDetachedHouse
71
79
71
72
3aa747167f0f4ae13028553f093392d7429079de
bigcode/the-stack
train
e9ba2a45b328ddb8fccf8de7
train
class
@dataclass class Flat(Property): """Flat specific property details""" name: str = "Flat" min_area: int = 100 max_area: int = 1_000 min_price: int = 70_000 max_price: int = 500_000 min_rooms: int = 1 max_rooms: int = 5
@dataclass class Flat(Property):
"""Flat specific property details""" name: str = "Flat" min_area: int = 100 max_area: int = 1_000 min_price: int = 70_000 max_price: int = 500_000 min_rooms: int = 1 max_rooms: int = 5
of bedrooms in the property. Must be lower than the total number of rooms with a maximum of 10 """ max_bedrooms = max(1, total_rooms - 1) return min(random.randint(1, max_bedrooms), 10) @dataclass class Flat(Property):
64
64
82
7
57
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
Flat
Flat
58
68
58
59
27debebf943602b79aac1c992869806e289debf3
bigcode/the-stack
train
a3d4ac671723e4671efd2c19
train
class
@dataclass class BadProperty(Property): """Property with unexepected data to potentially fail the validation tests""" name: str = "Bad Property" min_area: int = -1000 max_area: int = 1000 min_price: int = -100_000 max_price: int = 100 min_rooms: int = -100 max_rooms: int = 1000 chan...
@dataclass class BadProperty(Property):
"""Property with unexepected data to potentially fail the validation tests""" name: str = "Bad Property" min_area: int = -1000 max_area: int = 1000 min_price: int = -100_000 max_price: int = 100 min_rooms: int = -100 max_rooms: int = 1000 chance: bool = random.uniform(0, 1) > 0.8 ...
_000 min_price: int = 70_000 max_price: int = 1_500_000 min_rooms: int = 5 max_rooms: int = 15 @dataclass class TerracedHouse(Property): name: str = "TerracedHouse" min_area: int = 900 max_area: int = 2_000 min_price: int = 70_000 max_price: int = 500_000 min_rooms: int = 5 ...
132
132
442
8
123
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
BadProperty
BadProperty
126
177
126
127
6906320e3481057b077f15d5d3fbd2b96b672aee
bigcode/the-stack
train
60e92ac3723538ffad5fd8af
train
class
@dataclass class Maisonette(Property): name: str = "Maisonette" min_area: int = 1_000 max_area: int = 1_500 min_price: int = 100_000 max_price: int = 900_000 min_rooms: int = 4 max_rooms: int = 9
@dataclass class Maisonette(Property):
name: str = "Maisonette" min_area: int = 1_000 max_area: int = 1_500 min_price: int = 100_000 max_price: int = 900_000 min_rooms: int = 4 max_rooms: int = 9
int = 600 max_area: int = 1_500 min_price: int = 70_000 max_price: int = 400_000 min_rooms: int = 3 max_rooms: int = 6 @dataclass class Maisonette(Property):
64
64
79
8
55
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
Maisonette
Maisonette
93
101
93
94
961b296b4ff9fa75350549a2a8894a2f37781b4e
bigcode/the-stack
train
a72a0c68968d19a2bbe92989
train
class
@dataclass class House(Property): name: str = "House" min_area: int = 1_500 max_area: int = 4_000 min_price: int = 70_000 max_price: int = 1_500_000 min_rooms: int = 5 max_rooms: int = 15
@dataclass class House(Property):
name: str = "House" min_area: int = 1_500 max_area: int = 4_000 min_price: int = 70_000 max_price: int = 1_500_000 min_rooms: int = 5 max_rooms: int = 15
= 1_000 max_area: int = 1_500 min_price: int = 100_000 max_price: int = 900_000 min_rooms: int = 4 max_rooms: int = 9 @dataclass class House(Property):
64
64
79
7
56
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
House
House
104
112
104
105
5eab28f6fcb522dd6c8ee2af6f2397212e30d8bd
bigcode/the-stack
train
de76decca1aec0dff324343a
train
class
@dataclass(init=False) class Property(BaseProvider): """Property details generic to any property""" name: str = field() min_area: int = field() max_area: int = field() min_price: int = field() max_price: int = field() min_rooms: int = field() max_rooms: int = field() def address(se...
@dataclass(init=False) class Property(BaseProvider):
"""Property details generic to any property""" name: str = field() min_area: int = field() max_area: int = field() min_price: int = field() max_price: int = field() min_rooms: int = field() max_rooms: int = field() def address(self) -> str: """Create a property address""" ...
"""Generate fake property data for the cloud function example""" import datetime import random from dataclasses import dataclass, field from faker import Faker from faker.providers import BaseProvider fake = Faker("en_GB") @dataclass(init=False) class Property(BaseProvider):
56
112
376
10
46
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
Property
Property
13
55
13
14
5195b84f073768f743f83eec06fc8ca172dcd145
bigcode/the-stack
train
b06d91f7fd4fd13e95c0193a
train
class
@dataclass class TerracedHouse(Property): name: str = "TerracedHouse" min_area: int = 900 max_area: int = 2_000 min_price: int = 70_000 max_price: int = 500_000 min_rooms: int = 5 max_rooms: int = 9
@dataclass class TerracedHouse(Property):
name: str = "TerracedHouse" min_area: int = 900 max_area: int = 2_000 min_price: int = 70_000 max_price: int = 500_000 min_rooms: int = 5 max_rooms: int = 9
500 max_area: int = 4_000 min_price: int = 70_000 max_price: int = 1_500_000 min_rooms: int = 5 max_rooms: int = 15 @dataclass class TerracedHouse(Property):
64
64
79
9
54
julian-west/e4ds-snippets
gcp/cloud-functions/event-driven-testing/data_generator/properties.py
Python
TerracedHouse
TerracedHouse
115
123
115
116
343928d4c232d92bcb8c849f8e08eeb8d957ae75
bigcode/the-stack
train
948be8951450995c92f262d1
train
function
def drawSpecialMove(x, y, ComboCounter, Tspin, backToBack, board, tetris, PC, combo, mini, single, double, triple): if ComboCounter != 0: ComboCounter -= 1 if PC: drawText('Perfect Clear', x, y, WHITE) if combo: drawText(str(ComboCounter) + ' Combo', x, y + 40, WHITE) if mi...
def drawSpecialMove(x, y, ComboCounter, Tspin, backToBack, board, tetris, PC, combo, mini, single, double, triple):
if ComboCounter != 0: ComboCounter -= 1 if PC: drawText('Perfect Clear', x, y, WHITE) if combo: drawText(str(ComboCounter) + ' Combo', x, y + 40, WHITE) if mini: drawText('T-Spin Mini', x, y + 80, WHITE) if single: drawText('T-Spin Single', x, y + 80, WH...
y + 220, color) drawText('P1-q | P2-1: Rotate 180', x, y + 240, color) def drawSpecialMove(x, y, ComboCounter, Tspin, backToBack, board, tetris, PC, combo, mini, single, double, triple):
68
68
227
35
33
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawSpecialMove
drawSpecialMove
1,525
1,544
1,525
1,525
ddeaf567e61f148f99558bdbaaf4540ef20b0cde
bigcode/the-stack
train
f214e5386fa111cce4444932
train
function
def drawHoldPieceP1(piece): holdSurf = BASICFONT.render('Hold', True, TEXTCOLOR) holdRect = holdSurf.get_rect() holdRect.topleft = (WINDOWWIDTH - 1140, 80) DISPLAYSURF.blit(holdSurf, holdRect) if piece != None: drawPieceP1(piece, pixelx=WINDOWWIDTH-1140, pixely=120)
def drawHoldPieceP1(piece):
holdSurf = BASICFONT.render('Hold', True, TEXTCOLOR) holdRect = holdSurf.get_rect() holdRect.topleft = (WINDOWWIDTH - 1140, 80) DISPLAYSURF.blit(holdSurf, holdRect) if piece != None: drawPieceP1(piece, pixelx=WINDOWWIDTH-1140, pixely=120)
F.blit(nextSurf, nextRect) # draw the "next" piece for order, piece in enumerate(NEXT_PIECES): drawPieceP1(piece, pixelx=WINDOWWIDTH-740, pixely=120 + (order * 80)) def drawHoldPieceP1(piece):
64
64
90
8
56
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawHoldPieceP1
drawHoldPieceP1
1,471
1,478
1,471
1,471
1341b366b35fad60459c4eb912aa28955d0d403c
bigcode/the-stack
train
a79ece960b0cb38b9bd292bd
train
function
def drawPieceP1(piece, pixelx=None, pixely=None): shapeToDraw = PIECES[piece['shape']][piece['rotation']] if pixelx == None and pixely == None: # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure pixelx, pixely = convertToPixelCoordsP1(piece['x'], piec...
def drawPieceP1(piece, pixelx=None, pixely=None):
shapeToDraw = PIECES[piece['shape']][piece['rotation']] if pixelx == None and pixely == None: # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure pixelx, pixely = convertToPixelCoordsP1(piece['x'], piece['y']) # draw each of the boxes that make up...
(DISPLAYSURF, color, (XMARGIN+503 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3 + (BOXSIZE* (20 - receivedLine)), 4, BOXSIZE * receivedLine)) def drawPieceP1(piece, pixelx=None, pixely=None):
64
64
164
15
49
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawPieceP1
drawPieceP1
1,419
1,429
1,419
1,419
afc16cb1a4b2a334caa134d5cb085584ae36dc53
bigcode/the-stack
train
95c3331e5abf8411ab37aa32
train
function
def isValidPosition(board, piece, adjX=0, adjY=0): # Return True if the piece is within the board and not colliding if piece == None: return False for x in range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): isAboveBoard = y + piece['y'] + adjY < 0 if isAboveBoard o...
def isValidPosition(board, piece, adjX=0, adjY=0): # Return True if the piece is within the board and not colliding
if piece == None: return False for x in range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): isAboveBoard = y + piece['y'] + adjY < 0 if isAboveBoard or PIECES[piece['shape']][piece['rotation']][y][x] == BLANK: continue if not isOnBoard(x + pi...
)) return board def isOnBoard(x, y): return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT def isValidPosition(board, piece, adjX=0, adjY=0): # Return True if the piece is within the board and not colliding
64
64
175
34
29
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
isValidPosition
isValidPosition
1,086
1,099
1,086
1,087
6e5ada12696d19bdd07900105a09317bf260d491
bigcode/the-stack
train
2f555ca371ffd6882a44ad39
train
function
def GhostPiece(fallingPiece, board): ghostPiece = {'shape': fallingPiece['shape'], 'rotation': fallingPiece['rotation'], 'x': fallingPiece['x'], 'y': fallingPiece['y'], 'color': PIECES_COLOR[fallingPiece['shape']] + 7} for i in range(-1, B...
def GhostPiece(fallingPiece, board):
ghostPiece = {'shape': fallingPiece['shape'], 'rotation': fallingPiece['rotation'], 'x': fallingPiece['x'], 'y': fallingPiece['y'], 'color': PIECES_COLOR[fallingPiece['shape']] + 7} for i in range(-1, BOARDHEIGHT): if not isValidPo...
for y in range(TEMPLATEHEIGHT): if shapeToDraw[y][x] != BLANK: drawBoxP2(None, None, piece['color'], pixelx + (x * BOXSIZE), pixely + (y * BOXSIZE)) def GhostPiece(fallingPiece, board):
64
64
114
9
55
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
GhostPiece
GhostPiece
1,445
1,457
1,445
1,445
cfeefb88eed09d3bbc0ab4a0b42255a06a09a043
bigcode/the-stack
train
5d29733a8d52ce5c5fd6e7a4
train
function
def drawInstructions(x, y, color): drawText('tab: Quit', x, y, color) drawText('r: Reset', x, y + 20, color) drawText('p: Pause', x, y + 40, color) drawText('f: Fullscreen', x, y + 60, color) drawText('g: Small screen', x, y + 80, color) drawText('P1-e | P2-3: Hold', x, y + 100, color) drawT...
def drawInstructions(x, y, color):
drawText('tab: Quit', x, y, color) drawText('r: Reset', x, y + 20, color) drawText('p: Pause', x, y + 40, color) drawText('f: Fullscreen', x, y + 60, color) drawText('g: Small screen', x, y + 80, color) drawText('P1-e | P2-3: Hold', x, y + 100, color) drawText('P1-space | P2-v: Hard drop', x...
drawPieceP2(piece, pixelx=WINDOWWIDTH-540, pixely=120) def drawText(text, x, y, color): infoSurf = BASICFONT.render(text, True, color) infoRect = infoSurf.get_rect() infoRect.topleft = (x, y) DISPLAYSURF.blit(infoSurf, infoRect) def drawInstructions(x, y, color):
86
86
288
9
77
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawInstructions
drawInstructions
1,509
1,522
1,509
1,509
7d7c3227c6181ad4d8fce0b07943d6d22dc1a9aa
bigcode/the-stack
train
03178750321292aebad5f748
train
function
def drawNextPieceP2(NEXT_PIECES): # draw the "next" text nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR) nextRect = nextSurf.get_rect() nextRect.topleft = (WINDOWWIDTH - 120, 80) DISPLAYSURF.blit(nextSurf, nextRect) # draw the "next" piece for order, piece in enumerate(NEXT_PIECES): ...
def drawNextPieceP2(NEXT_PIECES): # draw the "next" text
nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR) nextRect = nextSurf.get_rect() nextRect.topleft = (WINDOWWIDTH - 120, 80) DISPLAYSURF.blit(nextSurf, nextRect) # draw the "next" piece for order, piece in enumerate(NEXT_PIECES): drawPieceP2(piece, pixelx=WINDOWWIDTH-140, pixely=120 +...
80) DISPLAYSURF.blit(holdSurf, holdRect) if piece != None: drawPieceP1(piece, pixelx=WINDOWWIDTH-1140, pixely=120) def drawNextPieceP2(NEXT_PIECES): # draw the "next" text
64
64
122
21
43
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawNextPieceP2
drawNextPieceP2
1,481
1,489
1,481
1,482
b52146a36f7c1a89e4c89a584977f06fdb9e1616
bigcode/the-stack
train
63e411bbb7c567f01ee8c0b9
train
function
def terminate(): pygame.quit() sys.exit()
def terminate():
pygame.quit() sys.exit()
.time() - P2TTripleTimer > 1: P2TTriple = False pygame.display.update() FPSCLOCK.tick(FPS) def makeTextObjs(text, font, color): surf = font.render(text, True, color) return surf, surf.get_rect() def terminate():
64
64
11
3
61
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
terminate
terminate
994
996
994
994
7aae35e48046a44dc8588125a97fbee0ced7cc7c
bigcode/the-stack
train
2389beed823bc488afd90917
train
function
def drawText(text, x, y, color): infoSurf = BASICFONT.render(text, True, color) infoRect = infoSurf.get_rect() infoRect.topleft = (x, y) DISPLAYSURF.blit(infoSurf, infoRect)
def drawText(text, x, y, color):
infoSurf = BASICFONT.render(text, True, color) infoRect = infoSurf.get_rect() infoRect.topleft = (x, y) DISPLAYSURF.blit(infoSurf, infoRect)
.topleft = (WINDOWWIDTH - 540, 80) DISPLAYSURF.blit(holdSurf, holdRect) if piece != None: drawPieceP2(piece, pixelx=WINDOWWIDTH-540, pixely=120) def drawText(text, x, y, color):
64
64
57
11
53
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawText
drawText
1,502
1,506
1,502
1,502
144c11a959b1a1eac210b2b68308857bd04b206b
bigcode/the-stack
train
836d2ad80711b2cd68545414
train
function
def drawBoxP1(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece). if color == B...
def drawBoxP1(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece).
if color == BLANK: return if loseP1: color = 14 if pixelx == None and pixely == None: pixelx, pixely = convertToPixelCoordsP1(boxx, boxy) pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx, pixely, BOXSIZE, BOXSIZE))
def drawBoxP1(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece).
86
64
167
86
0
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawBoxP1
drawBoxP1
1,327
1,338
1,327
1,331
cb76c1ea83bb81e0e2ed0cfacb223d22616971b8
bigcode/the-stack
train
cc12a9ea74191128fcc13e01
train
function
def getBlankBoard(): # create and return a new blank board data structure board = [] for i in range(BOARDWIDTH): board.append([BLANK] * (BOARDHEIGHT)) return board
def getBlankBoard(): # create and return a new blank board data structure
board = [] for i in range(BOARDWIDTH): board.append([BLANK] * (BOARDHEIGHT)) return board
if piece!=None and PIECES[piece['shape']][piece['rotation']][y][x] != BLANK: board[x + piece['x']][y + piece['y']] = piece['color'] def getBlankBoard(): # create and return a new blank board data structure
64
64
46
17
47
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
getBlankBoard
getBlankBoard
1,074
1,079
1,074
1,075
3e08baa665df0360cfd93ae751c7cf9ce1688084
bigcode/the-stack
train
2e4cee76a116719ea8cba394
train
function
def drawHiddenBoardP2(): pygame.draw.rect(DISPLAYSURF, BLACK, (XMARGIN+298 , TOPMARGIN +2, (BOARDWIDTH * BOXSIZE) + 10, (PLAYBOARD * BOXSIZE)))
def drawHiddenBoardP2():
pygame.draw.rect(DISPLAYSURF, BLACK, (XMARGIN+298 , TOPMARGIN +2, (BOARDWIDTH * BOXSIZE) + 10, (PLAYBOARD * BOXSIZE)))
board[x][y]) def drawHiddenBoardP1(): pygame.draw.rect(DISPLAYSURF, BLACK, (XMARGIN-302 , TOPMARGIN +2, (BOARDWIDTH * BOXSIZE) + 10, (PLAYBOARD * BOXSIZE))) def drawHiddenBoardP2():
63
64
51
7
56
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawHiddenBoardP2
drawHiddenBoardP2
1,391
1,392
1,391
1,391
550d01422b10b7aaa77fd7ccd0b8f5f73bcbe4de
bigcode/the-stack
train
e4d0a8d5965137c606b5a825
train
function
def reciveGarbage(board, line): y = 0 counter = 0 garbageHole = random.randrange(10) while counter < line: for pushUpY in range(y, BOARDHEIGHT - 1): for x in range(BOARDWIDTH): board[x][pushUpY] = board[x][pushUpY + 1] for x in range(BOARDWIDTH): i...
def reciveGarbage(board, line):
y = 0 counter = 0 garbageHole = random.randrange(10) while counter < line: for pushUpY in range(y, BOARDHEIGHT - 1): for x in range(BOARDWIDTH): board[x][pushUpY] = board[x][pushUpY + 1] for x in range(BOARDWIDTH): if x == garbageHole: ...
loop, y is the same. # This is so that if the line that was pulled down is also # complete, it will be removed. else: y -= 1 # move on to check next row up return numLinesRemoved def reciveGarbage(board, line):
64
64
133
9
54
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
reciveGarbage
reciveGarbage
1,189
1,202
1,189
1,189
e1254ab95a41e017de928c1ad507eadea391de90
bigcode/the-stack
train
cf6f67d4a7a201faa62310fc
train
function
def isCompleteLine(board, y): # Return True if the line filled with boxes with no gaps for x in range(BOARDWIDTH): if board[x][y] == BLANK: return False return True
def isCompleteLine(board, y): # Return True if the line filled with boxes with no gaps
for x in range(BOARDWIDTH): if board[x][y] == BLANK: return False return True
]) elif spinDirection == 'CCW': fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']]) def isCompleteLine(board, y): # Return True if the line filled with boxes with no gaps
64
64
50
22
42
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
isCompleteLine
isCompleteLine
1,159
1,164
1,159
1,160
7afbc6ed8c82724b3c0f900aa940b98f743d9e58
bigcode/the-stack
train
34597c823abf0cf6f2c2f80a
train
function
def removeCompleteLines(board): # Remove any completed lines on the board, move everything above them down, and return the number of complete lines. numLinesRemoved = 0 y = BOARDHEIGHT - 1 # start y at the bottom of the board while y >= 0: if isCompleteLine(board, y): # Remove the li...
def removeCompleteLines(board): # Remove any completed lines on the board, move everything above them down, and return the number of complete lines.
numLinesRemoved = 0 y = BOARDHEIGHT - 1 # start y at the bottom of the board while y >= 0: if isCompleteLine(board, y): # Remove the line and pull boxes down by one line. for pullDownY in range(y, 0, -1): for x in range(BOARDWIDTH): board[x...
if the line filled with boxes with no gaps for x in range(BOARDWIDTH): if board[x][y] == BLANK: return False return True def removeCompleteLines(board): # Remove any completed lines on the board, move everything above them down, and return the number of complete lines.
68
68
227
30
37
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
removeCompleteLines
removeCompleteLines
1,167
1,186
1,167
1,168
2c7692e6123da51ef7b410ee2cda4f0648a1afb2
bigcode/the-stack
train
bf55b94ca7b76bcbfd271e54
train
function
def sendLineFromP1(board, numLinesRemoved, P1Tspin, P1backToBack, P1ComboCounter, P1PerfectClear, P1backToBackPrint, P1Tetris, P1Combo, P1TMini, P1TSingle, P1TDouble, P1TTriple): blankBoard = getBlankBoard() lineSent = 0 if not P1Tspin: if numLinesRemoved == 0: lineSent += ATTACKTABLE[0...
def sendLineFromP1(board, numLinesRemoved, P1Tspin, P1backToBack, P1ComboCounter, P1PerfectClear, P1backToBackPrint, P1Tetris, P1Combo, P1TMini, P1TSingle, P1TDouble, P1TTriple):
blankBoard = getBlankBoard() lineSent = 0 if not P1Tspin: if numLinesRemoved == 0: lineSent += ATTACKTABLE[0] if numLinesRemoved == 1: P1backToBack = False lineSent += ATTACKTABLE[1] elif numLinesRemoved == 2: P1backToBack = False ...
while counter < line: for pushUpY in range(y, BOARDHEIGHT - 1): for x in range(BOARDWIDTH): board[x][pushUpY] = board[x][pushUpY + 1] for x in range(BOARDWIDTH): if x == garbageHole: board[x][BOARDHEIGHT - 1] = BLANK else: ...
171
171
570
69
101
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
sendLineFromP1
sendLineFromP1
1,205
1,260
1,205
1,205
0c8e1d3afe81c3bfe7407cd1891a17dc43b396da
bigcode/the-stack
train
0cee2e97d350d3c9728c5f9c
train
function
def drawBoardP2(board): # fill the background of the board for y in range(BOARDHEIGHT - 20): for x in range(BOARDWIDTH): pygame.draw.rect(DISPLAYSURF, GRAY1, (x*BOXSIZE + XMARGIN +300 , y*BOXSIZE + TOPMARGIN + PLAYBOARD * BOXSIZE + 2, BOXSIZE, BOXSIZE), 1) # draw the border around the bo...
def drawBoardP2(board): # fill the background of the board
for y in range(BOARDHEIGHT - 20): for x in range(BOARDWIDTH): pygame.draw.rect(DISPLAYSURF, GRAY1, (x*BOXSIZE + XMARGIN +300 , y*BOXSIZE + TOPMARGIN + PLAYBOARD * BOXSIZE + 2, BOXSIZE, BOXSIZE), 1) # draw the border around the board pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN+298...
XSIZE)), 3) # draw the individual boxes on the board for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): drawBoxP1(x, y, board[x][y]) def drawBoardP2(board): # fill the background of the board
64
64
203
16
48
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawBoardP2
drawBoardP2
1,374
1,384
1,374
1,375
8b854ff648362fd917baff2d4b76f650a44f5150
bigcode/the-stack
train
ebaa48bb066dd13c1e4bac48
train
function
def superRotationSystem(board, fallingPiece, spinDirection): set1 = ['J', 'L', 'S', 'T', 'Z'] set2 = ['I'] rotationAndDirection = [(fallingPiece['rotation'] == 1 and spinDirection == 'CW'), (fallingPiece['rotation'] == 0 and spinDirection == 'CCW'), ...
def superRotationSystem(board, fallingPiece, spinDirection):
set1 = ['J', 'L', 'S', 'T', 'Z'] set2 = ['I'] rotationAndDirection = [(fallingPiece['rotation'] == 1 and spinDirection == 'CW'), (fallingPiece['rotation'] == 0 and spinDirection == 'CCW'), (fallingPiece['rotation'] == 2 and spinDirecti...
range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): if ((x==0 and y==0) or (x==0 and y==2) or (x==2 and y==0) or (x==2 and y==2)): if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY): count += 1 elif board[x + piece['x'] + adjX][y + p...
150
150
502
12
137
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
superRotationSystem
superRotationSystem
1,117
1,156
1,117
1,117
3aa55443cd877e3487bec1ab208292b822f0edf8
bigcode/the-stack
train
05789dd194ccb57ba0bf5783
train
function
def getNewPieceP2(bag): # return a random new piece in a random rotation and color if len(bag) == 0: bag = list(PIECES.keys()) shape = bag[random.randrange(len(bag))] newPiece = {'shape': shape, 'rotation': 0, 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), ...
def getNewPieceP2(bag): # return a random new piece in a random rotation and color
if len(bag) == 0: bag = list(PIECES.keys()) shape = bag[random.randrange(len(bag))] newPiece = {'shape': shape, 'rotation': 0, 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), 'y': 19, # start it above the board (i.e. less than 0) 'co...
/ 2), 'y': 19, # start it above the board (i.e. less than 0) 'color': PIECES_COLOR[shape]} return newPiece def getNewPieceP2(bag): # return a random new piece in a random rotation and color
64
64
127
23
40
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
getNewPieceP2
getNewPieceP2
1,053
1,063
1,053
1,054
3222c7f3d91aae782afaa83f2e234036b8957e06
bigcode/the-stack
train
fade05898483ca5a1b60bda8
train
function
def isOnBoard(x, y): return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT
def isOnBoard(x, y):
return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT
+ piece['y']] = piece['color'] def getBlankBoard(): # create and return a new blank board data structure board = [] for i in range(BOARDWIDTH): board.append([BLANK] * (BOARDHEIGHT)) return board def isOnBoard(x, y):
64
64
25
8
55
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
isOnBoard
isOnBoard
1,082
1,083
1,082
1,082
610cadb183de8a99a0db81ccd6ccde3f3c9b3807
bigcode/the-stack
train
3fb61b0732315a79ade9b908
train
function
def is3ConnerRule(board, piece, adjX=0, adjY=0): count = 0 for x in range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): if ((x==0 and y==0) or (x==0 and y==2) or (x==2 and y==0) or (x==2 and y==2)): if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY): ...
def is3ConnerRule(board, piece, adjX=0, adjY=0):
count = 0 for x in range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): if ((x==0 and y==0) or (x==0 and y==2) or (x==2 and y==0) or (x==2 and y==2)): if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY): count += 1 elif board[x...
'] + adjY): return False if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK: return False return True def is3ConnerRule(board, piece, adjX=0, adjY=0):
64
64
168
20
43
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
is3ConnerRule
is3ConnerRule
1,102
1,114
1,102
1,102
86abdd54194d3b7fedc26bd310fa1cf3c5fb5ce9
bigcode/the-stack
train
911d17a1e01d022c732609be
train
function
def drawHiddenBoardP1(): pygame.draw.rect(DISPLAYSURF, BLACK, (XMARGIN-302 , TOPMARGIN +2, (BOARDWIDTH * BOXSIZE) + 10, (PLAYBOARD * BOXSIZE)))
def drawHiddenBoardP1():
pygame.draw.rect(DISPLAYSURF, BLACK, (XMARGIN-302 , TOPMARGIN +2, (BOARDWIDTH * BOXSIZE) + 10, (PLAYBOARD * BOXSIZE)))
+ 4, (PLAYBOARD * BOXSIZE)), 3) # draw the individual boxes on the board for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): drawBoxP2(x, y, board[x][y]) def drawHiddenBoardP1():
64
64
51
7
57
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawHiddenBoardP1
drawHiddenBoardP1
1,387
1,388
1,387
1,387
4f7ffd746c0f55540ec1b006025074b2abffc21d
bigcode/the-stack
train
74e25ecf401f303274a667bc
train
function
def drawAleartBarP1(receivedLine): color = (255,0,0) if receivedLine == 0: color = BLACK pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN-99 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3, 8, (PLAYBOARD * BOXSIZE) - 1),3) pygame.draw.rect(DISPLAYSURF, color, (XMARGIN-97 , TOPMARGIN + PLAYBOARD * B...
def drawAleartBarP1(receivedLine):
color = (255,0,0) if receivedLine == 0: color = BLACK pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN-99 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3, 8, (PLAYBOARD * BOXSIZE) - 1),3) pygame.draw.rect(DISPLAYSURF, color, (XMARGIN-97 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3 + (BOXSIZE* (20 - receive...
) def drawHiddenBoardP2(): pygame.draw.rect(DISPLAYSURF, BLACK, (XMARGIN+298 , TOPMARGIN +2, (BOARDWIDTH * BOXSIZE) + 10, (PLAYBOARD * BOXSIZE))) def drawAleartBarP1(receivedLine):
63
64
139
11
52
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawAleartBarP1
drawAleartBarP1
1,395
1,404
1,395
1,396
8a7bb098875bae51f07dafd1de6f7d8945e5d03a
bigcode/the-stack
train
75125932de3e2cf0dd3362df
train
function
def drawHoldPieceP2(piece): holdSurf = BASICFONT.render('Hold', True, TEXTCOLOR) holdRect = holdSurf.get_rect() holdRect.topleft = (WINDOWWIDTH - 540, 80) DISPLAYSURF.blit(holdSurf, holdRect) if piece != None: drawPieceP2(piece, pixelx=WINDOWWIDTH-540, pixely=120)
def drawHoldPieceP2(piece):
holdSurf = BASICFONT.render('Hold', True, TEXTCOLOR) holdRect = holdSurf.get_rect() holdRect.topleft = (WINDOWWIDTH - 540, 80) DISPLAYSURF.blit(holdSurf, holdRect) if piece != None: drawPieceP2(piece, pixelx=WINDOWWIDTH-540, pixely=120)
F.blit(nextSurf, nextRect) # draw the "next" piece for order, piece in enumerate(NEXT_PIECES): drawPieceP2(piece, pixelx=WINDOWWIDTH-140, pixely=120 + (order * 80)) def drawHoldPieceP2(piece):
64
64
88
8
56
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawHoldPieceP2
drawHoldPieceP2
1,492
1,499
1,492
1,492
c1c725441ad09aff255c981214b070a03f0fa097
bigcode/the-stack
train
dc35ad8a9341dd0ffe38418b
train
function
def drawBoardP1(board): # fill the background of the board for y in range(BOARDHEIGHT - 20): for x in range(BOARDWIDTH): pygame.draw.rect(DISPLAYSURF, GRAY1, (x*BOXSIZE + XMARGIN -300 , y*BOXSIZE + TOPMARGIN + PLAYBOARD * BOXSIZE + 2, BOXSIZE, BOXSIZE), 1) # draw the border around the bo...
def drawBoardP1(board): # fill the background of the board
for y in range(BOARDHEIGHT - 20): for x in range(BOARDWIDTH): pygame.draw.rect(DISPLAYSURF, GRAY1, (x*BOXSIZE + XMARGIN -300 , y*BOXSIZE + TOPMARGIN + PLAYBOARD * BOXSIZE + 2, BOXSIZE, BOXSIZE), 1) # draw the border around the board pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN-302...
pixelx, pixely = convertToPixelCoordsP2(boxx, boxy) pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx, pixely, BOXSIZE, BOXSIZE)) def drawBoardP1(board): # fill the background of the board
63
64
203
16
47
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawBoardP1
drawBoardP1
1,361
1,371
1,361
1,362
22be3837f07f1a113b69e1017a2316df8991175f
bigcode/the-stack
train
3e51a4c14526484ed9baf887
train
function
def drawAleartBarP2(receivedLine): color = (255,0,0) if receivedLine == 0: color = BLACK pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN+501 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3, 8, (PLAYBOARD * BOXSIZE) - 1),3) pygame.draw.rect(DISPLAYSURF, color, (XMARGIN+503 , TOPMARGIN + PLAYBOARD *...
def drawAleartBarP2(receivedLine):
color = (255,0,0) if receivedLine == 0: color = BLACK pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN+501 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3, 8, (PLAYBOARD * BOXSIZE) - 1),3) pygame.draw.rect(DISPLAYSURF, color, (XMARGIN+503 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3 + (BOXSIZE* (20 - recei...
pygame.draw.rect(DISPLAYSURF, color, (XMARGIN-97 , TOPMARGIN + PLAYBOARD * BOXSIZE + 3 + (BOXSIZE* (20 - receivedLine)), 4, BOXSIZE * receivedLine)) def drawAleartBarP2(receivedLine):
64
64
139
11
53
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawAleartBarP2
drawAleartBarP2
1,407
1,416
1,407
1,408
64d7b3ed319b818e2deb4dfc844c37e904ba499f
bigcode/the-stack
train
5605c4e033d56c5b3d5b7b2f
train
function
def convertToPixelCoordsP2(boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen. return (XMARGIN +300 + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))
def convertToPixelCoordsP2(boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen.
return (XMARGIN +300 + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))
pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx, pixely, BOXSIZE, BOXSIZE)) def convertToPixelCoordsP2(boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen.
64
64
65
36
28
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
convertToPixelCoordsP2
convertToPixelCoordsP2
1,341
1,344
1,341
1,343
69fcfa79daad80ccf706ba93ff4289bff63203b4
bigcode/the-stack
train
6243ad95eba0d925bce8cdd5
train
function
def drawPieceP2(piece, pixelx=None, pixely=None): shapeToDraw = PIECES[piece['shape']][piece['rotation']] if pixelx == None and pixely == None: # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure pixelx, pixely = convertToPixelCoordsP2(piece['x'], piec...
def drawPieceP2(piece, pixelx=None, pixely=None):
shapeToDraw = PIECES[piece['shape']][piece['rotation']] if pixelx == None and pixely == None: # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure pixelx, pixely = convertToPixelCoordsP2(piece['x'], piece['y']) # draw each of the boxes that make up...
EMPLATEHEIGHT): if shapeToDraw[y][x] != BLANK: drawBoxP1(None, None, piece['color'], pixelx + (x * BOXSIZE), pixely + (y * BOXSIZE)) def drawPieceP2(piece, pixelx=None, pixely=None):
64
64
164
15
49
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawPieceP2
drawPieceP2
1,432
1,442
1,432
1,432
296c1c841b8b9637929954bdb2c8d3f9a8fab377
bigcode/the-stack
train
07938a3cadd7b7d5ad0fa2d1
train
function
def sendLineFromP2(board, numLinesRemoved, P2Tspin, P2backToBack, P2ComboCounter, P2PerfectClear, P2backToBackPrint, P2Tetris, P2Combo, P2TMini, P2TSingle, P2TDouble, P2TTriple): blankBoard = getBlankBoard() lineSent = 0 if not P2Tspin: if numLinesRemoved == 0: lineSent += ATTACKTABLE[0...
def sendLineFromP2(board, numLinesRemoved, P2Tspin, P2backToBack, P2ComboCounter, P2PerfectClear, P2backToBackPrint, P2Tetris, P2Combo, P2TMini, P2TSingle, P2TDouble, P2TTriple):
blankBoard = getBlankBoard() lineSent = 0 if not P2Tspin: if numLinesRemoved == 0: lineSent += ATTACKTABLE[0] if numLinesRemoved == 1: P2backToBack = False lineSent += ATTACKTABLE[1] elif numLinesRemoved == 2: P2backToBack = False ...
lineSent += COMBOTABLE[P1ComboCounter - 1] else: lineSent += COMBOTABLE[12] else: P1ComboCounter = 0 return lineSent, P1backToBack, P1ComboCounter, numLinesRemoved, P1PerfectClear, P1backToBackPrint, P1Tetris, P1Combo, P1TMini, P1TSingle, P1TDouble, P1TTriple def sendLineFromP...
170
170
569
69
100
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
sendLineFromP2
sendLineFromP2
1,263
1,318
1,263
1,263
f7d44e87de6948ac8a9156da86e7015ef56260aa
bigcode/the-stack
train
2a3a4283ed47de41f8a31fa4
train
function
def checkForQuit(): for event in pygame.event.get(QUIT): # get all the QUIT events terminate() # terminate if any QUIT events are present for event in pygame.event.get(KEYUP): # get all the KEYUP events if event.key == K_ESCAPE: terminate() # terminate if the KEYUP event was for the ...
def checkForQuit():
for event in pygame.event.get(QUIT): # get all the QUIT events terminate() # terminate if any QUIT events are present for event in pygame.event.get(KEYUP): # get all the KEYUP events if event.key == K_ESCAPE: terminate() # terminate if the KEYUP event was for the Esc key pyga...
.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2) + 100) DISPLAYSURF.blit(pressKeySurf, pressKeyRect) while checkForKeyPress() == None: pygame.display.update() FPSCLOCK.tick() def checkForQuit():
64
64
94
5
59
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
checkForQuit
checkForQuit
1,031
1,037
1,031
1,031
f901c87d28530d6bb3f03be171e368dc2416fca7
bigcode/the-stack
train
fb73f69f8fa796df497539c6
train
function
def main(): global FPSCLOCK, DISPLAYSURF, SMALLFONT, BASICFONT, BIGFONT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) SMALLFONT = pygame.font.Font('freesansbold.ttf', 14) BASICFONT = pygame.font.Font('freesansbold.ttf', 18) BI...
def main():
global FPSCLOCK, DISPLAYSURF, SMALLFONT, BASICFONT, BIGFONT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) SMALLFONT = pygame.font.Font('freesansbold.ttf', 14) BASICFONT = pygame.font.Font('freesansbold.ttf', 18) BIGFONT = pyga...
( 1, 2)), (( 1, 0), (-2, 0), ( 1,-2), (-2, 1)), ((-1, 0), ( 2, 0), (-1, 2), ( 2,-1))] def main():
63
64
141
3
61
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
main
main
219
232
219
219
9c6bd7f249d494e33386e40de4d91ad1c4d9d90d
bigcode/the-stack
train
591496ea338a37ae1ad5a979
train
function
def getNewPieceP1(bag): # return a random new piece in a random rotation and color if len(bag) == 0: bag = list(PIECES.keys()) shape = bag[random.randrange(len(bag))] newPiece = {'shape': shape, 'rotation': 0, 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), ...
def getNewPieceP1(bag): # return a random new piece in a random rotation and color
if len(bag) == 0: bag = list(PIECES.keys()) shape = bag[random.randrange(len(bag))] newPiece = {'shape': shape, 'rotation': 0, 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), 'y': 19, # start it above the board (i.e. less than 0) 'co...
if event.key == K_ESCAPE: terminate() # terminate if the KEYUP event was for the Esc key pygame.event.post(event) # put the other KEYUP event objects back def getNewPieceP1(bag): # return a random new piece in a random rotation and color
64
64
127
23
40
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
getNewPieceP1
getNewPieceP1
1,040
1,050
1,040
1,041
7086dc6f5bddc9c359be7b3a1aa9c0ddc670126e
bigcode/the-stack
train
a18dd644ab9e634c99ec166c
train
function
def checkForKeyPress(): # Go through event queue looking for a KEYUP event. # Grab KEYDOWN events to remove them from the event queue. checkForQuit() for event in pygame.event.get([KEYDOWN, KEYUP]): if event.type == KEYDOWN: continue return event.key return None
def checkForKeyPress(): # Go through event queue looking for a KEYUP event. # Grab KEYDOWN events to remove them from the event queue.
checkForQuit() for event in pygame.event.get([KEYDOWN, KEYUP]): if event.type == KEYDOWN: continue return event.key return None
): surf = font.render(text, True, color) return surf, surf.get_rect() def terminate(): pygame.quit() sys.exit() def checkForKeyPress(): # Go through event queue looking for a KEYUP event. # Grab KEYDOWN events to remove them from the event queue.
64
64
72
33
31
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
checkForKeyPress
checkForKeyPress
999
1,008
999
1,001
94948292a881287ad7bc14fb067a3b1477294a70
bigcode/the-stack
train
a7648b53b8460d29d661ba30
train
function
def makeTextObjs(text, font, color): surf = font.render(text, True, color) return surf, surf.get_rect()
def makeTextObjs(text, font, color):
surf = font.render(text, True, color) return surf, surf.get_rect()
> 1: P1TTriple = False if P2TTriple: if time.time() - P2TTripleTimer > 1: P2TTriple = False pygame.display.update() FPSCLOCK.tick(FPS) def makeTextObjs(text, font, color):
64
64
29
10
54
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
makeTextObjs
makeTextObjs
989
991
989
989
b63c05063c6b9761f40cc3f27cf7b176d80df308
bigcode/the-stack
train
47e62f1f7b090b830b850830
train
function
def runGame(): # setup variables for the start of the game global loseP1, loseP2, DISPLAYSURF boardP1 = getBlankBoard() boardP2 = getBlankBoard() lastMoveDownTimeP1 = time.time() lastMoveSidewaysTimeP1 = time.time() lastFallTimeP1 = time.time() loseP1 = False movingDownP1 = False # n...
def runGame(): # setup variables for the start of the game
global loseP1, loseP2, DISPLAYSURF boardP1 = getBlankBoard() boardP2 = getBlankBoard() lastMoveDownTimeP1 = time.time() lastMoveSidewaysTimeP1 = time.time() lastFallTimeP1 = time.time() loseP1 = False movingDownP1 = False # note: there is no movingUp variable movingLeftP1 = False ...
), (-1, 0), ( 2, 1), (-1,-2)), ((-2, 0), ( 1, 0), (-2,-1), ( 1, 2)), (( 1, 0), (-2, 0), ( 1,-2), (-2, 1)), ((-1, 0), ( 2, 0), (-1, 2), ( 2,-1))] def main(): global FPSCLOCK, DISPLAYSURF, SMALLFONT, BASICFONT, BIGFONT pygame.init() FPSCLOCK = pygam...
256
256
9,315
15
241
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
runGame
runGame
235
987
235
236
0798b7921307aa49c7e82f6243be953147727c92
bigcode/the-stack
train
6e9cd24f3046fe7bb074106a
train
function
def drawNextPieceP1(NEXT_PIECES): # draw the "next" text nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR) nextRect = nextSurf.get_rect() nextRect.topleft = (WINDOWWIDTH - 720, 80) DISPLAYSURF.blit(nextSurf, nextRect) # draw the "next" piece for order, piece in enumerate(NEXT_PIECES): ...
def drawNextPieceP1(NEXT_PIECES): # draw the "next" text
nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR) nextRect = nextSurf.get_rect() nextRect.topleft = (WINDOWWIDTH - 720, 80) DISPLAYSURF.blit(nextSurf, nextRect) # draw the "next" piece for order, piece in enumerate(NEXT_PIECES): drawPieceP1(piece, pixelx=WINDOWWIDTH-740, pixely=120 +...
(-1, BOARDHEIGHT): if not isValidPosition(board, fallingPiece, adjY=i+2): break ghostPiece['y'] += i + 1 return ghostPiece def drawNextPieceP1(NEXT_PIECES): # draw the "next" text
64
64
122
21
42
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawNextPieceP1
drawNextPieceP1
1,460
1,468
1,460
1,461
e0744f6ef669f1a19122e266f994d9488d91c294
bigcode/the-stack
train
f5a0d66ced82e3970b83b921
train
function
def fade(width, height, x, y): fade = pygame.Surface((width, height)) fade.fill((WHITE)) for alpha in range(0, 300): fade.set_alpha(alpha) DISPLAYSURF.blit(fade, (x,y)) pygame.display.update() pygame.time.delay(5)
def fade(width, height, x, y):
fade = pygame.Surface((width, height)) fade.fill((WHITE)) for alpha in range(0, 300): fade.set_alpha(alpha) DISPLAYSURF.blit(fade, (x,y)) pygame.display.update() pygame.time.delay(5)
x, y + 80, WHITE) if backToBack: drawText('BackToBack', x, y + 120, WHITE) if tetris: drawText('Tetris', x, y + 160, WHITE) def fade(width, height, x, y):
64
64
70
11
53
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
fade
fade
1,547
1,554
1,547
1,547
f180aec78139a7c9b0f1deaa8a15e10f5f3890f1
bigcode/the-stack
train
ea532907b6827a00607dd43e
train
function
def convertToPixelCoordsP1(boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen. return (XMARGIN -300 + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))
def convertToPixelCoordsP1(boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen.
return (XMARGIN -300 + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))
2Tetris, P2Combo, P2TMini, P2TSingle, P2TDouble, P2TTriple def convertToPixelCoordsP1(boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen.
64
64
65
36
27
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
convertToPixelCoordsP1
convertToPixelCoordsP1
1,321
1,324
1,321
1,323
963a7716836ef18ace9eb2f7cd30439da237bb14
bigcode/the-stack
train
9c1daa3fc5bf15aa79f49d06
train
function
def drawBoxP2(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece). if color == B...
def drawBoxP2(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece).
if color == BLANK: return if loseP2: color = 14 if pixelx == None and pixely == None: pixelx, pixely = convertToPixelCoordsP2(boxx, boxy) pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx, pixely, BOXSIZE, BOXSIZE))
def drawBoxP2(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece).
86
64
168
86
0
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
drawBoxP2
drawBoxP2
1,347
1,358
1,347
1,351
6281bcd053e2baf84f99938baec7a526c3013785
bigcode/the-stack
train
54820dbd5080919afe0aafb1
train
function
def showTextScreen(text): # This function displays large text in the # center of the screen until a key is pressed. # Draw the text drop shadow # Draw the text titleSurf, titleRect = makeTextObjs(text, BIGFONT, TEXTCOLOR) titleRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2)) DISP...
def showTextScreen(text): # This function displays large text in the # center of the screen until a key is pressed. # Draw the text drop shadow # Draw the text
titleSurf, titleRect = makeTextObjs(text, BIGFONT, TEXTCOLOR) titleRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2)) DISPLAYSURF.blit(titleSurf, titleRect) # Draw the additional "Press a key to play." text. pressKeySurf, pressKeyRect = makeTextObjs('Press a key to play.', BASICFONT, TEXTC...
UP]): if event.type == KEYDOWN: continue return event.key return None def showTextScreen(text): # This function displays large text in the # center of the screen until a key is pressed. # Draw the text drop shadow # Draw the text
64
64
197
42
21
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
showTextScreen
showTextScreen
1,011
1,028
1,011
1,016
e6c965ac2082c4d1cb032643e989b7f1160a1302
bigcode/the-stack
train
d375a68639136b0801032f0a
train
function
def addToBoard(board, piece): # fill in the board based on piece's location, shape, and rotation for x in range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): if piece!=None and PIECES[piece['shape']][piece['rotation']][y][x] != BLANK: board[x + piece['x']][y + piece['y']] =...
def addToBoard(board, piece): # fill in the board based on piece's location, shape, and rotation
for x in range(TEMPLATEWIDTH): for y in range(TEMPLATEHEIGHT): if piece!=None and PIECES[piece['shape']][piece['rotation']][y][x] != BLANK: board[x + piece['x']][y + piece['y']] = piece['color']
2), 'y': 19, # start it above the board (i.e. less than 0) 'color': PIECES_COLOR[shape]} return newPiece def addToBoard(board, piece): # fill in the board based on piece's location, shape, and rotation
64
64
90
25
38
dinhlongviolin1/pygame-tetris
Tetris2.py
Python
addToBoard
addToBoard
1,066
1,071
1,066
1,067
89c40f46a03854df7ca289e1db07e86dc841ae96
bigcode/the-stack
train
5b56aa8520372743bd6acb29
train
class
class GermplasmUpdateDTO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map ...
class GermplasmUpdateDTO(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ OpenSilex API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: INSTANCE-SNAPSHOT Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F4...
91
256
2,976
8
82
OpenSILEX/opensilexClientToolsPython
opensilexClientToolsPython/models/germplasm_update_dto.py
Python
GermplasmUpdateDTO
GermplasmUpdateDTO
20
452
20
20
a22d290e8a4acc2859f42d34c266ed4c985fc14f
bigcode/the-stack
train
7a98f32bc69599da7b449d87
train
class
class BaseConventionView(AuthenticatedView): @property def _convention_uid(self): return self.request.matchdict["convention_uid"] @cache_per_request("convention") def get_convention(self): return get_active_by_uid(self._convention_uid) def validate(self): super().validate()...
class BaseConventionView(AuthenticatedView): @property
def _convention_uid(self): return self.request.matchdict["convention_uid"] @cache_per_request("convention") def get_convention(self): return get_active_by_uid(self._convention_uid) def validate(self): super().validate() try: self.get_convention() exc...
HTTPNotFound from iep.application.cache import cache_per_request from iep.application.drivers.query import NoResultFound from iep.auth.view_mixins import AuthenticatedView from iep.conventions.drivers.query import get_active_by_uid class BaseConventionView(AuthenticatedView): @property
64
64
90
12
51
socek/iep
backend/code/iep/conventions/view_mixins.py
Python
BaseConventionView
BaseConventionView
9
23
9
10
b9ded441a41309ca02704db40226029afee7a1a8
bigcode/the-stack
train
6641edee632dd08c21c239ae
train
function
def main(): setup( name=PACKAGE, version=VERSION, description="Common module for integrate allure with python-based frameworks", url="https://github.com/allure-framework/allure-python", author="QAMetaSoftware, Stanislav Seliverstov", author_email="sseliverstov@qameta....
def main():
setup( name=PACKAGE, version=VERSION, description="Common module for integrate allure with python-based frameworks", url="https://github.com/allure-framework/allure-python", author="QAMetaSoftware, Stanislav Seliverstov", author_email="sseliverstov@qameta.io", ...
Quality Assurance', 'Topic :: Software Development :: Testing', ] install_requires = [ "attrs>=16.0.0", "six>=1.9.0", "pluggy>=0.4.0", "enum34;python_version<'3.4'", ] def main():
64
64
137
3
61
vdsbenoit/allure-python
allure-python-commons/setup.py
Python
main
main
22
37
22
22
8518f52983679761d276e94a96963276edff6a36
bigcode/the-stack
train
cde5baf746b0f90ac8c5038f
train
class
class SearchServiceCreateOrUpdateParameters(Model): """Properties that describe an Azure Search service. :param location: The geographic location of the Search service. :type location: str :param tags: Tags to help categorize the Search service in the Azure Portal. :type tags: dict :param ...
class SearchServiceCreateOrUpdateParameters(Model):
"""Properties that describe an Azure Search service. :param location: The geographic location of the Search service. :type location: str :param tags: Tags to help categorize the Search service in the Azure Portal. :type tags: dict :param properties: Properties of the Search service. :t...
See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization impor...
64
64
195
9
54
CharaD7/azure-sdk-for-python
unreleased/azure-mgmt-search/azure/mgmt/search/models/search_service_create_or_update_parameters.py
Python
SearchServiceCreateOrUpdateParameters
SearchServiceCreateOrUpdateParameters
15
37
15
15
d84ffaa27c443eea1e7c1b0411e4e3b843865b59
bigcode/the-stack
train
9b331a06c4fbf9b274a384dc
train
class
class StubChatUI(ChatUI): def getGroupConversation(self, group, Class=StubConversation, stayHidden=0): return ChatUI.getGroupConversation(self, group, Class, stayHidden)
class StubChatUI(ChatUI):
def getGroupConversation(self, group, Class=StubConversation, stayHidden=0): return ChatUI.getGroupConversation(self, group, Class, stayHidden)
.trial.unittest import TestCase from twisted.test.proto_helpers import StringTransport from twisted.words.im.basechat import Conversation, ChatUI from twisted.words.im.ircsupport import IRCAccount, IRCProto class StubConversation(Conversation): def show(self): pass class StubChatUI(ChatUI):
64
64
42
7
56
OpenGeoscience/VTK
ThirdParty/Twisted/twisted/words/test/test_ircsupport.py
Python
StubChatUI
StubChatUI
22
24
22
22
65ea8ac2c373f8736adddd8c24f916212cdf2884
bigcode/the-stack
train
fd399eebf94a9799da880b45
train
class
class IRCProtoTests(TestCase): """ Tests for L{IRCProto}. """ def setUp(self): self.account = IRCAccount( "Some account", False, "alice", None, "example.com", 6667) self.proto = IRCProto(self.account, StubChatUI(), None) def test_login(self): """ When L{...
class IRCProtoTests(TestCase):
""" Tests for L{IRCProto}. """ def setUp(self): self.account = IRCAccount( "Some account", False, "alice", None, "example.com", 6667) self.proto = IRCProto(self.account, StubChatUI(), None) def test_login(self): """ When L{IRCProto} is connected to a tra...
.im.ircsupport}. """ from twisted.trial.unittest import TestCase from twisted.test.proto_helpers import StringTransport from twisted.words.im.basechat import Conversation, ChatUI from twisted.words.im.ircsupport import IRCAccount, IRCProto class StubConversation(Conversation): def show(self): pass c...
114
114
380
7
107
OpenGeoscience/VTK
ThirdParty/Twisted/twisted/words/test/test_ircsupport.py
Python
IRCProtoTests
IRCProtoTests
28
79
28
28
f80492983bb8eb92f24b1c0c4da20634e97548f2
bigcode/the-stack
train
b74908cbdf5cd9e22006cebb
train
class
class StubConversation(Conversation): def show(self): pass
class StubConversation(Conversation):
def show(self): pass
Tests for L{twisted.words.im.ircsupport}. """ from twisted.trial.unittest import TestCase from twisted.test.proto_helpers import StringTransport from twisted.words.im.basechat import Conversation, ChatUI from twisted.words.im.ircsupport import IRCAccount, IRCProto class StubConversation(Conversation):
64
64
14
6
57
OpenGeoscience/VTK
ThirdParty/Twisted/twisted/words/test/test_ircsupport.py
Python
StubConversation
StubConversation
16
18
16
16
316a7a4e3151135b34009ca80e8773f4f76f0cc8
bigcode/the-stack
train