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
6153ea1e934af830dfa43ceb
train
function
@pytest.mark.parametrize( "spec", [ "", "//", "//:!t", "//:?", "//:=", r"a:b\c", "a:b/c", "a:my#tgt#generated", ], ) def test_address_bad_target_component(spec: str) -> None: with pytest.raises(InvalidTargetName): AddressInput.parse...
@pytest.mark.parametrize( "spec", [ "", "//", "//:!t", "//:?", "//:=", r"a:b\c", "a:b/c", "a:my#tgt#generated", ], ) def test_address_bad_target_component(spec: str) -> None:
with pytest.raises(InvalidTargetName): AddressInput.parse(spec).dir_to_address()
@pytest.mark.parametrize( "spec", [ "", "//", "//:!t", "//:?", "//:=", r"a:b\c", "a:b/c", "a:my#tgt#generated", ], ) def test_address_bad_target_component(spec: str) -> None:
70
64
89
70
0
wonlay/pants
src/python/pants/build_graph/address_test.py
Python
test_address_bad_target_component
test_address_bad_target_component
129
144
129
142
b1532ec871913df0d339cdf2cf9767c8dbc63e8e
bigcode/the-stack
train
152a0f34d8e4586ddae6f306
train
function
def test_address_input_parse_spec() -> None: def assert_parsed( spec: str, *, path_component: str, target_component: str | None = None, parameters: dict[str, str] | None = None, generated_component: str | None = None, relative_to: str | None = None, ) -> N...
def test_address_input_parse_spec() -> None:
def assert_parsed( spec: str, *, path_component: str, target_component: str | None = None, parameters: dict[str, str] | None = None, generated_component: str | None = None, relative_to: str | None = None, ) -> None: ai = AddressInput.parse(spec, re...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import pytest from pants.build_graph.address import ( Address, AddressInput, AddressParseException, InvalidParameters, InvalidSpecP...
102
256
946
10
91
wonlay/pants
src/python/pants/build_graph/address_test.py
Python
test_address_input_parse_spec
test_address_input_parse_spec
21
104
21
21
d520d532ff055af9c9b80f155033049f98dfca90
bigcode/the-stack
train
48ca7cee7ccd417ace230991
train
function
def test_address_create_generated() -> None: assert Address("dir", target_name="generator").create_generated("generated") == Address( "dir", target_name="generator", generated_name="generated" ) with pytest.raises(AssertionError): Address("", target_name="t", relative_file_path="f.ext").crea...
def test_address_create_generated() -> None:
assert Address("dir", target_name="generator").create_generated("generated") == Address( "dir", target_name="generator", generated_name="generated" ) with pytest.raises(AssertionError): Address("", target_name="t", relative_file_path="f.ext").create_generated("gen") with pytest.raises(As...
_name="original"), ) def assert_noops(addr: Address) -> None: assert addr.maybe_convert_to_target_generator() is addr assert_noops(Address("a/b", target_name="c")) assert_noops(Address("a/b")) def test_address_create_generated() -> None:
63
64
98
9
54
wonlay/pants
src/python/pants/build_graph/address_test.py
Python
test_address_create_generated
test_address_create_generated
449
456
449
449
f5c9998cd802b41c193cc20d9aaefe8d3a3d9d05
bigcode/the-stack
train
36e102b515f88b5db9569ac6
train
function
def test_address_maybe_convert_to_target_generator() -> None: def assert_converts(addr: Address, *, expected: Address) -> None: assert addr.maybe_convert_to_target_generator() == expected assert_converts( Address( "a/b", target_name="c", generated_name="gener...
def test_address_maybe_convert_to_target_generator() -> None:
def assert_converts(addr: Address, *, expected: Address) -> None: assert addr.maybe_convert_to_target_generator() == expected assert_converts( Address( "a/b", target_name="c", generated_name="generated", ), expected=Address("a/b", target_name=...
,expected", (({}, ""), ({"k": "v"}, "@k=v"), ({"k1": "v", "k2": "v"}, "@k1=v,k2=v")) ) def test_address_parameters_repr(params: dict[str, str], expected: str) -> None: assert Address("", target_name="foo", parameters=params).parameters_repr == expected def test_address_maybe_convert_to_target_generator() -> None:
90
90
303
13
76
wonlay/pants
src/python/pants/build_graph/address_test.py
Python
test_address_maybe_convert_to_target_generator
test_address_maybe_convert_to_target_generator
416
446
416
416
e90f6e9300751325cb3153fb76370d6b4ac3e1d5
bigcode/the-stack
train
369cb1dfa0d231f1e10ac6b6
train
function
def app(opt): print(opt) train_loader = torch.utils.data.DataLoader( torchvision.datasets.CIFAR10( opt.data, train=True, transform=torchvision.transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip()...
def app(opt):
print(opt) train_loader = torch.utils.data.DataLoader( torchvision.datasets.CIFAR10( opt.data, train=True, transform=torchvision.transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), ...
threshold balancing algorithm that finds the proper thresholds of spiking neurons in SNN for ANN-SNN conversion. Sengupta et al. Going deeper in spiking neural networks: VGG and residual architectures. 2018 """ import argparse import torch import torch.nn as nn import torchvision import torchvision.transforms as tra...
109
109
365
4
104
neurom-iot/n3ml
test_spikenorm_snn_train.py
Python
app
app
19
61
19
19
66da4e56e80f8eeea311f67621c71cfb15074526
bigcode/the-stack
train
fccbf7b3b98804dfbc4ab11e
train
class
class DescribeUserCustomerLabelsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Cdn', '2014-11-11', 'DescribeUserCustomerLabels') def get_Uid(self): return self.get_query_params().get('Uid') def set_Uid(self,Uid): self.add_query_param('Uid',Uid) def get_SecurityToken(self): ...
class DescribeUserCustomerLabelsRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Cdn', '2014-11-11', 'DescribeUserCustomerLabels') def get_Uid(self): return self.get_query_params().get('Uid') def set_Uid(self,Uid): self.add_query_param('Uid',Uid) def get_SecurityToken(self): return self.get_query_params().get('SecurityToken') ...
an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class DescribeUserCustomerLabelsRequest(RpcRequest):
64
64
160
10
53
sdk-team/aliyun-openapi-python-sdk
aliyun-python-sdk-cdn/aliyunsdkcdn/request/v20141111/DescribeUserCustomerLabelsRequest.py
Python
DescribeUserCustomerLabelsRequest
DescribeUserCustomerLabelsRequest
21
42
21
22
091966cb99165ace962d62dbed5e208aa83d840e
bigcode/the-stack
train
640614b512c705e7fa7e6445
train
class
class Migration(migrations.Migration): dependencies = [ ('api', '0020_lexique'), ] operations = [ migrations.CreateModel( name='FoireAuxQuestions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='I...
class Migration(migrations.Migration):
dependencies = [ ('api', '0020_lexique'), ] operations = [ migrations.CreateModel( name='FoireAuxQuestions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('libelle', models...
# Generated by Django 2.0.2 on 2018-08-19 19:15 from django.db import migrations, models import markdownx.models class Migration(migrations.Migration):
43
64
161
7
35
heltleo/fanfiction
api/migrations/0021_auto_20180819_2115.py
Python
Migration
Migration
7
28
7
8
d89b616609d915e4277f298641c001e4f0cd9e3e
bigcode/the-stack
train
3b23875f4ba1b37b89f60944
train
function
def _log_big_success_msg(success_msg): cli_logger.newline() cli_logger.success("-" * len(success_msg)) cli_logger.success(success_msg) cli_logger.success("-" * len(success_msg)) cli_logger.newline()
def _log_big_success_msg(success_msg):
cli_logger.newline() cli_logger.success("-" * len(success_msg)) cli_logger.success(success_msg) cli_logger.success("-" * len(success_msg)) cli_logger.newline()
specified using either the --address flag " "or RAY_ADDRESS environment variable." ) address = os.environ["RAY_ADDRESS"] cli_logger.labeled_value("Job submission server address", address) return JobSubmissionClient(address, create_cluster_if_needed) def _log_big_success_msg...
64
64
50
9
55
clarng/ray
dashboard/modules/job/cli.py
Python
_log_big_success_msg
_log_big_success_msg
31
36
31
31
fda5b6e25606e5a115c0b1da9db61c2e67c7cf9c
bigcode/the-stack
train
a55a2c91a484971610c805d4
train
function
@job_cli_group.command("logs", help="Get the logs of a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.argument("...
@job_cli_group.command("logs", help="Get the logs of a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.argument("...
"""Gets the logs of a job. Example: >>> ray job logs <my_job_id> """ client = _get_sdk_client(address) sdk_version = client.get_version() # sdk version 0 did not have log streaming if follow: if int(sdk_version) > 0: asyncio.get_event_loop().run_until_complete(_t...
@job_cli_group.command("logs", help="Get the logs of a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.argument("...
145
86
288
145
0
clarng/ray
dashboard/modules/job/cli.py
Python
job_logs
job_logs
270
310
270
291
a043c79157ebd3033ce686866bd09bb95cc9c3fb
bigcode/the-stack
train
9bb4837b2da31719583cba48
train
function
@click.group("job") def job_cli_group(): pass
@click.group("job") def job_cli_group():
pass
"Status message: {status.message}") async def _tail_logs(client: JobSubmissionClient, job_id: str): async for lines in client.tail_job_logs(job_id): print(lines, end="") _log_job_status(client, job_id) @click.group("job") def job_cli_group():
64
64
13
10
54
clarng/ray
dashboard/modules/job/cli.py
Python
job_cli_group
job_cli_group
71
73
71
72
62638ead18bddd797eb38423adf63c12af9d4978
bigcode/the-stack
train
b19322b0a046dd89c409da31
train
function
def _log_big_error_msg(success_msg): cli_logger.newline() cli_logger.error("-" * len(success_msg)) cli_logger.error(success_msg) cli_logger.error("-" * len(success_msg)) cli_logger.newline()
def _log_big_error_msg(success_msg):
cli_logger.newline() cli_logger.error("-" * len(success_msg)) cli_logger.error(success_msg) cli_logger.error("-" * len(success_msg)) cli_logger.newline()
create_cluster_if_needed) def _log_big_success_msg(success_msg): cli_logger.newline() cli_logger.success("-" * len(success_msg)) cli_logger.success(success_msg) cli_logger.success("-" * len(success_msg)) cli_logger.newline() def _log_big_error_msg(success_msg):
64
64
50
9
55
clarng/ray
dashboard/modules/job/cli.py
Python
_log_big_error_msg
_log_big_error_msg
39
44
39
39
50c78130863e5360d979492a673071dbc9cbcef2
bigcode/the-stack
train
31dc0f801d662b17d570e8d1
train
function
@job_cli_group.command("submit", help="Submit a job to be executed on the cluster.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @c...
@job_cli_group.command("submit", help="Submit a job to be executed on the cluster.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @c...
"""Submits a job to be run on the cluster. Example: >>> ray job submit -- python my_script.py --arg=val """ client = _get_sdk_client(address, create_cluster_if_needed=True) final_runtime_env = {} if runtime_env is not None: if runtime_env_json is not None: raise Val...
@job_cli_group.command("submit", help="Submit a job to be executed on the cluster.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @c...
384
256
867
384
0
clarng/ray
dashboard/modules/job/cli.py
Python
job_submit
job_submit
76
197
76
136
bd4697b443e2037734236e1b2c2e44126ce4819b
bigcode/the-stack
train
87786f97e519eb62b75dad84
train
function
def _log_job_status(client: JobSubmissionClient, job_id: str): status = client.get_job_status(job_id) if status.status == JobStatus.SUCCEEDED: _log_big_success_msg(f"Job '{job_id}' succeeded") elif status.status == JobStatus.STOPPED: cli_logger.warning(f"Job '{job_id}' was stopped") elif...
def _log_job_status(client: JobSubmissionClient, job_id: str):
status = client.get_job_status(job_id) if status.status == JobStatus.SUCCEEDED: _log_big_success_msg(f"Job '{job_id}' succeeded") elif status.status == JobStatus.STOPPED: cli_logger.warning(f"Job '{job_id}' was stopped") elif status.status == JobStatus.FAILED: _log_big_error_msg(...
log_big_error_msg(success_msg): cli_logger.newline() cli_logger.error("-" * len(success_msg)) cli_logger.error(success_msg) cli_logger.error("-" * len(success_msg)) cli_logger.newline() def _log_job_status(client: JobSubmissionClient, job_id: str):
64
64
171
16
48
clarng/ray
dashboard/modules/job/cli.py
Python
_log_job_status
_log_job_status
47
61
47
47
c25d602c3802bb58ece3fede5d746be765fa28b1
bigcode/the-stack
train
c5d607b42e2ad39de874f1e1
train
function
async def _tail_logs(client: JobSubmissionClient, job_id: str): async for lines in client.tail_job_logs(job_id): print(lines, end="") _log_job_status(client, job_id)
async def _tail_logs(client: JobSubmissionClient, job_id: str):
async for lines in client.tail_job_logs(job_id): print(lines, end="") _log_job_status(client, job_id)
else: # Catch-all. cli_logger.print(f"Status for job '{job_id}': {status.status}") if status.message is not None: cli_logger.print(f"Status message: {status.message}") async def _tail_logs(client: JobSubmissionClient, job_id: str):
63
64
45
16
47
clarng/ray
dashboard/modules/job/cli.py
Python
_tail_logs
_tail_logs
64
68
64
64
c6a74c1713364af8e8ead7dd0132ac963ace39a2
bigcode/the-stack
train
2ffe8ff241435a3a4c7d79ac
train
function
@job_cli_group.command("stop", help="Attempt to stop a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.option( ...
@job_cli_group.command("stop", help="Attempt to stop a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.option( ...
"""Attempts to stop a job. Example: >>> ray job stop <my_job_id> """ client = _get_sdk_client(address) cli_logger.print(f"Attempting to stop job {job_id}") client.stop_job(job_id) if no_wait: return else: cli_logger.print( f"Waiting for job '{job_id}...
@job_cli_group.command("stop", help="Attempt to stop a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.option( ...
141
94
314
141
0
clarng/ray
dashboard/modules/job/cli.py
Python
job_stop
job_stop
223
267
223
243
e5e9092ecbd6e81f033952b05a36fd8e0f3e7ccc
bigcode/the-stack
train
44220473dc6aa9008594167d
train
function
def _get_sdk_client( address: Optional[str], create_cluster_if_needed: bool = False ) -> JobSubmissionClient: if address is None: if "RAY_ADDRESS" not in os.environ: raise ValueError( "Address must be specified using either the --address flag " "or RAY_ADDRES...
def _get_sdk_client( address: Optional[str], create_cluster_if_needed: bool = False ) -> JobSubmissionClient:
if address is None: if "RAY_ADDRESS" not in os.environ: raise ValueError( "Address must be specified using either the --address flag " "or RAY_ADDRESS environment variable." ) address = os.environ["RAY_ADDRESS"] cli_logger.labeled_value("J...
caler._private.cli_logger import add_click_logging_options, cli_logger, cf from ray.dashboard.modules.job.common import JobStatus from ray.dashboard.modules.job.sdk import JobSubmissionClient def _get_sdk_client( address: Optional[str], create_cluster_if_needed: bool = False ) -> JobSubmissionClient:
64
64
110
27
36
clarng/ray
dashboard/modules/job/cli.py
Python
_get_sdk_client
_get_sdk_client
15
28
15
18
249dc9aa8b99b4921a974931b7d0099268cb6fb8
bigcode/the-stack
train
4dc039c93eea705adba7993e
train
function
@job_cli_group.command("status", help="Get the status of a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.argume...
@job_cli_group.command("status", help="Get the status of a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.argume...
"""Queries for the current status of a job. Example: >>> ray job status <my_job_id> """ client = _get_sdk_client(address) _log_job_status(client, job_id)
@job_cli_group.command("status", help="Get the status of a running job.") @click.option( "--address", type=str, default=None, required=False, help=( "Address of the Ray cluster to connect to. Can also be specified " "using the RAY_ADDRESS environment variable." ), ) @click.argume...
98
64
143
98
0
clarng/ray
dashboard/modules/job/cli.py
Python
job_status
job_status
200
220
200
213
82eb1cc24ab81c2b1bb7e3b8b5fd5a762ff6dc62
bigcode/the-stack
train
208947f10a41e26039138bfe
train
class
class ZeroOut1Test(tf.test.TestCase): def test(self): result = zero_out_op_1.zero_out([5, 4, 3, 2, 1]) self.assertAllEqual(result, [5, 0, 0, 0, 0]) def test_namespace(self): result = zero_out_op_1.namespace_zero_out([5, 4, 3, 2, 1]) self.assertAllEqual(result, [5, 0, 0, 0, 0]) def test_namespac...
class ZeroOut1Test(tf.test.TestCase):
def test(self): result = zero_out_op_1.zero_out([5, 4, 3, 2, 1]) self.assertAllEqual(result, [5, 0, 0, 0, 0]) def test_namespace(self): result = zero_out_op_1.namespace_zero_out([5, 4, 3, 2, 1]) self.assertAllEqual(result, [5, 0, 0, 0, 0]) def test_namespace_call_op_on_op(self): x = zero_out...
License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test for ver...
92
92
307
10
81
EricRemmerswaal/tensorflow
tensorflow/examples/adding_an_op/zero_out_1_test.py
Python
ZeroOut1Test
ZeroOut1Test
24
47
24
25
b2b6a9acfb91b0d416d0ac081e5b286e0695e5b2
bigcode/the-stack
train
a3571d48f29e33793f2bcd48
train
function
def main(): args = parse_args() # world size in terms of number of processes dist_world_size = args.nproc_per_node * args.nnodes # set PyTorch distributed related environmental variables current_env = os.environ.copy() current_env["MASTER_ADDR"] = args.master_addr current_env["MASTER_PORT...
def main():
args = parse_args() # world size in terms of number of processes dist_world_size = args.nproc_per_node * args.nnodes # set PyTorch distributed related environmental variables current_env = os.environ.copy() current_env["MASTER_ADDR"] = args.master_addr current_env["MASTER_PORT"] = str(args...
") # positional parser.add_argument("training_script", type=str, help="The full path to the single GPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " ...
87
87
292
3
84
joshhochuli/OpenChem
launch.py
Python
main
main
177
221
177
178
5fb3cc976eebfdeffa128d6b5ab199599aa040f2
bigcode/the-stack
train
82513ae77f9f19b04ac644f5
train
function
def parse_args(): """ Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser(description="PyTorch distributed training launch " "helper utilty that will spawn up " "multiple d...
def parse_args():
""" Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser(description="PyTorch distributed training launch " "helper utilty that will spawn up " "multiple distributed process...
device_ids=[arg.local_rank], output_device=arg.local_rank) Please ensure that ``device_ids`` argument is set to be the only GPU device id that your code will be operating on. This is generally the local rank of the process. In other words, the ``device_ids`` needs...
120
120
403
4
115
joshhochuli/OpenChem
launch.py
Python
parse_args
parse_args
134
174
134
134
76008816f724fe69d21d2e8422ef22db8d9311ca
bigcode/the-stack
train
4bd2d1b628c4eead1ea54d09
train
function
def lists_equal(l1,l2): if not l1 and not l2: return True if len(l1) != len(l2): return False for i,li in enumerate(l1): if not (l2[i] == li): return False return True
def lists_equal(l1,l2):
if not l1 and not l2: return True if len(l1) != len(l2): return False for i,li in enumerate(l1): if not (l2[i] == li): return False return True
# compare two lists, to test equivalency def lists_equal(l1,l2):
18
64
65
8
9
crawles/tdd_python_examples
examples/compare_lists.py
Python
lists_equal
lists_equal
3
11
3
3
acd94854472b293176231dee533c2f907d0df027
bigcode/the-stack
train
33bdf3ecabef13be30d91571
train
class
class Job(object): """ A periodic job as used by :class:`Scheduler`. :param interval: A quantity of a certain time unit :param scheduler: The :class:`Scheduler <Scheduler>` instance that this job will register itself with once it has been fully configu...
class Job(object):
""" A periodic job as used by :class:`Scheduler`. :param interval: A quantity of a certain time unit :param scheduler: The :class:`Scheduler <Scheduler>` instance that this job will register itself with once it has been fully configured in :meth:`Job.do...
# module: schedule # file: job.py try: from collections.abc import Hashable except ImportError: from collections import Hashable import datetime import functools import logging import random import re logger = logging.getLogger('schedule') class ScheduleError(Exception): """Base schedule ...
112
256
3,093
4
107
magistrser/schedule
schedule/job.py
Python
Job
Job
31
424
31
31
c1ffcbc520a616973cadb0655d11b6bbde3ad1cd
bigcode/the-stack
train
27d1435e0b6465e531db29aa
train
class
class ScheduleValueError(ScheduleError): """Base schedule value error""" pass
class ScheduleValueError(ScheduleError):
"""Base schedule value error""" pass
collections.abc import Hashable except ImportError: from collections import Hashable import datetime import functools import logging import random import re logger = logging.getLogger('schedule') class ScheduleError(Exception): """Base schedule exception""" pass class ScheduleValueError(Sc...
64
64
18
8
55
magistrser/schedule
schedule/job.py
Python
ScheduleValueError
ScheduleValueError
21
23
21
21
f368bb6dcecd3c2a3b2e2a7e562bf7461dcffde8
bigcode/the-stack
train
e20ba88fc2c171ee770b9dd0
train
class
class ScheduleError(Exception): """Base schedule exception""" pass
class ScheduleError(Exception):
"""Base schedule exception""" pass
# module: schedule # file: job.py try: from collections.abc import Hashable except ImportError: from collections import Hashable import datetime import functools import logging import random import re logger = logging.getLogger('schedule') class ScheduleError(Exception):
61
64
14
5
56
magistrser/schedule
schedule/job.py
Python
ScheduleError
ScheduleError
16
18
16
16
6922887dfa166b06186a9bb006bb728e5aae2c68
bigcode/the-stack
train
35d08602b63a8313ce83e02f
train
class
class IntervalError(ScheduleValueError): """An improper interval was used""" pass
class IntervalError(ScheduleValueError):
"""An improper interval was used""" pass
import datetime import functools import logging import random import re logger = logging.getLogger('schedule') class ScheduleError(Exception): """Base schedule exception""" pass class ScheduleValueError(ScheduleError): """Base schedule value error""" pass class IntervalError(Schedul...
64
64
19
8
55
magistrser/schedule
schedule/job.py
Python
IntervalError
IntervalError
26
28
26
26
72ac419bf9e0434f918c8f50cc5216950acd52fc
bigcode/the-stack
train
e2d4f4fbd6ce8c025115267b
train
class
class GeneticAlgorithm(Algorithm): """References: [Book] An Introduction To Genetic Algorithms ( MIT )""" def __init__(self, **kwargs): super().__init__(**kwargs) selection_options = { # parent_selection options 'SEL1': self.tournament_selection, 'SEL2': self.roulette...
class GeneticAlgorithm(Algorithm):
"""References: [Book] An Introduction To Genetic Algorithms ( MIT )""" def __init__(self, **kwargs): super().__init__(**kwargs) selection_options = { # parent_selection options 'SEL1': self.tournament_selection, 'SEL2': self.roulette_wheel_selection, 'SEL3...
from NIM.algorithms.algorithm import Algorithm, Ackley import pandas as pd from numpy import argmin, asarray, apply_along_axis, where, full, inf, zeros, clip, fabs, sum, sort, fmin, fmax, empty_like, cumsum, argsort, arange, round, concatenate, append import logging logging.basicConfig() logger = logging.getLogger('GA...
98
256
1,883
6
92
buctlab/source-seeking-multi-robot-team-simulator
NIM/algorithms/genetic_algorithm.py
Python
GeneticAlgorithm
GeneticAlgorithm
11
207
11
11
edf83fbb0fa2d4112e82b0e9e8e2c8ee34581da4
bigcode/the-stack
train
44a74f043478f2f70c6890dd
train
class
class Collman: def __init__(self, path, req_channels=['collman15v2_Synapsin647', 'collman15v2_VGluT1_647', 'collman15v2_PSD95_488'], scale=0.1): channels = [] self.path = path self.scale = scale for channel in req_channels: print('Loading...
class Collman:
def __init__(self, path, req_channels=['collman15v2_Synapsin647', 'collman15v2_VGluT1_647', 'collman15v2_PSD95_488'], scale=0.1): channels = [] self.path = path self.scale = scale for channel in req_channels: print('Loading channel:', cha...
import numpy as np from skimage.measure import regionprops from skimage.transform import rescale class Collman:
25
87
293
4
20
Jos3f/Intensity-based-clustering-study
dognet/dognet/data/collman.py
Python
Collman
Collman
6
35
6
6
e531c74394a3727c0b193c67ed7ed33d1ed60d6e
bigcode/the-stack
train
523e1809e8077f49d2c0a259
train
class
class QasmArgs(string.Formatter): def __init__( self, precision: int = 10, version: str = '2.0', qubit_id_map: Dict['cirq.Qid', str] = None, meas_key_id_map: Dict[str, str] = None, ) -> None: """ Args: precision: The number of digits after the ...
class QasmArgs(string.Formatter):
def __init__( self, precision: int = 10, version: str = '2.0', qubit_id_map: Dict['cirq.Qid', str] = None, meas_key_id_map: Dict[str, str] = None, ) -> None: """ Args: precision: The number of digits after the decimal to show for ...
or implied. # See the License for the specific language governing permissions and # limitations under the License. import string from typing import TYPE_CHECKING, Union, Any, Tuple, TypeVar, Optional, Dict, Iterable from typing_extensions import Protocol from cirq import ops from cirq._doc import doc_private from c...
122
122
407
8
113
stubbi/Cirq
cirq-core/cirq/protocols/qasm.py
Python
QasmArgs
QasmArgs
32
72
32
32
ae978e788db166403ddaf2870488a4c832ca4042
bigcode/the-stack
train
5059e049d17cd17b0d588c87
train
class
class SupportsQasm(Protocol): """An object that can be turned into QASM code. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_(self) -> Union[No...
class SupportsQasm(Protocol):
"""An object that can be turned into QASM code. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_(self) -> Union[None, NotImplementedType, str]: ...
spec = '' return super().format_field(value, spec) def validate_version(self, *supported_versions: str) -> None: if self.version not in supported_versions: raise ValueError(f'QASM version {self.version} output is not supported.') class SupportsQasm(Protocol):
63
64
92
7
56
stubbi/Cirq
cirq-core/cirq/protocols/qasm.py
Python
SupportsQasm
SupportsQasm
75
85
75
75
dd43d3501ca2c8df3eef67b2093798a8182002d7
bigcode/the-stack
train
39d452b5a3ca9d5a93543ed0
train
class
class SupportsQasmWithArgs(Protocol): """An object that can be turned into QASM code. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_(self, arg...
class SupportsQasmWithArgs(Protocol):
"""An object that can be turned into QASM code. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_(self, args: QasmArgs) -> Union[None, NotImpleme...
into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_(self) -> Union[None, NotImplementedType, str]: pass class SupportsQasmWithArgs(Protocol):
64
64
100
9
54
stubbi/Cirq
cirq-core/cirq/protocols/qasm.py
Python
SupportsQasmWithArgs
SupportsQasmWithArgs
88
98
88
88
416914c111040512c7c67670fa82c89fe3b61d95
bigcode/the-stack
train
da29d9bc6badabd16874f7ef
train
class
class SupportsQasmWithArgsAndQubits(Protocol): """An object that can be turned into QASM code if it knows its qubits. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_...
class SupportsQasmWithArgsAndQubits(Protocol):
"""An object that can be turned into QASM code if it knows its qubits. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_( self, qubits: T...
backs based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_(self, args: QasmArgs) -> Union[None, NotImplementedType, str]: pass class SupportsQasmWithArgsAndQubits(Protocol):
64
64
124
13
50
stubbi/Cirq
cirq-core/cirq/protocols/qasm.py
Python
SupportsQasmWithArgsAndQubits
SupportsQasmWithArgsAndQubits
101
113
101
101
073ce43bc4ec7c24f921fe3edaf83b4c3a18fa3e
bigcode/the-stack
train
1b4f2fdccd03e34fa5dad53f
train
function
def qasm( val: Any, *, args: Optional[QasmArgs] = None, qubits: Optional[Iterable['cirq.Qid']] = None, default: TDefault = RaiseTypeErrorIfNotProvided, ) -> Union[str, TDefault]: """Returns QASM code for the given value, if possible. Different values require different sets of arguments. The...
def qasm( val: Any, *, args: Optional[QasmArgs] = None, qubits: Optional[Iterable['cirq.Qid']] = None, default: TDefault = RaiseTypeErrorIfNotProvided, ) -> Union[str, TDefault]:
"""Returns QASM code for the given value, if possible. Different values require different sets of arguments. The general rule of thumb is that circuits don't need any, operations need a `QasmArgs`, and gates need both a `QasmArgs` and `qubits`. Args: val: The value to turn into QASM code. ...
that can be turned into QASM code if it knows its qubits. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead. """ @doc_private def _qasm_( self, qubits: Tuple['cirq.Qid']...
175
175
584
60
114
stubbi/Cirq
cirq-core/cirq/protocols/qasm.py
Python
qasm
qasm
117
172
117
123
de82a96ade4ee4b1f4f82d329fb5cc0ceeab7c57
bigcode/the-stack
train
300b16129048f1c112525d2a
train
class
class Seq2SeqTest(test.TestCase): def testRNNDecoder(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 _, enc_state = rnn.static_rnn( ...
class Seq2SeqTest(test.TestCase):
def testRNNDecoder(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 _, enc_state = rnn.static_rnn( rnn_cell.GRUCell(2), inp, dtype=dt...
"AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for functional style sequence-to-seq...
256
256
10,292
9
246
jhabikal21/tensorflow
tensorflow/contrib/legacy_seq2seq/python/kernel_tests/seq2seq_test.py
Python
Seq2SeqTest
Seq2SeqTest
47
1,096
47
48
e7808d8acf93fa7d31f421dfa4f6fff702419bf2
bigcode/the-stack
train
4cf6aa56e1c4a4b68a83cb05
train
class
class Object3d(BEVBox3D): """The class stores details that are object-specific, such as bounding box coordinates, occulusion and so on. """ def __init__(self, center, size, label, calib=None): confidence = float(label[15]) if label.__len__() == 16 else -1.0 world_cam = calib['world_cam...
class Object3d(BEVBox3D):
"""The class stores details that are object-specific, such as bounding box coordinates, occulusion and so on. """ def __init__(self, center, size, label, calib=None): confidence = float(label[15]) if label.__len__() == 16 else -1.0 world_cam = calib['world_cam'] cam_img = calib...
_2', 'calib') pc = self.dataset.read_lidar(pc_path) calib = self.dataset.read_calib(calib_path) label = self.dataset.read_label(label_path, calib) reduced_pc = DataProcessing.remove_outside_points( pc, calib['world_cam'], calib['cam_img'], [375, 1242]) data = { ...
180
180
602
10
169
kylevedder/Open3D-ML
ml3d/datasets/kitti.py
Python
Object3d
Object3d
302
358
302
302
f51470e25f9774aee528bbb17ad731e4b62dffe3
bigcode/the-stack
train
f329a56e0f6e177486f9d3d7
train
class
class KITTI(BaseDataset): """This class is used to create a dataset based on the KITTI dataset, and used in object detection, visualizer, training, or testing. """ def __init__(self, dataset_path, name='KITTI', cache_dir='./logs/cache', ...
class KITTI(BaseDataset):
"""This class is used to create a dataset based on the KITTI dataset, and used in object detection, visualizer, training, or testing. """ def __init__(self, dataset_path, name='KITTI', cache_dir='./logs/cache', use_cache=False, ...
import numpy as np import os, argparse, pickle, sys from os.path import exists, join, isfile, dirname, abspath, split from pathlib import Path from glob import glob import logging import yaml from .base_dataset import BaseDataset, BaseDatasetSplit from ..utils import Config, make_dir, DATASET from .utils import DataPr...
129
256
1,719
6
123
kylevedder/Open3D-ML
ml3d/datasets/kitti.py
Python
KITTI
KITTI
20
254
20
20
666755c27b618c17d44b437a48a5af3fea4b0bcd
bigcode/the-stack
train
5329ad7e2740b0d177cb9440
train
class
class KITTISplit(): def __init__(self, dataset, split='train'): self.cfg = dataset.cfg path_list = dataset.get_split_list(split) log.info("Found {} pointclouds for {}".format(len(path_list), split)) self.path_list = path_list self.split = split self.dataset = datase...
class KITTISplit():
def __init__(self, dataset, split='train'): self.cfg = dataset.cfg path_list = dataset.get_split_list(split) log.info("Found {} pointclouds for {}".format(len(path_list), split)) self.path_list = path_list self.split = split self.dataset = dataset def __len__(se...
to the outputs passed in results. """ make_dir(self.cfg.test_result_folder) for attr, res in zip(attrs, results): name = attr['name'] path = join(self.cfg.test_result_folder, name + '.txt') f = open(path, 'w') for box in res: ...
92
92
309
6
86
kylevedder/Open3D-ML
ml3d/datasets/kitti.py
Python
KITTISplit
KITTISplit
257
299
257
258
141ec5f82f00abc0b300cbee9c55f645f623701f
bigcode/the-stack
train
a02d50895c18495af1d4fc81
train
function
def squared(a): a = int(a) return a * a
def squared(a):
a = int(a) return a * a
# Squared static method def squared(a):
10
64
15
4
5
krishnaeleti/StatCalcIS601
Calculator/Squared.py
Python
squared
squared
2
4
2
2
d654b9331eeb1232000bb467327675b1574b4ce1
bigcode/the-stack
train
057588f9d6ea280574137e4c
train
class
class AdjustSmoothL1Loss(nn.Module): def __init__(self, num_features, momentum=0.1, beta=1. /9): super(AdjustSmoothL1Loss, self).__init__() self.num_features = num_features self.momentum = momentum self.beta = beta self.register_buffer( 'running_mean', torch.empt...
class AdjustSmoothL1Loss(nn.Module):
def __init__(self, num_features, momentum=0.1, beta=1. /9): super(AdjustSmoothL1Loss, self).__init__() self.num_features = num_features self.momentum = momentum self.beta = beta self.register_buffer( 'running_mean', torch.empty(num_features).fill_(beta) ) ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch import nn import logging import torch.distributed as dist class AdjustSmoothL1Loss(nn.Module):
44
102
340
9
34
awesome-amy/retinamask_pytorch1.5
maskrcnn_benchmark/layers/adjust_smooth_l1_loss.py
Python
AdjustSmoothL1Loss
AdjustSmoothL1Loss
7
41
7
8
fe58ce05a1cd282aba72f6354662cc6eaa2ae5d5
bigcode/the-stack
train
e031eb511d0fb12627296b6a
train
class
class VolumeListAdminContextTestCase(test.TestCase): _authorized_roles = ['fake'] _unauthorized_roles = [] def _get_response(self, roles): ctx = context.RequestContext('admin', 'fake', False, roles=roles) req = webob.Request.blank('/v2/fake/volumes/det...
class VolumeListAdminContextTestCase(test.TestCase):
_authorized_roles = ['fake'] _unauthorized_roles = [] def _get_response(self, roles): ctx = context.RequestContext('admin', 'fake', False, roles=roles) req = webob.Request.blank('/v2/fake/volumes/detail' '?host=fake&all...
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import webob from cinder...
103
103
346
11
91
PythonGirlSam/rackspace_cinder_extensions
rackspace_cinder_extensions/tests/unit/test_volume_list_admin_context.py
Python
VolumeListAdminContextTestCase
VolumeListAdminContextTestCase
24
68
24
25
26842b27066be61ea19c07c100a59a3db821b84c
bigcode/the-stack
train
d5709dd839b65800ca9646e2
train
function
def get_data(): return [ { "module_name": "Email", "color": "grey", "icon": "octicon octicon-mail", "type": "page", "link": "email_inbox", "label": _("Email Inbox") }, { "module_name": "Desk", "label": _("Tools"), "color": "#FFF5A7", "reverse": 1, "icon": "octicon octicon-calenda...
def get_data():
return [ { "module_name": "Email", "color": "grey", "icon": "octicon octicon-mail", "type": "page", "link": "email_inbox", "label": _("Email Inbox") }, { "module_name": "Desk", "label": _("Tools"), "color": "#FFF5A7", "reverse": 1, "icon": "octicon octicon-calendar", "type": "...
from __future__ import unicode_literals from frappe import _ def get_data():
16
134
449
4
12
sibidharan/frappe
frappe/config/desktop.py
Python
get_data
get_data
4
63
4
4
45f2fd2e29af4586938247949dae374c3914732e
bigcode/the-stack
train
bf5b6902ba010d669a73bc85
train
function
def _should_perform_sliced_download(source_resource, destination_resource): """Returns True if conditions are right for a sliced download.""" if destination_resource.storage_url.is_pipe: # Can't write to different indices of pipe. return False if (not source_resource.crc32c_hash and properties.VALUE...
def _should_perform_sliced_download(source_resource, destination_resource):
"""Returns True if conditions are right for a sliced download.""" if destination_resource.storage_url.is_pipe: # Can't write to different indices of pipe. return False if (not source_resource.crc32c_hash and properties.VALUES.storage.check_hashes.Get() != properties.CheckHashes.NEVER.value): ...
_CHECK_WARNING) elif check_hashes == properties.CheckHashes.IF_FAST_ELSE_SKIP.value: log.warning(_NO_HASH_CHECK_WARNING) elif check_hashes == properties.CheckHashes.IF_FAST_ELSE_FAIL.value: raise errors.Error(_NO_HASH_CHECK_ERROR) def _should_perform_sliced_download(source_resource, destination_resource):
68
68
228
14
54
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/storage/tasks/cp/file_download_task.py
Python
_should_perform_sliced_download
_should_perform_sliced_download
96
117
96
96
590e21803dd3b48ff6533c78e1cfb3084d9bb1d5
bigcode/the-stack
train
40119cd23750bf3b8e7a12cd
train
function
def _log_or_raise_crc32c_issues(resource): """Informs user about non-standard hashing behavior. Args: resource (resource_reference.ObjectResource): For checking if object has known hash to validate against. Raises: errors.Error: gcloud storage set to fail if performance-optimized digesters c...
def _log_or_raise_crc32c_issues(resource):
"""Informs user about non-standard hashing behavior. Args: resource (resource_reference.ObjectResource): For checking if object has known hash to validate against. Raises: errors.Error: gcloud storage set to fail if performance-optimized digesters could not be created. """ if crc32c.IS_F...
_warning_base() _NO_HASH_CHECK_WARNING = _HASH_CHECK_WARNING_BASE.format( 'will not be validated') _SLOW_HASH_CHECK_WARNING = _HASH_CHECK_WARNING_BASE.format('may be slow') _NO_HASH_CHECK_ERROR = _HASH_CHECK_WARNING_BASE.format('was skipped') def _log_or_raise_crc32c_issues(resource):
66
66
222
12
54
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/storage/tasks/cp/file_download_task.py
Python
_log_or_raise_crc32c_issues
_log_or_raise_crc32c_issues
71
93
71
71
fdbd80c841595a3869e54d6f81a80d01599be1c2
bigcode/the-stack
train
9c7ad4d333a532ca118c2643
train
function
def _get_hash_check_warning_base(): # Create the text in a function so that we can test it easily. google_crc32c_install_steps = hash_util.get_google_crc32c_install_command() return textwrap.dedent( """\ This download {{}} since the google-crc32c binary is not installed, and Python hash computat...
def _get_hash_check_warning_base(): # Create the text in a function so that we can test it easily.
google_crc32c_install_steps = hash_util.get_google_crc32c_install_command() return textwrap.dedent( """\ This download {{}} since the google-crc32c binary is not installed, and Python hash computation will likely throttle performance. You can change this by installing the binary {crc32...
32c from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.core.util import scaled_integer TEMPORARY_FILE_SUFFIX = '_.gstmp' def _get_hash_check_warning_base(): # Create the text in a function so that we can test it easily.
64
64
146
24
40
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/storage/tasks/cp/file_download_task.py
Python
_get_hash_check_warning_base
_get_hash_check_warning_base
50
61
50
51
182a1362c2f1a8bb90e2e9da932adca97a3e230c
bigcode/the-stack
train
322e15185d2624ddcf9d123a
train
class
class FileDownloadTask(task.Task): """Represents a command operation triggering a file download.""" def __init__(self, source_resource, destination_resource, do_not_decompress=False, user_request_args=None): """Initializes task. Args: sourc...
class FileDownloadTask(task.Task):
"""Represents a command operation triggering a file download.""" def __init__(self, source_resource, destination_resource, do_not_decompress=False, user_request_args=None): """Initializes task. Args: source_resource (ObjectResource): Must c...
== properties.CheckHashes.IF_FAST_ELSE_FAIL.value: raise errors.Error(_NO_HASH_CHECK_ERROR) def _should_perform_sliced_download(source_resource, destination_resource): """Returns True if conditions are right for a sliced download.""" if destination_resource.storage_url.is_pipe: # Can't write to different...
256
256
1,264
7
249
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/storage/tasks/cp/file_download_task.py
Python
FileDownloadTask
FileDownloadTask
120
275
120
120
0bb7b94edd6d949c1385aa3dcc2a7ddd99508d41
bigcode/the-stack
train
8e7484dc800f742bdd8a155f
train
class
class DeploymentBindings(pinject.BindingSpec): def configure(self, bind): bind("datadog", to_class=DataDog) bind("prometheus", to_class=Prometheus) bind("kubernetes_secrets", to_class=KubernetesSecrets) bind("generic_init_secrets", to_class=GenericInitSecrets) bind("strongbox...
class DeploymentBindings(pinject.BindingSpec):
def configure(self, bind): bind("datadog", to_class=DataDog) bind("prometheus", to_class=Prometheus) bind("kubernetes_secrets", to_class=KubernetesSecrets) bind("generic_init_secrets", to_class=GenericInitSecrets) bind("strongbox_secrets", to_class=StrongboxSecrets) b...
__ import absolute_import import pinject as pinject from .datadog import DataDog from .deployer import DeploymentDeployer from .prometheus import Prometheus from .secrets import Secrets, KubernetesSecrets, GenericInitSecrets, StrongboxSecrets class DeploymentBindings(pinject.BindingSpec):
64
64
111
8
55
ariadnarouco/fiaas-deploy-daemon
fiaas_deploy_daemon/deployer/kubernetes/deployment/__init__.py
Python
DeploymentBindings
DeploymentBindings
27
35
27
27
a70b8094e03061849f25ecb54ed30681509b1007
bigcode/the-stack
train
25af6af83425f752eebeac6a
train
function
def se_diagonal_slices(grid, n): col_length = len(grid) row_length = len(grid[0]) # bottom half for i in range(1, col_length): diagonal = [grid[i + j][j] for j in range(0, col_length - i )] if len(diagonal) >= n: yield from slice_up(diagonal, n) # top half for i in ...
def se_diagonal_slices(grid, n):
col_length = len(grid) row_length = len(grid[0]) # bottom half for i in range(1, col_length): diagonal = [grid[i + j][j] for j in range(0, col_length - i )] if len(diagonal) >= n: yield from slice_up(diagonal, n) # top half for i in range(0, row_length): dia...
], grid)) for i in range(0, len(grid[0]))] for column in columns: yield from slice_up(column, n) def vertical_slices(grid, n): for row in grid: yield from slice_up(row, n) def se_diagonal_slices(grid, n):
64
64
143
10
54
chjdev/euler
python/problem11.py
Python
se_diagonal_slices
se_diagonal_slices
78
92
78
78
4305866eeb4afcdd701f99b593fd2891a3567c2e
bigcode/the-stack
train
3b8faa8ff408e9e663bafcb7
train
function
def sanitize(slices): return filter(lambda s: not 0 in s, slices)
def sanitize(slices):
return filter(lambda s: not 0 in s, slices)
col_length): diagonal = [grid[j][col_length - j + i - 1] for j in range(i, col_length)] if len(diagonal) >= n: yield from slice_up(diagonal, n) else: # done return def sanitize(slices):
64
64
19
5
58
chjdev/euler
python/problem11.py
Python
sanitize
sanitize
115
116
115
115
ad7b7046e77a74d0a552e2873aa321e11f9f80af
bigcode/the-stack
train
cb1e65b8d720de2b6541ee6b
train
function
def vertical_slices(grid, n): for row in grid: yield from slice_up(row, n)
def vertical_slices(grid, n):
for row in grid: yield from slice_up(row, n)
_slices(grid, n): # TODO check inputs, whatever columns = [list(map(lambda row: row[i], grid)) for i in range(0, len(grid[0]))] for column in columns: yield from slice_up(column, n) def vertical_slices(grid, n):
64
64
23
8
56
chjdev/euler
python/problem11.py
Python
vertical_slices
vertical_slices
73
75
73
73
6d17e784dd04bba2d895fda511e5ef83ea393fcf
bigcode/the-stack
train
f30b12b4fd1a0f18aaa9b8df
train
function
def prod(lst): return functools.reduce(lambda a, b: a*b, lst)
def prod(lst):
return functools.reduce(lambda a, b: a*b, lst)
1] for j in range(i, col_length)] if len(diagonal) >= n: yield from slice_up(diagonal, n) else: # done return def sanitize(slices): return filter(lambda s: not 0 in s, slices) def prod(lst):
64
64
18
4
60
chjdev/euler
python/problem11.py
Python
prod
prod
119
120
119
119
b467be4513d8955c20d1cfa2a44c8cd798cab97b
bigcode/the-stack
train
b36e0dd967f0a80a1023a772
train
function
def ne_diagonal_slices(grid, n): col_length = len(grid) row_length = len(grid[0]) # top left half for i in range(0, row_length): diagonal = [grid[r][i - r] for r in range(0, i+1)] if len(diagonal) >= n: yield from slice_up(diagonal, n) # bottom right half for i in r...
def ne_diagonal_slices(grid, n):
col_length = len(grid) row_length = len(grid[0]) # top left half for i in range(0, row_length): diagonal = [grid[r][i - r] for r in range(0, i+1)] if len(diagonal) >= n: yield from slice_up(diagonal, n) # bottom right half for i in range(1, col_length): diag...
for i in range(0, row_length): diagonal = [grid[r][r + i] for r in range(0, row_length - i)] if len(diagonal) >= n: yield from slice_up(diagonal, n) def ne_diagonal_slices(grid, n):
64
64
157
10
54
chjdev/euler
python/problem11.py
Python
ne_diagonal_slices
ne_diagonal_slices
95
112
95
95
89229e599631d341afe883b070eccdde6d27489f
bigcode/the-stack
train
ba5f9351d1dce196e45f2efe
train
function
def horizontal_slices(grid, n): # TODO check inputs, whatever columns = [list(map(lambda row: row[i], grid)) for i in range(0, len(grid[0]))] for column in columns: yield from slice_up(column, n)
def horizontal_slices(grid, n): # TODO check inputs, whatever
columns = [list(map(lambda row: row[i], grid)) for i in range(0, len(grid[0]))] for column in columns: yield from slice_up(column, n)
')] def slice_up(lst, n): if len(lst) == n: yield lst return for i in range(0, len(lst) - n + 1): yield lst[i:i+n] def horizontal_slices(grid, n): # TODO check inputs, whatever
64
64
58
16
48
chjdev/euler
python/problem11.py
Python
horizontal_slices
horizontal_slices
67
70
67
67
4f36bb79c19ac31b84fc81dd4e11540a1f1d3dc5
bigcode/the-stack
train
91fc251dddb41cfc1d0d8375
train
function
def slice_up(lst, n): if len(lst) == n: yield lst return for i in range(0, len(lst) - n + 1): yield lst[i:i+n]
def slice_up(lst, n):
if len(lst) == n: yield lst return for i in range(0, len(lst) - n + 1): yield lst[i:i+n]
23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """.strip().split('\n')] def slice_up(lst, n):
63
64
46
7
56
chjdev/euler
python/problem11.py
Python
slice_up
slice_up
58
64
58
58
325a70b5d7ad0beab88969b7a9ffae4c0a2bde5c
bigcode/the-stack
train
60f46191566143b125487e54
train
function
@register.filter def as_dict(obj): return dict(obj)
@register.filter def as_dict(obj):
return dict(obj)
from django import template register = template.Library() @register.filter def as_dict(obj):
19
64
14
9
10
beshrkayali/django-formapi
formapi/templatetags/formapi_utils.py
Python
as_dict
as_dict
6
8
6
7
c36c2e41a9fe88faba7414c2f4ebebf17707b67b
bigcode/the-stack
train
c473f355461fe2f49448c635
train
function
def call_paginated_endpoint(endpoint: Callable, field: str, **kwargs) -> List: collection = [] response = endpoint(limit=500, **kwargs) collection.extend(response[field]) next_cursor = response['response_metadata'].get('next_cursor') while next_cursor: response = endpoint(limit=500, cursor=n...
def call_paginated_endpoint(endpoint: Callable, field: str, **kwargs) -> List:
collection = [] response = endpoint(limit=500, **kwargs) collection.extend(response[field]) next_cursor = response['response_metadata'].get('next_cursor') while next_cursor: response = endpoint(limit=500, cursor=next_cursor, **kwargs) collection.extend(response[field]) next_c...
Client from slack.rtm.client import RTMClient from machine.models import User from machine.models import Channel from machine.settings import import_settings from machine.utils import Singleton logger = logging.getLogger(__name__) def call_paginated_endpoint(endpoint: Callable, field: str, **kwargs) -> List:
64
64
99
19
45
repudi8or/slack-machine
machine/clients/singletons/slack.py
Python
call_paginated_endpoint
call_paginated_endpoint
16
25
16
16
ebf3f38011c6cf2482786dd811268b7edfce0eed
bigcode/the-stack
train
32537ffed40babe15d72cd07
train
class
class LowLevelSlackClient(metaclass=Singleton): def __init__(self): _settings, _ = import_settings() slack_api_token = _settings.get('SLACK_API_TOKEN', None) http_proxy = _settings.get('HTTP_PROXY', None) self.rtm_client = RTMClient(token=slack_api_token, proxy=http_proxy) se...
class LowLevelSlackClient(metaclass=Singleton):
def __init__(self): _settings, _ = import_settings() slack_api_token = _settings.get('SLACK_API_TOKEN', None) http_proxy = _settings.get('HTTP_PROXY', None) self.rtm_client = RTMClient(token=slack_api_token, proxy=http_proxy) self.web_client = WebClient(token=slack_api_token,...
import logging from typing import Callable, Dict, List import asyncio from slack.web.client import WebClient from slack.rtm.client import RTMClient from machine.models import User from machine.models import Channel from machine.settings import import_settings from machine.utils import Singleton logger = logging.getL...
176
256
995
11
164
repudi8or/slack-machine
machine/clients/singletons/slack.py
Python
LowLevelSlackClient
LowLevelSlackClient
28
129
28
28
7ed5dd0b606ed068be366053a4d6806bf44cd1c9
bigcode/the-stack
train
9ebaa600cec61ae02b8b8646
train
class
class ProductsConfig(AppConfig): name = 'djgumroad.products'
class ProductsConfig(AppConfig):
name = 'djgumroad.products'
from django.apps import AppConfig class ProductsConfig(AppConfig):
13
64
15
6
6
Maharshi-Pathak/gumroad-clone
djgumroad/products/apps.py
Python
ProductsConfig
ProductsConfig
4
5
4
4
3eb461980a674fe86c498002f5a58cfb1a4f1aeb
bigcode/the-stack
train
22955bc99fe1528d85abf517
train
class
class SurfaceTypeTest(unittest.TestCase): def test_set_clip( self ): """ see if surface.set_clip(None) works correctly. """ s = pygame.Surface((800, 600)) r = pygame.Rect(10, 10, 10, 10) s.set_clip(r) r.move_ip(10, 0) s.set_clip(None) res = s.get_clip(...
class SurfaceTypeTest(unittest.TestCase):
def test_set_clip( self ): """ see if surface.set_clip(None) works correctly. """ s = pygame.Surface((800, 600)) r = pygame.Rect(10, 10, 10, 10) s.set_clip(r) r.move_ip(10, 0) s.set_clip(None) res = s.get_clip() # this was garbled before. ...
'pygame') if not is_pygame_pkg: sys.path.insert(0, parent_dir) else: is_pygame_pkg = __name__.startswith('pygame.tests.') if is_pygame_pkg: from pygame.tests import test_utils from pygame.tests.test_utils import test_not_implemented, unittest try: from pygame.tests.test_utils.arrin...
256
256
10,154
8
248
JasonQSong/Sinners
[Python][AVG]Sinners/Lib27/pygame/tests/surface_test.py
Python
SurfaceTypeTest
SurfaceTypeTest
45
1,102
45
45
9bb9229d4ee8eeeacc5b6c409685cb2818faa451
bigcode/the-stack
train
26b9bd19613130ad5ce2c4f5
train
function
def longify(i): """If i is an int, cast to a long while preserving the bits""" if i < 0: return 0xFFFFFFFF & i return long(i)
def longify(i):
"""If i is an int, cast to a long while preserving the bits""" if i < 0: return 0xFFFFFFFF & i return long(i)
_bytes, as_unicode from pygame._view import View def intify(i): """If i is a long, cast to an int while preserving the bits""" if 0x80000000 & i: return int((0xFFFFFFFF & i)) return i def longify(i):
64
64
43
5
58
JasonQSong/Sinners
[Python][AVG]Sinners/Lib27/pygame/tests/surface_test.py
Python
longify
longify
38
42
38
38
e73ae81abb7c9a55bafef10ed3d4a654df690500
bigcode/the-stack
train
f5849eb3eba879e96dd723c6
train
class
class SurfaceBlendTest (unittest.TestCase): _test_palette = [(0, 0, 0, 255), (10, 30, 60, 0), (25, 75, 100, 128), (200, 150, 100, 200), (0, 100, 200, 255)] surf_size = (10, 12) _test_points = [((0, 0), 1), ((4, 5), 1), ((9,...
class SurfaceBlendTest (unittest.TestCase):
_test_palette = [(0, 0, 0, 255), (10, 30, 60, 0), (25, 75, 100, 128), (200, 150, 100, 200), (0, 100, 200, 255)] surf_size = (10, 12) _test_points = [((0, 0), 1), ((4, 5), 1), ((9, 0), 2), ((5, 5), 2), ((0...
for shifts in [[0, 8, 16, 24], [8, 16, 24, 0], [24, 16, 8, 0], [16, 8, 0, 24]]: masks = [0xff << s for s in shifts] s = pygame.Surface((4, 2), pygame.SRCALPHA, 32, masks) self._check_interface_rgba(s, 3) def test_array_interface_rgb(self): for shi...
256
256
3,359
10
246
JasonQSong/Sinners
[Python][AVG]Sinners/Lib27/pygame/tests/surface_test.py
Python
SurfaceBlendTest
SurfaceBlendTest
1,269
1,576
1,269
1,270
3d7b70c30dc5b77b2b7517e0a7599a066f460679
bigcode/the-stack
train
29a423db377d54c1bba26aee
train
class
class SurfaceGetViewTest (unittest.TestCase): # These tests requires ctypes. They are disabled if ctypes # is not installed. # try: ArrayInterface except NameError: __tags__ = ('ignore', 'subprocess_ignore') lilendian = pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN def ...
class SurfaceGetViewTest (unittest.TestCase): # These tests requires ctypes. They are disabled if ctypes # is not installed. #
try: ArrayInterface except NameError: __tags__ = ('ignore', 'subprocess_ignore') lilendian = pygame.get_sdl_byteorder () == pygame.LIL_ENDIAN def _check_interface_2D(self, s): s_w, s_h = s.get_size() s_bytesize = s.get_bytesize(); s_pitch = s.get_pitch() ...
_size() for x in range(w): for y in range(h): self.failUnlessEqual(surf.get_at((x, y)), comp.get_at((x, y))) # Confirm keyword arguments and per-pixel alpha spot_color = (0, 255, 0, 128) surf = pygame.Surface((4, 4), pygame...
256
256
1,832
32
224
JasonQSong/Sinners
[Python][AVG]Sinners/Lib27/pygame/tests/surface_test.py
Python
SurfaceGetViewTest
SurfaceGetViewTest
1,104
1,267
1,104
1,108
8c14a6564e88fe308dd985a81c677d9739712f00
bigcode/the-stack
train
c8de2fc169a8a5c3055f10a0
train
class
class SurfaceSelfBlitTest(unittest.TestCase): """Blit to self tests. This test case is in response to MotherHamster Bugzilla Bug 19. """ _test_palette = [(0, 0, 0, 255), (255, 0, 0, 0), (0, 255, 0, 255)] surf_size = (9, 6) def _fill_surface(self, su...
class SurfaceSelfBlitTest(unittest.TestCase):
"""Blit to self tests. This test case is in response to MotherHamster Bugzilla Bug 19. """ _test_palette = [(0, 0, 0, 255), (255, 0, 0, 0), (0, 255, 0, 255)] surf_size = (9, 6) def _fill_surface(self, surf, palette=None): if palette is None:...
, b: max(a - b, 0)), ('BLEND_RGBA_MULT', (0, 7, 100, 255), lambda a, b: (a * b) // 256), ('BLEND_RGBA_MIN', (0, 255, 0, 255), min), ('BLEND_RGBA_MAX', (0, 255, 0, 255), max)] for dst in destinations: dst_palette = [dst.unmap_rgb(d...
256
256
1,951
10
246
JasonQSong/Sinners
[Python][AVG]Sinners/Lib27/pygame/tests/surface_test.py
Python
SurfaceSelfBlitTest
SurfaceSelfBlitTest
1,578
1,757
1,578
1,578
3f79f86a7fa511e2bcd3105a6ca5b97d4a53a814
bigcode/the-stack
train
008d34d327da8e0e8bc73774
train
function
def intify(i): """If i is a long, cast to an int while preserving the bits""" if 0x80000000 & i: return int((0xFFFFFFFF & i)) return i
def intify(i):
"""If i is a long, cast to an int while preserving the bits""" if 0x80000000 & i: return int((0xFFFFFFFF & i)) return i
from test.test_utils import test_not_implemented, unittest try: from test.test_utils.arrinter import * except ImportError: pass import pygame from pygame.locals import * from pygame.compat import xrange_, as_bytes, as_unicode from pygame._view import View def intify(i):
64
64
47
5
58
JasonQSong/Sinners
[Python][AVG]Sinners/Lib27/pygame/tests/surface_test.py
Python
intify
intify
32
36
32
32
c873f051df0e14dfba6791f0fff5ff0a310e2cdb
bigcode/the-stack
train
72ef50f5d2b1179c0433bdcf
train
class
class ServicesTestJSON(base.BaseIdentityV2AdminTest): def _del_service(self, service_id): # Deleting the service created in this method self.client.delete_service(service_id) # Checking whether service is deleted successfully self.assertRaises(lib_exc.NotFound, self.client.get_servi...
class ServicesTestJSON(base.BaseIdentityV2AdminTest):
def _del_service(self, service_id): # Deleting the service created in this method self.client.delete_service(service_id) # Checking whether service is deleted successfully self.assertRaises(lib_exc.NotFound, self.client.get_service, service_id) @test.id...
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
193
228
760
12
180
anshprat/tempest
tempest/api/identity/admin/v2/test_services.py
Python
ServicesTestJSON
ServicesTestJSON
24
100
24
25
74aaea8aeefbd0b643bda67473eefc4b1f31b7d2
bigcode/the-stack
train
258ece35f11d87dde127a75a
train
class
class PocketSphinxRecognizerTest(unittest.TestCase): def setUp(self): with patch('mycroft.configuration.Configuration.get') as \ mock_config_get: conf = base_config() conf['hotwords']['hey mycroft']['module'] = 'pocketsphinx' mock_config_get.return_value =...
class PocketSphinxRecognizerTest(unittest.TestCase):
def setUp(self): with patch('mycroft.configuration.Configuration.get') as \ mock_config_get: conf = base_config() conf['hotwords']['hey mycroft']['module'] = 'pocketsphinx' mock_config_get.return_value = conf rl = RecognizerLoop() s...
patch import os from speech_recognition import WavFile from mycroft.client.speech.listener import RecognizerLoop from mycroft.configuration import Configuration from test.util import base_config DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data") class PocketSphinxRecognizerTest(unittest.Tes...
69
69
231
10
59
NeonJarbas/NeonCore
test/unittests/client/test_local_recognizer.py
Python
PocketSphinxRecognizerTest
PocketSphinxRecognizerTest
28
49
28
28
43ea518c01864fefbcaa7f1444309429e81bbd03
bigcode/the-stack
train
2c7512461a547e1dc4101cd2
train
class
class LocalRecognizerInitTest(unittest.TestCase): @patch.object(Configuration, 'get') def testRecognizer(self, mock_config_get): test_config = base_config() mock_config_get.return_value = test_config # Test "Hey Mycroft" rl = RecognizerLoop() self.assertEqual(rl.wakeword...
class LocalRecognizerInitTest(unittest.TestCase): @patch.object(Configuration, 'get')
def testRecognizer(self, mock_config_get): test_config = base_config() mock_config_get.return_value = test_config # Test "Hey Mycroft" rl = RecognizerLoop() self.assertEqual(rl.wakeword_recognizer.key_phrase, "hey mycroft") # Test "Hey Victoria" test_config[...
testRecognitionInLongerUtterance(self): source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav")) with source as audio: assert self.recognizer.found_wake_word(audio.stream.read()) class LocalRecognizerInitTest(unittest.TestCase): @patch.object(Configuration, 'get')
69
69
230
18
51
NeonJarbas/NeonCore
test/unittests/client/test_local_recognizer.py
Python
LocalRecognizerInitTest
LocalRecognizerInitTest
52
73
52
53
c6cdf59d72584fdfb404a6203f9c9e56ef852d26
bigcode/the-stack
train
4f5c92947cfeacc08154da08
train
function
def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=0.0001, power=0.75, init_lr=0.001): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (1 + gamma * iter_num) ** (- power) i = 0 for param_group in optimizer.param_groups: param_g...
def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=0.0001, power=0.75, init_lr=0.001):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (1 + gamma * iter_num) ** (- power) i = 0 for param_group in optimizer.param_groups: param_group['lr'] = lr * param_lr[i] i += 1 return optimizer
import numpy as np def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=0.0001, power=0.75, init_lr=0.001):
38
64
108
33
4
YBZh/AuxSelfTrain
utils/lr_schedule.py
Python
inv_lr_scheduler
inv_lr_scheduler
4
12
4
5
39c3d31b70da95650c31a0ff2337dd2058013243
bigcode/the-stack
train
b742787eea2a3e2141e4146b
train
function
def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0): return np.float(2.0 * (high - low) / (1.0 + np.exp(- alpha * iter_num / max_iter)) - (high - low) + low)
def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0):
return np.float(2.0 * (high - low) / (1.0 + np.exp(- alpha * iter_num / max_iter)) - (high - low) + low)
for param_group in optimizer.param_groups: param_group['lr'] = lr * param_lr[i] i += 1 return optimizer def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0):
64
64
74
32
31
YBZh/AuxSelfTrain
utils/lr_schedule.py
Python
calc_coeff
calc_coeff
15
18
15
15
6eafe079eea06303a4bae1dee7066223e295ac4f
bigcode/the-stack
train
f4b222944e548d1118894e83
train
class
class WalletTest(SovranocoinTestFramework): def set_test_params(self): self.num_nodes = 4 self.setup_clean_chain = True def setup_network(self): self.add_nodes(4) self.start_node(0) self.start_node(1) self.start_node(2) connect_nodes(self.nodes[0], 1) ...
class WalletTest(SovranocoinTestFramework):
def set_test_params(self): self.num_nodes = 4 self.setup_clean_chain = True def setup_network(self): self.add_nodes(4) self.start_node(0) self.start_node(1) self.start_node(2) connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[1], 2) ...
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet.""" from test_framework.test_framework import SovranocoinTestFramework from test_framew...
118
256
2,039
11
107
SovranoCoin/sovranocoin
test/functional/wallet_basic.py
Python
WalletTest
WalletTest
17
193
17
17
9c53959bbdb63fc127cf65d5fc12e6ef57c39e6f
bigcode/the-stack
train
9ebc5208a956d5ed543efd13
train
function
def test_get_version() -> None: assert get_version()
def test_get_version() -> None:
assert get_version()
from dwalk.version import get_version def test_get_version() -> None:
16
64
13
8
7
cariad/dwalk
dwalk/test_version.py
Python
test_get_version
test_get_version
4
5
4
4
872b059e78bf1d26f68f9cd29871e3def0cdfdcb
bigcode/the-stack
train
3735aea66efcff1f0cdcaca5
train
class
@generic_utils.register_keras_serializable() @keras_export('keras.optimizers.experimental.Adadelta', v1=[]) class Adadelta(optimizer.Optimizer): r"""Optimizer that implements the Adadelta algorithm. Adadelta optimization is a stochastic gradient descent method that is based on adaptive learning rate per dimensio...
@generic_utils.register_keras_serializable() @keras_export('keras.optimizers.experimental.Adadelta', v1=[]) class Adadelta(optimizer.Optimizer):
r"""Optimizer that implements the Adadelta algorithm. Adadelta optimization is a stochastic gradient descent method that is based on adaptive learning rate per dimension to address two drawbacks: - The continual decay of learning rates throughout training. - The need for a manually selected global learning ...
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
222
256
1,284
34
187
ma7555/keras
keras/optimizer_experimental/adadelta.py
Python
Adadelta
Adadelta
24
155
24
26
b27bb69ae3fbbf6ba546bc60544db0b4d12e2473
bigcode/the-stack
train
d74989ed1acdb087c31b4284
train
class
@API.resource('/api/v1/users') class UsersAPI(Resource): """Gets list of users. Uses ndb Cursor for pagination. Obtaining users is executed in parallel with obtaining total count via *_async functions """ def get(self): parser = default_parser() args = parser.parse_args() compare...
@API.resource('/api/v1/users') class UsersAPI(Resource):
"""Gets list of users. Uses ndb Cursor for pagination. Obtaining users is executed in parallel with obtaining total count via *_async functions """ def get(self): parser = default_parser() args = parser.parse_args() compare ,date = to_compare_date(args.newer, args.older, args.ord...
ArgumentValidator, make_list_response,\ make_empty_ok_response, default_parser, to_compare_date from flask import request, g from pydash import _ from api.decorators import model_by_key, user_by_username, authorization_required, admin_required @API.resource('/api/v1/users') class UsersAPI(Resource):
65
65
217
14
50
TBxy/gae-angular-material-init
main/api/v1/user_api.py
Python
UsersAPI
UsersAPI
20
38
20
21
ceb2b33d3bccc5df4f4ff48b9eb95d3b4a3f4a28
bigcode/the-stack
train
b3b51b128cf53378f58de3e5
train
class
@API.resource('/api/v1/users/<string:username>') class UserByUsernameAPI(Resource): @user_by_username def get(self, username): """Loads user's properties. If logged user is admin it loads also non public properties""" if auth.is_admin(): properties = User.get_private_properties() ...
@API.resource('/api/v1/users/<string:username>') class UserByUsernameAPI(Resource): @user_by_username
def get(self, username): """Loads user's properties. If logged user is admin it loads also non public properties""" if auth.is_admin(): properties = User.get_private_properties() else: properties = User.get_public_properties() return g.user_db.to_dict(include=...
()) for u in users] total_count = total_count_future.get_result() if total_count_future else False return make_list_response(users, next_cursor, more, total_count) @API.resource('/api/v1/users/<string:username>') class UserByUsernameAPI(Resource): @user_by_username
64
64
87
26
38
TBxy/gae-angular-material-init
main/api/v1/user_api.py
Python
UserByUsernameAPI
UserByUsernameAPI
41
50
41
43
5de2992fe8faa62ab854505481809687fa76b9ac
bigcode/the-stack
train
d71b7a01aff7e14a0c8aa41a
train
class
@API.resource('/api/v1/users/<string:key>') class UserByKeyAPI(Resource): @authorization_required @model_by_key def put(self, key): """Updates user's properties""" update_properties = ['name', 'bio', 'email', 'location', 'avatar_url', 'facebook', 'github', 'gplus...
@API.resource('/api/v1/users/<string:key>') class UserByKeyAPI(Resource): @authorization_required @model_by_key
def put(self, key): """Updates user's properties""" update_properties = ['name', 'bio', 'email', 'location', 'avatar_url', 'facebook', 'github', 'gplus', 'linkedin', 'twitter', 'instagram'] if auth.is_admin(): update_properties += ['verified', 'active...
auth.is_admin(): properties = User.get_private_properties() else: properties = User.get_public_properties() return g.user_db.to_dict(include=properties) @API.resource('/api/v1/users/<string:key>') class UserByKeyAPI(Resource): @authorization_required @model_by_key
64
64
209
30
34
TBxy/gae-angular-material-init
main/api/v1/user_api.py
Python
UserByKeyAPI
UserByKeyAPI
53
79
53
56
723b14afe1bcb09b075412374c6b762114c89231
bigcode/the-stack
train
377d33641e1e2231d35825be
train
class
@API.resource('/api/v1/users/<string:key>/password') class UserPasswordAPI(Resource): @authorization_required @model_by_key def post(self, key): """Changes user's password""" parser = reqparse.RequestParser() parser.add_argument('currentPassword', type=UserValidator.create('password'...
@API.resource('/api/v1/users/<string:key>/password') class UserPasswordAPI(Resource): @authorization_required @model_by_key
def post(self, key): """Changes user's password""" parser = reqparse.RequestParser() parser.add_argument('currentPassword', type=UserValidator.create('password', required=False), dest='current_password') parser.add_argument('newPassword', type=UserValidator.create('password'), dest='...
_required @model_by_key def delete(self, key): """Deletes user""" g.model_key.delete() return make_empty_ok_response() @API.resource('/api/v1/users/<string:key>/password') class UserPasswordAPI(Resource): @authorization_required @model_by_key
64
64
191
31
33
TBxy/gae-angular-material-init
main/api/v1/user_api.py
Python
UserPasswordAPI
UserPasswordAPI
82
98
82
85
9ad53398c2d96e05d75ff835317ef257c18b56d0
bigcode/the-stack
train
fb4e12d6850b96d3f3a88568
train
class
class WrappedFunction(function.ConcreteFunction): """Wraps a tf V1 piece of code in a function.""" def __init__(self, fn_graph, variable_holder, attrs=None, signature=None): super(WrappedFunction, self).__init__( fn_graph, attrs=attrs, signature=signature) self._variable_holder = variable_holder ...
class WrappedFunction(function.ConcreteFunction):
"""Wraps a tf V1 piece of code in a function.""" def __init__(self, fn_graph, variable_holder, attrs=None, signature=None): super(WrappedFunction, self).__init__( fn_graph, attrs=attrs, signature=signature) self._variable_holder = variable_holder if ops.executing_eagerly_outside_functions(): ...
control_flow_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope from tensorflow.python.util import nest from tensorflow.python.util.tf_export import tf_export class VariableHolder(object): """Holds variables for a python function.""" def __init__(self, f...
256
256
1,196
8
247
takafreak/tensorflow
tensorflow/python/eager/wrap_function.py
Python
WrappedFunction
WrappedFunction
67
186
67
67
c854a0867b499aa3935ac97a2ba6746dc0ab39eb
bigcode/the-stack
train
11b87b6b84e32f6fa5c348ea
train
function
@tf_export(v1=["wrap_function"]) def wrap_function(fn, signature, name=None): """Wraps the TF 1.x function fn into a graph function. The python function `fn` will be called once with symbolic arguments specified in the `signature`, traced, and turned into a graph function. Any variables created by `fn` will be...
@tf_export(v1=["wrap_function"]) def wrap_function(fn, signature, name=None):
"""Wraps the TF 1.x function fn into a graph function. The python function `fn` will be called once with symbolic arguments specified in the `signature`, traced, and turned into a graph function. Any variables created by `fn` will be owned by the object returned by `wrap_function`. The resulting graph functi...
external_capture] = lift_map[internal_capture] pruned_graph.inputs.extend(lift_map[x] for x in flat_feeds) pruned_graph.inputs.extend(pruned_graph.captures.values()) pruned_graph.variables = self.graph.variables def _structured_output_mapping(fetched): lifted = lift_map[fetched] if isinsta...
195
195
650
19
175
takafreak/tensorflow
tensorflow/python/eager/wrap_function.py
Python
wrap_function
wrap_function
189
258
189
190
494af948e64a6fabac94a078a2ca00f38d382275
bigcode/the-stack
train
ad2ed2319a9edd50c64f8541
train
class
class VariableHolder(object): """Holds variables for a python function.""" def __init__(self, fn): self._fn = fn self._variables = [] def variable_creator_scope(self, next_creator, **kwargs): """Creates variables & adds them to collections to match legacy code.""" v = next_creator(**kwargs) ...
class VariableHolder(object):
"""Holds variables for a python function.""" def __init__(self, fn): self._fn = fn self._variables = [] def variable_creator_scope(self, next_creator, **kwargs): """Creates variables & adds them to collections to match legacy code.""" v = next_creator(**kwargs) self._variables.append(v) ...
from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope from tensorflow.python.util import nest from tensorflow.python.util.tf_expo...
64
64
199
5
58
takafreak/tensorflow
tensorflow/python/eager/wrap_function.py
Python
VariableHolder
VariableHolder
37
63
37
37
5679cd21188f7dca9c0636242d66da170e9eeafc
bigcode/the-stack
train
9dd6b2f707de10f19922fd36
train
class
class VerboseConsumerAgent(ConsumerAgent): async def handle_request(self, data, topic: WatchTrainingTopic): data = json.loads(data) if data['action'] == 'connected': training_id = topic.latest_training_id await self.websocket.send_text...
class VerboseConsumerAgent(ConsumerAgent):
async def handle_request(self, data, topic: WatchTrainingTopic): data = json.loads(data) if data['action'] == 'connected': training_id = topic.latest_training_id await self.websocket.send_text(topic.metric_image(training_id = training_id)) ...
from fastapi import WebSocket import json from app.topics.consumer_agent import ConsumerAgent from app.topics.watch_training.topic import WatchTrainingTopic class VerboseConsumerAgent(ConsumerAgent):
42
64
97
10
31
joatom/watchtrain
api/app/topics/watch_training/consumer_agent.py
Python
VerboseConsumerAgent
VerboseConsumerAgent
7
21
7
9
7798efcd2ed3f93b0a3a7df85d37c0285235c5c9
bigcode/the-stack
train
5823806906ce149765562d7e
train
class
class WatchConsumerAgent(ConsumerAgent): async def handle_request(self, data, topic: WatchTrainingTopic): data = json.loads(data) if data['action'] == 'connected': training_id = topic.latest_training_id await self.websocket.send_text(t...
class WatchConsumerAgent(ConsumerAgent):
async def handle_request(self, data, topic: WatchTrainingTopic): data = json.loads(data) if data['action'] == 'connected': training_id = topic.latest_training_id await self.websocket.send_text(topic.metric_image(training_id = training_id)) ...
training_id = topic.latest_training_id await self.websocket.send_text(topic.metric_image(training_id = training_id)) await self.websocket.send_text(topic.training_progress(training_id = training_id)) else: await self.websocket.send_text(json....
62
64
82
9
53
joatom/watchtrain
api/app/topics/watch_training/consumer_agent.py
Python
WatchConsumerAgent
WatchConsumerAgent
25
36
25
27
daf415f67a77c0b40b35a29e7f451ed1aa8dcc40
bigcode/the-stack
train
85150276f8ec0400ca652107
train
function
def parse_args(): argnumber = len(sys.argv) arg1 = sys.argv[1] arg2 = sys.argv[2] return {'url':arg1,'conferenceid':arg2}
def parse_args():
argnumber = len(sys.argv) arg1 = sys.argv[1] arg2 = sys.argv[2] return {'url':arg1,'conferenceid':arg2}
|_|____/____/ |_| |____/|_| \_\_____/_/ \_\_|\_\ usage: meetbreak.py <targeturl> <conferenceid> example: meetbreak.py https://meet.example.com 5001 """ print(b) def parse_args(): ...
64
64
40
4
60
ElevenPaths/m33tfinder
meetbreak.py
Python
parse_args
parse_args
42
47
42
43
b95d4b7a345a1ae585d0c0075e842d43b11d6875
bigcode/the-stack
train
36482a612582211588841020
train
function
async def do_req(urllogin, response, line, semaphore): async with semaphore: async with aiohttp.ClientSession() as session: try: async with session.post(urllogin, json={"name":"test","passcode":str(line),"guid":response['conferenceGuid'],"sourceGuid":response['sourceGuid'],"conferenceId":response['confer...
async def do_req(urllogin, response, line, semaphore):
async with semaphore: async with aiohttp.ClientSession() as session: try: async with session.post(urllogin, json={"name":"test","passcode":str(line),"guid":response['conferenceGuid'],"sourceGuid":response['sourceGuid'],"conferenceId":response['conferenceId'],"webkitRTC":"true","mozRTC":"false","flash":"fa...
number = len(sys.argv) arg1 = sys.argv[1] arg2 = sys.argv[2] return {'url':arg1,'conferenceid':arg2} #%%%%%%% Test Passcode %%%%%%%# async def do_req(urllogin, response, line, semaphore):
63
64
201
17
46
ElevenPaths/m33tfinder
meetbreak.py
Python
do_req
do_req
51
66
51
51
999c35907da0e2dfc7b38d336eca4193a3a463dd
bigcode/the-stack
train
84a8c80236d7f06d2c150c9b
train
function
def banner(): b = """ __ __ _______________ ____ ____ _____ _ _ __ | \/ |___ /___ /_ _| __ )| _ \| ____| / \ | |/ / | |\/| | |_ \ |_ \ | | | _ \| |_) | _| / _ \ | ' / | | | |___) |__) || | | |_) | _ <| |___ / ___ \| . \ |_| |_|____/____/ |_| |____/|_| \_\_____/_/ \_\_|\_\ ...
def banner():
b = """ __ __ _______________ ____ ____ _____ _ _ __ | \/ |___ /___ /_ _| __ )| _ \| ____| / \ | |/ / | |\/| | |_ \ |_ \ | | | _ \| |_) | _| / _ \ | ' / | | | |___) |__) || | | |_) | _ <| |___ / ___ \| . \ |_| |_|____/____/ |_| |____/|_| \_\_____/_/ \_\_|\_\ ...
import asyncio import concurrent.futures from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) #%%%%%%% Context Variables %%%%%%%# version = 1.0 #%%%%%%% Functions %%%%%%%# def banner():
64
64
174
3
61
ElevenPaths/m33tfinder
meetbreak.py
Python
banner
banner
26
40
26
26
5cdc0bbd17a9c57d8f6eef0d345422c8014ee3d3
bigcode/the-stack
train
dffd8efff0e9cfc20f45842f
train
function
def main(): banner() params = parse_args() #%%%%%%% Inicialize Parameters %%%%%%%# urllogin = params.get('url') + "/guestLoginRequest.sf" url = params.get('url') + "/guestConference.sf" confid = params.get('conferenceid') paramsjson = {'id':str(confid),'passcode':""} main.guessed = 0 #%%%%%%% Print Confere...
def main():
banner() params = parse_args() #%%%%%%% Inicialize Parameters %%%%%%%# urllogin = params.get('url') + "/guestLoginRequest.sf" url = params.get('url') + "/guestConference.sf" confid = params.get('conferenceid') paramsjson = {'id':str(confid),'passcode':""} main.guessed = 0 #%%%%%%% Print Conference Informati...
),"guid":response['conferenceGuid'],"sourceGuid":response['sourceGuid'],"conferenceId":response['conferenceId'],"webkitRTC":"true","mozRTC":"false","flash":"false","screenShare":"false","resolutionGuid":response['resolutionGuid']},verify_ssl=False) as query: data = await query.json() if (data['reason'] ...
146
146
489
3
142
ElevenPaths/m33tfinder
meetbreak.py
Python
main
main
68
127
68
69
eb49e87a2f2c8d127a33c7cd12ee319ee8c5db3d
bigcode/the-stack
train
e883d95bf4f36e2bc60667f3
train
class
@Seq2SeqEncoder.register("qanet_encoder", exist_ok=True) class QaNetEncoder(Seq2SeqEncoder): """ Stack multiple QANetEncoderBlock into one sequence encoder. # Parameters input_dim : `int`, required. The input dimension of the encoder. hidden_dim : `int`, required. The hidden dimens...
@Seq2SeqEncoder.register("qanet_encoder", exist_ok=True) class QaNetEncoder(Seq2SeqEncoder):
""" Stack multiple QANetEncoderBlock into one sequence encoder. # Parameters input_dim : `int`, required. The input dimension of the encoder. hidden_dim : `int`, required. The hidden dimension used for convolution output channels, multi-head attention output and the final o...
from overrides import overrides import torch from torch.nn import Dropout from torch.nn import LayerNorm from torch.nn import ModuleList from allennlp.modules.feedforward import FeedForward from allennlp.modules.residual_with_layer_dropout import ResidualWithLayerDropout from allennlp.modules.seq2seq_encoders.seq2seq_e...
165
256
861
25
139
jens321/allennlp-models
allennlp_models/rc/qanet/qanet_encoder.py
Python
QaNetEncoder
QaNetEncoder
17
119
17
18
6a81d98fab4c9adab63c395e5943008bfc36b347
bigcode/the-stack
train
34d45c9202496d998c326d50
train
class
@Seq2SeqEncoder.register("qanet_encoder_block", exist_ok=True) class QaNetEncoderBlock(Seq2SeqEncoder): """ Implements the encoder block described in [QANet: Combining Local Convolution with Global Self-attention for Reading Comprehension](https://openreview.net/forum?id=B14TlG-RW). One encoder block m...
@Seq2SeqEncoder.register("qanet_encoder_block", exist_ok=True) class QaNetEncoderBlock(Seq2SeqEncoder):
""" Implements the encoder block described in [QANet: Combining Local Convolution with Global Self-attention for Reading Comprehension](https://openreview.net/forum?id=B14TlG-RW). One encoder block mainly contains 4 parts: 1. Add position embedding. 2. Several depthwise seperable convo...
hidden_dim, attention_projection_dim, feedforward_hidden_dim, num_convs_per_block, conv_kernel_size, num_attention_heads, use_positional_encoding, dropout_prob, layer_dropout_undecayed_prob, ...
256
256
1,399
27
228
jens321/allennlp-models
allennlp_models/rc/qanet/qanet_encoder.py
Python
QaNetEncoderBlock
QaNetEncoderBlock
123
274
123
124
6e224acfbfd1c42646228ac196e1f9264cd22086
bigcode/the-stack
train
57fab66a9c1752f68af53ff3
train
class
class TestCompileMethod(unittest.TestCase): def setUp(self): self.board = Board(9,9,10) self.board.compile() def test_cells_to_have_a_number_of_bomb_neighbors_equals_to_their_own_value(self): for row in range(len(self.board.board)): for col in range(len(self.board.board[...
class TestCompileMethod(unittest.TestCase):
def setUp(self): self.board = Board(9,9,10) self.board.compile() def test_cells_to_have_a_number_of_bomb_neighbors_equals_to_their_own_value(self): for row in range(len(self.board.board)): for col in range(len(self.board.board[row])): cell = self.board.ge...
import unittest from pymine.board import Board class TestCompileMethod(unittest.TestCase):
18
64
158
8
9
ndrbrt/pymine-engine
pymine/tests/test_board_compile.py
Python
TestCompileMethod
TestCompileMethod
5
19
5
5
dd8969aa6434b3329f98b24791fc02c9fd3c35ab
bigcode/the-stack
train
2e43cdb190cb91688c8bde15
train
class
class Loggable(metaclass=abc.ABCMeta): def __init__(self, logger=None, **kwargs): if not logger: self.logger = logging.getLogger(__name__) else: self.logger = logger
class Loggable(metaclass=abc.ABCMeta):
def __init__(self, logger=None, **kwargs): if not logger: self.logger = logging.getLogger(__name__) else: self.logger = logger
import abc import logging class Loggable(metaclass=abc.ABCMeta):
18
64
49
12
5
debayan/starsem2018-entity-linking
entitylinking/base_objects.py
Python
Loggable
Loggable
5
11
5
6
5ae7a06e6bb4c4de16e0b56797cc48a76a5dde6d
bigcode/the-stack
train
211a0b862ac7b769ec5e8950
train
class
class BaseSession(ABC): """Base class of all sessions""" def __init__(self, configuration: SessionConfiguration, instance_meta: SessionMetaData): """ Constructor :param configuration: Data and utilities common to all session types :param instan...
class BaseSession(ABC):
"""Base class of all sessions""" def __init__(self, configuration: SessionConfiguration, instance_meta: SessionMetaData): """ Constructor :param configuration: Data and utilities common to all session types :param instance_meta: Session metadat...
create_identifier) from robot_server.service.session.command_execution import CommandQueue, \ CommandExecutor, create_command from robot_server.service.session.configuration import SessionConfiguration from robot_server.service.session.models import session as models from robot_server.service.session.models import...
144
144
482
6
138
ferlzc/opentrons
robot-server/robot_server/service/session/session_types/base_session.py
Python
BaseSession
BaseSession
27
108
27
27
b0395d1563c9b5e13fb1c8d93eb58827148990de
bigcode/the-stack
train
4982fa78104b1fbe112c4242
train
class
@dataclass(frozen=True) class SessionMetaData: name: Optional[str] = None description: Optional[str] = None create_params: Optional[models.SessionCreateParamType] = None identifier: IdentifierType = field( default_factory=create_identifier ) created_at: datetime = field(default_factory=u...
@dataclass(frozen=True) class SessionMetaData:
name: Optional[str] = None description: Optional[str] = None create_params: Optional[models.SessionCreateParamType] = None identifier: IdentifierType = field( default_factory=create_identifier ) created_at: datetime = field(default_factory=utc_now)
Queue, \ CommandExecutor, create_command from robot_server.service.session.configuration import SessionConfiguration from robot_server.service.session.models import session as models from robot_server.service.session.models import command as command_models from opentrons.util.helpers import utc_now @dataclass(froze...
64
64
73
11
52
ferlzc/opentrons
robot-server/robot_server/service/session/session_types/base_session.py
Python
SessionMetaData
SessionMetaData
16
24
16
17
25c8d87bcb2f31a19d34f6e1338665c1f7291e58
bigcode/the-stack
train
c5b920abcc3f5de15385076b
train
function
def numpy_to_pb(name, np_data, out_filename): tensor = numpy_helper.from_array(np_data, name) onnx.save_tensor(tensor, out_filename)
def numpy_to_pb(name, np_data, out_filename):
tensor = numpy_helper.from_array(np_data, name) onnx.save_tensor(tensor, out_filename)
[:] = [672, 672] np_array = numpy_helper.to_array(tensor) print("Name:", tensor.name) print("Data Type:", tensor.data_type) print("Shape:", np_array.shape) #print(np_array) def numpy_to_pb(name, np_data, out_filename):
64
64
35
12
52
ChenHuaYou/cONNXr
scripts/print_pb.py
Python
numpy_to_pb
numpy_to_pb
28
30
28
28
5997babc34fab10e7ac4c0a733e3a7e9731357db
bigcode/the-stack
train
f8369d91d67448f47e657fd7
train
function
def print_pb_file(filename): tensor = onnx.load_tensor(filename) print(tensor.name) print(tensor.dims) print(len(tensor.raw_data)) print(dir(tensor)) #tensor.dims[:] = [672, 672] np_array = numpy_helper.to_array(tensor) print("Name:", tensor.name) print("Data Type:", tensor.data_ty...
def print_pb_file(filename):
tensor = onnx.load_tensor(filename) print(tensor.name) print(tensor.dims) print(len(tensor.raw_data)) print(dir(tensor)) #tensor.dims[:] = [672, 672] np_array = numpy_helper.to_array(tensor) print("Name:", tensor.name) print("Data Type:", tensor.data_type) print("Shape:", np_ar...
import onnx import sys import numpy from onnx import numpy_helper """ file: print_pb.py description: Just some utilities to print .pb files see: """ def print_pb_file(filename):
48
64
94
6
42
ChenHuaYou/cONNXr
scripts/print_pb.py
Python
print_pb_file
print_pb_file
14
24
14
14
dc826383d2f50d80dda6ce5b9c973a7d01fbee83
bigcode/the-stack
train
7a67469600767b20d6aff359
train
class
class HttpService: name = "http_service" @http("GET", "/") def index(self, request): return "" @http("GET", "/user/<int:id>") def get_user(self, request, id): return str(id) @http("POST", "/user") def do_post(self, request): return ""
class HttpService:
name = "http_service" @http("GET", "/") def index(self, request): return "" @http("GET", "/user/<int:id>") def get_user(self, request, id): return str(id) @http("POST", "/user") def do_post(self, request): return ""
from nameko.web.handlers import http class HttpService:
12
64
76
4
7
paulcsmith/web-frameworks
python/nameko/server.py
Python
HttpService
HttpService
4
17
4
4
8bda9476be520b079e4dee2872051046369be8b7
bigcode/the-stack
train
70bd203b06b188288b204dc5
train
class
class MADDPGAgent(object): """Uses multiple DDPG agents which solves the environment by playing against each other""" def __init__(self, state_size, action_size, num_agents, seed): """Initialize an MADDPGAgent object. Params : state_size (int) --- dimension of each state action_size (int) --- dimensio...
class MADDPGAgent(object):
"""Uses multiple DDPG agents which solves the environment by playing against each other""" def __init__(self, state_size, action_size, num_agents, seed): """Initialize an MADDPGAgent object. Params : state_size (int) --- dimension of each state action_size (int) --- dimension of each action num_age...
_model.parameters()): target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data) class OUNoise(object): """Ornstein-Uhlenbeck process.""" def __init__(self, size, seed, mu = 0., theta = 0.15, sigma = 0.2): """Initialize parameters and noise process.""" self.mu = mu * np.ones...
220
221
739
7
212
ht0rohit/Deep-Reinforcement-Learning
2CollaborativeTableTennisProject/agent.py
Python
MADDPGAgent
MADDPGAgent
225
302
225
225
7b77d932eaa641afaa223e8f362af3d0c005a33c
bigcode/the-stack
train
126e3d29bafe4944bf7fe9f9
train
class
class ReplayBuffer(object): """Fixed-size buffer to store experience tuples.""" def __init__(self, buffer_size, batch_size, num_agents, seed): """Initialize a ReplayBuffer object. Params: action_size (int) --- dimension of each action buffer_size (int) --- maximum size of buffer batch_size (int) ---...
class ReplayBuffer(object):
"""Fixed-size buffer to store experience tuples.""" def __init__(self, buffer_size, batch_size, num_agents, seed): """Initialize a ReplayBuffer object. Params: action_size (int) --- dimension of each action buffer_size (int) --- maximum size of buffer batch_size (int) --- size of each training batc...
from model import Actor, Critic BUFFER_SIZE = int(1e5) # replay buffer size BATCH_SIZE = 128 # minibatch size GAMMA = 0.99 # discount factor TAU = 1e-3 # for soft update of target parameters LR_ACTOR = 1e-4 # learning rate of the actor LR_CRITIC = 1e-3 # learning rate of the critic WEIGHT_DECAY = 0 # L2 we...
144
146
487
5
139
ht0rohit/Deep-Reinforcement-Learning
2CollaborativeTableTennisProject/agent.py
Python
ReplayBuffer
ReplayBuffer
24
66
24
24
b6dc87d94997a935f8eeb14e67d780242a871965
bigcode/the-stack
train
fe7e558bc6967ce12fc289da
train
class
class OUNoise(object): """Ornstein-Uhlenbeck process.""" def __init__(self, size, seed, mu = 0., theta = 0.15, sigma = 0.2): """Initialize parameters and noise process.""" self.mu = mu * np.ones(size) self.theta = theta self.sigma = sigma random.seed(seed) self.size = size self.reset() def ...
class OUNoise(object):
"""Ornstein-Uhlenbeck process.""" def __init__(self, size, seed, mu = 0., theta = 0.15, sigma = 0.2): """Initialize parameters and noise process.""" self.mu = mu * np.ones(size) self.theta = theta self.sigma = sigma random.seed(seed) self.size = size self.reset() def reset(self): """Reset...
) tau (float) --- interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data) class OUNoise(object):
62
64
184
6
56
ht0rohit/Deep-Reinforcement-Learning
2CollaborativeTableTennisProject/agent.py
Python
OUNoise
OUNoise
197
221
197
197
189df73da899107622cbd30f05ce0ac49b91c329
bigcode/the-stack
train
5f7e1d99cfbc514e3f9184fb
train
class
class Agent(object): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed): """Initialize an Agent object. Params : state_size (int) --- dimension of each state action_size (int) --- dimension of each action seed (int) --- random seed """ ...
class Agent(object):
"""Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed): """Initialize an Agent object. Params : state_size (int) --- dimension of each state action_size (int) --- dimension of each action seed (int) --- random seed """ self.state_size = sta...
list containing values from each agent states = [torch.from_numpy(np.vstack([e.states[index] for e in experiences if e is not None])).float().to(device) for index in range(self.num_agents)] actions = [torch.from_numpy(np.vstack([e.actions[index] for e in experiences if e is not None])).float().to(device) for index...
256
256
1,140
4
252
ht0rohit/Deep-Reinforcement-Learning
2CollaborativeTableTennisProject/agent.py
Python
Agent
Agent
73
193
73
73
d89034e9ab2ffcedcdc2a3ed8f24a81007536fd5
bigcode/the-stack
train
7d787c69a076a670c187104d
train
class
class CsvFaceModel(BaseModel): name: str src_url: str = '' comment: str = '' encoding: np.ndarray class Config: arbitrary_types_allowed = True
class CsvFaceModel(BaseModel):
name: str src_url: str = '' comment: str = '' encoding: np.ndarray class Config: arbitrary_types_allowed = True
import os import csv import base64 from typing import List, Tuple import json import requests import numpy as np from PIL import Image from pydantic import BaseModel class CsvFaceModel(BaseModel):
48
64
42
7
40
KuroiCc/myjlab2021-2nd-final-work
star_face_similarity/utils.py
Python
CsvFaceModel
CsvFaceModel
13
20
13
13
70fad24826c181f7f3b907e32616ff9e34561ef0
bigcode/the-stack
train
f7f425e0c653f89d9777181c
train
function
def find_all_file(path: str): file_list = [] files = os.listdir(path) for file in files: file_path = os.path.join(path, file) if os.path.isdir(file_path): inner_file_list = find_all_file(file_path) file_list = file_list + inner_file_list elif os.path.isfile(f...
def find_all_file(path: str):
file_list = [] files = os.listdir(path) for file in files: file_path = os.path.join(path, file) if os.path.isdir(file_path): inner_file_list = find_all_file(file_path) file_list = file_list + inner_file_list elif os.path.isfile(file_path): file_li...
os.makedirs(os.path.abspath(path)) extension = image_url.rsplit('.')[-1] with open(f'{path}/{name}.{extension}', 'wb') as f: f.write(res.content) return os.path.abspath(f'{path}/{name}.{extension}') def find_all_file(path: str):
63
64
87
8
55
KuroiCc/myjlab2021-2nd-final-work
star_face_similarity/utils.py
Python
find_all_file
find_all_file
74
86
74
74
d09189a2af755cb106103bb77bb196cda57d52ff
bigcode/the-stack
train
3e8487e4467225be1960984c
train
function
def load_image_json(file_path: str) -> Tuple[list, list]: """ ! deprecated Load JSON saved by func `save_image_json` return Tuple[face_name_list, face_encoding_list] """ print('This function is deprecated. Use load_data_csv instead') with open(file_path, 'r') as f: face_name_list, fa...
def load_image_json(file_path: str) -> Tuple[list, list]:
""" ! deprecated Load JSON saved by func `save_image_json` return Tuple[face_name_list, face_encoding_list] """ print('This function is deprecated. Use load_data_csv instead') with open(file_path, 'r') as f: face_name_list, face_encoding_list = zip(*json.load(f)) return face_nam...
face_encoding must be the same length') face_encoding_list = map(lambda x: x.tolist(), face_encoding) with open(file_path, 'w') as f: json.dump(list(zip(face_names, face_encoding_list)), f) def load_image_json(file_path: str) -> Tuple[list, list]:
64
64
97
15
49
KuroiCc/myjlab2021-2nd-final-work
star_face_similarity/utils.py
Python
load_image_json
load_image_json
140
150
140
140
351d008d730b29b66bc0cf887e70deeee96ddd98
bigcode/the-stack
train
360ce923b013c7243044bade
train
function
def save_image_json(face_names: list, face_encoding: List[np.ndarray], file_path: str): """ ! deprecated Save to JSON as shape like List[Tuple[face_name, face_encoding]] """ print('This function is deprecated. Use save_data_csv instead') if len(face_names) == len(face_encoding): raise Va...
def save_image_json(face_names: list, face_encoding: List[np.ndarray], file_path: str):
""" ! deprecated Save to JSON as shape like List[Tuple[face_name, face_encoding]] """ print('This function is deprecated. Use save_data_csv instead') if len(face_names) == len(face_encoding): raise ValueError('face_names and face_encoding must be the same length') face_encoding_list ...
ATE_270) elif orientation == 8: # 90度回転 img_rotate = img.transpose(Image.ROTATE_90) else: pass return img_rotate def save_image_json(face_names: list, face_encoding: List[np.ndarray], file_path: str):
64
64
128
21
42
KuroiCc/myjlab2021-2nd-final-work
star_face_similarity/utils.py
Python
save_image_json
save_image_json
127
137
127
127
6e61758d6c526f7db0573c7d5674aeb46a1bca7f
bigcode/the-stack
train