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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7277371ec50409a9c705f393 | train | function | def test_update_local_deleted_file(runner, client, directory_tree):
"""Check updating local deleted files."""
assert 0 == runner.invoke(cli, ["dataset", "add", "-c", "my-data", str(directory_tree)]).exit_code
file1 = Path(DATA_DIR) / "my-data" / directory_tree.name / "file1"
file1.unlink()
client.r... | def test_update_local_deleted_file(runner, client, directory_tree):
| """Check updating local deleted files."""
assert 0 == runner.invoke(cli, ["dataset", "add", "-c", "my-data", str(directory_tree)]).exit_code
file1 = Path(DATA_DIR) / "my-data" / directory_tree.name / "file1"
file1.unlink()
client.repo.git.add("--all")
client.repo.index.commit("deleted file1")
... | ).entity.checksum
result = runner.invoke(cli, ["dataset", "update", "my-data"])
assert 0 == result.exit_code, format_result_exception(result)
dataset = load_dataset(client, "my-data")
assert new_checksum_file1 == dataset.find_file(file1).entity.checksum
assert new_checksum_file2 == dataset.find_fi... | 110 | 110 | 369 | 14 | 96 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_update_local_deleted_file | test_update_local_deleted_file | 2,035 | 2,067 | 2,035 | 2,035 | 549f31f12ff7d7bab066a6298abcb4b2618826c6 | bigcode/the-stack | train |
1f184656bb5e655af86d44e0 | train | function | def test_dataset_rm_failure(runner, client):
"""Test errors in removal of a dataset."""
assert 2 == runner.invoke(cli, ["dataset", "rm"]).exit_code
assert 1 == runner.invoke(cli, ["dataset", "rm", "does-not-exist"]).exit_code
| def test_dataset_rm_failure(runner, client):
| """Test errors in removal of a dataset."""
assert 2 == runner.invoke(cli, ["dataset", "rm"]).exit_code
assert 1 == runner.invoke(cli, ["dataset", "rm", "does-not-exist"]).exit_code
| _result_exception(result)
assert "OK" in result.output
assert not load_dataset(client, "my-dataset")
result = runner.invoke(cli, ["doctor"], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
def test_dataset_rm_failure(runner, client):
| 64 | 64 | 62 | 10 | 54 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_dataset_rm_failure | test_dataset_rm_failure | 974 | 977 | 974 | 974 | 335b97519533db6488268167226af116c2d36052 | bigcode/the-stack | train |
97993522a9c58499fc5ac270 | train | function | def test_immutability_for_tags(runner, client):
"""Test dataset is mutated after a change to dataset tags."""
assert 0 == runner.invoke(cli, ["dataset", "create", "my-data"]).exit_code
old_dataset = load_dataset(client, "my-data")
# Add a tag
assert 0 == runner.invoke(cli, ["dataset", "tag", "my-d... | def test_immutability_for_tags(runner, client):
| """Test dataset is mutated after a change to dataset tags."""
assert 0 == runner.invoke(cli, ["dataset", "create", "my-data"]).exit_code
old_dataset = load_dataset(client, "my-data")
# Add a tag
assert 0 == runner.invoke(cli, ["dataset", "tag", "my-data", "new-tag"]).exit_code
dataset = load_... | old_dataset = load_dataset(client, "my-data")
assert 0 == runner.invoke(cli, ["dataset", "update", "--external"]).exit_code
dataset = load_dataset(client, "my-data")
assert dataset.id == old_dataset.id
def test_immutability_for_tags(runner, client):
| 64 | 64 | 170 | 12 | 51 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_immutability_for_tags | test_immutability_for_tags | 1,698 | 1,715 | 1,698 | 1,698 | 5ce35dffe6e746f19867d9fc31cc893ec87cddc3 | bigcode/the-stack | train |
6ca3c7e48b37d9cb5d5df470 | train | function | def test_overwrite_external_file(runner, client, directory_tree, subdirectory):
"""Check overwriting external and normal files."""
# Add external file
result = runner.invoke(cli, ["dataset", "add", "--create", "--external", "my-data", str(directory_tree)])
assert 0 == result.exit_code, format_result_exc... | def test_overwrite_external_file(runner, client, directory_tree, subdirectory):
| """Check overwriting external and normal files."""
# Add external file
result = runner.invoke(cli, ["dataset", "add", "--create", "--external", "my-data", str(directory_tree)])
assert 0 == result.exit_code, format_result_exception(result)
# Cannot add the same file
result = runner.invoke(cli, [... | dataset = load_dataset(client, "my-data")
assert dataset.find_file(path.relative_to(client.path)) is not None
# Symbolic links should not be tracked
attr_path = client.path / ".gitattributes"
assert not attr_path.exists() or "file1" not in attr_path.read_text()
def test_overwrite_external_file(runn... | 84 | 84 | 281 | 17 | 67 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_overwrite_external_file | test_overwrite_external_file | 1,516 | 1,537 | 1,516 | 1,516 | 18d97bb0d82bf0eb8ae8afbd68dbc229a48c8c46 | bigcode/the-stack | train |
6acabcf5f51b4619de0e0af6 | train | function | def test_datasets_provenance_after_remove(runner, client, directory_tree):
"""Test datasets provenance is updated after removing a dataset."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-data", "-c", str(directory_tree)]).exit_code
dataset = load_dataset(client, "my-data")
assert 0 == runner... | def test_datasets_provenance_after_remove(runner, client, directory_tree):
| """Test datasets provenance is updated after removing a dataset."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-data", "-c", str(directory_tree)]).exit_code
dataset = load_dataset(client, "my-data")
assert 0 == runner.invoke(cli, ["dataset", "rm", "my-data"]).exit_code
datasets_provenan... | 3 == len(current_version.dataset_files)
assert 1 == len(current_version.files)
assert {path} == {f.entity.path for f in current_version.files}
assert current_version.identifier != current_version.initial_identifier
def test_datasets_provenance_after_remove(runner, client, directory_tree):
| 64 | 64 | 205 | 17 | 46 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_datasets_provenance_after_remove | test_datasets_provenance_after_remove | 1,866 | 1,885 | 1,866 | 1,866 | 5ea1a81d86fbfcb21c8e2a669c243a7fd46cf6da | bigcode/the-stack | train |
d1478e9b2a424f33d8fc7c12 | train | function | def test_add_and_create_dataset_with_lfs_warning(directory_tree, runner, project, client_with_lfs_warning):
"""Test add data with lfs warning."""
# Add succeeds with --create
result = runner.invoke(
cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)], catch_exceptions=False
... | def test_add_and_create_dataset_with_lfs_warning(directory_tree, runner, project, client_with_lfs_warning):
| """Test add data with lfs warning."""
# Add succeeds with --create
result = runner.invoke(
cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)], catch_exceptions=False
)
assert 0 == result.exit_code, format_result_exception(result)
assert "Adding these files to Git LF... | , add with --create fails
result = runner.invoke(cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)])
assert 1 == result.exit_code
def test_add_and_create_dataset_with_lfs_warning(directory_tree, runner, project, client_with_lfs_warning):
| 64 | 64 | 125 | 23 | 40 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_add_and_create_dataset_with_lfs_warning | test_add_and_create_dataset_with_lfs_warning | 387 | 397 | 387 | 387 | ff03c83308f4ea9416abe4518a291ddca5a32450 | bigcode/the-stack | train |
05dd4926c246dd8652a1ddda | train | function | @pytest.mark.parametrize(
"uri", ["10.5281/zenodo.3363060", "doi:10.5281/zenodo.3363060", "https://zenodo.org/record/3363060"]
)
def test_dataset_provider_resolution_zenodo(doi_responses, uri):
"""Check that zenodo uris resolve to ZenodoProvider."""
provider, _ = ProviderFactory.from_uri(uri)
assert typ... | @pytest.mark.parametrize(
"uri", ["10.5281/zenodo.3363060", "doi:10.5281/zenodo.3363060", "https://zenodo.org/record/3363060"]
)
def test_dataset_provider_resolution_zenodo(doi_responses, uri):
| """Check that zenodo uris resolve to ZenodoProvider."""
provider, _ = ProviderFactory.from_uri(uri)
assert type(provider) is ZenodoProvider
| @pytest.mark.parametrize(
"uri", ["10.5281/zenodo.3363060", "doi:10.5281/zenodo.3363060", "https://zenodo.org/record/3363060"]
)
def test_dataset_provider_resolution_zenodo(doi_responses, uri):
| 65 | 64 | 100 | 65 | 0 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_dataset_provider_resolution_zenodo | test_dataset_provider_resolution_zenodo | 1,057 | 1,063 | 1,057 | 1,060 | eea485f690529e45adf6e5a9da60c4917455ccec | bigcode/the-stack | train |
d9c7e35a61872bac8646dc19 | train | function | @pytest.mark.serial
def test_unauthorized_import(mock_kg, client, runner):
"""Test importing without a valid token."""
client.set_value("http", "renku.ch", "not-renku-token", global_only=True)
result = runner.invoke(
cli, ["dataset", "import", "https://renku.ch/projects/user/project-name/datasets/1... | @pytest.mark.serial
def test_unauthorized_import(mock_kg, client, runner):
| """Test importing without a valid token."""
client.set_value("http", "renku.ch", "not-renku-token", global_only=True)
result = runner.invoke(
cli, ["dataset", "import", "https://renku.ch/projects/user/project-name/datasets/123"], catch_exceptions=False
)
assert 1 == result.exit_code
as... | ", dir1]).exit_code
dataset = load_dataset(client, "my-data")
assert {"file1", "file2", "file3"} == {Path(f.entity.path).name for f in dataset.files}
@pytest.mark.serial
def test_unauthorized_import(mock_kg, client, runner):
| 64 | 64 | 122 | 18 | 46 | TaoSunVoyage/renku-python | tests/cli/test_datasets.py | Python | test_unauthorized_import | test_unauthorized_import | 1,975 | 1,986 | 1,975 | 1,976 | 6be892d33e5b6cde4fb36eddec6f625eb35383a2 | bigcode/the-stack | train |
f2c94d4c1fed576e8a304364 | train | function | def safe(callable, *args, **kwargs):
try:
callable(*args)
except:
if 'msg' in kwargs: print(kwargs['msg'], file=sys.stderr)
sys.exit(2)
| def safe(callable, *args, **kwargs):
| try:
callable(*args)
except:
if 'msg' in kwargs: print(kwargs['msg'], file=sys.stderr)
sys.exit(2)
| p {}'.format(bin))
mkdir_p(bin)
def run(*cmd):
print('++', *cmd)
if sys.platform.startswith('win'):
shell = True
else:
shell = False
subprocess.check_call(cmd, shell=shell)
def safe(callable, *args, **kwargs):
| 64 | 64 | 44 | 11 | 53 | mzdun/panelberry | build/build_any.py | Python | safe | safe | 33 | 38 | 33 | 33 | aaf09f07cb8f8a3a51e54a0a246ad6e4ab83c858 | bigcode/the-stack | train |
4c558dd74d12e4ac1658e1ec | train | function | def rm_r(path):
if not os.path.exists(path): return
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
| def rm_r(path):
| if not os.path.exists(path): return
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
| sys, os, shutil, errno, subprocess
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path): pass
else: raise
def rm_r(path):
| 64 | 64 | 34 | 5 | 58 | mzdun/panelberry | build/build_any.py | Python | rm_r | rm_r | 11 | 16 | 11 | 11 | f6833e2b32a02cba94d5a947788afd5b3c902fc0 | bigcode/the-stack | train |
f709d6b2e84037fe5012edda | train | function | def run(*cmd):
print('++', *cmd)
if sys.platform.startswith('win'):
shell = True
else:
shell = False
subprocess.check_call(cmd, shell=shell)
| def run(*cmd):
| print('++', *cmd)
if sys.platform.startswith('win'):
shell = True
else:
shell = False
subprocess.check_call(cmd, shell=shell)
| .exists(path): return
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
def clean_dir(bin):
print('++ rm -r {}'.format(bin))
rm_r(bin)
print('++ mkdir -p {}'.format(bin))
mkdir_p(bin)
def run(*cmd):
| 64 | 64 | 43 | 5 | 59 | mzdun/panelberry | build/build_any.py | Python | run | run | 24 | 31 | 24 | 24 | b5dee0981f7363236a456bfe8bdb9228f5b4d1f9 | bigcode/the-stack | train |
c7ff93d2024f24f16badd6f3 | train | class | class cmake:
def __init__(self, os_name):
self.srcdir = os.path.abspath(os.path.join(os.path.split(__file__)[0], os.pardir, 'source'))
self.bindir = os.path.join(os.getcwd(), 'bin', os_name)
self.pkgdir = os.path.join(os.getcwd(), 'pkgs', os_name)
def configure(self, *args, **kwargs):
if 'CEF_ROOT' not in os... | class cmake:
| def __init__(self, os_name):
self.srcdir = os.path.abspath(os.path.join(os.path.split(__file__)[0], os.pardir, 'source'))
self.bindir = os.path.join(os.getcwd(), 'bin', os_name)
self.pkgdir = os.path.join(os.getcwd(), 'pkgs', os_name)
def configure(self, *args, **kwargs):
if 'CEF_ROOT' not in os.environ:
... | -r {}'.format(bin))
rm_r(bin)
print('++ mkdir -p {}'.format(bin))
mkdir_p(bin)
def run(*cmd):
print('++', *cmd)
if sys.platform.startswith('win'):
shell = True
else:
shell = False
subprocess.check_call(cmd, shell=shell)
def safe(callable, *args, **kwargs):
try:
callable(*args)
except:
if 'msg' in k... | 116 | 116 | 389 | 4 | 112 | mzdun/panelberry | build/build_any.py | Python | cmake | cmake | 40 | 75 | 40 | 40 | 82ab6584fbb2e91f4372a27186a3b99568a63b48 | bigcode/the-stack | train |
94b9022a02278aa647d28ac7 | train | function | def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path): pass
else: raise
| def mkdir_p(path):
| try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path): pass
else: raise
| from __future__ import print_function
import sys, os, shutil, errno, subprocess
def mkdir_p(path):
| 24 | 64 | 49 | 5 | 18 | mzdun/panelberry | build/build_any.py | Python | mkdir_p | mkdir_p | 4 | 9 | 4 | 4 | a83005cb31c75845e1e4c2e5a6301576d28970cd | bigcode/the-stack | train |
04cc76abfaa0b26a0bcc9104 | train | function | def clean_dir(bin):
print('++ rm -r {}'.format(bin))
rm_r(bin)
print('++ mkdir -p {}'.format(bin))
mkdir_p(bin)
| def clean_dir(bin):
| print('++ rm -r {}'.format(bin))
rm_r(bin)
print('++ mkdir -p {}'.format(bin))
mkdir_p(bin)
| 5
if exc.errno == errno.EEXIST and os.path.isdir(path): pass
else: raise
def rm_r(path):
if not os.path.exists(path): return
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
def clean_dir(bin):
| 64 | 64 | 34 | 5 | 59 | mzdun/panelberry | build/build_any.py | Python | clean_dir | clean_dir | 18 | 22 | 18 | 18 | 4d4a5d8e9473e8cd5fd92f6d74c73e180faf58f2 | bigcode/the-stack | train |
793b0675bcae0b075b25a5f7 | train | function | def get_args_from_command_line():
"""Parse the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--country_code", type=str,
default="US")
parser.add_argument("--method", type=str, default='topk')
parser.add_argument("--threshold", type=float,
... | def get_args_from_command_line():
| """Parse the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--country_code", type=str,
default="US")
parser.add_argument("--method", type=str, default='topk')
parser.add_argument("--threshold", type=float,
default=0.... |
import re
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
def get_args_from_command_line():
| 64 | 64 | 92 | 7 | 57 | worldbank/SDG-big-data | twitter-analytics/code/3-model_evaluation/recall/estimate_recall.py | Python | get_args_from_command_line | get_args_from_command_line | 14 | 24 | 14 | 14 | 9357e9ebaa7d0e9dd5ba22b82de3c01a72c218fa | bigcode/the-stack | train |
c208eac0d4deca6221b07f52 | train | function | def dispatch(v: typing.Any) -> typing.Any:
function, *returns = _from_signature(
__name__,
dispatch_map,
(
_aztype(v),
_ltype(v),
_ttype(v),
),
)
with numpy.errstate(all="ignore"):
return v._wrap_result(
_flavor_of(v),
... | def dispatch(v: typing.Any) -> typing.Any:
| function, *returns = _from_signature(
__name__,
dispatch_map,
(
_aztype(v),
_ltype(v),
_ttype(v),
),
)
with numpy.errstate(all="ignore"):
return v._wrap_result(
_flavor_of(v),
function(
v.lib,... | (AzimuthalRhoPhi, LongitudinalEta, TemporalT): (rhophi_eta_t, float),
(AzimuthalRhoPhi, LongitudinalEta, TemporalTau): (rhophi_eta_tau, float),
}
def dispatch(v: typing.Any) -> typing.Any:
| 64 | 64 | 117 | 11 | 53 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | dispatch | dispatch | 113 | 134 | 113 | 113 | cbfa8db8f9cfd969b8cbb6ab3651b621e6fed087 | bigcode/the-stack | train |
28e219fc64afd529db910c75 | train | function | def rhophi_eta_tau(lib, rho, phi, eta, tau):
return lib.maximum(
tau2.rhophi_eta_tau(lib, rho, phi, eta, tau)
+ mag2.rhophi_eta(lib, rho, phi, eta),
0,
)
| def rhophi_eta_tau(lib, rho, phi, eta, tau):
| return lib.maximum(
tau2.rhophi_eta_tau(lib, rho, phi, eta, tau)
+ mag2.rhophi_eta(lib, rho, phi, eta),
0,
)
| , theta, tau)
+ mag2.rhophi_theta(lib, rho, phi, theta),
0,
)
def rhophi_eta_t(lib, rho, phi, eta, t):
return t ** 2
def rhophi_eta_tau(lib, rho, phi, eta, tau):
| 64 | 64 | 60 | 15 | 48 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | rhophi_eta_tau | rhophi_eta_tau | 89 | 94 | 89 | 89 | 9af2fb9cb808402aa056bd66bc5f66a369c8499b | bigcode/the-stack | train |
924b60d7ee8453d415f60f09 | train | function | def xy_eta_tau(lib, x, y, eta, tau):
return lib.maximum(
tau2.xy_eta_tau(lib, x, y, eta, tau) + mag2.xy_eta(lib, x, y, eta), 0
)
| def xy_eta_tau(lib, x, y, eta, tau):
| return lib.maximum(
tau2.xy_eta_tau(lib, x, y, eta, tau) + mag2.xy_eta(lib, x, y, eta), 0
)
| _tau(lib, x, y, theta, tau) + mag2.xy_theta(lib, x, y, theta), 0
)
def xy_eta_t(lib, x, y, eta, t):
return t ** 2
def xy_eta_tau(lib, x, y, eta, tau):
| 64 | 64 | 53 | 14 | 49 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | xy_eta_tau | xy_eta_tau | 57 | 60 | 57 | 57 | 9424ef1efc14158016b0a91be8aff0202bcab019 | bigcode/the-stack | train |
d4a674d307f2686a1514acf4 | train | function | def rhophi_eta_t(lib, rho, phi, eta, t):
return t ** 2
| def rhophi_eta_t(lib, rho, phi, eta, t):
| return t ** 2
| theta, tau):
return lib.maximum(
tau2.rhophi_theta_tau(lib, rho, phi, theta, tau)
+ mag2.rhophi_theta(lib, rho, phi, theta),
0,
)
def rhophi_eta_t(lib, rho, phi, eta, t):
| 64 | 64 | 22 | 15 | 49 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | rhophi_eta_t | rhophi_eta_t | 85 | 86 | 85 | 85 | 27d408379606a97971796c0ceecb6718ac56ba78 | bigcode/the-stack | train |
f0193257d73aa929d6065504 | train | function | def xy_z_t(lib, x, y, z, t):
return t ** 2
| def xy_z_t(lib, x, y, z, t):
| return t ** 2
| inalEta,
LongitudinalTheta,
LongitudinalZ,
TemporalT,
TemporalTau,
_aztype,
_flavor_of,
_from_signature,
_ltype,
_ttype,
)
def xy_z_t(lib, x, y, z, t):
| 64 | 64 | 21 | 14 | 50 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | xy_z_t | xy_z_t | 35 | 36 | 35 | 35 | 91158017aae1b0d6870f653e4f8768edaf79a239 | bigcode/the-stack | train |
6a05225a9552dd4a1352f1fb | train | function | def xy_z_tau(lib, x, y, z, tau):
return lib.maximum(tau2.xy_z_tau(lib, x, y, z, tau) + mag2.xy_z(lib, x, y, z), 0)
| def xy_z_tau(lib, x, y, z, tau):
| return lib.maximum(tau2.xy_z_tau(lib, x, y, z, tau) + mag2.xy_z(lib, x, y, z), 0)
| Tau,
_aztype,
_flavor_of,
_from_signature,
_ltype,
_ttype,
)
def xy_z_t(lib, x, y, z, t):
return t ** 2
def xy_z_tau(lib, x, y, z, tau):
| 64 | 64 | 50 | 14 | 49 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | xy_z_tau | xy_z_tau | 39 | 40 | 39 | 39 | 74b499361d88d18df45991df839cb5ce3c25bf0e | bigcode/the-stack | train |
a8c17205b46bb4c9509dd9ae | train | function | def rhophi_z_tau(lib, rho, phi, z, tau):
return lib.maximum(
tau2.rhophi_z_tau(lib, rho, phi, z, tau) + mag2.rhophi_z(lib, rho, phi, z), 0
)
| def rhophi_z_tau(lib, rho, phi, z, tau):
| return lib.maximum(
tau2.rhophi_z_tau(lib, rho, phi, z, tau) + mag2.rhophi_z(lib, rho, phi, z), 0
)
| , x, y, eta, tau) + mag2.xy_eta(lib, x, y, eta), 0
)
def rhophi_z_t(lib, rho, phi, z, t):
return t ** 2
def rhophi_z_tau(lib, rho, phi, z, tau):
| 64 | 64 | 58 | 15 | 48 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | rhophi_z_tau | rhophi_z_tau | 67 | 70 | 67 | 67 | c097cfe689792b5ceaebe84fbb2c874af838a8dc | bigcode/the-stack | train |
0c10700826a04ed8b5834a0d | train | function | def xy_theta_t(lib, x, y, theta, t):
return t ** 2
| def xy_theta_t(lib, x, y, theta, t):
| return t ** 2
| def xy_z_tau(lib, x, y, z, tau):
return lib.maximum(tau2.xy_z_tau(lib, x, y, z, tau) + mag2.xy_z(lib, x, y, z), 0)
def xy_theta_t(lib, x, y, theta, t):
| 64 | 64 | 21 | 14 | 50 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | xy_theta_t | xy_theta_t | 43 | 44 | 43 | 43 | aec8a5f672a9f5750656eb8d1c52b9bc87487828 | bigcode/the-stack | train |
e04a50ea12c30a382490484b | train | function | def rhophi_theta_t(lib, rho, phi, theta, t):
return t ** 2
| def rhophi_theta_t(lib, rho, phi, theta, t):
| return t ** 2
| phi, z, tau):
return lib.maximum(
tau2.rhophi_z_tau(lib, rho, phi, z, tau) + mag2.rhophi_z(lib, rho, phi, z), 0
)
def rhophi_theta_t(lib, rho, phi, theta, t):
| 64 | 64 | 22 | 15 | 49 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | rhophi_theta_t | rhophi_theta_t | 73 | 74 | 73 | 73 | f5b5aa4124423aafcc8a2019d60af9b1ab1c9ec7 | bigcode/the-stack | train |
c6119f9236db2a6b4a9fd1ed | train | function | def rhophi_z_t(lib, rho, phi, z, t):
return t ** 2
| def rhophi_z_t(lib, rho, phi, z, t):
| return t ** 2
| (lib, x, y, eta, tau):
return lib.maximum(
tau2.xy_eta_tau(lib, x, y, eta, tau) + mag2.xy_eta(lib, x, y, eta), 0
)
def rhophi_z_t(lib, rho, phi, z, t):
| 64 | 64 | 22 | 15 | 49 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | rhophi_z_t | rhophi_z_t | 63 | 64 | 63 | 63 | 69df6a39cc81205272cc08b6ff01f81a477accbd | bigcode/the-stack | train |
ca32b8e5a1e00b943bbf9bd5 | train | function | def xy_eta_t(lib, x, y, eta, t):
return t ** 2
| def xy_eta_t(lib, x, y, eta, t):
| return t ** 2
| _tau(lib, x, y, theta, tau):
return lib.maximum(
tau2.xy_theta_tau(lib, x, y, theta, tau) + mag2.xy_theta(lib, x, y, theta), 0
)
def xy_eta_t(lib, x, y, eta, t):
| 64 | 64 | 21 | 14 | 50 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | xy_eta_t | xy_eta_t | 53 | 54 | 53 | 53 | b5e7e9a99bceee407c9096ea3b3601e382fab4ea | bigcode/the-stack | train |
56ff98ca67c622584109ebec | train | function | def rhophi_theta_tau(lib, rho, phi, theta, tau):
return lib.maximum(
tau2.rhophi_theta_tau(lib, rho, phi, theta, tau)
+ mag2.rhophi_theta(lib, rho, phi, theta),
0,
)
| def rhophi_theta_tau(lib, rho, phi, theta, tau):
| return lib.maximum(
tau2.rhophi_theta_tau(lib, rho, phi, theta, tau)
+ mag2.rhophi_theta(lib, rho, phi, theta),
0,
)
| , phi, z, tau) + mag2.rhophi_z(lib, rho, phi, z), 0
)
def rhophi_theta_t(lib, rho, phi, theta, t):
return t ** 2
def rhophi_theta_tau(lib, rho, phi, theta, tau):
| 64 | 64 | 60 | 15 | 48 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | rhophi_theta_tau | rhophi_theta_tau | 77 | 82 | 77 | 77 | 323867943d6accf32ee9e26e911b82777fc3f25f | bigcode/the-stack | train |
0944f0463569c6f7294e1180 | train | function | def xy_theta_tau(lib, x, y, theta, tau):
return lib.maximum(
tau2.xy_theta_tau(lib, x, y, theta, tau) + mag2.xy_theta(lib, x, y, theta), 0
)
| def xy_theta_tau(lib, x, y, theta, tau):
| return lib.maximum(
tau2.xy_theta_tau(lib, x, y, theta, tau) + mag2.xy_theta(lib, x, y, theta), 0
)
| .xy_z_tau(lib, x, y, z, tau) + mag2.xy_z(lib, x, y, z), 0)
def xy_theta_t(lib, x, y, theta, t):
return t ** 2
def xy_theta_tau(lib, x, y, theta, tau):
| 64 | 64 | 53 | 14 | 49 | pfackeldey/vector | src/vector/_compute/lorentz/t2.py | Python | xy_theta_tau | xy_theta_tau | 47 | 50 | 47 | 47 | 83f677eadcb2b9f16776cc50d9d653759ad30ccb | bigcode/the-stack | train |
1af45d7e0ec1502a71c69a3f | train | class | class TestRequiriment(unittest.TestCase):
pass
| class TestRequiriment(unittest.TestCase):
| pass
| # Copyright (c) 2021, matbrgz and Contributors
# See license.txt
# import frappe
import unittest
class TestRequiriment(unittest.TestCase):
| 36 | 64 | 11 | 9 | 26 | mohsinalimat/rocknext | rocknext/software_engineering/doctype/requiriment/test_requiriment.py | Python | TestRequiriment | TestRequiriment | 7 | 8 | 7 | 7 | 270460067b59cc06654257b9d5bfe731c2d7642f | bigcode/the-stack | train |
7bce2eab6c3a9f3ba625be3b | train | class | class ChaliceDeploymentError(Exception):
def __init__(self, error):
# type: (Exception) -> None
self.original_error = error
where = self._get_error_location(error)
msg = self._wrap_text(
'ERROR - %s, received the following error:' % where
)
msg += '\n\n'
... | class ChaliceDeploymentError(Exception):
| def __init__(self, error):
# type: (Exception) -> None
self.original_error = error
where = self._get_error_location(error)
msg = self._wrap_text(
'ERROR - %s, received the following error:' % where
)
msg += '\n\n'
msg += self._wrap_text(self._get_e... | import DisplayOnlyExecutor
from chalice.deploy.packager import PipRunner
from chalice.deploy.packager import SubprocessPip
from chalice.deploy.packager import DependencyBuilder as PipDependencyBuilder
from chalice.deploy.packager import LambdaDeploymentPackager
from chalice.deploy.packager import AppOnlyDeploymentPack... | 256 | 256 | 867 | 7 | 249 | Chen188/chalice | chalice/deploy/deployer.py | Python | ChaliceDeploymentError | ChaliceDeploymentError | 146 | 250 | 146 | 146 | b491f6a4e7bd6c7492236737e8495a889ffbc55e | bigcode/the-stack | train |
031275c39a71aa010a581805 | train | class | class BuildStage(object):
def __init__(self, steps):
# type: (List[BaseDeployStep]) -> None
self._steps = steps
def execute(self, config, resources):
# type: (Config, List[models.Model]) -> None
for resource in resources:
for step in self._steps:
step... | class BuildStage(object):
| def __init__(self, steps):
# type: (List[BaseDeployStep]) -> None
self._steps = steps
def execute(self, config, resources):
# type: (Config, List[models.Model]) -> None
for resource in resources:
for step in self._steps:
step.handle(config, resource)
| GenIAMPolicy) -> None
if isinstance(resource.document, models.Placeholder):
policy = self._policy_gen.generate_policy(config)
if models.RoleTraits.VPC_NEEDED in resource.traits:
policy['Statement'].append(VPC_ATTACH_POLICY)
resource.document = policy
class Bui... | 64 | 64 | 80 | 5 | 58 | Chen188/chalice | chalice/deploy/deployer.py | Python | BuildStage | BuildStage | 643 | 652 | 643 | 643 | 4a1142791266a2c123ff1ab8654a915654b9b3b6 | bigcode/the-stack | train |
380d82c45ddeedcd6ca302fa | train | function | def create_default_deployer(session, config, ui):
# type: (Session, Config, UI) -> Deployer
return _create_deployer(session, config, ui, Executor, ResultsRecorder)
| def create_default_deployer(session, config, ui):
# type: (Session, Config, UI) -> Deployer
| return _create_deployer(session, config, ui, Executor, ResultsRecorder)
| ):
# type: (Session, Config, UI) -> Deployer
return _create_deployer(session, config, ui, DisplayOnlyExecutor,
NoopResultsRecorder)
def create_default_deployer(session, config, ui):
# type: (Session, Config, UI) -> Deployer
| 64 | 64 | 43 | 26 | 38 | Chen188/chalice | chalice/deploy/deployer.py | Python | create_default_deployer | create_default_deployer | 259 | 261 | 259 | 260 | 0c6e57f0846db6f4b306251c32b984363e4eb564 | bigcode/the-stack | train |
712487841f00e9f189aa8075 | train | function | def create_plan_only_deployer(session, config, ui):
# type: (Session, Config, UI) -> Deployer
return _create_deployer(session, config, ui, DisplayOnlyExecutor,
NoopResultsRecorder)
| def create_plan_only_deployer(session, config, ui):
# type: (Session, Config, UI) -> Deployer
| return _create_deployer(session, config, ui, DisplayOnlyExecutor,
NoopResultsRecorder)
| get_mb(self, value):
# type: (int) -> str
return '%.1f MB' % (float(value) / (1024 ** 2))
def create_plan_only_deployer(session, config, ui):
# type: (Session, Config, UI) -> Deployer
| 64 | 64 | 49 | 27 | 37 | Chen188/chalice | chalice/deploy/deployer.py | Python | create_plan_only_deployer | create_plan_only_deployer | 253 | 256 | 253 | 254 | fc4445576ffd6d1b03080a29e12a59303c10a042 | bigcode/the-stack | train |
857a0e070b5236b53a02955e | train | class | class ManagedLayerDeploymentPackager(BaseDeployStep):
# If we're creating a layer for non-app code there's two different
# packagers we need. One for the Lambda functions (app code) and
# one for the Lambda layer (requirements.txt + vendor).
def __init__(self,
lambda_packager, # type:... | class ManagedLayerDeploymentPackager(BaseDeployStep):
# If we're creating a layer for non-app code there's two different
# packagers we need. One for the Lambda functions (app code) and
# one for the Lambda layer (requirements.txt + vendor).
| def __init__(self,
lambda_packager, # type: BaseLambdaDeploymentPackager
layer_packager, # type: BaseLambdaDeploymentPackager
):
# type: (...) -> None
self._lambda_packager = lambda_packager
self._layer_packager = layer_packager
def ... | = packager
def handle_deploymentpackage(self, config, resource):
# type: (Config, models.DeploymentPackage) -> None
if isinstance(resource.filename, models.Placeholder):
zip_filename = self._packager.create_deployment_package(
config.project_dir, config.lambda_python_ve... | 128 | 128 | 427 | 57 | 70 | Chen188/chalice | chalice/deploy/deployer.py | Python | ManagedLayerDeploymentPackager | ManagedLayerDeploymentPackager | 458 | 500 | 458 | 461 | 365d5592fff7db1ba436a2e9ac8d300c7a412087 | bigcode/the-stack | train |
e24481a086740f40b0b2e94b | train | class | class Deployer(object):
BACKEND_NAME = 'api'
def __init__(self,
application_builder, # type: ApplicationGraphBuilder
deps_builder, # type: DependencyBuilder
build_stage, # type: BuildStage
plan_stage, # type: PlanSt... | class Deployer(object):
| BACKEND_NAME = 'api'
def __init__(self,
application_builder, # type: ApplicationGraphBuilder
deps_builder, # type: DependencyBuilder
build_stage, # type: BuildStage
plan_stage, # type: PlanStage
swe... | osutils=osutils,
),
SwaggerBuilder(
swagger_generator=swagger_gen,
),
LambdaEventSourcePolicyInjector(),
WebsocketPolicyInjector()
],
)
return build_stage
def create_deletion_deployer(client, ui):
# type: (... | 140 | 140 | 468 | 5 | 135 | Chen188/chalice | chalice/deploy/deployer.py | Python | Deployer | Deployer | 352 | 410 | 352 | 352 | f1754823ca41a806f2bfb934a23bc984b40699f1 | bigcode/the-stack | train |
7e9a0860dec2647b8f1af991 | train | class | class DeploymentReporter(object):
# We want the API URLs to be displayed last.
_SORT_ORDER = {
'rest_api': 100,
'websocket_api': 100,
'domain_name': 100
}
# The default is chosen to sort before the rest_api
_DEFAULT_ORDERING = 50
def __init__(self, ui):
# type: (... | class DeploymentReporter(object):
# We want the API URLs to be displayed last.
| _SORT_ORDER = {
'rest_api': 100,
'websocket_api': 100,
'domain_name': 100
}
# The default is chosen to sort before the rest_api
_DEFAULT_ORDERING = 50
def __init__(self, ui):
# type: (UI) -> None
self._ui = ui
def generate_report(self, deployed_values):
... | , str, str) -> None
deployed_dir = self._osutils.joinpath(
project_dir, '.chalice', 'deployed')
deployed_filename = self._osutils.joinpath(
deployed_dir, '%s.json' % chalice_stage_name)
if not self._osutils.directory_exists(deployed_dir):
self._osutils.makedir... | 174 | 174 | 583 | 17 | 156 | Chen188/chalice | chalice/deploy/deployer.py | Python | DeploymentReporter | DeploymentReporter | 682 | 748 | 682 | 683 | 559a0610c62723203ed406062290b01ef170c6bd | bigcode/the-stack | train |
28d246f7148fac6964c640d5 | train | class | class DeploymentPackager(BaseDeployStep):
def __init__(self, packager):
# type: (LambdaDeploymentPackager) -> None
self._packager = packager
def handle_deploymentpackage(self, config, resource):
# type: (Config, models.DeploymentPackage) -> None
if isinstance(resource.filename, ... | class DeploymentPackager(BaseDeployStep):
| def __init__(self, packager):
# type: (LambdaDeploymentPackager) -> None
self._packager = packager
def handle_deploymentpackage(self, config, resource):
# type: (Config, models.DeploymentPackage) -> None
if isinstance(resource.filename, models.Placeholder):
zip_filen... | ._lambda_memory_size
def handle_domainname(self, config, resource):
# type: (Config, models.DomainName) -> None
if resource.tls_version is None:
resource.tls_version = models.TLSVersion.create(
DEFAULT_TLS_VERSION)
class DeploymentPackager(BaseDeployStep):
| 64 | 64 | 107 | 8 | 56 | Chen188/chalice | chalice/deploy/deployer.py | Python | DeploymentPackager | DeploymentPackager | 445 | 455 | 445 | 445 | 244c33aa655188c00b84285b00f549e59d6cd4cd | bigcode/the-stack | train |
1e2a8c03cdf9bfc24f00f91e | train | class | class BaseDeployStep(object):
def handle(self, config, resource):
# type: (Config, models.Model) -> None
name = 'handle_%s' % resource.__class__.__name__.lower()
handler = getattr(self, name, None)
if handler is not None:
handler(config, resource)
| class BaseDeployStep(object):
| def handle(self, config, resource):
# type: (Config, models.Model) -> None
name = 'handle_%s' % resource.__class__.__name__.lower()
handler = getattr(self, name, None)
if handler is not None:
handler(config, resource)
| ice_stage_name,
config.project_dir,
)
return deployed_values
def _validate_config(self, config):
# type: (Config) -> None
try:
validate_configuration(config)
except ValueError as e:
raise ChaliceDeploymentError(e)
class BaseDeployStep(obje... | 64 | 64 | 68 | 6 | 58 | Chen188/chalice | chalice/deploy/deployer.py | Python | BaseDeployStep | BaseDeployStep | 413 | 419 | 413 | 413 | 6e533d00537e15a3565f40879b58d1269a2fd36c | bigcode/the-stack | train |
fff1960deb38703ab3a8ea76 | train | function | def _create_deployer(session, # type: Session
config, # type: Config
ui, # type: UI
executor_cls, # type: Type[BaseExecutor]
recorder_cls, # type: Type[ResultsRecorder]
):
# type: (...)... | def _create_deployer(session, # type: Session
config, # type: Config
ui, # type: UI
executor_cls, # type: Type[BaseExecutor]
recorder_cls, # type: Type[ResultsRecorder]
):
# type: (...)... | client = TypedAWSClient(session)
osutils = OSUtils()
return Deployer(
application_builder=ApplicationGraphBuilder(),
deps_builder=DependencyBuilder(),
build_stage=create_build_stage(
osutils, UI(), TemplatedSwaggerGenerator(), config
),
plan_stage=PlanStag... | def _create_deployer(session, # type: Session
config, # type: Config
ui, # type: UI
executor_cls, # type: Type[BaseExecutor]
recorder_cls, # type: Type[ResultsRecorder]
):
# type: (...)... | 68 | 64 | 189 | 68 | 0 | Chen188/chalice | chalice/deploy/deployer.py | Python | _create_deployer | _create_deployer | 264 | 286 | 264 | 270 | 37fe58cc3a5e78ad5e886cc9062c3e76792786e1 | bigcode/the-stack | train |
d5322d619bd67313a8dd4736 | train | function | def create_deletion_deployer(client, ui):
# type: (TypedAWSClient, UI) -> Deployer
return Deployer(
application_builder=ApplicationGraphBuilder(),
deps_builder=DependencyBuilder(),
build_stage=BuildStage(steps=[]),
plan_stage=NoopPlanner(),
sweeper=ResourceSweeper(),
... | def create_deletion_deployer(client, ui):
# type: (TypedAWSClient, UI) -> Deployer
| return Deployer(
application_builder=ApplicationGraphBuilder(),
deps_builder=DependencyBuilder(),
build_stage=BuildStage(steps=[]),
plan_stage=NoopPlanner(),
sweeper=ResourceSweeper(),
executor=Executor(client, ui),
recorder=ResultsRecorder(osutils=OSUtils()),... | utils,
),
SwaggerBuilder(
swagger_generator=swagger_gen,
),
LambdaEventSourcePolicyInjector(),
WebsocketPolicyInjector()
],
)
return build_stage
def create_deletion_deployer(client, ui):
# type: (TypedAWSClient, UI) -> Deplo... | 64 | 64 | 92 | 25 | 38 | Chen188/chalice | chalice/deploy/deployer.py | Python | create_deletion_deployer | create_deletion_deployer | 339 | 349 | 339 | 340 | 6051b925a56807915564d65b62ff8082c47e9d8f | bigcode/the-stack | train |
6de247a5ba422623d7c17a6c | train | class | class WebsocketPolicyInjector(BaseDeployStep):
def __init__(self):
# type: () -> None
self._policy_injected = False
def handle_websocketapi(self, config, resource):
# type: (Config, models.WebsocketAPI) -> None
self._inject_into_function(config, resource.connect_function)
... | class WebsocketPolicyInjector(BaseDeployStep):
| def __init__(self):
# type: () -> None
self._policy_injected = False
def handle_websocketapi(self, config, resource):
# type: (Config, models.WebsocketAPI) -> None
self._inject_into_function(config, resource.connect_function)
self._inject_into_function(config, resource.m... | .ManagedIAMRole) and
isinstance(role.policy, models.AutoGenIAMPolicy) and
not isinstance(role.policy.document, models.Placeholder)
)
def _inject_trigger_policy(self, document, policy):
# type: (Dict[str, Any], Dict[str, Any]) -> None
document['Statement'].append(poli... | 79 | 79 | 266 | 9 | 70 | Chen188/chalice | chalice/deploy/deployer.py | Python | WebsocketPolicyInjector | WebsocketPolicyInjector | 576 | 606 | 576 | 576 | 91f1ca97c5729e94673d9247b073ea5fb399f448 | bigcode/the-stack | train |
f33410f926885d0774d75619 | train | function | def create_build_stage(osutils, ui, swagger_gen, config):
# type: (OSUtils, UI, SwaggerGenerator, Config) -> BuildStage
pip_runner = PipRunner(pip=SubprocessPip(osutils=osutils),
osutils=osutils)
dependency_builder = PipDependencyBuilder(
osutils=osutils,
pip_runne... | def create_build_stage(osutils, ui, swagger_gen, config):
# type: (OSUtils, UI, SwaggerGenerator, Config) -> BuildStage
| pip_runner = PipRunner(pip=SubprocessPip(osutils=osutils),
osutils=osutils)
dependency_builder = PipDependencyBuilder(
osutils=osutils,
pip_runner=pip_runner
)
deployment_packager = cast(BaseDeployStep, None)
if config.automatic_layer:
deployment_pa... | osutils=osutils, remote_state=RemoteState(
client, config.deployed_resources(config.chalice_stage)),
),
sweeper=ResourceSweeper(),
executor=executor_cls(client, ui),
recorder=recorder_cls(osutils=osutils),
)
def create_build_stage(osutils, ui, swagger_gen,... | 89 | 89 | 298 | 33 | 56 | Chen188/chalice | chalice/deploy/deployer.py | Python | create_build_stage | create_build_stage | 289 | 336 | 289 | 290 | 2c98be0ff4fbe063222ae19904f9745c58db5110 | bigcode/the-stack | train |
48e58a83071605627ee9ed4b | train | class | class InjectDefaults(BaseDeployStep):
def __init__(self, lambda_timeout=DEFAULT_LAMBDA_TIMEOUT,
lambda_memory_size=DEFAULT_LAMBDA_MEMORY_SIZE,
tls_version=DEFAULT_TLS_VERSION):
# type: (int, int, str) -> None
self._lambda_timeout = lambda_timeout
self._lambd... | class InjectDefaults(BaseDeployStep):
| def __init__(self, lambda_timeout=DEFAULT_LAMBDA_TIMEOUT,
lambda_memory_size=DEFAULT_LAMBDA_MEMORY_SIZE,
tls_version=DEFAULT_TLS_VERSION):
# type: (int, int, str) -> None
self._lambda_timeout = lambda_timeout
self._lambda_memory_size = lambda_memory_size
... | config, resource):
# type: (Config, models.Model) -> None
name = 'handle_%s' % resource.__class__.__name__.lower()
handler = getattr(self, name, None)
if handler is not None:
handler(config, resource)
class InjectDefaults(BaseDeployStep):
| 64 | 64 | 201 | 7 | 57 | Chen188/chalice | chalice/deploy/deployer.py | Python | InjectDefaults | InjectDefaults | 422 | 442 | 422 | 422 | 2e6aec8e37adc7b92afc115474a6e9e49426172e | bigcode/the-stack | train |
ff86ada9db048c7e02b4edf8 | train | class | class PolicyGenerator(BaseDeployStep):
def __init__(self, policy_gen, osutils):
# type: (AppPolicyGenerator, OSUtils) -> None
self._policy_gen = policy_gen
self._osutils = osutils
def _read_document_from_file(self, filename):
# type: (PolicyGenerator, str) -> Dict[str, Any]
... | class PolicyGenerator(BaseDeployStep):
| def __init__(self, policy_gen, osutils):
# type: (AppPolicyGenerator, OSUtils) -> None
self._policy_gen = policy_gen
self._osutils = osutils
def _read_document_from_file(self, filename):
# type: (PolicyGenerator, str) -> Dict[str, Any]
try:
return json.loads(... | .AutoGenIAMPolicy) and
not isinstance(role.policy.document,
models.Placeholder)):
self._inject_policy(
role.policy.document,
POST_TO_WEBSOCKET_CONNECTION_POLICY.copy())
self._policy_injected = True
def _inject_policy(self, d... | 93 | 93 | 310 | 7 | 86 | Chen188/chalice | chalice/deploy/deployer.py | Python | PolicyGenerator | PolicyGenerator | 609 | 640 | 609 | 609 | 49c89931b1c745fba4e3684b0439236042717ffe | bigcode/the-stack | train |
a97c3295a1c03dda20a40982 | train | class | class ResultsRecorder(object):
def __init__(self, osutils):
# type: (OSUtils) -> None
self._osutils = osutils
def record_results(self, results, chalice_stage_name, project_dir):
# type: (Any, str, str) -> None
deployed_dir = self._osutils.joinpath(
project_dir, '.cha... | class ResultsRecorder(object):
| def __init__(self, osutils):
# type: (OSUtils) -> None
self._osutils = osutils
def record_results(self, results, chalice_stage_name, project_dir):
# type: (Any, str, str) -> None
deployed_dir = self._osutils.joinpath(
project_dir, '.chalice', 'deployed')
depl... | BaseDeployStep]) -> None
self._steps = steps
def execute(self, config, resources):
# type: (Config, List[models.Model]) -> None
for resource in resources:
for step in self._steps:
step.handle(config, resource)
class ResultsRecorder(object):
| 64 | 64 | 171 | 5 | 59 | Chen188/chalice | chalice/deploy/deployer.py | Python | ResultsRecorder | ResultsRecorder | 655 | 673 | 655 | 655 | 0663a14a989a7f01264f9344a5de9db3d943c452 | bigcode/the-stack | train |
4a4e9cc264382d93d9745d9c | train | class | class SwaggerBuilder(BaseDeployStep):
def __init__(self, swagger_generator):
# type: (SwaggerGenerator) -> None
self._swagger_generator = swagger_generator
def handle_restapi(self, config, resource):
# type: (Config, models.RestAPI) -> None
swagger_doc = self._swagger_generator.... | class SwaggerBuilder(BaseDeployStep):
| def __init__(self, swagger_generator):
# type: (SwaggerGenerator) -> None
self._swagger_generator = swagger_generator
def handle_restapi(self, config, resource):
# type: (Config, models.RestAPI) -> None
swagger_doc = self._swagger_generator.generate_swagger(
config.c... | :
# An empty package is not valid in Lambda. There's
# no point in trying to represent it in the model
# because nothing downstream (planner, SAM/tf) can
# consume as a useful entity.
resource.is_empty = True
class SwaggerBuilder(BaseDeplo... | 64 | 64 | 90 | 7 | 56 | Chen188/chalice | chalice/deploy/deployer.py | Python | SwaggerBuilder | SwaggerBuilder | 503 | 512 | 503 | 503 | 0564e2541a7c5c13c788b846cb694739a2c8a9dc | bigcode/the-stack | train |
ebd4cc2e3abc00af6a205704 | train | class | class LambdaEventSourcePolicyInjector(BaseDeployStep):
def __init__(self):
# type: () -> None
self._sqs_policy_injected = False
self._kinesis_policy_injected = False
self._ddb_policy_injected = False
def handle_sqseventsource(self, config, resource):
# type: (Config, mod... | class LambdaEventSourcePolicyInjector(BaseDeployStep):
| def __init__(self):
# type: () -> None
self._sqs_policy_injected = False
self._kinesis_policy_injected = False
self._ddb_policy_injected = False
def handle_sqseventsource(self, config, resource):
# type: (Config, models.SQSEventSource) -> None
# The sqs integrati... |
)
resource.deployment_package.filename = zip_filename
except EmptyPackageError:
# An empty package is not valid in Lambda. There's
# no point in trying to represent it in the model
# because nothing downstream (planner, SAM/tf... | 175 | 175 | 585 | 10 | 164 | Chen188/chalice | chalice/deploy/deployer.py | Python | LambdaEventSourcePolicyInjector | LambdaEventSourcePolicyInjector | 515 | 573 | 515 | 515 | afda9e96b854a2a65a180983ac7b4781479261aa | bigcode/the-stack | train |
57f3231125fddcba5def39fd | train | class | class NoopResultsRecorder(ResultsRecorder):
def record_results(self, results, chalice_stage_name, project_dir):
# type: (Any, str, str) -> None
return None
| class NoopResultsRecorder(ResultsRecorder):
| def record_results(self, results, chalice_stage_name, project_dir):
# type: (Any, str, str) -> None
return None
| self._osutils.directory_exists(deployed_dir):
self._osutils.makedirs(deployed_dir)
serialized = serialize_to_json(results)
self._osutils.set_file_contents(
filename=deployed_filename,
contents=serialized,
binary=False
)
class NoopResultsRecorder(R... | 64 | 64 | 43 | 9 | 55 | Chen188/chalice | chalice/deploy/deployer.py | Python | NoopResultsRecorder | NoopResultsRecorder | 676 | 679 | 676 | 676 | b3a60471a447da76b493f4c1f87651c0eb65e14e | bigcode/the-stack | train |
87404961e3b89e6aac69de01 | train | class | class BetterAI(AI):
"""
BetterAI: Thinks about what it is doing a little more - picks a priority
continent and priorities holding and reinforcing it.
"""
def start(self):
self.area_priority = list(self.world.areas)
random.shuffle(self.area_priority)
def priority(self):
... | class BetterAI(AI):
| """
BetterAI: Thinks about what it is doing a little more - picks a priority
continent and priorities holding and reinforcing it.
"""
def start(self):
self.area_priority = list(self.world.areas)
random.shuffle(self.area_priority)
def priority(self):
priority = sorted([t... | from gym_risk.envs.game.ai import AI
import random
import collections
class BetterAI(AI):
| 23 | 130 | 435 | 6 | 16 | leoandeol/gym-risk | gym_risk/envs/game/ai/better.py | Python | BetterAI | BetterAI | 6 | 57 | 6 | 6 | d678ce0b531afb38aec21ad64e595ea26bfa9546 | bigcode/the-stack | train |
d329ca145a51bdd1d1b7b2dd | train | class | class TimeSeries(Series):
"""
Distributed collection of time series data.
Backed by an RDD of key-value pairs where the key is an identifier
and the value is a one-dimensional array. The common index
specifies the time of each entry in the array.
Parameters
----------
rdd : RDD of (tup... | class TimeSeries(Series):
| """
Distributed collection of time series data.
Backed by an RDD of key-value pairs where the key is an identifier
and the value is a one-dimensional array. The common index
specifies the time of each entry in the array.
Parameters
----------
rdd : RDD of (tuple, array) pairs
R... | from numpy import sqrt, pi, angle, fft, fix, zeros, roll, dot, mean, \
array, size, diag, tile, ones, asarray, polyfit, polyval, arange, \
percentile, ceil, float64
from thunder.rdds.series import Series
from thunder.utils.common import loadMatVar, checkParams
class TimeSeries(Series):
| 79 | 256 | 2,408 | 6 | 72 | Andrewosh/thunder | python/thunder/rdds/timeseries.py | Python | TimeSeries | TimeSeries | 9 | 325 | 9 | 9 | 187353b1fa7606d4909b72f1513042dc02301230 | bigcode/the-stack | train |
e65cb3184db44fd2e13bae5c | train | function | def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {'message': "I'm working!"}
| def test_read_main():
| response = client.get("/")
assert response.status_code == 200
assert response.json() == {'message': "I'm working!"}
| from fastapi.testclient import TestClient
from cooler.main import app
client = TestClient(app)
def test_read_main():
| 26 | 64 | 34 | 5 | 21 | YasminTeles/cooler | tests/test_main.py | Python | test_read_main | test_read_main | 8 | 11 | 8 | 8 | a48987bf99644d77704864032d68c53655b459ff | bigcode/the-stack | train |
717cdedb4b6a4c390045cbd6 | train | class | class EasyZoneCircuit(EasycontrolCircuit):
def __init__(
self, connector, attr_id, db, _type, bus_type, current_date=None, **kwargs
):
super().__init__(
connector=connector,
attr_id=attr_id,
db=db,
_type=_type,
bus_type=bus_type,
... | class EasyZoneCircuit(EasycontrolCircuit):
| def __init__(
self, connector, attr_id, db, _type, bus_type, current_date=None, **kwargs
):
super().__init__(
connector=connector,
attr_id=attr_id,
db=db,
_type=_type,
bus_type=bus_type,
current_date=current_date,
)
... | from .base import EasycontrolCircuit
from bosch_thermostat_client.const import (
HVAC_ACTION,
HVAC_HEAT,
HVAC_OFF,
NAME,
STATUS,
MODE_TO_SETPOINT,
ID,
ACTIVE_PROGRAM,
URI,
)
from bosch_thermostat_client.operation_mode import EasyControlOperationModeHelper
from bosch_thermostat_client... | 96 | 193 | 645 | 9 | 86 | bosch-thermostat/bosch-thermostat-client-python | bosch_thermostat_client/circuits/easycontrol/zone.py | Python | EasyZoneCircuit | EasyZoneCircuit | 17 | 109 | 17 | 17 | a81bd8ccc7a90e78dee2f5b7854df0dfb9ac5ae2 | bigcode/the-stack | train |
77b8105abf2190c94577d24a | train | class | class Proyectos(models.Model):
proyecto = models.ForeignKey('voluntariado.Proyecto')
voluntario = models.ForeignKey('voluntariado.Voluntario')
horas = models.PositiveIntegerField(default=0)
fecha = models.DateField(default=date.today)
actividad = models.CharField('Actividad', max_length=200)
cl... | class Proyectos(models.Model):
| proyecto = models.ForeignKey('voluntariado.Proyecto')
voluntario = models.ForeignKey('voluntariado.Voluntario')
horas = models.PositiveIntegerField(default=0)
fecha = models.DateField(default=date.today)
actividad = models.CharField('Actividad', max_length=200)
class Meta:
verbose_name ... | # -*- coding: utf-8 -*-
from django.db import models
from datetime import date
class Proyectos(models.Model):
| 25 | 64 | 108 | 6 | 18 | dmallcott/HOI-Voluntariado | hoi_project/apps/registros/models.py | Python | Proyectos | Proyectos | 6 | 18 | 6 | 6 | 0fae2e008a22872cca233a275e7b14014a0b8e36 | bigcode/the-stack | train |
372fad0ca6686c70689a98b4 | train | class | class Servicios(models.Model):
servicio = models.ForeignKey('voluntariado.Servicio')
voluntario = models.ForeignKey('voluntariado.Voluntario')
horas = models.PositiveIntegerField(default=0)
fecha = models.DateField(default=date.today)
actividad = models.CharField('Actividad', max_length=200)
cl... | class Servicios(models.Model):
| servicio = models.ForeignKey('voluntariado.Servicio')
voluntario = models.ForeignKey('voluntariado.Voluntario')
horas = models.PositiveIntegerField(default=0)
fecha = models.DateField(default=date.today)
actividad = models.CharField('Actividad', max_length=200)
class Meta:
verbose_name ... | .DateField(default=date.today)
actividad = models.CharField('Actividad', max_length=200)
class Meta:
verbose_name = "Registro de proyecto"
verbose_name_plural = "Registro de proyectos"
def __unicode__(self):
return unicode(self.proyecto.titulo)
class Servicios(models.Model):
| 64 | 64 | 107 | 5 | 59 | dmallcott/HOI-Voluntariado | hoi_project/apps/registros/models.py | Python | Servicios | Servicios | 21 | 33 | 21 | 21 | 5423df8f5254166dcbcd4d82e88b91712b09319c | bigcode/the-stack | train |
9c40378867ec040339bf5dd8 | train | class | class TestSubmitSelfServiceSettingsFlowWithProfileMethodBody(unittest.TestCase):
"""SubmitSelfServiceSettingsFlowWithProfileMethodBody unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testSubmitSelfServiceSettingsFlowWithProfileMethodBody(self):
"""Test Su... | class TestSubmitSelfServiceSettingsFlowWithProfileMethodBody(unittest.TestCase):
| """SubmitSelfServiceSettingsFlowWithProfileMethodBody unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testSubmitSelfServiceSettingsFlowWithProfileMethodBody(self):
"""Test SubmitSelfServiceSettingsFlowWithProfileMethodBody"""
# FIXME: construct ob... |
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import ory_client
from ory_client.model.submit_self_service_settings_flow_with_profile_method_body import SubmitSelfServiceSettingsFlowWithProfileMethodBody
class TestSubmitSelfServiceSettingsFlowWithProfileMethodBody(unittest.TestCase)... | 64 | 64 | 113 | 15 | 48 | sproutfi/sdk | clients/client/python/test/test_submit_self_service_settings_flow_with_profile_method_body.py | Python | TestSubmitSelfServiceSettingsFlowWithProfileMethodBody | TestSubmitSelfServiceSettingsFlowWithProfileMethodBody | 19 | 32 | 19 | 19 | 08415664e5ce9e2915a08e31e4b77822dc9b7aee | bigcode/the-stack | train |
3e2269abbad9b41fe7008494 | train | function | def get_columns():
return [
{
"label": _("Purchase Order"),
"fieldtype": "Link",
"fieldname": "purchase_order",
"options": "Purchase Order",
"width": 150
},
{
"label": _("Date"),
"fieldtype": "Date",
"fieldname": "date",
"hidden": 1,
"width": 150
},
{
"label": _("Supplier"),
... | def get_columns():
| return [
{
"label": _("Purchase Order"),
"fieldtype": "Link",
"fieldname": "purchase_order",
"options": "Purchase Order",
"width": 150
},
{
"label": _("Date"),
"fieldtype": "Date",
"fieldname": "date",
"hidden": 1,
"width": 150
},
{
"label": _("Supplier"),
"fieldtype": "Li... | (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
if filters.from_date >= filters.to_date:
frappe.msgprint(_("To Date must be greater than From Date"))
d... | 97 | 97 | 324 | 4 | 92 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_columns | get_columns | 17 | 64 | 17 | 17 | b80e11621a8135488a50dbfcf83bfe0fca89793d | bigcode/the-stack | train |
a5421c124c39ad8758456a3a | train | function | def get_purchase_order_item_supplied(po):
return frappe.get_all("Purchase Order Item Supplied", filters=[
('parent', 'IN', po)
], fields=['parent', 'rm_item_code', 'required_qty'])
| def get_purchase_order_item_supplied(po):
| return frappe.get_all("Purchase Order Item Supplied", filters=[
('parent', 'IN', po)
], fields=['parent', 'rm_item_code', 'required_qty'])
| 1)
], fields=["name", "purchase_order"])
def get_stock_entry_detail(se):
return frappe.get_all("Stock Entry Detail", filters=[
["parent", "in", se]
],
fields=["parent", "item_code", "qty"])
def get_purchase_order_item_supplied(po):
| 64 | 64 | 47 | 9 | 55 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_purchase_order_item_supplied | get_purchase_order_item_supplied | 134 | 137 | 134 | 134 | 32e3a578d8ad09384395f1463ff02ec294b1c7f8 | bigcode/the-stack | train |
5458414d990fbb9ac5cf4939 | train | function | def execute(filters=None):
if filters.from_date >= filters.to_date:
frappe.msgprint(_("To Date must be greater than From Date"))
data = []
columns = get_columns()
get_data(data , filters)
return columns, data
| def execute(filters=None):
| if filters.from_date >= filters.to_date:
frappe.msgprint(_("To Date must be greater than From Date"))
data = []
columns = get_columns()
get_data(data , filters)
return columns, data
| # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
| 50 | 64 | 49 | 5 | 45 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | execute | execute | 8 | 15 | 8 | 8 | a6eb285633c9ab6d97ea7e30f21092e6e59f6506 | bigcode/the-stack | train |
f601d9bee722a7c062b84583 | train | function | def get_po(filters):
record_filters = [
["is_subcontracted", "=", "Yes"],
["supplier", "=", filters.supplier],
["transaction_date", "<=", filters.to_date],
["transaction_date", ">=", filters.from_date],
["docstatus", "=", 1]
]
return frappe.get_all("Purchase Order", filters=record_filters, fields=["n... | def get_po(filters):
| record_filters = [
["is_subcontracted", "=", "Yes"],
["supplier", "=", filters.supplier],
["transaction_date", "<=", filters.to_date],
["transaction_date", ">=", filters.from_date],
["docstatus", "=", 1]
]
return frappe.get_all("Purchase Order", filters=record_filters, fields=["name", "transaction_da... | upplier': order.supplier,
'rm_item_code': item.rm_item_code,
'r_qty': item.required_qty,
't_qty':transferred_qty,
'p_qty':item.required_qty - transferred_qty
}
data.append(row)
return(data)
def get_po(filters):
| 64 | 64 | 95 | 5 | 59 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_po | get_po | 92 | 100 | 92 | 92 | 411a4521632a5ba29b8aeab385d31570953a1a2e | bigcode/the-stack | train |
86ae908aecfd0f0e2f73678d | train | function | def get_data(data, filters):
po = get_po(filters)
po_transferred_qty_map = frappe._dict(get_transferred_quantity([v.name for v in po]))
sub_items = get_purchase_order_item_supplied([v.name for v in po])
for order in po:
for item in sub_items:
if order.name == item.parent and order.name in po_transferred_qty_... | def get_data(data, filters):
| po = get_po(filters)
po_transferred_qty_map = frappe._dict(get_transferred_quantity([v.name for v in po]))
sub_items = get_purchase_order_item_supplied([v.name for v in po])
for order in po:
for item in sub_items:
if order.name == item.parent and order.name in po_transferred_qty_map and \
item.required_q... | name": "t_qty",
"width": 100
},
{
"label": _("Pending Quantity"),
"fieldtype": "Float",
"fieldname": "p_qty",
"width": 100
}
]
def get_data(data, filters):
| 68 | 68 | 229 | 7 | 61 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_data | get_data | 66 | 90 | 66 | 66 | b95dc7cf1007cb2ff80506c6477aaae7c0861e0e | bigcode/the-stack | train |
21d6b911376343b5a642aa2f | train | function | def get_transferred_quantity(po_name):
stock_entries = get_stock_entry(po_name)
stock_entries_detail = get_stock_entry_detail([v.name for v in stock_entries])
po_transferred_qty_map = {}
for entry in stock_entries:
for details in stock_entries_detail:
if details.parent == entry.name:
details["Purchase_or... | def get_transferred_quantity(po_name):
| stock_entries = get_stock_entry(po_name)
stock_entries_detail = get_stock_entry_detail([v.name for v in stock_entries])
po_transferred_qty_map = {}
for entry in stock_entries:
for details in stock_entries_detail:
if details.parent == entry.name:
details["Purchase_order"] = entry.purchase_order
if ent... | "<=", filters.to_date],
["transaction_date", ">=", filters.from_date],
["docstatus", "=", 1]
]
return frappe.get_all("Purchase Order", filters=record_filters, fields=["name", "transaction_date", "supplier"])
def get_transferred_quantity(po_name):
| 64 | 64 | 175 | 8 | 56 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_transferred_quantity | get_transferred_quantity | 102 | 118 | 102 | 102 | 0857855f00c6fa2e27b52e6c5c78c1d39d46f5f2 | bigcode/the-stack | train |
d89e72d8b9803e422c377662 | train | function | def get_stock_entry(po):
return frappe.get_all("Stock Entry", filters=[
('purchase_order', 'IN', po),
('stock_entry_type', '=', 'Send to Subcontractor'),
('docstatus', '=', 1)
], fields=["name", "purchase_order"])
| def get_stock_entry(po):
| return frappe.get_all("Stock Entry", filters=[
('purchase_order', 'IN', po),
('stock_entry_type', '=', 'Send to Subcontractor'),
('docstatus', '=', 1)
], fields=["name", "purchase_order"])
| ][details.item_code] = details.qty
else:
po_transferred_qty_map[entry.purchase_order][details.item_code] = po_transferred_qty_map[entry.purchase_order].get(details.item_code, 0) + details.qty
return po_transferred_qty_map
def get_stock_entry(po):
| 64 | 64 | 62 | 6 | 57 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_stock_entry | get_stock_entry | 121 | 126 | 121 | 121 | 7f34c5368e549763d5477c132211bfea0e71bc5c | bigcode/the-stack | train |
ee722a9c39e8c6aa3106eaf8 | train | function | def get_stock_entry_detail(se):
return frappe.get_all("Stock Entry Detail", filters=[
["parent", "in", se]
],
fields=["parent", "item_code", "qty"])
| def get_stock_entry_detail(se):
| return frappe.get_all("Stock Entry Detail", filters=[
["parent", "in", se]
],
fields=["parent", "item_code", "qty"])
| ):
return frappe.get_all("Stock Entry", filters=[
('purchase_order', 'IN', po),
('stock_entry_type', '=', 'Send to Subcontractor'),
('docstatus', '=', 1)
], fields=["name", "purchase_order"])
def get_stock_entry_detail(se):
| 64 | 64 | 43 | 7 | 57 | Mindhome/field_service | mindhome_alpha/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/subcontracted_raw_materials_to_be_transferred.py | Python | get_stock_entry_detail | get_stock_entry_detail | 128 | 132 | 128 | 128 | aba324a477d57deaa7fa452e8105bb47f4458b45 | bigcode/the-stack | train |
97025c2070422da1fff7bbb0 | train | class | class PostCachePageTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user("dslatsis")
def setUp(self):
self.auth_client = Client()
self.auth_client.force_login(PostCachePageTests.user)
def test_correct_cache_work(s... | class PostCachePageTests(TestCase):
@classmethod
| def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user("dslatsis")
def setUp(self):
self.auth_client = Client()
self.auth_client.force_login(PostCachePageTests.user)
def test_correct_cache_work(self):
"""Проверка корректности работы кеша."""... | from django.core.cache import cache
from django.test import Client, TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from posts.models import Post
User = get_user_model()
class PostCachePageTests(TestCase):
@classmethod
| 55 | 64 | 191 | 12 | 43 | DmitriyL02/hw05_final | posts/tests/test_cache.py | Python | PostCachePageTests | PostCachePageTests | 11 | 48 | 11 | 13 | 07354020e67a795796a97bf81a7f2e14884ac46b | bigcode/the-stack | train |
dc19a162b813aba95aec96e8 | train | function | def parser():
basic_desc = "Plot summary of performance results for VIO pipeline."
main_parser = argparse.ArgumentParser(description="{}".format(basic_desc))
input_options = main_parser.add_argument_group("input options")
input_options.add_argument(
"vio_results_path", help="Path to the **YAML**... | def parser():
| basic_desc = "Plot summary of performance results for VIO pipeline."
main_parser = argparse.ArgumentParser(description="{}".format(basic_desc))
input_options = main_parser.add_argument_group("input options")
input_options.add_argument(
"vio_results_path", help="Path to the **YAML** file containi... | #!/usr/bin/env python
import os
import sys
import argparse
import argcomplete
import csv
from ruamel import yaml
import glog as log
# This is to avoid using tkinter
import matplotlib
matplotlib.use('Agg')
import evaluation.tools as evt
def parser():
| 60 | 64 | 135 | 3 | 56 | MIT-SPARK/spark_vio_evaluation | evaluation/tools/performance_summary.py | Python | parser | parser | 19 | 29 | 19 | 19 | fffac16133b18d6cc920ca14a8df151decf6010c | bigcode/the-stack | train |
0e414e687c17ffd361b115e4 | train | function | def write_vio_results_summary(results, vio_results_summary_path):
# Get APE.
ATE_mean = results['absolute_errors'].stats['mean']
ATE_rmse = results['absolute_errors'].stats['rmse']
# Get RPE for smallest segments.
#assert(len(results['relative_errors']) > 0)
#RPE_mean = results['relative_errors'... | def write_vio_results_summary(results, vio_results_summary_path):
# Get APE.
| ATE_mean = results['absolute_errors'].stats['mean']
ATE_rmse = results['absolute_errors'].stats['rmse']
# Get RPE for smallest segments.
#assert(len(results['relative_errors']) > 0)
#RPE_mean = results['relative_errors'][0]['mean']
#RPE_rmse = results['relative_errors'][0]['rmse']
# Generate... | .yaml")
input_options.add_argument(
"vio_results_summary_path", help="Path to the **CSV** file containing the VIO summary results.",
default="./results/V1_01_easy/S/results_summary.csv")
return main_parser
def write_vio_results_summary(results, vio_results_summary_path):
# Get APE.
| 69 | 69 | 231 | 19 | 49 | MIT-SPARK/spark_vio_evaluation | evaluation/tools/performance_summary.py | Python | write_vio_results_summary | write_vio_results_summary | 31 | 47 | 31 | 32 | df778b7be7a0ef964a52b068a194c7bed7d0ff51 | bigcode/the-stack | train |
ff6fbb0e2a04bc587431a252 | train | function | def main(vio_results_path, vio_results_summary_path):
# Read vio results yaml file.
log.info("Reading VIO results from: %s" % vio_results_path)
if os.path.exists(vio_results_path):
with open(vio_results_path,'r') as input:
results = yaml.load(input, Loader=yaml.Loader)
write_... | def main(vio_results_path, vio_results_summary_path):
# Read vio results yaml file.
| log.info("Reading VIO results from: %s" % vio_results_path)
if os.path.exists(vio_results_path):
with open(vio_results_path,'r') as input:
results = yaml.load(input, Loader=yaml.Loader)
write_vio_results_summary(results, vio_results_summary_path)
return True
else:
... | writer = csv.DictWriter(vio_results_summary_file, fieldnames=performance_metrics)
writer.writeheader()
writer.writerow({'ATE_mean': ATE_mean, 'ATE_rmse': ATE_rmse})
def main(vio_results_path, vio_results_summary_path):
# Read vio results yaml file.
| 64 | 64 | 116 | 20 | 44 | MIT-SPARK/spark_vio_evaluation | evaluation/tools/performance_summary.py | Python | main | main | 49 | 59 | 49 | 50 | 91667dcab7a1e48e858eab33aa71e86d4b1462f0 | bigcode/the-stack | train |
7bcc75b679aea4bd321a3abd | train | class | class GroupSelectionDialog(QtWidgets.QDialog):
""" Contains the logic for group selection dialog.
"""
def __init__(self, experiment, parent, handler):
QtWidgets.QDialog.__init__(self, parent)
self.ui = Ui_groupSelectionDialog()
self.ui.setupUi(self)
self.handler = handler
... | class GroupSelectionDialog(QtWidgets.QDialog):
| """ Contains the logic for group selection dialog.
"""
def __init__(self, experiment, parent, handler):
QtWidgets.QDialog.__init__(self, parent)
self.ui = Ui_groupSelectionDialog()
self.ui.setupUi(self)
self.handler = handler
subjects = experiment.subjects.keys()
... | """ Contains a class for logic of the group selection dialog.
"""
import logging
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from meggie.utilities.dialogs.groupSelectionDialogUi import Ui_groupSelectionDialog
from meggie.utilities.messaging import exc_messagebox
from meggie.utilities.validators import valid... | 76 | 208 | 694 | 9 | 66 | Teekuningas/meggie | meggie/utilities/dialogs/groupSelectionDialogMain.py | Python | GroupSelectionDialog | GroupSelectionDialog | 14 | 86 | 14 | 14 | 5fdb9e13cbae8ceea46ef1122781c6329324212d | bigcode/the-stack | train |
0e51636080afa0a42d4a0895 | train | class | class AssociateRouteTableRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive... | class AssociateRouteTableRequest:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class AssociateRouteTableRequest:
| 34 | 235 | 786 | 6 | 27 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-vpc/huaweicloudsdkvpc/v2/model/associate_route_table_request.py | Python | AssociateRouteTableRequest | AssociateRouteTableRequest | 11 | 138 | 11 | 13 | d3d24d0cd4a44b55425935727fa0f452df452373 | bigcode/the-stack | train |
96bc66f69c6e7b8876a5c3f1 | train | function | @bot.on(ChatAction)
@errors_handler
async def ANTI_SPAMBOT(welcm):
try:
''' Ban a recently joined user if it
matches the spammer checking algorithm. '''
if not ANTI_SPAMBOT:
return
if welcm.user_joined or welcm.user_added:
adder = None
ignore = ... | @bot.on(ChatAction)
@errors_handler
async def ANTI_SPAMBOT(welcm):
| try:
''' Ban a recently joined user if it
matches the spammer checking algorithm. '''
if not ANTI_SPAMBOT:
return
if welcm.user_joined or welcm.user_added:
adder = None
ignore = False
users = None
if welcm.user_added:
... | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
''' A module for helping ban group join spammers. '''
from asyncio import sleep
from requests import get
from teletho... | 179 | 256 | 1,189 | 21 | 157 | AnggiFn21/AFn21 | userbot/modules/anti_spambot.py | Python | ANTI_SPAMBOT | ANTI_SPAMBOT | 21 | 182 | 21 | 23 | 4153c0c4d4fdf6321e87934620acd3082ad2b060 | bigcode/the-stack | train |
d87ca5546013305ab3f4409e | train | class | class CmdLister(Commande):
"""Commande 'lister'"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "lister", "list")
self.nom_categorie = "objets"
self.schema = ""
self.aide_courte = "liste les objets en vente"
self.aide_lon... | class CmdLister(Commande):
| """Commande 'lister'"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "lister", "list")
self.nom_categorie = "objets"
self.schema = ""
self.aide_courte = "liste les objets en vente"
self.aide_longue = \
"Cette comma... | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant la commande 'lister'."""
from primaires.interpreteur.commande.commande import Commande
class CmdLister(Commande):
| 64 | 64 | 183 | 7 | 56 | vlegoff/tsunami | src/primaires/commerce/commandes/lister/__init__.py | Python | CmdLister | CmdLister | 35 | 55 | 35 | 36 | c4d68475b468be5cb6f4ce534a277f6486ba0f28 | bigcode/the-stack | train |
8cf0f5491472620c8f8c067b | train | function | def CandidatusSaccharibacteriaBacterium4787(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new inst... | def CandidatusSaccharibacteriaBacterium4787(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
| """Return new instance of the Candidatus Saccharibacteria bacterium 47-87 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preproc... | Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedG... | 186 | 186 | 620 | 85 | 100 | AnacletoLAB/ensmallen_graph | bindings/python/ensmallen/datasets/string/candidatussaccharibacteriabacterium4787.py | Python | CandidatusSaccharibacteriaBacterium4787 | CandidatusSaccharibacteriaBacterium4787 | 30 | 104 | 30 | 39 | e7f0605026e6396ae05e1cd18b8f8861e202906a | bigcode/the-stack | train |
6127ff28edc4f0620396bccf | train | function | def run_to_file(time_, timeUnits, run, channels_, segments, runIndx, fileName):
out_folder_name = 'runs_output'
f = open(os.path.join(os.getcwd(), out_folder_name, fileName.split('.')[0]+'_Run-'+str(runIndx)+'.'+fileName.split('.')[1], 'w'))
titleRow = 'Time ('+timeUnits+')'
for i in channels_:
... | def run_to_file(time_, timeUnits, run, channels_, segments, runIndx, fileName):
| out_folder_name = 'runs_output'
f = open(os.path.join(os.getcwd(), out_folder_name, fileName.split('.')[0]+'_Run-'+str(runIndx)+'.'+fileName.split('.')[1], 'w'))
titleRow = 'Time ('+timeUnits+')'
for i in channels_:
#titleRow += ' '+channels[i]+'('+runUnits[i].replace(' ', '')+')'
titleR... | j in range(segments):
channel_temp.append(run_channel[j*totalSamples:(j+1)*totalSamples])
data_mV_segmented.append(channel_temp)
return data_mV_segmented
def run_to_file(time_, timeUnits, run, channels_, segments, runIndx, fileName):
| 64 | 64 | 210 | 22 | 41 | michael11892/picoscopeDataLogger | data_processing_macros.py | Python | run_to_file | run_to_file | 37 | 52 | 37 | 37 | 74b0597ca78f7a9d08c126040eee689b63454549 | bigcode/the-stack | train |
63286cce81b54f2899573bf1 | train | function | def clear_file(fileName):
ls = listdir()
for file in ls:
if file.split('_') == fileName.split('.')[0] and file.split('.')[1] == filename.split('.')[1]:
'''f = open(file, 'w')
f.close()'''
os.remove(file)
| def clear_file(fileName):
| ls = listdir()
for file in ls:
if file.split('_') == fileName.split('.')[0] and file.split('.')[1] == filename.split('.')[1]:
'''f = open(file, 'w')
f.close()'''
os.remove(file)
| n')
for element in range(len(run[-1][segment])):
outLine = ''
for channel in range(len(run)):
outLine += ' '+str(run[channel][segment][element])
f.write(str(time_[element])+outLine+'\n')
f.close()
def clear_file(fileName):
| 64 | 64 | 63 | 6 | 58 | michael11892/picoscopeDataLogger | data_processing_macros.py | Python | clear_file | clear_file | 54 | 60 | 54 | 54 | a780323fbc98724f0b56066bb0f7599376693576 | bigcode/the-stack | train |
5fd16f032b78a34899c5d95c | train | function | def run_to_mV(chandle, status, run, channels_, cranges_, totalSamples, segments):
data_mV_segmented = []
for i in range(len(channels_)):
run_channel = adc_to_mV(chandle, status, run[i], cranges_[i])
channel_temp = []
for j in range(segments):
channel_temp.append(run_channel[j... | def run_to_mV(chandle, status, run, channels_, cranges_, totalSamples, segments):
| data_mV_segmented = []
for i in range(len(channels_)):
run_channel = adc_to_mV(chandle, status, run[i], cranges_[i])
channel_temp = []
for j in range(segments):
channel_temp.append(run_channel[j*totalSamples:(j+1)*totalSamples])
data_mV_segmented.append(channel_temp)
... | segment isnt an array
temp += adc2mV(segment, crange, maxADC)
except:
temp += adc2mV(buffer, crange, maxADC)
return temp
def run_to_mV(chandle, status, run, channels_, cranges_, totalSamples, segments):
| 64 | 64 | 110 | 22 | 41 | michael11892/picoscopeDataLogger | data_processing_macros.py | Python | run_to_mV | run_to_mV | 27 | 35 | 27 | 27 | 6f1e088fcbd9a8aa0bb9d0ea55305afe05b02131 | bigcode/the-stack | train |
e886a1437ed68210e6c2ce4d | train | function | def adc_to_mV(chandle, status, buffer, crange):
# find maximum ADC count value
maxADC = ctypes.c_int16()
status["maximumValue"] = ps.ps2000aMaximumValue(chandle, ctypes.byref(maxADC))
assert_pico_ok(status["maximumValue"])
# convert ADC counts data to mV
temp = []
try:
for segment i... | def adc_to_mV(chandle, status, buffer, crange):
# find maximum ADC count value
| maxADC = ctypes.c_int16()
status["maximumValue"] = ps.ps2000aMaximumValue(chandle, ctypes.byref(maxADC))
assert_pico_ok(status["maximumValue"])
# convert ADC counts data to mV
temp = []
try:
for segment in buffer:
check = len(segment) #Will create an exception if segment isn... | 2000a import ps2000a as ps
from picosdk.functions import adc2mV, assert_pico_ok
channels = ['A', 'B', 'C', 'D']
def adc_to_mV(chandle, status, buffer, crange):
# find maximum ADC count value
| 64 | 64 | 142 | 23 | 41 | michael11892/picoscopeDataLogger | data_processing_macros.py | Python | adc_to_mV | adc_to_mV | 10 | 25 | 10 | 11 | f0d3a78210ff3ced16bcc0f46b5f4b1f08dde4e4 | bigcode/the-stack | train |
03c76f2b185cf2f5e147483d | train | class | class CoupledTimeIntegratorBase(timeintegrator.TimeIntegratorBase):
"""
Base class for coupled 2D-3D time integrators
Provides common functionality for updating diagnostic fields etc.
"""
def __init__(self, solver):
"""
:arg solver: :class:`.FlowSolver` object
"""
se... | class CoupledTimeIntegratorBase(timeintegrator.TimeIntegratorBase):
| """
Base class for coupled 2D-3D time integrators
Provides common functionality for updating diagnostic fields etc.
"""
def __init__(self, solver):
"""
:arg solver: :class:`.FlowSolver` object
"""
self.solver = solver
self.options = solver.options
sel... | """
Time integrators for solving coupled 2D-3D system of equations.
"""
from .utility import *
from . import timeintegrator
from .log import *
from . import rungekutta
from abc import ABC, abstractproperty
import numpy
class CoupledTimeIntegratorBase(timeintegrator.TimeIntegratorBase):
| 66 | 256 | 1,120 | 13 | 52 | thetisproject/cofs | thetis/coupled_timeintegrator.py | Python | CoupledTimeIntegratorBase | CoupledTimeIntegratorBase | 12 | 127 | 12 | 12 | 33ce8e18a7e9e204c4fbe5d5e26139eaf468e9f7 | bigcode/the-stack | train |
a0f1c5bef3047b9856da8bc2 | train | class | class CoupledTwoStageRK(CoupledTimeIntegrator):
"""
Coupled time integrator based on SSPRK(2,2) scheme
This ALE time integration method uses SSPRK(2,2) scheme to advance the 3D
equations and a compatible implicit Trapezoid method to advance the 2D
equations. Backward Euler scheme is used for vertic... | class CoupledTwoStageRK(CoupledTimeIntegrator):
| """
Coupled time integrator based on SSPRK(2,2) scheme
This ALE time integration method uses SSPRK(2,2) scheme to advance the 3D
equations and a compatible implicit Trapezoid method to advance the 2D
equations. Backward Euler scheme is used for vertical diffusion.
"""
integrator_2d = rungek... | _limiter_for_velocity:
self.solver.uv_limiter.apply(self.fields.uv_3d)
if self.options.use_implicit_vertical_diffusion:
self._update_2d_coupling()
self._update_baroclinicity()
self._update_turbulence(t)
if self.options.solve_salinity:
... | 256 | 256 | 1,531 | 12 | 244 | thetisproject/cofs | thetis/coupled_timeintegrator.py | Python | CoupledTwoStageRK | CoupledTwoStageRK | 563 | 710 | 563 | 563 | daf77dca97cd1ff33f88671d39204fe88e8a5bc6 | bigcode/the-stack | train |
9eb83c477916507fd48459c5 | train | class | class CoupledTimeIntegrator(CoupledTimeIntegratorBase, ABC):
"""
Base class of mode-split time integrators that use 2D, 3D and implicit 3D
time integrators.
"""
@abstractproperty
def integrator_2d(self):
"""time integrator for 2D equations"""
pass
@abstractproperty
def i... | class CoupledTimeIntegrator(CoupledTimeIntegratorBase, ABC):
| """
Base class of mode-split time integrators that use 2D, 3D and implicit 3D
time integrators.
"""
@abstractproperty
def integrator_2d(self):
"""time integrator for 2D equations"""
pass
@abstractproperty
def integrator_3d(self):
"""time integrator for explicit 3... | do_2d_coupling=False,
do_vert_diffusion=False,
do_ale_update=False,
do_stab_params=False,
do_turbulence=False):
"""Default routine for updating all... | 256 | 256 | 3,150 | 14 | 242 | thetisproject/cofs | thetis/coupled_timeintegrator.py | Python | CoupledTimeIntegrator | CoupledTimeIntegrator | 130 | 395 | 130 | 130 | 8b3577db88ecbc6dbe1d469b0da79292d7aa9f0a | bigcode/the-stack | train |
ef0bbc4f6d28d7f9d7fb45df | train | class | class CoupledLeapFrogAM3(CoupledTimeIntegrator):
"""
Leap-Frog Adams-Moulton 3 time integrator for coupled 2D-3D problem
This is an ALE time integrator.
Implementation follows the SLIM time integrator by Karna et al (2013)
Karna, et al. (2013). A baroclinic discontinuous Galerkin finite element
... | class CoupledLeapFrogAM3(CoupledTimeIntegrator):
| """
Leap-Frog Adams-Moulton 3 time integrator for coupled 2D-3D problem
This is an ALE time integrator.
Implementation follows the SLIM time integrator by Karna et al (2013)
Karna, et al. (2013). A baroclinic discontinuous Galerkin finite element
model for coastal flows. Ocean Modelling, 61(0)... | esteppers.mom_impl.initialize(self.fields.uv_3d)
if self.options.solve_salinity:
self.timesteppers.salt_expl.initialize(self.fields.salt_3d)
if self.options.use_implicit_vertical_diffusion:
self.timesteppers.salt_impl.initialize(self.fields.salt_3d)
if self.option... | 256 | 256 | 1,736 | 14 | 241 | thetisproject/cofs | thetis/coupled_timeintegrator.py | Python | CoupledLeapFrogAM3 | CoupledLeapFrogAM3 | 398 | 560 | 398 | 398 | 1e6141a3608796130ee5eb4fa84b05e56e0b55c1 | bigcode/the-stack | train |
27810dc882d76c5952c594f5 | train | class | class DuplicatedChannelError(RaidenRecoverableError):
"""Raised if someone tries to create a channel that already exists."""
| class DuplicatedChannelError(RaidenRecoverableError):
| """Raised if someone tries to create a channel that already exists."""
| """
class EthNodeInterfaceError(RaidenError):
"""Raised when the underlying ETH node does not support an rpc interface"""
class AddressWithoutCode(RaidenError):
"""Raised on attempt to execute contract on address without a code."""
class DuplicatedChannelError(RaidenRecoverableError):
| 63 | 64 | 27 | 13 | 50 | tirkarthi/raiden | raiden/exceptions.py | Python | DuplicatedChannelError | DuplicatedChannelError | 252 | 253 | 252 | 252 | 826fb829ca8c1dea43c8134a904765d6ff2a83f3 | bigcode/the-stack | train |
67dd4f22b70f6e57b077471f | train | class | class UserDepositNotConfigured(RaidenRecoverableError):
"""Raised when trying to perform operations on a user deposit contract but none has been
configured for the Raiden node.
"""
| class UserDepositNotConfigured(RaidenRecoverableError):
| """Raised when trying to perform operations on a user deposit contract but none has been
configured for the Raiden node.
"""
| SyncMaxTimeoutReached(RaidenRecoverableError):
"""Raised if processing the matrix response takes longer than the poll timeout."""
class ConfigurationError(RaidenError):
"""Raised when there is something wrong with the provided Raiden Configuration/arguments"""
class UserDepositNotConfigured(RaidenRecoverableE... | 64 | 64 | 40 | 12 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | UserDepositNotConfigured | UserDepositNotConfigured | 391 | 394 | 391 | 391 | b8ca5af07a238d0260b423ebfd1e9b6b4e347280 | bigcode/the-stack | train |
dbdf8d1876b5bbbb7fa3d847 | train | class | class DepositMismatch(RaidenRecoverableError):
"""Raised when the requested deposit is lower than actual channel deposit
Used when a *user* tries to deposit a given amount of tokens in a channel,
but the on-chain amount is already higher.
"""
| class DepositMismatch(RaidenRecoverableError):
| """Raised when the requested deposit is lower than actual channel deposit
Used when a *user* tries to deposit a given amount of tokens in a channel,
but the on-chain amount is already higher.
"""
|
class DepositOverLimit(RaidenError):
"""Raised when the requested deposit is over the limit
Used when a *user* tries to deposit a given amount of token in a channel,
but the amount is over the testing limit.
"""
class DepositMismatch(RaidenRecoverableError):
| 63 | 64 | 55 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | DepositMismatch | DepositMismatch | 135 | 140 | 135 | 135 | 805d192c0f0bc83ea6f335a8c3a7f3710671022d | bigcode/the-stack | train |
aabb9ee7155db130cfccd07c | train | class | class ServiceRequestFailed(RaidenError):
"""Raised when a request to one of the raiden services fails."""
| class ServiceRequestFailed(RaidenError):
| """Raised when a request to one of the raiden services fails."""
| when an argument needs to be always non-zero,
violation of this condition is not a BrokenPreconditionError, but
RaidenValidationError.
This exception can also be used when preconditions are not satisfied
on another Raiden node.
"""
class ServiceRequestFailed(RaidenError):
| 63 | 64 | 24 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | ServiceRequestFailed | ServiceRequestFailed | 326 | 327 | 326 | 326 | bf80fad2c106383b9d4763383075ed7ee3522946 | bigcode/the-stack | train |
1daecbec2e84d6ebb5f0e8b8 | train | class | class MintFailed(RaidenError):
"""Raised when an attempt to mint a testnet token failed."""
| class MintFailed(RaidenError):
| """Raised when an attempt to mint a testnet token failed."""
| raiden node is not capable of mediating this payment, or the
FeeSchedule is outdated/inconsistent."""
class TokenNetworkDeprecated(RaidenError):
"""Raised when the token network proxy safety switch
is turned on (i.e deprecated).
"""
class MintFailed(RaidenError):
| 63 | 64 | 22 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | MintFailed | MintFailed | 375 | 376 | 375 | 375 | eed8e992ed44a8a0e8b53c4bc03a856efae2a04f | bigcode/the-stack | train |
968850a25b7d43bd3436ea2f | train | class | class WithdrawMismatch(RaidenRecoverableError):
"""Raised when the requested withdraw is larger than actual channel balance."""
| class WithdrawMismatch(RaidenRecoverableError):
| """Raised when the requested withdraw is larger than actual channel balance."""
| when a *user* tries to deposit a given amount of tokens in a channel,
but the on-chain amount is already higher.
"""
class InvalidChannelID(RaidenError):
"""Raised when the user provided value is not a channel id."""
class WithdrawMismatch(RaidenRecoverableError):
| 63 | 64 | 24 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | WithdrawMismatch | WithdrawMismatch | 147 | 148 | 147 | 147 | b2f0ac5c54e2a3e809a5c13b8e9f54e66685e42a | bigcode/the-stack | train |
0577fbdc1c1038674a7dfc02 | train | class | class ServiceRequestIOURejected(PFSReturnedError):
"""Raised when a service request fails due to a problem with the iou."""
| class ServiceRequestIOURejected(PFSReturnedError):
| """Raised when a service request fails due to a problem with the iou."""
| ("error_code", 0),
error_details=response_json.get("error_details"),
)
if PFSError.is_iou_rejected(error_params["error_code"]):
return ServiceRequestIOURejected(**error_params)
return cls(**error_params)
class ServiceRequestIOURejected(PFSReturnedError):
| 64 | 64 | 28 | 11 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | ServiceRequestIOURejected | ServiceRequestIOURejected | 358 | 359 | 358 | 358 | c488afd519965391044f5c6d8e80a72d8eba15a2 | bigcode/the-stack | train |
2ad718b2bc0802e3c52a5f9e | train | class | class InsufficientFunds(RaidenError):
"""Raised when provided account doesn't have token funds to complete the
requested deposit.
Used when a *user* tries to deposit a given amount of token in a channel,
but his account doesn't have enough funds to pay for the deposit.
"""
| class InsufficientFunds(RaidenError):
| """Raised when provided account doesn't have token funds to complete the
requested deposit.
Used when a *user* tries to deposit a given amount of token in a channel,
but his account doesn't have enough funds to pay for the deposit.
"""
| Error sometimes, and we want to differentiate our own exceptions
from those.
"""
class PaymentConflict(RaidenRecoverableError):
"""Raised when there is another payment with the same identifier but the
attributes of the payment don't match.
"""
class InsufficientFunds(RaidenError):
| 63 | 64 | 62 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InsufficientFunds | InsufficientFunds | 118 | 124 | 118 | 118 | 62cb6cd702ebff049dbe905c29b7595ed32711cd | bigcode/the-stack | train |
d3c958ce5ff457d378cc3dcd | train | class | class InsufficientGasReserve(RaidenError):
"""Raised when an action cannot be done because the available balance
is not sufficient for the lifecycles of all active channels.
"""
| class InsufficientGasReserve(RaidenError):
| """Raised when an action cannot be done because the available balance
is not sufficient for the lifecycles of all active channels.
"""
| ReplacementTransactionUnderpriced(RaidenError):
"""Raised when a replacement transaction is rejected by the blockchain"""
class EthereumNonceTooLow(RaidenUnrecoverableError):
"""Raised when a new transaction is sent with a nonce that has been used already."""
class InsufficientGasReserve(RaidenError):
| 63 | 64 | 40 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | InsufficientGasReserve | InsufficientGasReserve | 295 | 298 | 295 | 295 | 205216c92eb74f2dea9875a05c0af1376d9934ca | bigcode/the-stack | train |
725749ec364bbcb7fde1eebb | train | class | class MatrixSyncMaxTimeoutReached(RaidenRecoverableError):
"""Raised if processing the matrix response takes longer than the poll timeout."""
| class MatrixSyncMaxTimeoutReached(RaidenRecoverableError):
| """Raised if processing the matrix response takes longer than the poll timeout."""
| i.e deprecated).
"""
class MintFailed(RaidenError):
"""Raised when an attempt to mint a testnet token failed."""
class SerializationError(RaidenError):
"""Invalid data are to be (de-)serialized."""
class MatrixSyncMaxTimeoutReached(RaidenRecoverableError):
| 63 | 64 | 28 | 13 | 50 | tirkarthi/raiden | raiden/exceptions.py | Python | MatrixSyncMaxTimeoutReached | MatrixSyncMaxTimeoutReached | 383 | 384 | 383 | 383 | 122882344a418033319530650c06ee001a56ff0a | bigcode/the-stack | train |
e832bcd07c0d42de4fd90549 | train | class | class InvalidChannelID(RaidenError):
"""Raised when the user provided value is not a channel id."""
| class InvalidChannelID(RaidenError):
| """Raised when the user provided value is not a channel id."""
| DepositMismatch(RaidenRecoverableError):
"""Raised when the requested deposit is lower than actual channel deposit
Used when a *user* tries to deposit a given amount of tokens in a channel,
but the on-chain amount is already higher.
"""
class InvalidChannelID(RaidenError):
| 63 | 64 | 23 | 9 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidChannelID | InvalidChannelID | 143 | 144 | 143 | 143 | 99618d4c80867d185e3d85785d7dd163a52df57e | bigcode/the-stack | train |
a22cf9ca03cdfee1019c3f2e | train | class | class BrokenPreconditionError(RaidenError):
"""Raised when the chain doesn't satisfy transaction preconditions
that proxies check at the specified block.
This exception should be used, when the proxy already sees that,
on the specified block, due to the blockchain state, an assert
or a revert in th... | class BrokenPreconditionError(RaidenError):
| """Raised when the chain doesn't satisfy transaction preconditions
that proxies check at the specified block.
This exception should be used, when the proxy already sees that,
on the specified block, due to the blockchain state, an assert
or a revert in the smart contract would be hit for the trigge... | channels.
"""
class InsufficientEth(RaidenError):
"""Raised when an on-chain action failed because we could not pay for
the gas. (The case we try to avoid with `InsufficientGasReserve`
exceptions.)
"""
class BrokenPreconditionError(RaidenError):
| 63 | 64 | 150 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | BrokenPreconditionError | BrokenPreconditionError | 308 | 323 | 308 | 308 | 7a9feb814ddb0609f5e1fbdb539af42470a3086a | bigcode/the-stack | train |
38013a87d0abc7797018a904 | train | class | class APIServerPortInUseError(RaidenError):
"""Raised when API server port is already in use"""
| class APIServerPortInUseError(RaidenError):
| """Raised when API server port is already in use"""
| idenRecoverableError):
"""Raised if someone tries to create a channel that already exists."""
class UnexpectedChannelState(RaidenRecoverableError):
"""Raised if an operation is attempted on a channel while it is in an unexpected state."""
class APIServerPortInUseError(RaidenError):
| 63 | 64 | 25 | 13 | 50 | tirkarthi/raiden | raiden/exceptions.py | Python | APIServerPortInUseError | APIServerPortInUseError | 260 | 261 | 260 | 260 | 43bb70ba6f6431d8e0341c698362e730e68f2128 | bigcode/the-stack | train |
9f760ecf19d643cc8e6d42df | train | class | class InvalidSecret(RaidenError):
"""Raised when the user provided value is not a valid secret."""
| class InvalidSecret(RaidenError):
| """Raised when the user provided value is not a valid secret."""
| is not binary or it is not 20 bytes long.
Exception used to enforce the sandwich encoding for python APIs. The
internal address representation used by Raiden is binary, the binary
address must be validated at the edges before calling internal functions.
"""
class InvalidSecret(RaidenError):
| 63 | 64 | 22 | 8 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | InvalidSecret | InvalidSecret | 170 | 171 | 170 | 170 | 34c535c549ff05dcc54f01fe300714a7c68d0f15 | bigcode/the-stack | train |
67ef05ffda4b75223ac17deb | train | class | class ReplacementTransactionUnderpriced(RaidenError):
"""Raised when a replacement transaction is rejected by the blockchain"""
| class ReplacementTransactionUnderpriced(RaidenError):
| """Raised when a replacement transaction is rejected by the blockchain"""
|
than STATE_PRUNING_AFTER_BLOCKS blocks
"""
class InvalidNumberInput(RaidenError):
"""Raised when the user provided an invalid number"""
class TransportError(RaidenError):
"""Raised when a transport encounters an unexpected error"""
class ReplacementTransactionUnderpriced(RaidenError):
| 64 | 64 | 23 | 10 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | ReplacementTransactionUnderpriced | ReplacementTransactionUnderpriced | 287 | 288 | 287 | 287 | 8fa6ce411d8ac2efe5259992fab56b7940edb646 | bigcode/the-stack | train |
b4aff31b4f8182eadce1a667 | train | class | class AddressWithoutCode(RaidenError):
"""Raised on attempt to execute contract on address without a code."""
| class AddressWithoutCode(RaidenError):
| """Raised on attempt to execute contract on address without a code."""
| Limit(RaidenError):
"""Raised when an invalid channel participant
deposit limit is passed to the token network registry proxy.
"""
class EthNodeInterfaceError(RaidenError):
"""Raised when the underlying ETH node does not support an rpc interface"""
class AddressWithoutCode(RaidenError):
| 64 | 64 | 23 | 9 | 55 | tirkarthi/raiden | raiden/exceptions.py | Python | AddressWithoutCode | AddressWithoutCode | 248 | 249 | 248 | 248 | d843de84b61a4b11d2e74ba0ca12bb7cfe84862f | bigcode/the-stack | train |
eb4267457179233729533daf | train | class | class EthNodeInterfaceError(RaidenError):
"""Raised when the underlying ETH node does not support an rpc interface"""
| class EthNodeInterfaceError(RaidenError):
| """Raised when the underlying ETH node does not support an rpc interface"""
| invalid token network deposit
limit is passed to the token network registry proxy.
"""
class InvalidChannelParticipantDepositLimit(RaidenError):
"""Raised when an invalid channel participant
deposit limit is passed to the token network registry proxy.
"""
class EthNodeInterfaceError(RaidenError):... | 63 | 64 | 25 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | EthNodeInterfaceError | EthNodeInterfaceError | 244 | 245 | 244 | 244 | 8c2a850c2fa17a790758a9fbef1d91899ca95ff0 | bigcode/the-stack | train |
6645dfc479806a2bdd984d60 | train | class | class UnexpectedChannelState(RaidenRecoverableError):
"""Raised if an operation is attempted on a channel while it is in an unexpected state."""
| class UnexpectedChannelState(RaidenRecoverableError):
| """Raised if an operation is attempted on a channel while it is in an unexpected state."""
| """
class AddressWithoutCode(RaidenError):
"""Raised on attempt to execute contract on address without a code."""
class DuplicatedChannelError(RaidenRecoverableError):
"""Raised if someone tries to create a channel that already exists."""
class UnexpectedChannelState(RaidenRecoverableError):
| 63 | 64 | 30 | 11 | 52 | tirkarthi/raiden | raiden/exceptions.py | Python | UnexpectedChannelState | UnexpectedChannelState | 256 | 257 | 256 | 256 | 02fd3ad3e50ba38f6de8fc56474fe16439ecf5ca | bigcode/the-stack | train |
a5e4364e511bc2e92cf95ed0 | train | class | class AlreadyRegisteredTokenAddress(RaidenError):
"""Raised when the token address in already registered with the given network."""
| class AlreadyRegisteredTokenAddress(RaidenError):
| """Raised when the token address in already registered with the given network."""
| an action that requires two different partners"""
class UnknownTokenAddress(RaidenError):
"""Raised when the token address in unknown."""
class TokenNotRegistered(RaidenError):
"""Raised if there is no token network for token used when opening a channel"""
class AlreadyRegisteredTokenAddress(RaidenError):
| 64 | 64 | 25 | 10 | 54 | tirkarthi/raiden | raiden/exceptions.py | Python | AlreadyRegisteredTokenAddress | AlreadyRegisteredTokenAddress | 216 | 217 | 216 | 216 | 19f8f968c1c9f6db537b31e15806b227c6f2de54 | bigcode/the-stack | train |
967acbd1b4fbaa0aae7506a5 | train | class | class PaymentConflict(RaidenRecoverableError):
"""Raised when there is another payment with the same identifier but the
attributes of the payment don't match.
"""
| class PaymentConflict(RaidenRecoverableError):
| """Raised when there is another payment with the same identifier but the
attributes of the payment don't match.
"""
| RaidenValidationError is considered as a
recoverable error.
We prefer this exception over ValueError because libraries (e.g. web3.py)
raise ValueError sometimes, and we want to differentiate our own exceptions
from those.
"""
class PaymentConflict(RaidenRecoverableError):
| 63 | 64 | 35 | 10 | 53 | tirkarthi/raiden | raiden/exceptions.py | Python | PaymentConflict | PaymentConflict | 112 | 115 | 112 | 112 | c543dc028860b4e221043710c4230a81ccf1370c | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.