blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95f78468fe1ec0aa3371467e6b3d89ae58b5cc31 | [
"super(EncoderAttention, self).__init__()\nresnet = _load_resnet101_model()\nmodules = list(resnet.children())[:-2]\nself.resnet = nn.Sequential(*modules)\nself.adaptive_pool = nn.AdaptiveAvgPool2d((14, 14))\nfor param in self.resnet.parameters():\n param.requires_grad = False",
"features = self.resnet(imgs)\n... | <|body_start_0|>
super(EncoderAttention, self).__init__()
resnet = _load_resnet101_model()
modules = list(resnet.children())[:-2]
self.resnet = nn.Sequential(*modules)
self.adaptive_pool = nn.AdaptiveAvgPool2d((14, 14))
for param in self.resnet.parameters():
p... | CNN encoder. | EncoderAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderAttention:
"""CNN encoder."""
def __init__(self):
"""Initialize encoder. Args: encoded_img_size (int): Output size. attention_method (str): Attention method to use. Supported attentions methods are "ByPixel" and "ByChannel"."""
<|body_0|>
def forward(self, imgs):
... | stack_v2_sparse_classes_36k_train_030800 | 4,057 | permissive | [
{
"docstring": "Initialize encoder. Args: encoded_img_size (int): Output size. attention_method (str): Attention method to use. Supported attentions methods are \"ByPixel\" and \"ByChannel\".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Forward propagation. Args: im... | 3 | stack_v2_sparse_classes_30k_train_001157 | Implement the Python class `EncoderAttention` described below.
Class description:
CNN encoder.
Method signatures and docstrings:
- def __init__(self): Initialize encoder. Args: encoded_img_size (int): Output size. attention_method (str): Attention method to use. Supported attentions methods are "ByPixel" and "ByChann... | Implement the Python class `EncoderAttention` described below.
Class description:
CNN encoder.
Method signatures and docstrings:
- def __init__(self): Initialize encoder. Args: encoded_img_size (int): Output size. attention_method (str): Attention method to use. Supported attentions methods are "ByPixel" and "ByChann... | fdebb153ae6d5dc9ed61968e474949f4d067e6e4 | <|skeleton|>
class EncoderAttention:
"""CNN encoder."""
def __init__(self):
"""Initialize encoder. Args: encoded_img_size (int): Output size. attention_method (str): Attention method to use. Supported attentions methods are "ByPixel" and "ByChannel"."""
<|body_0|>
def forward(self, imgs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderAttention:
"""CNN encoder."""
def __init__(self):
"""Initialize encoder. Args: encoded_img_size (int): Output size. attention_method (str): Attention method to use. Supported attentions methods are "ByPixel" and "ByChannel"."""
super(EncoderAttention, self).__init__()
resne... | the_stack_v2_python_sparse | models/encoder.py | SarahAlkhateeb/Image-Captioning-with-Different-Decoders | train | 0 |
269fe995e823f8a01f6c561d2b476b449a47f3e6 | [
"if ip_version not in (u'ip4', u'ip6'):\n raise ValueError(u'IP version is not in correct format')\ncmd = u'adl_allowlist_enable_disable'\nerr_msg = f\"Failed to add ADL allowlist on interface {interface} on host {node[u'host']}\"\nargs = dict(sw_if_index=Topology.get_interface_sw_index(node, interface), fib_id=... | <|body_start_0|>
if ip_version not in (u'ip4', u'ip6'):
raise ValueError(u'IP version is not in correct format')
cmd = u'adl_allowlist_enable_disable'
err_msg = f"Failed to add ADL allowlist on interface {interface} on host {node[u'host']}"
args = dict(sw_if_index=Topology.ge... | ADL utilities. | Adl | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adl:
"""ADL utilities."""
def adl_add_allowlist_entry(node, interface, ip_version, fib_id, default_adl=0):
"""Add adl allowlisted entry. :param node: Node to add ADL allowlist on. :param interface: Interface of the node where the ADL is added. :param ip_version: IP version. 'ip4' and... | stack_v2_sparse_classes_36k_train_030801 | 3,282 | permissive | [
{
"docstring": "Add adl allowlisted entry. :param node: Node to add ADL allowlist on. :param interface: Interface of the node where the ADL is added. :param ip_version: IP version. 'ip4' and 'ip6' are valid values. :param fib_id: Specify the fib table ID. :param default_adl: 1 => enable non-ip4, non-ip6 filtrat... | 2 | stack_v2_sparse_classes_30k_train_005488 | Implement the Python class `Adl` described below.
Class description:
ADL utilities.
Method signatures and docstrings:
- def adl_add_allowlist_entry(node, interface, ip_version, fib_id, default_adl=0): Add adl allowlisted entry. :param node: Node to add ADL allowlist on. :param interface: Interface of the node where t... | Implement the Python class `Adl` described below.
Class description:
ADL utilities.
Method signatures and docstrings:
- def adl_add_allowlist_entry(node, interface, ip_version, fib_id, default_adl=0): Add adl allowlisted entry. :param node: Node to add ADL allowlist on. :param interface: Interface of the node where t... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class Adl:
"""ADL utilities."""
def adl_add_allowlist_entry(node, interface, ip_version, fib_id, default_adl=0):
"""Add adl allowlisted entry. :param node: Node to add ADL allowlist on. :param interface: Interface of the node where the ADL is added. :param ip_version: IP version. 'ip4' and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adl:
"""ADL utilities."""
def adl_add_allowlist_entry(node, interface, ip_version, fib_id, default_adl=0):
"""Add adl allowlisted entry. :param node: Node to add ADL allowlist on. :param interface: Interface of the node where the ADL is added. :param ip_version: IP version. 'ip4' and 'ip6' are va... | the_stack_v2_python_sparse | resources/libraries/python/Adl.py | FDio/csit | train | 28 |
dc8d7ef1307ebead8175433115dee5ed5fae4521 | [
"self.spliter = []\nself.train_data = train_data\nself.target = target\nself.fit(self.train_data, self.target)",
"counter = Counter(elements)\nprobs = [counter[c] / len(elements) for c in elements]\nreturn -sum((p * np.log(p) for p in probs))",
"try:\n spliter = self.find_the_min_spilter(train_data, target)\... | <|body_start_0|>
self.spliter = []
self.train_data = train_data
self.target = target
self.fit(self.train_data, self.target)
<|end_body_0|>
<|body_start_1|>
counter = Counter(elements)
probs = [counter[c] / len(elements) for c in elements]
return -sum((p * np.log(... | Tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tree:
def __init__(self, train_data, target):
""":param train_data: 训练集 :param target: 训练标签"""
<|body_0|>
def entropy(self, elements):
"""算信息熵 :param elements: :return:"""
<|body_1|>
def fit(self, train_data, target):
"""用训练集训练,会找到所有的合适切分点并记录到sel... | stack_v2_sparse_classes_36k_train_030802 | 4,182 | no_license | [
{
"docstring": ":param train_data: 训练集 :param target: 训练标签",
"name": "__init__",
"signature": "def __init__(self, train_data, target)"
},
{
"docstring": "算信息熵 :param elements: :return:",
"name": "entropy",
"signature": "def entropy(self, elements)"
},
{
"docstring": "用训练集训练,会找到所有... | 5 | stack_v2_sparse_classes_30k_train_009476 | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def __init__(self, train_data, target): :param train_data: 训练集 :param target: 训练标签
- def entropy(self, elements): 算信息熵 :param elements: :return:
- def fit(self, train_data, target): 用训练集... | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def __init__(self, train_data, target): :param train_data: 训练集 :param target: 训练标签
- def entropy(self, elements): 算信息熵 :param elements: :return:
- def fit(self, train_data, target): 用训练集... | 8e0fa8a8e55d37ca94b0f150d22e8ea6d7fd0317 | <|skeleton|>
class Tree:
def __init__(self, train_data, target):
""":param train_data: 训练集 :param target: 训练标签"""
<|body_0|>
def entropy(self, elements):
"""算信息熵 :param elements: :return:"""
<|body_1|>
def fit(self, train_data, target):
"""用训练集训练,会找到所有的合适切分点并记录到sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tree:
def __init__(self, train_data, target):
""":param train_data: 训练集 :param target: 训练标签"""
self.spliter = []
self.train_data = train_data
self.target = target
self.fit(self.train_data, self.target)
def entropy(self, elements):
"""算信息熵 :param elements: :... | the_stack_v2_python_sparse | day3/homework1.py | bfmq/nlp | train | 0 | |
39b2110306ffbf176b3fc00fee4e37696b58f44c | [
"firsts, others = data\nstat = self.ChiSquared(firsts) + self.ChiSquared(others)\nreturn stat",
"hist = thinkstats2.Hist(lengths)\nobserved = np.array(hist.Freqs(self.values))\nexpected = self.expected_probs * len(lengths)\nstat = sum((observed - expected) ** 2 / expected)\nreturn stat",
"firsts, others = self.... | <|body_start_0|>
firsts, others = data
stat = self.ChiSquared(firsts) + self.ChiSquared(others)
return stat
<|end_body_0|>
<|body_start_1|>
hist = thinkstats2.Hist(lengths)
observed = np.array(hist.Freqs(self.values))
expected = self.expected_probs * len(lengths)
... | Tests difference in pregnancy length using a chi-squared statistic. | PregLengthTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PregLengthTest:
"""Tests difference in pregnancy length using a chi-squared statistic."""
def TestStatistic(self, data):
"""Computes the test statistic. data: pair of lists of pregnancy lengths"""
<|body_0|>
def ChiSquared(self, lengths):
"""Computes the chi-squa... | stack_v2_sparse_classes_36k_train_030803 | 10,162 | permissive | [
{
"docstring": "Computes the test statistic. data: pair of lists of pregnancy lengths",
"name": "TestStatistic",
"signature": "def TestStatistic(self, data)"
},
{
"docstring": "Computes the chi-squared statistic. lengths: sequence of lengths returns: float",
"name": "ChiSquared",
"signat... | 4 | stack_v2_sparse_classes_30k_train_009654 | Implement the Python class `PregLengthTest` described below.
Class description:
Tests difference in pregnancy length using a chi-squared statistic.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: pair of lists of pregnancy lengths
- def ChiSquared(self, lengths): ... | Implement the Python class `PregLengthTest` described below.
Class description:
Tests difference in pregnancy length using a chi-squared statistic.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: pair of lists of pregnancy lengths
- def ChiSquared(self, lengths): ... | 30a85d5137db95e01461ad21519bc1bdf294044b | <|skeleton|>
class PregLengthTest:
"""Tests difference in pregnancy length using a chi-squared statistic."""
def TestStatistic(self, data):
"""Computes the test statistic. data: pair of lists of pregnancy lengths"""
<|body_0|>
def ChiSquared(self, lengths):
"""Computes the chi-squa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PregLengthTest:
"""Tests difference in pregnancy length using a chi-squared statistic."""
def TestStatistic(self, data):
"""Computes the test statistic. data: pair of lists of pregnancy lengths"""
firsts, others = data
stat = self.ChiSquared(firsts) + self.ChiSquared(others)
... | the_stack_v2_python_sparse | CompStats/hypothesis.py | sunny2309/scipy_conf_notebooks | train | 2 |
4b5138967c1399153a6017b312fffa391e733bdc | [
"cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))\ncube.remove_coord('forecast_period')\nself.time_points = np.arange(1487311200, 1487354400, 3600).astype(np.int64)\nself.cube = add_coordinate(cube, self.time_points, 'time', dtype=np... | <|body_start_0|>
cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))
cube.remove_coord('forecast_period')
self.time_points = np.arange(1487311200, 1487354400, 3600).astype(np.int64)
self.cube = add_coordinate... | Test wrapper for iris cube extraction at desired times. | Test_extract_cube_at_time | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_extract_cube_at_time:
"""Test wrapper for iris cube extraction at desired times."""
def setUp(self):
"""Set up a test cube with several time points"""
<|body_0|>
def test_valid_time(self):
"""Case for a time that is available within the diagnostic cube."""
... | stack_v2_sparse_classes_36k_train_030804 | 19,622 | permissive | [
{
"docstring": "Set up a test cube with several time points",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Case for a time that is available within the diagnostic cube.",
"name": "test_valid_time",
"signature": "def test_valid_time(self)"
},
{
"docstring": "... | 4 | null | Implement the Python class `Test_extract_cube_at_time` described below.
Class description:
Test wrapper for iris cube extraction at desired times.
Method signatures and docstrings:
- def setUp(self): Set up a test cube with several time points
- def test_valid_time(self): Case for a time that is available within the ... | Implement the Python class `Test_extract_cube_at_time` described below.
Class description:
Test wrapper for iris cube extraction at desired times.
Method signatures and docstrings:
- def setUp(self): Set up a test cube with several time points
- def test_valid_time(self): Case for a time that is available within the ... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_extract_cube_at_time:
"""Test wrapper for iris cube extraction at desired times."""
def setUp(self):
"""Set up a test cube with several time points"""
<|body_0|>
def test_valid_time(self):
"""Case for a time that is available within the diagnostic cube."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_extract_cube_at_time:
"""Test wrapper for iris cube extraction at desired times."""
def setUp(self):
"""Set up a test cube with several time points"""
cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))
... | the_stack_v2_python_sparse | improver_tests/utilities/temporal/test_temporal.py | metoppv/improver | train | 101 |
7c04a9e08f70dc91de18611bf736587c0c9dcd67 | [
"if isinstance(var, Quantity):\n self.var = var\nelse:\n raise ValueError('var must be a Quantity')\nself.name = name\nself.measure_count = 0\nself.units = self.var.units",
"prenoise_value = container.observe(value, key=key)\nassert prenoise_value.dimensionality == self.units.dimensionality\nmeasurement = N... | <|body_start_0|>
if isinstance(var, Quantity):
self.var = var
else:
raise ValueError('var must be a Quantity')
self.name = name
self.measure_count = 0
self.units = self.var.units
<|end_body_0|>
<|body_start_1|>
prenoise_value = container.observe(v... | Measure a property of one container with Gaussian error | Measurer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Measurer:
"""Measure a property of one container with Gaussian error"""
def __init__(self, name, var):
"""Parameters ---------- name: str Name of the LiquidTransfer device. Will be used in assigning names to each volume transfer sample var: Distribution (volume units) Error in volume... | stack_v2_sparse_classes_36k_train_030805 | 11,805 | permissive | [
{
"docstring": "Parameters ---------- name: str Name of the LiquidTransfer device. Will be used in assigning names to each volume transfer sample var: Distribution (volume units) Error in volume drawn. TODO: allow variance to be drawn from a prior",
"name": "__init__",
"signature": "def __init__(self, n... | 3 | stack_v2_sparse_classes_30k_train_011564 | Implement the Python class `Measurer` described below.
Class description:
Measure a property of one container with Gaussian error
Method signatures and docstrings:
- def __init__(self, name, var): Parameters ---------- name: str Name of the LiquidTransfer device. Will be used in assigning names to each volume transfe... | Implement the Python class `Measurer` described below.
Class description:
Measure a property of one container with Gaussian error
Method signatures and docstrings:
- def __init__(self, name, var): Parameters ---------- name: str Name of the LiquidTransfer device. Will be used in assigning names to each volume transfe... | b6c03b900d34f8a5570c51af22ef2d589da2a050 | <|skeleton|>
class Measurer:
"""Measure a property of one container with Gaussian error"""
def __init__(self, name, var):
"""Parameters ---------- name: str Name of the LiquidTransfer device. Will be used in assigning names to each volume transfer sample var: Distribution (volume units) Error in volume... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Measurer:
"""Measure a property of one container with Gaussian error"""
def __init__(self, name, var):
"""Parameters ---------- name: str Name of the LiquidTransfer device. Will be used in assigning names to each volume transfer sample var: Distribution (volume units) Error in volume drawn. TODO:... | the_stack_v2_python_sparse | bellini/devices.py | choderalab/bellini | train | 4 |
e864327a837f59188aa01a10d763c0827779d836 | [
"self.is_training = is_training\nself.use_bfloat16 = use_bfloat16\nself.saturate_uint8 = saturate_uint8\nself.scale_and_center = scale_and_center\nself.use_default_augment = use_default_augment\nself.batch_size = batch_size\nself.augmentation = augmentation\nself.num_classes = NUM_CLASSES\nself.num_images = SPLIT_T... | <|body_start_0|>
self.is_training = is_training
self.use_bfloat16 = use_bfloat16
self.saturate_uint8 = saturate_uint8
self.scale_and_center = scale_and_center
self.use_default_augment = use_default_augment
self.batch_size = batch_size
self.augmentation = augmentat... | Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation data is in the same format bu... | ImageNetInput | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The... | stack_v2_sparse_classes_36k_train_030806 | 16,434 | permissive | [
{
"docstring": "Initialize ImageNetInput. Args: split: data split, either 'train' or 'test'. is_training: `bool` for whether the input is for training. batch_size: The global batch size to use. augmentation: callable which performs augmentation on images. use_bfloat16: If True, use bfloat16 precision; else use ... | 4 | stack_v2_sparse_classes_30k_train_013795 | Implement the Python class `ImageNetInput` described below.
Class description:
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-0000... | Implement the Python class `ImageNetInput` described below.
Class description:
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-0000... | f8b7f184b91d6144927c7c4b34f7d9c0313f8a39 | <|skeleton|>
class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation d... | the_stack_v2_python_sparse | imagenet/datasets/imagenet.py | paulxiong/fixmatch | train | 1 |
b5fccf2bd2997aa01ff98409b3da657ba559e7da | [
"super().__init__()\nself.mlp_query = nn.Linear(query_dim, att_dim, bias=False)\nself.mlp_key = nn.Linear(key_dim, att_dim, bias=False)",
"query = query.unsqueeze(1)\nquery = self.mlp_query(query)\nkeys = self.mlp_key(keys).transpose(1, 2)\nenergy = torch.bmm(query, keys)\nif key_len is not None:\n mask = []\n... | <|body_start_0|>
super().__init__()
self.mlp_query = nn.Linear(query_dim, att_dim, bias=False)
self.mlp_key = nn.Linear(key_dim, att_dim, bias=False)
<|end_body_0|>
<|body_start_1|>
query = query.unsqueeze(1)
query = self.mlp_query(query)
keys = self.mlp_key(keys).transp... | dotAttn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dotAttn:
def __init__(self, query_dim, key_dim, att_dim):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, key_len=None, scaling=1.0):
""":param query: previou... | stack_v2_sparse_classes_36k_train_030807 | 10,910 | no_license | [
{
"docstring": "basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim",
"name": "__init__",
"signature": "def __init__(self, query_dim, key_dim, att_dim)"
},
{
"docstring": ":param query: previous hidden state of the decoder, in shape (batch, dec_d... | 2 | stack_v2_sparse_classes_30k_train_010863 | Implement the Python class `dotAttn` described below.
Class description:
Implement the dotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- def forward(self, query, ke... | Implement the Python class `dotAttn` described below.
Class description:
Implement the dotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- def forward(self, query, ke... | d354b06afbd8ae8172314af524f4f6cdeded363c | <|skeleton|>
class dotAttn:
def __init__(self, query_dim, key_dim, att_dim):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, key_len=None, scaling=1.0):
""":param query: previou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dotAttn:
def __init__(self, query_dim, key_dim, att_dim):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
super().__init__()
self.mlp_query = nn.Linear(query_dim, att_dim, bias=False)
self.mlp_key = nn.Linear(key_dim, ... | the_stack_v2_python_sparse | style_word_alignment/self-attn-mask/model.py | ihungalexhsu/Text-style-tranfer | train | 1 | |
35e3dc56730612e0299c97f3686bb8e0ba37a776 | [
"super().__init__(name=name)\nself.pool = pool\nself._queue = message_queue\nself.daemon = True\nself.idle = True\nself.started = time.time()",
"if self.pool.name:\n time_in_queue = time.time() - queueing_time\n THREADPOOL_QUEUEING_TIME.RecordEvent(time_in_queue, fields=[self.pool.name])\n start_time = t... | <|body_start_0|>
super().__init__(name=name)
self.pool = pool
self._queue = message_queue
self.daemon = True
self.idle = True
self.started = time.time()
<|end_body_0|>
<|body_start_1|>
if self.pool.name:
time_in_queue = time.time() - queueing_time
... | The workers used in the ThreadPool class. | _WorkerThread | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _WorkerThread:
"""The workers used in the ThreadPool class."""
def __init__(self, message_queue, pool, name):
"""Initializer. This creates a new worker object for the ThreadPool class. Args: message_queue: A queue.Queue object used by the ThreadPool class to communicate with the work... | stack_v2_sparse_classes_36k_train_030808 | 18,809 | permissive | [
{
"docstring": "Initializer. This creates a new worker object for the ThreadPool class. Args: message_queue: A queue.Queue object used by the ThreadPool class to communicate with the workers. When a new task arrives, the ThreadPool notifies the workers by putting a message into this queue that has the format (t... | 4 | stack_v2_sparse_classes_30k_test_001151 | Implement the Python class `_WorkerThread` described below.
Class description:
The workers used in the ThreadPool class.
Method signatures and docstrings:
- def __init__(self, message_queue, pool, name): Initializer. This creates a new worker object for the ThreadPool class. Args: message_queue: A queue.Queue object ... | Implement the Python class `_WorkerThread` described below.
Class description:
The workers used in the ThreadPool class.
Method signatures and docstrings:
- def __init__(self, message_queue, pool, name): Initializer. This creates a new worker object for the ThreadPool class. Args: message_queue: A queue.Queue object ... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class _WorkerThread:
"""The workers used in the ThreadPool class."""
def __init__(self, message_queue, pool, name):
"""Initializer. This creates a new worker object for the ThreadPool class. Args: message_queue: A queue.Queue object used by the ThreadPool class to communicate with the work... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _WorkerThread:
"""The workers used in the ThreadPool class."""
def __init__(self, message_queue, pool, name):
"""Initializer. This creates a new worker object for the ThreadPool class. Args: message_queue: A queue.Queue object used by the ThreadPool class to communicate with the workers. When a n... | the_stack_v2_python_sparse | grr/server/grr_response_server/threadpool.py | google/grr | train | 4,683 |
f068a05ac79b3e12972bc2787e57ff4255d0ea92 | [
"self.mm = slt()\nself.urla = ParamsTest().selenium_url_sempreprod()\nself.url = f'{self.urla}scp/inventory/optlist'",
"driver = self.mm.sem_login()\nsleep(2)\ndriver.get(self.url)\nreturn driver"
] | <|body_start_0|>
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url = f'{self.urla}scp/inventory/optlist'
<|end_body_0|>
<|body_start_1|>
driver = self.mm.sem_login()
sleep(2)
driver.get(self.url)
return driver
<|end_body_1|>
| SemOptList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
<|body_0|>
def optlist(self):
"""定义driver"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url... | stack_v2_sparse_classes_36k_train_030809 | 850 | no_license | [
{
"docstring": "运营管理系统 供应链管理 库存管理 ----- 拣货单页面",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "定义driver",
"name": "optlist",
"signature": "def optlist(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018807 | Implement the Python class `SemOptList` described below.
Class description:
Implement the SemOptList class.
Method signatures and docstrings:
- def __init__(self): 运营管理系统 供应链管理 库存管理 ----- 拣货单页面
- def optlist(self): 定义driver | Implement the Python class `SemOptList` described below.
Class description:
Implement the SemOptList class.
Method signatures and docstrings:
- def __init__(self): 运营管理系统 供应链管理 库存管理 ----- 拣货单页面
- def optlist(self): 定义driver
<|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货... | 97f9e4f286d017ee39ceeae0c730f1c4971499e7 | <|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
<|body_0|>
def optlist(self):
"""定义driver"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url = f'{self.urla}scp/inventory/optlist'
def optlist(self):
"""定义driver"""
driver = self.mm.sem_login()
slee... | the_stack_v2_python_sparse | setting/optlist/optlist.py | qq183727918/selenium_ui | train | 0 | |
d97408bd1a9da1afde336964e916ee3dc933bf7b | [
"self.vocab = vocab\npunct = '[:punct:]' + '\"\\'ˊ"〃ײ᳓″״‶˶ʺ“”˝'\nnum_like = '\\\\d+(?:[.,]\\\\d(?![.,]?[0-9])|(?![.,]?[0-9]))?'\nsep = f\"\\\\d{punct}'\\\\n[:space:]\"\ndefault = f\"[^{sep}]+(?:['ˊ](?=[[:alpha:]]|$))?\"\nexceptions = '|'.join(TOKENIZER_EXCEPTIONS)\nacronym = '[A-Z][A-Z0-9]*[.](?=[A-Z0-9])'\nself.wo... | <|body_start_0|>
self.vocab = vocab
punct = '[:punct:]' + '"\'ˊ"〃ײ᳓″״‶˶ʺ“”˝'
num_like = '\\d+(?:[.,]\\d(?![.,]?[0-9])|(?![.,]?[0-9]))?'
sep = f"\\d{punct}'\\n[:space:]"
default = f"[^{sep}]+(?:['ˊ](?=[[:alpha:]]|$))?"
exceptions = '|'.join(TOKENIZER_EXCEPTIONS)
ac... | EDSTokenizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EDSTokenizer:
def __init__(self, vocab: Vocab) -> None:
"""Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead of ["ACR5"] - newlines: " " -> [" ", " ", " "] instead of [" "] and should be around 5-6 times faster... | stack_v2_sparse_classes_36k_train_030810 | 3,908 | permissive | [
{
"docstring": "Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: \"ACR5\" -> [\"ACR\", \"5\"] instead of [\"ACR5\"] - newlines: \" \" -> [\" \", \" \", \" \"] instead of [\" \"] and should be around 5-6 times faster than its standard French counterpart. Parameters... | 2 | stack_v2_sparse_classes_30k_train_015375 | Implement the Python class `EDSTokenizer` described below.
Class description:
Implement the EDSTokenizer class.
Method signatures and docstrings:
- def __init__(self, vocab: Vocab) -> None: Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead ... | Implement the Python class `EDSTokenizer` described below.
Class description:
Implement the EDSTokenizer class.
Method signatures and docstrings:
- def __init__(self, vocab: Vocab) -> None: Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead ... | 57e86002735097342b16c8f3edb770a231f4d526 | <|skeleton|>
class EDSTokenizer:
def __init__(self, vocab: Vocab) -> None:
"""Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead of ["ACR5"] - newlines: " " -> [" ", " ", " "] instead of [" "] and should be around 5-6 times faster... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EDSTokenizer:
def __init__(self, vocab: Vocab) -> None:
"""Tokenizer class for French clinical documents. It better handles tokenization around: - numbers: "ACR5" -> ["ACR", "5"] instead of ["ACR5"] - newlines: " " -> [" ", " ", " "] instead of [" "] and should be around 5-6 times faster than its stan... | the_stack_v2_python_sparse | edsnlp/language.py | aphp/edsnlp | train | 98 | |
07d13d6180b8f5f5b3ce1fa1deb4027067541ff7 | [
"self._API_GETTERS['id', 'name', 'description'] = events.get_event if version.parse(connection.web_version) >= version.parse('11.3.0200') else objects.get_object_info\nif id is None and name is None:\n raise AttributeError(\"Please specify either 'name' or 'id' parameter in the constructor.\")\nif id is None:\n ... | <|body_start_0|>
self._API_GETTERS['id', 'name', 'description'] = events.get_event if version.parse(connection.web_version) >= version.parse('11.3.0200') else objects.get_object_info
if id is None and name is None:
raise AttributeError("Please specify either 'name' or 'id' parameter in the c... | Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions | Event | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
"""Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions"""
def __init__(self, connection: Connection, id: str=None, name: str=None):
"""Initialize the Event o... | stack_v2_sparse_classes_36k_train_030811 | 3,584 | permissive | [
{
"docstring": "Initialize the Event object, populates it with I-Server data. Specify either `id` or `name`. When `id` is provided (not `None`), `name` is omitted. Args: connection: MicroStrategy connection object returned by `connection.Connection()`. id: Event ID name: Event name",
"name": "__init__",
... | 2 | null | Implement the Python class `Event` described below.
Class description:
Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions
Method signatures and docstrings:
- def __init__(self, connection: Connecti... | Implement the Python class `Event` described below.
Class description:
Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions
Method signatures and docstrings:
- def __init__(self, connection: Connecti... | 720af7e673ed62462366d1406e5ea14792461e94 | <|skeleton|>
class Event:
"""Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions"""
def __init__(self, connection: Connection, id: str=None, name: str=None):
"""Initialize the Event o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Event:
"""Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions"""
def __init__(self, connection: Connection, id: str=None, name: str=None):
"""Initialize the Event object, popula... | the_stack_v2_python_sparse | mstrio/distribution_services/event.py | paulbailey/mstrio-py | train | 0 |
61d961f54b90fa54a30ac1574a0b875fd5b3a6b9 | [
"split = None\nfirst_sep_match_index = min([n for n, i in enumerate(seps) if i in stem], default=None)\nfirst_sep_match = seps[first_sep_match_index] if first_sep_match_index != None else None\nsplit = stem.split(first_sep_match)\n_lensplit = len(split)\nif _lensplit == 0:\n sID, position = (split[0], 0)\nelif l... | <|body_start_0|>
split = None
first_sep_match_index = min([n for n, i in enumerate(seps) if i in stem], default=None)
first_sep_match = seps[first_sep_match_index] if first_sep_match_index != None else None
split = stem.split(first_sep_match)
_lensplit = len(split)
if _le... | Collection of method for parsing a filename | ParserMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserMethods:
"""Collection of method for parsing a filename"""
def parse_filestem_to_sid_and_pos(stem: str, seps=('_', ' ', '-')):
"""Parser for the filenames -> finds SampleID and sample position Parameters ---------- # ramanfile_stem : str # The filepath which the is parsed seps ... | stack_v2_sparse_classes_36k_train_030812 | 7,682 | permissive | [
{
"docstring": "Parser for the filenames -> finds SampleID and sample position Parameters ---------- # ramanfile_stem : str # The filepath which the is parsed seps : tuple of str default ordered collection of seperators tried for split default : ('_', ' ', '-') Returns ------- tuple of strings Collection of str... | 3 | stack_v2_sparse_classes_30k_train_016798 | Implement the Python class `ParserMethods` described below.
Class description:
Collection of method for parsing a filename
Method signatures and docstrings:
- def parse_filestem_to_sid_and_pos(stem: str, seps=('_', ' ', '-')): Parser for the filenames -> finds SampleID and sample position Parameters ---------- # rama... | Implement the Python class `ParserMethods` described below.
Class description:
Collection of method for parsing a filename
Method signatures and docstrings:
- def parse_filestem_to_sid_and_pos(stem: str, seps=('_', ' ', '-')): Parser for the filenames -> finds SampleID and sample position Parameters ---------- # rama... | 1a9d8107bf44f2ce568d7c9a93613823a1863d51 | <|skeleton|>
class ParserMethods:
"""Collection of method for parsing a filename"""
def parse_filestem_to_sid_and_pos(stem: str, seps=('_', ' ', '-')):
"""Parser for the filenames -> finds SampleID and sample position Parameters ---------- # ramanfile_stem : str # The filepath which the is parsed seps ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParserMethods:
"""Collection of method for parsing a filename"""
def parse_filestem_to_sid_and_pos(stem: str, seps=('_', ' ', '-')):
"""Parser for the filenames -> finds SampleID and sample position Parameters ---------- # ramanfile_stem : str # The filepath which the is parsed seps : tuple of st... | the_stack_v2_python_sparse | src/raman_fitting/indexer/filename_parser.py | RassoulTOP/raman-fitting | train | 0 |
907f6cc2c0f1fa5aed9e3fabd99b2a87bb4fbf9e | [
"n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\ndp = [0] * n\ndp[0] = nums[0]\ndp[1] = max(nums[0], nums[1])\nfor i in range(2, n):\n dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\nreturn dp[n - 1]",
"n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\nfirst, second... | <|body_start_0|>
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[n - 1]
<... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def rob(self, nums: List[int]) -> int:
"""动态规划。"""
<|body_0|>
def rob_2(self, nums: List[int]) -> int:
"""动态规划(优化空间)。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
if n == 0:
return 0
if ... | stack_v2_sparse_classes_36k_train_030813 | 3,605 | no_license | [
{
"docstring": "动态规划。",
"name": "rob",
"signature": "def rob(self, nums: List[int]) -> int"
},
{
"docstring": "动态规划(优化空间)。",
"name": "rob_2",
"signature": "def rob_2(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_014877 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 动态规划。
- def rob_2(self, nums: List[int]) -> int: 动态规划(优化空间)。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 动态规划。
- def rob_2(self, nums: List[int]) -> int: 动态规划(优化空间)。
<|skeleton|>
class OfficialSolution:
def rob(self, nums:... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def rob(self, nums: List[int]) -> int:
"""动态规划。"""
<|body_0|>
def rob_2(self, nums: List[int]) -> int:
"""动态规划(优化空间)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def rob(self, nums: List[int]) -> int:
"""动态规划。"""
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
... | the_stack_v2_python_sparse | 0198_house-robber.py | Nigirimeshi/leetcode | train | 0 | |
712328b9342690f14a4a9983a8ae3fdc963e78ab | [
"for val in ['string', 1.5]:\n with self.subTest(x=1):\n self.assertRaises(TypeError, factorize, val)",
"for i in (-1, -10, -100):\n with self.subTest(x=2):\n self.assertRaises(ValueError, factorize, i)",
"for key, val in [(0, (0,)), (1, (1,))]:\n with self.subTest(x=3):\n self.ass... | <|body_start_0|>
for val in ['string', 1.5]:
with self.subTest(x=1):
self.assertRaises(TypeError, factorize, val)
<|end_body_0|>
<|body_start_1|>
for i in (-1, -10, -100):
with self.subTest(x=2):
self.assertRaises(ValueError, factorize, i)
<|end_b... | TestFactorize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFactorize:
def test_wrong_types_raise_exception(self):
"""test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5"""
<|body_0|>
def test_negative(self... | stack_v2_sparse_classes_36k_train_030814 | 3,111 | no_license | [
{
"docstring": "test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5",
"name": "test_wrong_types_raise_exception",
"signature": "def test_wrong_types_raise_exception(self)"
},
... | 6 | stack_v2_sparse_classes_30k_train_015363 | Implement the Python class `TestFactorize` described below.
Class description:
Implement the TestFactorize class.
Method signatures and docstrings:
- def test_wrong_types_raise_exception(self): test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение Typ... | Implement the Python class `TestFactorize` described below.
Class description:
Implement the TestFactorize class.
Method signatures and docstrings:
- def test_wrong_types_raise_exception(self): test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение Typ... | c1ff0d6fd4371a86b5f10e5220353eaa7e63d6ca | <|skeleton|>
class TestFactorize:
def test_wrong_types_raise_exception(self):
"""test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5"""
<|body_0|>
def test_negative(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFactorize:
def test_wrong_types_raise_exception(self):
"""test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5"""
for val in ['string', 1.5]:
with self.su... | the_stack_v2_python_sparse | course_2/week_01/06_factorize.py | flanker-d/coursera_python | train | 0 | |
3d723c4c908b2393b1cd891282bd5e4aa7c20fb5 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn X509CertificateAuthenticationMethodConfiguration()",
"from .authentication_method_configuration import AuthenticationMethodConfiguration\nfrom .authentication_method_target import AuthenticationMethodTarget\nfrom .x509_certificate_auth... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return X509CertificateAuthenticationMethodConfiguration()
<|end_body_0|>
<|body_start_1|>
from .authentication_method_configuration import AuthenticationMethodConfiguration
from .authentication... | X509CertificateAuthenticationMethodConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class X509CertificateAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> X509CertificateAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse nod... | stack_v2_sparse_classes_36k_train_030815 | 4,581 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: X509CertificateAuthenticationMethodConfiguration",
"name": "create_from_discriminator_value",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_000353 | Implement the Python class `X509CertificateAuthenticationMethodConfiguration` described below.
Class description:
Implement the X509CertificateAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> X509CertificateAuthen... | Implement the Python class `X509CertificateAuthenticationMethodConfiguration` described below.
Class description:
Implement the X509CertificateAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> X509CertificateAuthen... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class X509CertificateAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> X509CertificateAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse nod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class X509CertificateAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> X509CertificateAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to re... | the_stack_v2_python_sparse | msgraph/generated/models/x509_certificate_authentication_method_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8f137d008020c7ced4fbdc8729b2541b2c5b72f0 | [
"from __builtin__ import xrange\nif not head:\n return\n\ndef move(node):\n onode = node\n prev = None\n ppnode = None\n while node:\n ppnode = prev\n prev = node\n node = node.next\n prev.next = onode\n if ppnode:\n ppnode.next = None\n else:\n prev.next =... | <|body_start_0|>
from __builtin__ import xrange
if not head:
return
def move(node):
onode = node
prev = None
ppnode = None
while node:
ppnode = prev
prev = node
node = node.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode 這個太慢啦!!!"""
<|body_0|>
def rewrite(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030816 | 2,963 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode 這個太慢啦!!!",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rewrite",
"signature": "def rewrite(self, head, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode 這個太慢啦!!!
- def rewrite(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode 這個太慢啦!!!
- def rewrite(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|sk... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode 這個太慢啦!!!"""
<|body_0|>
def rewrite(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode 這個太慢啦!!!"""
from __builtin__ import xrange
if not head:
return
def move(node):
onode = node
prev = None
ppnode = None
whi... | the_stack_v2_python_sparse | co_ms/61_Rotate_List.py | vsdrun/lc_public | train | 6 | |
51a0c9cc95d3f3864e6729d51bc23eaa91f3340e | [
"self.clear()\nself.__plot()\nself._plt.legend(loc=self.LEGEND)\nself._plt.grid(self.SHOW_GRID)\nself._plt.axes.set_xlim(left=0)\nself._plt.axes.set_xlim(right=self._pitchTracker.length)\nself._plt.axes.set_ylim(bottom=self.Y_BOTTOM)\nself._plt.axes.set_ylim(top=self.Y_TOP)\nself._labelRefresh()",
"self._plt.plot... | <|body_start_0|>
self.clear()
self.__plot()
self._plt.legend(loc=self.LEGEND)
self._plt.grid(self.SHOW_GRID)
self._plt.axes.set_xlim(left=0)
self._plt.axes.set_xlim(right=self._pitchTracker.length)
self._plt.axes.set_ylim(bottom=self.Y_BOTTOM)
self._plt.ax... | Handles pitch tracking plots. | PitchPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PitchPlot:
"""Handles pitch tracking plots."""
def update(self):
"""Updates plot with latest data."""
<|body_0|>
def __plot(self):
"""Plot the different types of pitch data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.clear()
se... | stack_v2_sparse_classes_36k_train_030817 | 2,630 | no_license | [
{
"docstring": "Updates plot with latest data.",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Plot the different types of pitch data.",
"name": "__plot",
"signature": "def __plot(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017531 | Implement the Python class `PitchPlot` described below.
Class description:
Handles pitch tracking plots.
Method signatures and docstrings:
- def update(self): Updates plot with latest data.
- def __plot(self): Plot the different types of pitch data. | Implement the Python class `PitchPlot` described below.
Class description:
Handles pitch tracking plots.
Method signatures and docstrings:
- def update(self): Updates plot with latest data.
- def __plot(self): Plot the different types of pitch data.
<|skeleton|>
class PitchPlot:
"""Handles pitch tracking plots."... | 6d29e1e0b2335c90452a832373dcf3058cec33e9 | <|skeleton|>
class PitchPlot:
"""Handles pitch tracking plots."""
def update(self):
"""Updates plot with latest data."""
<|body_0|>
def __plot(self):
"""Plot the different types of pitch data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PitchPlot:
"""Handles pitch tracking plots."""
def update(self):
"""Updates plot with latest data."""
self.clear()
self.__plot()
self._plt.legend(loc=self.LEGEND)
self._plt.grid(self.SHOW_GRID)
self._plt.axes.set_xlim(left=0)
self._plt.axes.set_xlim... | the_stack_v2_python_sparse | emotionAnalyzer/plots/pitch.py | vkepuska/LivePitchTracking | train | 0 |
bbd9d12c80d38497ecdc27c6d45cda2400f2eb61 | [
"target = []\ni = 0\nwhile i < len(nums):\n if index[i] == i:\n target.append(nums[i])\n else:\n self.insert(target, index[i], nums[i])\n i += 1\nreturn target",
"i = 0\nnumInsert = num\nwhile i < len(target) - index:\n temp = target[index + i]\n target[index + i] = numInsert\n num... | <|body_start_0|>
target = []
i = 0
while i < len(nums):
if index[i] == i:
target.append(nums[i])
else:
self.insert(target, index[i], nums[i])
i += 1
return target
<|end_body_0|>
<|body_start_1|>
i = 0
nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
"""Time: O(n^2), where n = len(nums) Space: O(n), where n = len(nums)"""
<|body_0|>
def insert(self, target: List[int], index: int, num: int) -> None:
"""Time: O(n), where n = len(... | stack_v2_sparse_classes_36k_train_030818 | 1,002 | no_license | [
{
"docstring": "Time: O(n^2), where n = len(nums) Space: O(n), where n = len(nums)",
"name": "createTargetArray",
"signature": "def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]"
},
{
"docstring": "Time: O(n), where n = len(nums) Space: O(n), where n = len(nums)",
"... | 2 | stack_v2_sparse_classes_30k_train_011257 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: Time: O(n^2), where n = len(nums) Space: O(n), where n = len(nums)
- def insert(self, target: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: Time: O(n^2), where n = len(nums) Space: O(n), where n = len(nums)
- def insert(self, target: List[in... | b68f8a7b3cab871e86e58c7c9b49a7bf74453b53 | <|skeleton|>
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
"""Time: O(n^2), where n = len(nums) Space: O(n), where n = len(nums)"""
<|body_0|>
def insert(self, target: List[int], index: int, num: int) -> None:
"""Time: O(n), where n = len(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
"""Time: O(n^2), where n = len(nums) Space: O(n), where n = len(nums)"""
target = []
i = 0
while i < len(nums):
if index[i] == i:
target.append(nums[i])
... | the_stack_v2_python_sparse | Python Solutions/Easy/1389.py | rajpatel5/LeetCode | train | 0 | |
740fc092c741adec1a99efd2ba1edeb6747b5e91 | [
"super().__init__(framework=framework)\nassert schedule_timesteps > 0\nself.schedule_timesteps = schedule_timesteps\nself.initial_p = initial_p\nself.decay_rate = decay_rate",
"if self.framework == 'torch' and torch and isinstance(t, torch.Tensor):\n t = t.float()\nreturn self.initial_p * self.decay_rate ** (t... | <|body_start_0|>
super().__init__(framework=framework)
assert schedule_timesteps > 0
self.schedule_timesteps = schedule_timesteps
self.initial_p = initial_p
self.decay_rate = decay_rate
<|end_body_0|>
<|body_start_1|>
if self.framework == 'torch' and torch and isinstance... | Exponential decay schedule from `initial_p` to `final_p`. Reduces output over `schedule_timesteps`. After this many time steps always returns `final_p`. | ExponentialSchedule | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExponentialSchedule:
"""Exponential decay schedule from `initial_p` to `final_p`. Reduces output over `schedule_timesteps`. After this many time steps always returns `final_p`."""
def __init__(self, schedule_timesteps: int, framework: Optional[str]=None, initial_p: float=1.0, decay_rate: flo... | stack_v2_sparse_classes_36k_train_030819 | 1,829 | permissive | [
{
"docstring": "Initializes a ExponentialSchedule instance. Args: schedule_timesteps: Number of time steps for which to linearly anneal initial_p to final_p. framework: The framework descriptor string, e.g. \"tf\", \"torch\", or None. initial_p: Initial output value. decay_rate: The percentage of the original v... | 2 | null | Implement the Python class `ExponentialSchedule` described below.
Class description:
Exponential decay schedule from `initial_p` to `final_p`. Reduces output over `schedule_timesteps`. After this many time steps always returns `final_p`.
Method signatures and docstrings:
- def __init__(self, schedule_timesteps: int, ... | Implement the Python class `ExponentialSchedule` described below.
Class description:
Exponential decay schedule from `initial_p` to `final_p`. Reduces output over `schedule_timesteps`. After this many time steps always returns `final_p`.
Method signatures and docstrings:
- def __init__(self, schedule_timesteps: int, ... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class ExponentialSchedule:
"""Exponential decay schedule from `initial_p` to `final_p`. Reduces output over `schedule_timesteps`. After this many time steps always returns `final_p`."""
def __init__(self, schedule_timesteps: int, framework: Optional[str]=None, initial_p: float=1.0, decay_rate: flo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExponentialSchedule:
"""Exponential decay schedule from `initial_p` to `final_p`. Reduces output over `schedule_timesteps`. After this many time steps always returns `final_p`."""
def __init__(self, schedule_timesteps: int, framework: Optional[str]=None, initial_p: float=1.0, decay_rate: float=0.1):
... | the_stack_v2_python_sparse | rllib/utils/schedules/exponential_schedule.py | ray-project/ray | train | 29,482 |
6c4ffc78aedd145d5f26e8c08c48a762f1e1dffb | [
"self.variable_matcher = VariablePatternMatcher(variable_string)\nself.degree_matcher = NumberPatternMatcher(degree_string)\nself.term_matcher = NumberPatternMatcher(term_string)",
"term = monomial.get_total_degree()\nif not self.term_matcher.match(term):\n return True\nfor degree, variable in zip(monomial, va... | <|body_start_0|>
self.variable_matcher = VariablePatternMatcher(variable_string)
self.degree_matcher = NumberPatternMatcher(degree_string)
self.term_matcher = NumberPatternMatcher(term_string)
<|end_body_0|>
<|body_start_1|>
term = monomial.get_total_degree()
if not self.term_ma... | Filters out monomials based on their degree in particular variables and their overal degree. | DegreeFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DegreeFilter:
"""Filters out monomials based on their degree in particular variables and their overal degree."""
def __init__(self, variable_string, degree_string, term_string):
"""Creates a new DegreeFilter from the given parameters. This filter will filter OUT any monomials with de... | stack_v2_sparse_classes_36k_train_030820 | 29,454 | no_license | [
{
"docstring": "Creates a new DegreeFilter from the given parameters. This filter will filter OUT any monomials with degree as specified by degree_string in one of the variables as specified by variable_string with TOTAL degree as specified by term_string. Args: variable_string - '/' delimited list of variables... | 2 | stack_v2_sparse_classes_30k_train_001729 | Implement the Python class `DegreeFilter` described below.
Class description:
Filters out monomials based on their degree in particular variables and their overal degree.
Method signatures and docstrings:
- def __init__(self, variable_string, degree_string, term_string): Creates a new DegreeFilter from the given para... | Implement the Python class `DegreeFilter` described below.
Class description:
Filters out monomials based on their degree in particular variables and their overal degree.
Method signatures and docstrings:
- def __init__(self, variable_string, degree_string, term_string): Creates a new DegreeFilter from the given para... | eb413191f865968f6d6e76292bca09a94e08bef7 | <|skeleton|>
class DegreeFilter:
"""Filters out monomials based on their degree in particular variables and their overal degree."""
def __init__(self, variable_string, degree_string, term_string):
"""Creates a new DegreeFilter from the given parameters. This filter will filter OUT any monomials with de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DegreeFilter:
"""Filters out monomials based on their degree in particular variables and their overal degree."""
def __init__(self, variable_string, degree_string, term_string):
"""Creates a new DegreeFilter from the given parameters. This filter will filter OUT any monomials with degree as speci... | the_stack_v2_python_sparse | mbfit/polynomials/filters.py | agoetz/MB-Fit | train | 1 |
b658698b670d72a91e53e311eed5a5eaeb83727f | [
"for account in cloud_accounts:\n rc, rsp = cal.get_image_list(RwcalYang.YangData_RwProject_Project_CloudAccounts_CloudAccountList.from_dict(account.as_dict()))\n assert rc == RwTypes.RwStatus.SUCCESS\n if rsp is not None:\n for image in rsp.imageinfo_list:\n if random_image_name in image... | <|body_start_0|>
for account in cloud_accounts:
rc, rsp = cal.get_image_list(RwcalYang.YangData_RwProject_Project_CloudAccounts_CloudAccountList.from_dict(account.as_dict()))
assert rc == RwTypes.RwStatus.SUCCESS
if rsp is not None:
for image in rsp.imageinfo_... | TestNsrTeardown | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNsrTeardown:
def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal):
"""Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images"""
<|body_0|>
def test_terminate_nsr(self, rwvnfr_proxy, rwnsr_proxy... | stack_v2_sparse_classes_36k_train_030821 | 26,676 | no_license | [
{
"docstring": "Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images",
"name": "test_delete_embedded_images",
"signature": "def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal)"
},
{
"docstring": "Terminate the insta... | 3 | null | Implement the Python class `TestNsrTeardown` described below.
Class description:
Implement the TestNsrTeardown class.
Method signatures and docstrings:
- def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal): Deletes images embedded in VNF from VIM. It only deletes additional images, not the F... | Implement the Python class `TestNsrTeardown` described below.
Class description:
Implement the TestNsrTeardown class.
Method signatures and docstrings:
- def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal): Deletes images embedded in VNF from VIM. It only deletes additional images, not the F... | cdd0abe80a76d533d08a51c7970d8ded06624b7d | <|skeleton|>
class TestNsrTeardown:
def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal):
"""Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images"""
<|body_0|>
def test_terminate_nsr(self, rwvnfr_proxy, rwnsr_proxy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestNsrTeardown:
def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal):
"""Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images"""
for account in cloud_accounts:
rc, rsp = cal.get_image_list(RwcalYang.Ya... | the_stack_v2_python_sparse | osm/SO/rwlaunchpad/ra/pytest/ns/test_onboard.py | dennis-me/Pishahang | train | 2 | |
735b20bb667d6889b0d6c9437bcb726a54d7f9ae | [
"wind_u = set_up_variable_cube(np.full((10, 10), 2.1, dtype=np.float32), name='grid_eastward_wind', units='m s-1', spatial_grid='equalarea')\nwind_v = wind_u.copy(data=np.full((10, 10), 2.4, dtype=np.float32))\nwind_v.rename('grid_northward_wind')\nself.background_flow = iris.cube.CubeList([wind_u, wind_v])\nflow_d... | <|body_start_0|>
wind_u = set_up_variable_cube(np.full((10, 10), 2.1, dtype=np.float32), name='grid_eastward_wind', units='m s-1', spatial_grid='equalarea')
wind_v = wind_u.copy(data=np.full((10, 10), 2.4, dtype=np.float32))
wind_v.rename('grid_northward_wind')
self.background_flow = iri... | Test for the _perturb_background_flow private utility | Test__perturb_background_flow | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__perturb_background_flow:
"""Test for the _perturb_background_flow private utility"""
def setUp(self):
"""Set up input cubes"""
<|body_0|>
def test_basic(self):
"""Test function returns cubes with expected names"""
<|body_1|>
def test_values(sel... | stack_v2_sparse_classes_36k_train_030822 | 7,066 | permissive | [
{
"docstring": "Set up input cubes",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test function returns cubes with expected names",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test function returns expected values",
"name... | 5 | null | Implement the Python class `Test__perturb_background_flow` described below.
Class description:
Test for the _perturb_background_flow private utility
Method signatures and docstrings:
- def setUp(self): Set up input cubes
- def test_basic(self): Test function returns cubes with expected names
- def test_values(self): ... | Implement the Python class `Test__perturb_background_flow` described below.
Class description:
Test for the _perturb_background_flow private utility
Method signatures and docstrings:
- def setUp(self): Set up input cubes
- def test_basic(self): Test function returns cubes with expected names
- def test_values(self): ... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__perturb_background_flow:
"""Test for the _perturb_background_flow private utility"""
def setUp(self):
"""Set up input cubes"""
<|body_0|>
def test_basic(self):
"""Test function returns cubes with expected names"""
<|body_1|>
def test_values(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__perturb_background_flow:
"""Test for the _perturb_background_flow private utility"""
def setUp(self):
"""Set up input cubes"""
wind_u = set_up_variable_cube(np.full((10, 10), 2.1, dtype=np.float32), name='grid_eastward_wind', units='m s-1', spatial_grid='equalarea')
wind_v =... | the_stack_v2_python_sparse | improver_tests/nowcasting/optical_flow/test_utilities.py | metoppv/improver | train | 101 |
dde1af8e1b85a498b9306fdfcb5fb5de232cb59c | [
"param = {'imgPath': [{'name': '123', 'url': 'http://file.chinaylzl.com/test/userHead/2018/11/16/38acfc8085c249628beffed54bccb2c7.png'}, {'name': '456', 'url': 'http://file.chinaylzl.com/test/userHead/2018/11/16/38acfc8085c249628beffed54bccb2c7.png'}, {'name': '789', 'url': 'http://file.chinaylzl.com/test/userHead/... | <|body_start_0|>
param = {'imgPath': [{'name': '123', 'url': 'http://file.chinaylzl.com/test/userHead/2018/11/16/38acfc8085c249628beffed54bccb2c7.png'}, {'name': '456', 'url': 'http://file.chinaylzl.com/test/userHead/2018/11/16/38acfc8085c249628beffed54bccb2c7.png'}, {'name': '789', 'url': 'http://file.chinaylz... | TestGovernProduct | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGovernProduct:
def test_1_add_product(self):
"""【适老化】:添加产品"""
<|body_0|>
def test_2_get_product_list(self):
"""【适老化】:分页查询产品列表"""
<|body_1|>
def test_3_update_product(self):
"""【适老化】:编辑产品信息"""
<|body_2|>
def test_4_stop_start_prod... | stack_v2_sparse_classes_36k_train_030823 | 4,407 | no_license | [
{
"docstring": "【适老化】:添加产品",
"name": "test_1_add_product",
"signature": "def test_1_add_product(self)"
},
{
"docstring": "【适老化】:分页查询产品列表",
"name": "test_2_get_product_list",
"signature": "def test_2_get_product_list(self)"
},
{
"docstring": "【适老化】:编辑产品信息",
"name": "test_3_upd... | 5 | stack_v2_sparse_classes_30k_train_018993 | Implement the Python class `TestGovernProduct` described below.
Class description:
Implement the TestGovernProduct class.
Method signatures and docstrings:
- def test_1_add_product(self): 【适老化】:添加产品
- def test_2_get_product_list(self): 【适老化】:分页查询产品列表
- def test_3_update_product(self): 【适老化】:编辑产品信息
- def test_4_stop_s... | Implement the Python class `TestGovernProduct` described below.
Class description:
Implement the TestGovernProduct class.
Method signatures and docstrings:
- def test_1_add_product(self): 【适老化】:添加产品
- def test_2_get_product_list(self): 【适老化】:分页查询产品列表
- def test_3_update_product(self): 【适老化】:编辑产品信息
- def test_4_stop_s... | 024bb8f0e8be7d19abfb14b405ef79bd85cc6b7b | <|skeleton|>
class TestGovernProduct:
def test_1_add_product(self):
"""【适老化】:添加产品"""
<|body_0|>
def test_2_get_product_list(self):
"""【适老化】:分页查询产品列表"""
<|body_1|>
def test_3_update_product(self):
"""【适老化】:编辑产品信息"""
<|body_2|>
def test_4_stop_start_prod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGovernProduct:
def test_1_add_product(self):
"""【适老化】:添加产品"""
param = {'imgPath': [{'name': '123', 'url': 'http://file.chinaylzl.com/test/userHead/2018/11/16/38acfc8085c249628beffed54bccb2c7.png'}, {'name': '456', 'url': 'http://file.chinaylzl.com/test/userHead/2018/11/16/38acfc8085c249628... | the_stack_v2_python_sparse | test_case/test_house/test_govern_product.py | cjuan123/auto_api | train | 0 | |
4b5138967c1399153a6017b312fffa391e733bdc | [
"dt = datetime(2017, 11, 22, 1, 0)\ncycletime = '20171122T0100Z'\nresult = datetime_to_cycletime(dt)\nself.assertIsInstance(result, str)\nself.assertEqual(result, cycletime)",
"dt = datetime(2017, 11, 22, 1, 0)\ncycletime = '201711220100'\nresult = datetime_to_cycletime(dt, cycletime_format='%Y%m%d%H%M')\nself.as... | <|body_start_0|>
dt = datetime(2017, 11, 22, 1, 0)
cycletime = '20171122T0100Z'
result = datetime_to_cycletime(dt)
self.assertIsInstance(result, str)
self.assertEqual(result, cycletime)
<|end_body_0|>
<|body_start_1|>
dt = datetime(2017, 11, 22, 1, 0)
cycletime =... | Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ. | Test_datetime_to_cycletime | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_datetime_to_cycletime:
"""Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ."""
def test_basic(self):
"""Test that a datetime object is returned of the expected value."""
<|body_0|>
def test_define_cycletime_format(self... | stack_v2_sparse_classes_36k_train_030824 | 19,622 | permissive | [
{
"docstring": "Test that a datetime object is returned of the expected value.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test when a cycletime is defined.",
"name": "test_define_cycletime_format",
"signature": "def test_define_cycletime_format(self)"
... | 3 | null | Implement the Python class `Test_datetime_to_cycletime` described below.
Class description:
Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ.
Method signatures and docstrings:
- def test_basic(self): Test that a datetime object is returned of the expected value.
- def t... | Implement the Python class `Test_datetime_to_cycletime` described below.
Class description:
Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ.
Method signatures and docstrings:
- def test_basic(self): Test that a datetime object is returned of the expected value.
- def t... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_datetime_to_cycletime:
"""Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ."""
def test_basic(self):
"""Test that a datetime object is returned of the expected value."""
<|body_0|>
def test_define_cycletime_format(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_datetime_to_cycletime:
"""Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ."""
def test_basic(self):
"""Test that a datetime object is returned of the expected value."""
dt = datetime(2017, 11, 22, 1, 0)
cycletime = '20171122T01... | the_stack_v2_python_sparse | improver_tests/utilities/temporal/test_temporal.py | metoppv/improver | train | 101 |
665ed5547fded31e772603cbac24ee671c4c965c | [
"first_password = prompt_pass('Enter password')\nsecond_password = prompt_pass('Enter password again')\nif first_password != second_password:\n sys.stderr.write(\"Passwords don't match, try again.\\n\")\n self.get_password_from_prompt()\nreturn first_password",
"if not password:\n password = self.get_pas... | <|body_start_0|>
first_password = prompt_pass('Enter password')
second_password = prompt_pass('Enter password again')
if first_password != second_password:
sys.stderr.write("Passwords don't match, try again.\n")
self.get_password_from_prompt()
return first_passwor... | Create a new Timesketch user. | AddUser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddUser:
"""Create a new Timesketch user."""
def get_password_from_prompt(self):
"""Get password from the command line prompt."""
<|body_0|>
def run(self, username, password):
"""Creates the user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030825 | 21,666 | permissive | [
{
"docstring": "Get password from the command line prompt.",
"name": "get_password_from_prompt",
"signature": "def get_password_from_prompt(self)"
},
{
"docstring": "Creates the user.",
"name": "run",
"signature": "def run(self, username, password)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017668 | Implement the Python class `AddUser` described below.
Class description:
Create a new Timesketch user.
Method signatures and docstrings:
- def get_password_from_prompt(self): Get password from the command line prompt.
- def run(self, username, password): Creates the user. | Implement the Python class `AddUser` described below.
Class description:
Create a new Timesketch user.
Method signatures and docstrings:
- def get_password_from_prompt(self): Get password from the command line prompt.
- def run(self, username, password): Creates the user.
<|skeleton|>
class AddUser:
"""Create a ... | 19ccce5e29d2636c67a0a1e8554a28144ffd3faf | <|skeleton|>
class AddUser:
"""Create a new Timesketch user."""
def get_password_from_prompt(self):
"""Get password from the command line prompt."""
<|body_0|>
def run(self, username, password):
"""Creates the user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddUser:
"""Create a new Timesketch user."""
def get_password_from_prompt(self):
"""Get password from the command line prompt."""
first_password = prompt_pass('Enter password')
second_password = prompt_pass('Enter password again')
if first_password != second_password:
... | the_stack_v2_python_sparse | timesketch/tsctl.py | kovakina/timesketch | train | 5 |
d63fbf23d3fc1c8e3be519a34145c3ddfcc26580 | [
"if x <= 1:\n return x\nlow, high = (0, x)\nprint('low\\tmid\\thigh')\nwhile low <= high:\n mid = low + (high - low) // 2\n est = mid ** 2\n if est > x:\n print('{}\\t{}\\t{}, 答案比 mid 小, 要往左邊走'.format(low, mid, high))\n high = mid - 1\n else:\n print('{}\\t{}\\t{}, 答案比 mid 大, 要往右... | <|body_start_0|>
if x <= 1:
return x
low, high = (0, x)
print('low\tmid\thigh')
while low <= high:
mid = low + (high - low) // 2
est = mid ** 2
if est > x:
print('{}\t{}\t{}, 答案比 mid 小, 要往左邊走'.format(low, mid, high))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrtOld(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x <= 1:
return x
low, high = (0, x)
print('lo... | stack_v2_sparse_classes_36k_train_030826 | 1,320 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrtOld",
"signature": "def mySqrtOld(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020764 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrtOld(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrtOld(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrtOld(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
if x <= 1:
return x
low, high = (0, x)
print('low\tmid\thigh')
while low <= high:
mid = low + (high - low) // 2
est = mid ** 2
if est > x:
print... | the_stack_v2_python_sparse | cs_notes/binary_search/sqrt_x.py | hwc1824/LeetCodeSolution | train | 0 | |
516737dca3465c39b1d0c27f9d564a28f7a6218e | [
"cls.region1_model_alias = 'swift_gr_region1'\ncls.region1_proxy_app = 'swift-proxy-region1'\nsuper(SwiftProxyMultiZoneTests, cls).setUpClass(application_name=cls.region1_proxy_app, model_alias=cls.region1_model_alias)\ncls.region1_model_name = cls.model_aliases[cls.region1_model_alias]\ncls.storage_topology = swif... | <|body_start_0|>
cls.region1_model_alias = 'swift_gr_region1'
cls.region1_proxy_app = 'swift-proxy-region1'
super(SwiftProxyMultiZoneTests, cls).setUpClass(application_name=cls.region1_proxy_app, model_alias=cls.region1_model_alias)
cls.region1_model_name = cls.model_aliases[cls.region1_... | Tests specific to swift proxy in multi zone environment. | SwiftProxyMultiZoneTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwiftProxyMultiZoneTests:
"""Tests specific to swift proxy in multi zone environment."""
def setUpClass(cls):
"""Run class setup for running tests."""
<|body_0|>
def tearDown(cls):
"""Remove test resources. The retry decorator is needed as it is luck of the draw ... | stack_v2_sparse_classes_36k_train_030827 | 19,089 | permissive | [
{
"docstring": "Run class setup for running tests.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Remove test resources. The retry decorator is needed as it is luck of the draw as to whether a delete of a newly created container will result in a 404. Retrying will ... | 3 | stack_v2_sparse_classes_30k_val_000726 | Implement the Python class `SwiftProxyMultiZoneTests` described below.
Class description:
Tests specific to swift proxy in multi zone environment.
Method signatures and docstrings:
- def setUpClass(cls): Run class setup for running tests.
- def tearDown(cls): Remove test resources. The retry decorator is needed as it... | Implement the Python class `SwiftProxyMultiZoneTests` described below.
Class description:
Tests specific to swift proxy in multi zone environment.
Method signatures and docstrings:
- def setUpClass(cls): Run class setup for running tests.
- def tearDown(cls): Remove test resources. The retry decorator is needed as it... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class SwiftProxyMultiZoneTests:
"""Tests specific to swift proxy in multi zone environment."""
def setUpClass(cls):
"""Run class setup for running tests."""
<|body_0|>
def tearDown(cls):
"""Remove test resources. The retry decorator is needed as it is luck of the draw ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwiftProxyMultiZoneTests:
"""Tests specific to swift proxy in multi zone environment."""
def setUpClass(cls):
"""Run class setup for running tests."""
cls.region1_model_alias = 'swift_gr_region1'
cls.region1_proxy_app = 'swift-proxy-region1'
super(SwiftProxyMultiZoneTests,... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/swift/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
c55c5029ae1f27829a4a25ae194fa50520fdfd25 | [
"if self.action in ('create', 'partial_update'):\n return ResponseWriteableSerializer\nreturn super().get_serializer_class()",
"children_belonging_to_user = Child.objects.filter(user__id=self.request.user.id)\nif 'study_uuid' in self.kwargs:\n study_uuid = self.kwargs['study_uuid']\n study = get_object_o... | <|body_start_0|>
if self.action in ('create', 'partial_update'):
return ResponseWriteableSerializer
return super().get_serializer_class()
<|end_body_0|>
<|body_start_1|>
children_belonging_to_user = Child.objects.filter(user__id=self.request.user.id)
if 'study_uuid' in self.... | Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children. | ResponseViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different ... | stack_v2_sparse_classes_36k_train_030828 | 18,786 | permissive | [
{
"docstring": "Return a different serializer for create views",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Overrides queryset. The overall idea is that we want to limit the responses one can retrieve through the API to two cases: 1) A user i... | 2 | null | Implement the Python class `ResponseViewSet` described below.
Class description:
Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children.
Method signatures and docstrin... | Implement the Python class `ResponseViewSet` described below.
Class description:
Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children.
Method signatures and docstrin... | 053714ecfbceeb2f27f73ebee3ae890726874693 | <|skeleton|>
class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different serializer fo... | the_stack_v2_python_sparse | api/views.py | lookit/lookit-api | train | 12 |
7da3e39ca62aa5e6d31f453429c4669b8d71f702 | [
"super().__init__(**kwargs)\nself.hidden_size = hidden_size\nself.rnn = nn.RNN(input_size=input_size, hidden_size=hidden_size, batch_first=True)\nself.linear = nn.Linear(hidden_size, self.n_params)\ndel self._params",
"x = F.pad(x, (0, 0, 1, 0))[..., :-1, :]\nh, _ = self.rnn(x)\nparams = self.linear(h).unsqueeze(... | <|body_start_0|>
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size=input_size, hidden_size=hidden_size, batch_first=True)
self.linear = nn.Linear(hidden_size, self.n_params)
del self._params
<|end_body_0|>
<|body_start_1|>
x = F.pad(x... | SplineRNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplineRNN:
def __init__(self, hidden_size, input_size=1, **kwargs):
"""RNN produces the parameter for a spline flow. Args: n_knots: Number of knots for the spline. hidden_size: Size of the RNN hidden state. in_features: Data dimension. min_value: Value below which the transformation is i... | stack_v2_sparse_classes_36k_train_030829 | 2,931 | permissive | [
{
"docstring": "RNN produces the parameter for a spline flow. Args: n_knots: Number of knots for the spline. hidden_size: Size of the RNN hidden state. in_features: Data dimension. min_value: Value below which the transformation is identity. max_value: Value above which the transformation is identity.",
"na... | 4 | stack_v2_sparse_classes_30k_val_000223 | Implement the Python class `SplineRNN` described below.
Class description:
Implement the SplineRNN class.
Method signatures and docstrings:
- def __init__(self, hidden_size, input_size=1, **kwargs): RNN produces the parameter for a spline flow. Args: n_knots: Number of knots for the spline. hidden_size: Size of the R... | Implement the Python class `SplineRNN` described below.
Class description:
Implement the SplineRNN class.
Method signatures and docstrings:
- def __init__(self, hidden_size, input_size=1, **kwargs): RNN produces the parameter for a spline flow. Args: n_knots: Number of knots for the spline. hidden_size: Size of the R... | 19df15fb6f0701e0a2cb9f6afc8a5dfe87a80f40 | <|skeleton|>
class SplineRNN:
def __init__(self, hidden_size, input_size=1, **kwargs):
"""RNN produces the parameter for a spline flow. Args: n_knots: Number of knots for the spline. hidden_size: Size of the RNN hidden state. in_features: Data dimension. min_value: Value below which the transformation is i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplineRNN:
def __init__(self, hidden_size, input_size=1, **kwargs):
"""RNN produces the parameter for a spline flow. Args: n_knots: Number of knots for the spline. hidden_size: Size of the RNN hidden state. in_features: Data dimension. min_value: Value below which the transformation is identity. max_v... | the_stack_v2_python_sparse | ttpp/flows/rnn.py | TrendingTechnology/triangular-tpp | train | 0 | |
3f4d9f0cf8360445bad19e3d8cfb97f550be2594 | [
"if any(np.array([top_peak_rh, freezing_pt_rh, bl_top_rh, surface_rh]) > 1):\n raise ValueError('Some RH values are given above 1, make sure RH is not in %.If this was done on purpose, ignore this warning')\nself.top_peak_T = top_peak_T\nself.top_peak_rh = top_peak_rh\nself.freezing_pt_rh = freezing_pt_rh\nself.... | <|body_start_0|>
if any(np.array([top_peak_rh, freezing_pt_rh, bl_top_rh, surface_rh]) > 1):
raise ValueError('Some RH values are given above 1, make sure RH is not in %.If this was done on purpose, ignore this warning')
self.top_peak_T = top_peak_T
self.top_peak_rh = top_peak_rh
... | Defines a C-shaped polynomial model, that depends on T in the upper troposphere. The RH increases linearly in the boundary layer from the surface. Between the top of the boundary layer and the freezing level (T=273.15K), the rh is a quadratic function of p, defined by its values at these to points, and a zero derivativ... | PolynomialCshapedRH | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolynomialCshapedRH:
"""Defines a C-shaped polynomial model, that depends on T in the upper troposphere. The RH increases linearly in the boundary layer from the surface. Between the top of the boundary layer and the freezing level (T=273.15K), the rh is a quadratic function of p, defined by its ... | stack_v2_sparse_classes_36k_train_030830 | 13,283 | permissive | [
{
"docstring": "Parameters: top_peak_T (float): Temperature of the upper tropospheric peak. If None, coupled to the cold-point. top_peak_rh (float in [0;1]): value of relative humidity at the upper-tropospheric peak. freezing_pt_rh (float in [0;1]): value of relative humidity at the freezing point. bl_top_p (fl... | 2 | stack_v2_sparse_classes_30k_val_000060 | Implement the Python class `PolynomialCshapedRH` described below.
Class description:
Defines a C-shaped polynomial model, that depends on T in the upper troposphere. The RH increases linearly in the boundary layer from the surface. Between the top of the boundary layer and the freezing level (T=273.15K), the rh is a q... | Implement the Python class `PolynomialCshapedRH` described below.
Class description:
Defines a C-shaped polynomial model, that depends on T in the upper troposphere. The RH increases linearly in the boundary layer from the surface. Between the top of the boundary layer and the freezing level (T=273.15K), the rh is a q... | 2d9b5a78a1aab5d4dd2ccca99ddbce388de02738 | <|skeleton|>
class PolynomialCshapedRH:
"""Defines a C-shaped polynomial model, that depends on T in the upper troposphere. The RH increases linearly in the boundary layer from the surface. Between the top of the boundary layer and the freezing level (T=273.15K), the rh is a quadratic function of p, defined by its ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolynomialCshapedRH:
"""Defines a C-shaped polynomial model, that depends on T in the upper troposphere. The RH increases linearly in the boundary layer from the surface. Between the top of the boundary layer and the freezing level (T=273.15K), the rh is a quadratic function of p, defined by its values at the... | the_stack_v2_python_sparse | konrad/humidity/relative_humidity.py | atmtools/konrad | train | 17 |
d192ee19acfa1fe7574c69fb686e5ffc6437a772 | [
"self.destination_module_globals = globals()\nself.family = family\nif not isinstance(self.family, list) and (not isinstance(self.family, tuple)):\n self.family = [family]",
"for family in self.family:\n new_klass, klass_name = self._create_interface(klass, family)\n self.destination_module_globals[klass... | <|body_start_0|>
self.destination_module_globals = globals()
self.family = family
if not isinstance(self.family, list) and (not isinstance(self.family, tuple)):
self.family = [family]
<|end_body_0|>
<|body_start_1|>
for family in self.family:
new_klass, klass_nam... | Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals(). | DeepLearningDecorator | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepLearningDecorator:
"""Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals()."""
def __init__(self, family):
... | stack_v2_sparse_classes_36k_train_030831 | 8,565 | permissive | [
{
"docstring": "Initialize the ValidationDecorator class. Parameters ---------- family: str or list of str the families associated to the network.",
"name": "__init__",
"signature": "def __init__(self, family)"
},
{
"docstring": "Create the validator. Parameters ---------- function: callable the... | 3 | null | Implement the Python class `DeepLearningDecorator` described below.
Class description:
Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals().
... | Implement the Python class `DeepLearningDecorator` described below.
Class description:
Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals().
... | 7a807ed690929563ce36086eaf0998d0e8856aea | <|skeleton|>
class DeepLearningDecorator:
"""Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals()."""
def __init__(self, family):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepLearningDecorator:
"""Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals()."""
def __init__(self, family):
"""Initia... | the_stack_v2_python_sparse | pynet/interfaces.py | Duplums/pynet | train | 0 |
e64e31c8a81647b668a1d542990932a1152e8e4c | [
"HateCrimesandTrafficking = apps.get_model('cts_forms', 'HateCrimesandTrafficking')\nProtectedClass = apps.get_model('cts_forms', 'ProtectedClass')\nhc_labels = {label: value for value, label in HATE_CRIMES_TRAFFICKING_MODEL_CHOICES}\nfor hc in HateCrimesandTrafficking.objects.all():\n try:\n hc.value = h... | <|body_start_0|>
HateCrimesandTrafficking = apps.get_model('cts_forms', 'HateCrimesandTrafficking')
ProtectedClass = apps.get_model('cts_forms', 'ProtectedClass')
hc_labels = {label: value for value, label in HATE_CRIMES_TRAFFICKING_MODEL_CHOICES}
for hc in HateCrimesandTrafficking.objec... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forward(apps, schema_editor):
"""Set value field of existing HateCrimesandTrafficking and ProtectedClass instances to those matching their labels set in original field Instances of these models may exist which are no longer defined in the associated *_MODEL_CHOICES. These ... | stack_v2_sparse_classes_36k_train_030832 | 3,100 | no_license | [
{
"docstring": "Set value field of existing HateCrimesandTrafficking and ProtectedClass instances to those matching their labels set in original field Instances of these models may exist which are no longer defined in the associated *_MODEL_CHOICES. These instances are considered inactive and won't be displayed... | 2 | null | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forward(apps, schema_editor): Set value field of existing HateCrimesandTrafficking and ProtectedClass instances to those matching their labels set in original field Instanc... | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forward(apps, schema_editor): Set value field of existing HateCrimesandTrafficking and ProtectedClass instances to those matching their labels set in original field Instanc... | d5d6338cf54a09c2f6c88cd3affa3d7f49bdf693 | <|skeleton|>
class Migration:
def forward(apps, schema_editor):
"""Set value field of existing HateCrimesandTrafficking and ProtectedClass instances to those matching their labels set in original field Instances of these models may exist which are no longer defined in the associated *_MODEL_CHOICES. These ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forward(apps, schema_editor):
"""Set value field of existing HateCrimesandTrafficking and ProtectedClass instances to those matching their labels set in original field Instances of these models may exist which are no longer defined in the associated *_MODEL_CHOICES. These instances are ... | the_stack_v2_python_sparse | crt_portal/cts_forms/migrations/0067_populate_new_choice_fields.py | usdoj-crt/crt-portal | train | 18 | |
cd27fe89552bbf3af4e4044db3a33afbc07f7ca1 | [
"super().__init__(scope, id, **kwargs)\nvpc = ec2.Vpc.from_lookup(self, f'{id}-vpc', vpc_id='vpc-dfff4bb4')\nbucket = s3.Bucket.from_bucket_name(self, f'{id}-export-bucket', 'rezoning-exports')\ns3_access_policy = iam.PolicyStatement(actions=['s3:*'], resources=[bucket.bucket_arn, f'{bucket.bucket_arn}/*', f'arn:aw... | <|body_start_0|>
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc.from_lookup(self, f'{id}-vpc', vpc_id='vpc-dfff4bb4')
bucket = s3.Bucket.from_bucket_name(self, f'{id}-export-bucket', 'rezoning-exports')
s3_access_policy = iam.PolicyStatement(actions=['s3:*'], resources=[bucket.bucke... | rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/app.py author: @ciaranevans | rezoningApiLambdaStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class rezoningApiLambdaStack:
"""rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/a... | stack_v2_sparse_classes_36k_train_030833 | 7,248 | no_license | [
{
"docstring": "Define stack.",
"name": "__init__",
"signature": "def __init__(self, scope: core.Construct, id: str, memory: int=1024, timeout: int=30, concurrent: int=100, code_dir: str='./', **kwargs: Any) -> None"
},
{
"docstring": "Build docker image and create package.",
"name": "create... | 2 | stack_v2_sparse_classes_30k_train_015481 | Implement the Python class `rezoningApiLambdaStack` described below.
Class description:
rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec... | Implement the Python class `rezoningApiLambdaStack` described below.
Class description:
rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec... | 27a2a48d861d4be636ec36a7b11ac856032b5053 | <|skeleton|>
class rezoningApiLambdaStack:
"""rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class rezoningApiLambdaStack:
"""rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/app.py author:... | the_stack_v2_python_sparse | stack/app.py | zacharlie/rezoning-explorer-api | train | 0 |
670036a557f81dbb4809906b034b526c704b7536 | [
"InputFinder.__init__(self, system=system, environment_inputs=environment_inputs, objective=objective, objective_aggregator=objective_aggregator, system_estimator=system_estimator, dominance_func=dominance_func, pool_size=pool_size, last_inputs=last_inputs)\nself.ga_params = ga_params\nself._plan_finder = EmptyPlan... | <|body_start_0|>
InputFinder.__init__(self, system=system, environment_inputs=environment_inputs, objective=objective, objective_aggregator=objective_aggregator, system_estimator=system_estimator, dominance_func=dominance_func, pool_size=pool_size, last_inputs=last_inputs)
self.ga_params = ga_params
... | Sequence of control inputs GA Input Finder It is a genetic algorithm that generates sequences of control inputs. A sequence can be composed of different control inputs Attributes: ga_params (dict): initialization parameters of :py:class:`~sp.core.heuristic.nsgaii.NSGAII` class | SGAInputFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SGAInputFinder:
"""Sequence of control inputs GA Input Finder It is a genetic algorithm that generates sequences of control inputs. A sequence can be composed of different control inputs Attributes: ga_params (dict): initialization parameters of :py:class:`~sp.core.heuristic.nsgaii.NSGAII` class"... | stack_v2_sparse_classes_36k_train_030834 | 6,676 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, system, environment_inputs, objective, objective_aggregator, system_estimator, dominance_func, pool_size, last_inputs, load_chunk_distribution=None, **ga_params)"
},
{
"docstring": "Execute the heuristic Return... | 2 | stack_v2_sparse_classes_30k_train_008035 | Implement the Python class `SGAInputFinder` described below.
Class description:
Sequence of control inputs GA Input Finder It is a genetic algorithm that generates sequences of control inputs. A sequence can be composed of different control inputs Attributes: ga_params (dict): initialization parameters of :py:class:`~... | Implement the Python class `SGAInputFinder` described below.
Class description:
Sequence of control inputs GA Input Finder It is a genetic algorithm that generates sequences of control inputs. A sequence can be composed of different control inputs Attributes: ga_params (dict): initialization parameters of :py:class:`~... | ce7045918f60c92ce1ed5ca4389b969bf28e6b82 | <|skeleton|>
class SGAInputFinder:
"""Sequence of control inputs GA Input Finder It is a genetic algorithm that generates sequences of control inputs. A sequence can be composed of different control inputs Attributes: ga_params (dict): initialization parameters of :py:class:`~sp.core.heuristic.nsgaii.NSGAII` class"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SGAInputFinder:
"""Sequence of control inputs GA Input Finder It is a genetic algorithm that generates sequences of control inputs. A sequence can be composed of different control inputs Attributes: ga_params (dict): initialization parameters of :py:class:`~sp.core.heuristic.nsgaii.NSGAII` class"""
def _... | the_stack_v2_python_sparse | sp/system_controller/optimizer/llc/input_finder/sga.py | adysonmaia/phd-sp-dynamic | train | 0 |
6f57081234bf8bafac5407c33d554d30cf321321 | [
"if left > right:\n return 0\nelif right - left <= 1:\n return max(self.nums[left:right + 1])\n'memoization: 있으면 그거 return'\nif (left, right) in self.memo:\n return self.memo[left, right]\n'left(0)번째 집을 훔치는 경우'\ninclude_left = self.nums[left] + self.help(left + 2, right)\n'left(0)번째 집을 안 훔치는 경우'\nexclude_l... | <|body_start_0|>
if left > right:
return 0
elif right - left <= 1:
return max(self.nums[left:right + 1])
'memoization: 있으면 그거 return'
if (left, right) in self.memo:
return self.memo[left, right]
'left(0)번째 집을 훔치는 경우'
include_left = self... | nums에서 left부터 right까지의 부분을 놓고 봤을 때 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""nums에서 left부터 right까지의 부분을 놓고 봤을 때"""
def help(self, left, right):
"""base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much"""
... | stack_v2_sparse_classes_36k_train_030835 | 1,893 | no_license | [
{
"docstring": "base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much",
"name": "help",
"signature": "def help(self, left, right)"
},
{
"docstring": "예외 처리: 3개 ... | 2 | stack_v2_sparse_classes_30k_train_002898 | Implement the Python class `Solution` described below.
Class description:
nums에서 left부터 right까지의 부분을 놓고 봤을 때
Method signatures and docstrings:
- def help(self, left, right): base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐... | Implement the Python class `Solution` described below.
Class description:
nums에서 left부터 right까지의 부분을 놓고 봤을 때
Method signatures and docstrings:
- def help(self, left, right): base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐... | 9c29941e19b7dd2a2037b110dd6e16690e9a0cc2 | <|skeleton|>
class Solution:
"""nums에서 left부터 right까지의 부분을 놓고 봤을 때"""
def help(self, left, right):
"""base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""nums에서 left부터 right까지의 부분을 놓고 봤을 때"""
def help(self, left, right):
"""base case * 현재는 0번과 -1번이 이웃이 아님 1. left > right는 안됨 -> return 0 2. (right - left) <= 1 : 여기선 하나 밖에 못 턺 -> return max(nums) * nums가 4개, 5개, 6개일 땐 각각 케이스가 3, 5, 11개 나오긴 하는데 여기까지 하는 건 too much"""
if left > rig... | the_stack_v2_python_sparse | algorithm/2022/0705_213_House_Robber_II/Wooseong.py | ai-kmu/etc | train | 3 |
b723536260d0739ea6a1b67fc29f591d07cd3c5f | [
"super().__init__()\nself.receiver = RCReceiver(read_pin_config(mock_bbio=mock_bbio))\nself.keep_reading = True\nself.read_interval = read_interval()",
"while True:\n self.receiver.send_inputs()\n sleep(self.read_interval)"
] | <|body_start_0|>
super().__init__()
self.receiver = RCReceiver(read_pin_config(mock_bbio=mock_bbio))
self.keep_reading = True
self.read_interval = read_interval()
<|end_body_0|>
<|body_start_1|>
while True:
self.receiver.send_inputs()
sleep(self.read_inte... | A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension. | RCInputThread | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RCInputThread:
"""A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension."""
def __init__(self, mock_bbio=None):
"""Builds a new RC input thread.""... | stack_v2_sparse_classes_36k_train_030836 | 849 | permissive | [
{
"docstring": "Builds a new RC input thread.",
"name": "__init__",
"signature": "def __init__(self, mock_bbio=None)"
},
{
"docstring": "Starts a regular input read interval.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019990 | Implement the Python class `RCInputThread` described below.
Class description:
A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension.
Method signatures and docstrings:
- def __init... | Implement the Python class `RCInputThread` described below.
Class description:
A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension.
Method signatures and docstrings:
- def __init... | b5d75cb82e4bc3e9c4e428a288c6ac98a4aa2c52 | <|skeleton|>
class RCInputThread:
"""A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension."""
def __init__(self, mock_bbio=None):
"""Builds a new RC input thread.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RCInputThread:
"""A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension."""
def __init__(self, mock_bbio=None):
"""Builds a new RC input thread."""
sup... | the_stack_v2_python_sparse | src/rc_input/rc_input_thread.py | vt-sailbot/sailbot-21 | train | 5 |
c0842e1f7964bb37d045041e7d17b4bb7c5a0373 | [
"super().__init__(config_entry, driver, info)\nproperty_key_name = self.info.primary_value.property_key_name\nself._attr_name = self.generate_name(alternate_value_name=self.info.primary_value.property_name, additional_info=[property_key_name] if property_key_name else None)",
"if not self.info.primary_value.metad... | <|body_start_0|>
super().__init__(config_entry, driver, info)
property_key_name = self.info.primary_value.property_key_name
self._attr_name = self.generate_name(alternate_value_name=self.info.primary_value.property_name, additional_info=[property_key_name] if property_key_name else None)
<|end_b... | Representation of a Z-Wave config parameter number. | ZWaveConfigParameterNumberEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveConfigParameterNumberEntity:
"""Representation of a Z-Wave config parameter number."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveConfigParameterNumber entity."""
<|body_0|>
def extra_state_a... | stack_v2_sparse_classes_36k_train_030837 | 6,343 | permissive | [
{
"docstring": "Initialize a ZWaveConfigParameterNumber entity.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None"
},
{
"docstring": "Return extra state attributes for entity.",
"name": "extra_state_attributes"... | 2 | null | Implement the Python class `ZWaveConfigParameterNumberEntity` described below.
Class description:
Representation of a Z-Wave config parameter number.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None: Initialize a ZWaveConfigParameterNu... | Implement the Python class `ZWaveConfigParameterNumberEntity` described below.
Class description:
Representation of a Z-Wave config parameter number.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None: Initialize a ZWaveConfigParameterNu... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZWaveConfigParameterNumberEntity:
"""Representation of a Z-Wave config parameter number."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveConfigParameterNumber entity."""
<|body_0|>
def extra_state_a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZWaveConfigParameterNumberEntity:
"""Representation of a Z-Wave config parameter number."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveConfigParameterNumber entity."""
super().__init__(config_entry, driver, info)
... | the_stack_v2_python_sparse | homeassistant/components/zwave_js/number.py | home-assistant/core | train | 35,501 |
3a8d93b88dd5712dd86d7208bf715837ca543cb7 | [
"parser.add_argument('--service', '-s', help='Limit to specific service.')\nparser.add_argument('--version', '-v', help='Limit to specific version.')\nparser.add_argument('--limit', required=False, type=int, default=200, help='Number of log entries to show.')\nparser.add_argument('--level', required=False, default=... | <|body_start_0|>
parser.add_argument('--service', '-s', help='Limit to specific service.')
parser.add_argument('--version', '-v', help='Limit to specific version.')
parser.add_argument('--limit', required=False, type=int, default=200, help='Number of log entries to show.')
parser.add_arg... | Reads log entries for the current App Engine app. | Read | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Read:
"""Reads log entries for the current App Engine app."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the argument... | stack_v2_sparse_classes_36k_train_030838 | 4,274 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The list of... | 2 | stack_v2_sparse_classes_30k_train_017149 | Implement the Python class `Read` described below.
Class description:
Reads log entries for the current App Engine app.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namesp... | Implement the Python class `Read` described below.
Class description:
Reads log entries for the current App Engine app.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namesp... | c97dd7b906e5ef3ec157581fd0bcadd3e3fc220e | <|skeleton|>
class Read:
"""Reads log entries for the current App Engine app."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the argument... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Read:
"""Reads log entries for the current App Engine app."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('--service', '-s', help='Limit to specific service.')
parser.add_argument('--version', '-v', help='Limit to specific version.')
parser... | the_stack_v2_python_sparse | files/home/gcloud/google-cloud-sdk/lib/surface/app/logs/read.py | vo0doO/com.termux | train | 2 |
cf6dacbd65c8153924f5f096da51f6580d9f5b42 | [
"Graph.__init__(self, name)\nself.instance_norm_affine = instance_norm_affine\nself.target_channels = target_channels\nself.filter_counts = [initial_filter_count, initial_filter_count * 2, initial_filter_count * 4, initial_filter_count * 8]",
"conv_down1 = ops.conv2d_downsample_leaky(input, self.KERNEL_SIZE, self... | <|body_start_0|>
Graph.__init__(self, name)
self.instance_norm_affine = instance_norm_affine
self.target_channels = target_channels
self.filter_counts = [initial_filter_count, initial_filter_count * 2, initial_filter_count * 4, initial_filter_count * 8]
<|end_body_0|>
<|body_start_1|>
... | Discriminator base class for CycleGAN architecture. | Discriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Discriminator:
"""Discriminator base class for CycleGAN architecture."""
def __init__(self, name, instance_norm_affine, initial_filter_count, target_channels=1):
"""Setter constructor. Arguments: name -- The variable scope name for the discriminator's graph. initial_filter_count -- T... | stack_v2_sparse_classes_36k_train_030839 | 20,875 | permissive | [
{
"docstring": "Setter constructor. Arguments: name -- The variable scope name for the discriminator's graph. initial_filter_count -- The number of filters in the first layer of the discriminator. Later layers use multiples of this value. instance_norm_affine -- Whether the instance norm layers shall contain a ... | 2 | stack_v2_sparse_classes_30k_train_002563 | Implement the Python class `Discriminator` described below.
Class description:
Discriminator base class for CycleGAN architecture.
Method signatures and docstrings:
- def __init__(self, name, instance_norm_affine, initial_filter_count, target_channels=1): Setter constructor. Arguments: name -- The variable scope name... | Implement the Python class `Discriminator` described below.
Class description:
Discriminator base class for CycleGAN architecture.
Method signatures and docstrings:
- def __init__(self, name, instance_norm_affine, initial_filter_count, target_channels=1): Setter constructor. Arguments: name -- The variable scope name... | 181f794a7c31311ab4cb9b76df5f1ab3bc6ef64d | <|skeleton|>
class Discriminator:
"""Discriminator base class for CycleGAN architecture."""
def __init__(self, name, instance_norm_affine, initial_filter_count, target_channels=1):
"""Setter constructor. Arguments: name -- The variable scope name for the discriminator's graph. initial_filter_count -- T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Discriminator:
"""Discriminator base class for CycleGAN architecture."""
def __init__(self, name, instance_norm_affine, initial_filter_count, target_channels=1):
"""Setter constructor. Arguments: name -- The variable scope name for the discriminator's graph. initial_filter_count -- The number of ... | the_stack_v2_python_sparse | code/cyclegan/model/architecture.py | Sirius291/trafficsign-cyclegan | train | 0 |
63ead2b56773beeb8e9760388e7afb09f99b3130 | [
"filters = ()\nresult = model_admin.get_queryset(request)[:5]\nfor res in result:\n filters = filters + ((res.title, res.title),)\nreturn filters",
"title = self.value()\nprint('query set ... %s' % title)\nif title:\n return queryset.filter(title__contains=title)\nelse:\n return queryset.all()"
] | <|body_start_0|>
filters = ()
result = model_admin.get_queryset(request)[:5]
for res in result:
filters = filters + ((res.title, res.title),)
return filters
<|end_body_0|>
<|body_start_1|>
title = self.value()
print('query set ... %s' % title)
if titl... | 标题过滤器 | TitleFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
"""只显示前5个title作为过滤词"""
<|body_0|>
def queryset(self, request, queryset):
"""过滤方式"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
filters = ()
result = model_admin.get_quer... | stack_v2_sparse_classes_36k_train_030840 | 1,665 | no_license | [
{
"docstring": "只显示前5个title作为过滤词",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "过滤方式",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016939 | Implement the Python class `TitleFilter` described below.
Class description:
标题过滤器
Method signatures and docstrings:
- def lookups(self, request, model_admin): 只显示前5个title作为过滤词
- def queryset(self, request, queryset): 过滤方式 | Implement the Python class `TitleFilter` described below.
Class description:
标题过滤器
Method signatures and docstrings:
- def lookups(self, request, model_admin): 只显示前5个title作为过滤词
- def queryset(self, request, queryset): 过滤方式
<|skeleton|>
class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
... | a12ad8144938e96ea33881d29eee7f5ecfe2bd08 | <|skeleton|>
class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
"""只显示前5个title作为过滤词"""
<|body_0|>
def queryset(self, request, queryset):
"""过滤方式"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
"""只显示前5个title作为过滤词"""
filters = ()
result = model_admin.get_queryset(request)[:5]
for res in result:
filters = filters + ((res.title, res.title),)
return filters
def queryset(self, ... | the_stack_v2_python_sparse | wiki/admin.py | ting723/viking | train | 0 |
8a336c19012c20b7705a952a3d5e9f42a12417cf | [
"i = j = 0\nn, m = (len(t), len(s))\nwhile i < n and j < m:\n if t[i] == s[j]:\n i += 1\n j += 1\n else:\n i += 1\nreturn j == m",
"n, m = (len(s), len(t))\ndp = [[0] * 26 for _ in range(m)]\ndp.append([m] * 26)\nfor i in range(m - 1, -1, -1):\n for j in range(26):\n dp[i][j] ... | <|body_start_0|>
i = j = 0
n, m = (len(t), len(s))
while i < n and j < m:
if t[i] == s[j]:
i += 1
j += 1
else:
i += 1
return j == m
<|end_body_0|>
<|body_start_1|>
n, m = (len(s), len(t))
dp = [[0] *... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""唔, 2020-07-27每日一题 又做了一遍 双指针: 两个指针从0开始遍历两个字符串 如果两个指针的值相等两个指针均后移 如果不相等s的指针原地等待匹配,t的指针后移 最后判断s的指针与s的字符串长度是否相等。 时间复杂度:O(n + m),因为需要把n和m全部遍历一遍 空间复杂度:O(1),没有利用到额外空间 :param s: :param t: :return:"""
<|body_0|>
def isSubse... | stack_v2_sparse_classes_36k_train_030841 | 2,412 | no_license | [
{
"docstring": "唔, 2020-07-27每日一题 又做了一遍 双指针: 两个指针从0开始遍历两个字符串 如果两个指针的值相等两个指针均后移 如果不相等s的指针原地等待匹配,t的指针后移 最后判断s的指针与s的字符串长度是否相等。 时间复杂度:O(n + m),因为需要把n和m全部遍历一遍 空间复杂度:O(1),没有利用到额外空间 :param s: :param t: :return:",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s: str, t: str) -> bool"
},
{
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 唔, 2020-07-27每日一题 又做了一遍 双指针: 两个指针从0开始遍历两个字符串 如果两个指针的值相等两个指针均后移 如果不相等s的指针原地等待匹配,t的指针后移 最后判断s的指针与s的字符串长度是否相等。 时间复杂度:O(n + m),因为需要把n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 唔, 2020-07-27每日一题 又做了一遍 双指针: 两个指针从0开始遍历两个字符串 如果两个指针的值相等两个指针均后移 如果不相等s的指针原地等待匹配,t的指针后移 最后判断s的指针与s的字符串长度是否相等。 时间复杂度:O(n + m),因为需要把n... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""唔, 2020-07-27每日一题 又做了一遍 双指针: 两个指针从0开始遍历两个字符串 如果两个指针的值相等两个指针均后移 如果不相等s的指针原地等待匹配,t的指针后移 最后判断s的指针与s的字符串长度是否相等。 时间复杂度:O(n + m),因为需要把n和m全部遍历一遍 空间复杂度:O(1),没有利用到额外空间 :param s: :param t: :return:"""
<|body_0|>
def isSubse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""唔, 2020-07-27每日一题 又做了一遍 双指针: 两个指针从0开始遍历两个字符串 如果两个指针的值相等两个指针均后移 如果不相等s的指针原地等待匹配,t的指针后移 最后判断s的指针与s的字符串长度是否相等。 时间复杂度:O(n + m),因为需要把n和m全部遍历一遍 空间复杂度:O(1),没有利用到额外空间 :param s: :param t: :return:"""
i = j = 0
n, m = (len(t), len(s))... | the_stack_v2_python_sparse | 判断子序列.py | cjrzs/MyLeetCode | train | 8 | |
e184dc5a56df5f6ee2125c1d378ea6fd362a1f6a | [
"a = 'sql_error.ini'\nsql_error = open(a, 'r')\nerrors = sql_error.readlines()\nsql_error.close()\nself.errors = errors\nself.link = link",
"domain = url.split('?')[0]\nparams = {}\nparam = url.split('?')[1]\nfor pm in param.split('&'):\n key, value = pm.split('=')\n try:\n int(value)\n value ... | <|body_start_0|>
a = 'sql_error.ini'
sql_error = open(a, 'r')
errors = sql_error.readlines()
sql_error.close()
self.errors = errors
self.link = link
<|end_body_0|>
<|body_start_1|>
domain = url.split('?')[0]
params = {}
param = url.split('?')[1]
... | Scan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scan:
def __init__(self, link):
"""type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test"""
<|body_0|>
def create_link(self, url):
"""Create a link with symbol ' type url : str param url : which url to ... | stack_v2_sparse_classes_36k_train_030842 | 2,642 | no_license | [
{
"docstring": "type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test",
"name": "__init__",
"signature": "def __init__(self, link)"
},
{
"docstring": "Create a link with symbol ' type url : str param url : which url to add ' return... | 4 | stack_v2_sparse_classes_30k_train_009156 | Implement the Python class `Scan` described below.
Class description:
Implement the Scan class.
Method signatures and docstrings:
- def __init__(self, link): type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test
- def create_link(self, url): Create a li... | Implement the Python class `Scan` described below.
Class description:
Implement the Scan class.
Method signatures and docstrings:
- def __init__(self, link): type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test
- def create_link(self, url): Create a li... | 111e4fcb2e3fb8e632ffed85b7c9e53ba2ed1c14 | <|skeleton|>
class Scan:
def __init__(self, link):
"""type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test"""
<|body_0|>
def create_link(self, url):
"""Create a link with symbol ' type url : str param url : which url to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scan:
def __init__(self, link):
"""type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test"""
a = 'sql_error.ini'
sql_error = open(a, 'r')
errors = sql_error.readlines()
sql_error.close()
self.errors... | the_stack_v2_python_sparse | sqli/src/scan.py | ZUI520/Python | train | 2 | |
dd928d3552120fb2ce786dd3230442a7889d8da7 | [
"context = self.get_context_data()\ncontext.update(self.context)\nwith django_mail.get_connection(settings.NOTIFICATION_EMAIL_BACKEND) as connection:\n subject, text_body, html_body = render_email_templates('password_reset', context)\n msg = AnymailMessage(subject=subject, body=text_body, to=to, from_email=se... | <|body_start_0|>
context = self.get_context_data()
context.update(self.context)
with django_mail.get_connection(settings.NOTIFICATION_EMAIL_BACKEND) as connection:
subject, text_body, html_body = render_email_templates('password_reset', context)
msg = AnymailMessage(subje... | Custom class to modify base functionality in Djoser's PasswordResetEmail class | CustomPasswordResetEmail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomPasswordResetEmail:
"""Custom class to modify base functionality in Djoser's PasswordResetEmail class"""
def send(self, to, *args, **kwargs):
"""Overrides djoser.email.PasswordResetEmail#send to use our mail API."""
<|body_0|>
def get_context_data(self):
""... | stack_v2_sparse_classes_36k_train_030843 | 8,366 | permissive | [
{
"docstring": "Overrides djoser.email.PasswordResetEmail#send to use our mail API.",
"name": "send",
"signature": "def send(self, to, *args, **kwargs)"
},
{
"docstring": "Adds base_url to the template context",
"name": "get_context_data",
"signature": "def get_context_data(self)"
}
] | 2 | null | Implement the Python class `CustomPasswordResetEmail` described below.
Class description:
Custom class to modify base functionality in Djoser's PasswordResetEmail class
Method signatures and docstrings:
- def send(self, to, *args, **kwargs): Overrides djoser.email.PasswordResetEmail#send to use our mail API.
- def ge... | Implement the Python class `CustomPasswordResetEmail` described below.
Class description:
Custom class to modify base functionality in Djoser's PasswordResetEmail class
Method signatures and docstrings:
- def send(self, to, *args, **kwargs): Overrides djoser.email.PasswordResetEmail#send to use our mail API.
- def ge... | ba7442482da97d463302658c0aac989567ee1241 | <|skeleton|>
class CustomPasswordResetEmail:
"""Custom class to modify base functionality in Djoser's PasswordResetEmail class"""
def send(self, to, *args, **kwargs):
"""Overrides djoser.email.PasswordResetEmail#send to use our mail API."""
<|body_0|>
def get_context_data(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomPasswordResetEmail:
"""Custom class to modify base functionality in Djoser's PasswordResetEmail class"""
def send(self, to, *args, **kwargs):
"""Overrides djoser.email.PasswordResetEmail#send to use our mail API."""
context = self.get_context_data()
context.update(self.conte... | the_stack_v2_python_sparse | authentication/views.py | mitodl/open-discussions | train | 13 |
362fb0e29581a686579a0fc954080699df184d60 | [
"self.always_use_ssd = always_use_ssd\nself.id = id\nself.min_requests = min_requests\nself.name = name\nself.priority = priority\nself.random_write_hydra_pct = random_write_hydra_pct\nself.random_write_ssd_pct = random_write_ssd_pct\nself.seq_write_hydra_pct = seq_write_hydra_pct\nself.seq_write_ssd_pct = seq_writ... | <|body_start_0|>
self.always_use_ssd = always_use_ssd
self.id = id
self.min_requests = min_requests
self.name = name
self.priority = priority
self.random_write_hydra_pct = random_write_hydra_pct
self.random_write_ssd_pct = random_write_ssd_pct
self.seq_wri... | Implementation of the 'QoSPolicy' model. Specifies the Quality of Service (QoS) Policy details. Attributes: always_use_ssd (bool): Specifies whether to always write to SSD even if SeqWriteSsdPct is 0. id (long|int): Specifies Id of the QoS Policy. min_requests (int): Specifies minimum number of requests, corresponding ... | QoSPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QoSPolicy:
"""Implementation of the 'QoSPolicy' model. Specifies the Quality of Service (QoS) Policy details. Attributes: always_use_ssd (bool): Specifies whether to always write to SSD even if SeqWriteSsdPct is 0. id (long|int): Specifies Id of the QoS Policy. min_requests (int): Specifies minim... | stack_v2_sparse_classes_36k_train_030844 | 4,491 | permissive | [
{
"docstring": "Constructor for the QoSPolicy class",
"name": "__init__",
"signature": "def __init__(self, always_use_ssd=None, id=None, min_requests=None, name=None, priority=None, random_write_hydra_pct=None, random_write_ssd_pct=None, seq_write_hydra_pct=None, seq_write_ssd_pct=None, weight=None, wor... | 2 | null | Implement the Python class `QoSPolicy` described below.
Class description:
Implementation of the 'QoSPolicy' model. Specifies the Quality of Service (QoS) Policy details. Attributes: always_use_ssd (bool): Specifies whether to always write to SSD even if SeqWriteSsdPct is 0. id (long|int): Specifies Id of the QoS Poli... | Implement the Python class `QoSPolicy` described below.
Class description:
Implementation of the 'QoSPolicy' model. Specifies the Quality of Service (QoS) Policy details. Attributes: always_use_ssd (bool): Specifies whether to always write to SSD even if SeqWriteSsdPct is 0. id (long|int): Specifies Id of the QoS Poli... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class QoSPolicy:
"""Implementation of the 'QoSPolicy' model. Specifies the Quality of Service (QoS) Policy details. Attributes: always_use_ssd (bool): Specifies whether to always write to SSD even if SeqWriteSsdPct is 0. id (long|int): Specifies Id of the QoS Policy. min_requests (int): Specifies minim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QoSPolicy:
"""Implementation of the 'QoSPolicy' model. Specifies the Quality of Service (QoS) Policy details. Attributes: always_use_ssd (bool): Specifies whether to always write to SSD even if SeqWriteSsdPct is 0. id (long|int): Specifies Id of the QoS Policy. min_requests (int): Specifies minimum number of ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/qo_s_policy.py | cohesity/management-sdk-python | train | 24 |
0432b4a890f5f992f5ee9eb1ed4b81c665267411 | [
"make_test_data()\nurl = reverse('areas')\nself.client.login(username='secretary', password='secretary+password')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)",
"make_test_data()\naugment_data()\nareas = Group.objects.filter(type='area', state='active')\nurl = reverse('areas_view'... | <|body_start_0|>
make_test_data()
url = reverse('areas')
self.client.login(username='secretary', password='secretary+password')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
<|end_body_0|>
<|body_start_1|>
make_test_data()
augment_da... | MainTestCase | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainTestCase:
def test_main(self):
"""Main Test"""
<|body_0|>
def test_view(self):
"""View Test"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
make_test_data()
url = reverse('areas')
self.client.login(username='secretary', password=... | stack_v2_sparse_classes_36k_train_030845 | 1,226 | permissive | [
{
"docstring": "Main Test",
"name": "test_main",
"signature": "def test_main(self)"
},
{
"docstring": "View Test",
"name": "test_view",
"signature": "def test_view(self)"
}
] | 2 | null | Implement the Python class `MainTestCase` described below.
Class description:
Implement the MainTestCase class.
Method signatures and docstrings:
- def test_main(self): Main Test
- def test_view(self): View Test | Implement the Python class `MainTestCase` described below.
Class description:
Implement the MainTestCase class.
Method signatures and docstrings:
- def test_main(self): Main Test
- def test_view(self): View Test
<|skeleton|>
class MainTestCase:
def test_main(self):
"""Main Test"""
<|body_0|>
... | 5af455fbe6b0c7e60b8af360718345ba044597a4 | <|skeleton|>
class MainTestCase:
def test_main(self):
"""Main Test"""
<|body_0|>
def test_view(self):
"""View Test"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainTestCase:
def test_main(self):
"""Main Test"""
make_test_data()
url = reverse('areas')
self.client.login(username='secretary', password='secretary+password')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_view(self)... | the_stack_v2_python_sparse | ietf/secr/areas/tests.py | wpjesus/codematch | train | 1 | |
5cf338b07054a033e3510c6cc4504c378a844078 | [
"self.continuous_schedule = continuous_schedule\nself.daily_schedule = daily_schedule\nself.monthly_schedule = monthly_schedule\nself.periodicity = periodicity\nself.rpo_schedule = rpo_schedule",
"if dictionary is None:\n return None\ncontinuous_schedule = cohesity_management_sdk.models.continuous_schedule.Con... | <|body_start_0|>
self.continuous_schedule = continuous_schedule
self.daily_schedule = daily_schedule
self.monthly_schedule = monthly_schedule
self.periodicity = periodicity
self.rpo_schedule = rpo_schedule
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime periods when new Job Runs should NOT be started.... | SchedulingPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulingPolicy:
"""Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime peri... | stack_v2_sparse_classes_36k_train_030846 | 4,041 | permissive | [
{
"docstring": "Constructor for the SchedulingPolicy class",
"name": "__init__",
"signature": "def __init__(self, continuous_schedule=None, daily_schedule=None, monthly_schedule=None, periodicity=None, rpo_schedule=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Arg... | 2 | stack_v2_sparse_classes_30k_train_017249 | Implement the Python class `SchedulingPolicy` described below.
Class description:
Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous... | Implement the Python class `SchedulingPolicy` described below.
Class description:
Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SchedulingPolicy:
"""Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime peri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchedulingPolicy:
"""Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime periods when new ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/scheduling_policy.py | cohesity/management-sdk-python | train | 24 |
345280c6c4b3d63a3e64f006a2960838ac3c0c5c | [
"self.order = []\nself.objects = {}\nif objects:\n for uri, ct in objects:\n self.add_object(uri, ct)",
"if uri not in self.objects:\n self.order.append(uri)\n self.objects[uri] = contenttype",
"retl = []\nfor k in self.order:\n if not ct or ct == self.objects[k]:\n retl.append((k, sel... | <|body_start_0|>
self.order = []
self.objects = {}
if objects:
for uri, ct in objects:
self.add_object(uri, ct)
<|end_body_0|>
<|body_start_1|>
if uri not in self.objects:
self.order.append(uri)
self.objects[uri] = contenttype
<|end_bo... | A class storing URI for media file, such as css, java script along with content type | MediaHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediaHandler:
"""A class storing URI for media file, such as css, java script along with content type"""
def __init__(self, objects=[]):
"""Initialization method. The argument objects must be sequence of sequence, like (('foo.css', 'text/css'), ('bar.js', 'text/javascript'))."""
... | stack_v2_sparse_classes_36k_train_030847 | 8,943 | permissive | [
{
"docstring": "Initialization method. The argument objects must be sequence of sequence, like (('foo.css', 'text/css'), ('bar.js', 'text/javascript')).",
"name": "__init__",
"signature": "def __init__(self, objects=[])"
},
{
"docstring": "A method to add given media object to the instance, keep... | 4 | stack_v2_sparse_classes_30k_test_001069 | Implement the Python class `MediaHandler` described below.
Class description:
A class storing URI for media file, such as css, java script along with content type
Method signatures and docstrings:
- def __init__(self, objects=[]): Initialization method. The argument objects must be sequence of sequence, like (('foo.c... | Implement the Python class `MediaHandler` described below.
Class description:
A class storing URI for media file, such as css, java script along with content type
Method signatures and docstrings:
- def __init__(self, objects=[]): Initialization method. The argument objects must be sequence of sequence, like (('foo.c... | e1209f7d44d1c59ff9d373b7d89d414f31a9c28b | <|skeleton|>
class MediaHandler:
"""A class storing URI for media file, such as css, java script along with content type"""
def __init__(self, objects=[]):
"""Initialization method. The argument objects must be sequence of sequence, like (('foo.css', 'text/css'), ('bar.js', 'text/javascript'))."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MediaHandler:
"""A class storing URI for media file, such as css, java script along with content type"""
def __init__(self, objects=[]):
"""Initialization method. The argument objects must be sequence of sequence, like (('foo.css', 'text/css'), ('bar.js', 'text/javascript'))."""
self.orde... | the_stack_v2_python_sparse | aha/widget/handler.py | Letractively/aha-gae | train | 0 |
6899a1784fea90a7f2afd9071e9d56a95e8dde55 | [
"super(GaussianFilterNd, self).__init__()\nself.dims = dims\nself.sigma = nn.Parameter(torch.tensor(sigma, dtype=torch.float32), requires_grad=trainable)\nself.truncate = truncate\nself.kernel_size = kernel_size\nself.padding_mode = padding_mode\nself.padding_value = padding_value",
"for dim in self.dims:\n te... | <|body_start_0|>
super(GaussianFilterNd, self).__init__()
self.dims = dims
self.sigma = nn.Parameter(torch.tensor(sigma, dtype=torch.float32), requires_grad=trainable)
self.truncate = truncate
self.kernel_size = kernel_size
self.padding_mode = padding_mode
self.pa... | A differentiable gaussian filter | GaussianFilterNd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianFilterNd:
"""A differentiable gaussian filter"""
def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False):
"""Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is app... | stack_v2_sparse_classes_36k_train_030848 | 8,932 | permissive | [
{
"docstring": "Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is applied. Negative values won't work sigma (float): standard deviation of the gaussian filter (blur size) truncate (float, optional): truncate the filter at this many standard deviations (default: 4.0)... | 2 | stack_v2_sparse_classes_30k_test_001032 | Implement the Python class `GaussianFilterNd` described below.
Class description:
A differentiable gaussian filter
Method signatures and docstrings:
- def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False): Creates a 1d gaussian filter Args: dims ([... | Implement the Python class `GaussianFilterNd` described below.
Class description:
A differentiable gaussian filter
Method signatures and docstrings:
- def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False): Creates a 1d gaussian filter Args: dims ([... | 0664dba9b637f64b089b3a44b191dd24da84a30e | <|skeleton|>
class GaussianFilterNd:
"""A differentiable gaussian filter"""
def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False):
"""Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianFilterNd:
"""A differentiable gaussian filter"""
def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False):
"""Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is applied. Negativ... | the_stack_v2_python_sparse | pysaliency/torch_utils.py | matthias-k/pysaliency | train | 142 |
30018671dd6ed5fb4baa21b9c63cdc64d914bfa2 | [
"batch = batch.to(self.device)\nnoisy_wavs, lens = batch.noisy_sig\nnoisy_feats = self.compute_feats(noisy_wavs)\nmask = self.modules.model(noisy_feats)\nmask = torch.squeeze(mask, 2)\npredict_spec = torch.mul(mask, noisy_feats)\npredict_wav = self.hparams.resynth(torch.expm1(predict_spec), noisy_wavs)\nreturn (pre... | <|body_start_0|>
batch = batch.to(self.device)
noisy_wavs, lens = batch.noisy_sig
noisy_feats = self.compute_feats(noisy_wavs)
mask = self.modules.model(noisy_feats)
mask = torch.squeeze(mask, 2)
predict_spec = torch.mul(mask, noisy_feats)
predict_wav = self.hpara... | SEBrain | [
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEBrain:
def compute_forward(self, batch, stage):
"""Forward computations from the waveform batches to the enhanced output."""
<|body_0|>
def compute_feats(self, wavs):
"""Feature computation pipeline"""
<|body_1|>
def compute_objectives(self, prediction... | stack_v2_sparse_classes_36k_train_030849 | 8,973 | permissive | [
{
"docstring": "Forward computations from the waveform batches to the enhanced output.",
"name": "compute_forward",
"signature": "def compute_forward(self, batch, stage)"
},
{
"docstring": "Feature computation pipeline",
"name": "compute_feats",
"signature": "def compute_feats(self, wavs... | 5 | stack_v2_sparse_classes_30k_train_004655 | Implement the Python class `SEBrain` described below.
Class description:
Implement the SEBrain class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Forward computations from the waveform batches to the enhanced output.
- def compute_feats(self, wavs): Feature computation pipeline
- def ... | Implement the Python class `SEBrain` described below.
Class description:
Implement the SEBrain class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Forward computations from the waveform batches to the enhanced output.
- def compute_feats(self, wavs): Feature computation pipeline
- def ... | d4c9a53773f13d5a2843f25bc7f89482936e2f17 | <|skeleton|>
class SEBrain:
def compute_forward(self, batch, stage):
"""Forward computations from the waveform batches to the enhanced output."""
<|body_0|>
def compute_feats(self, wavs):
"""Feature computation pipeline"""
<|body_1|>
def compute_objectives(self, prediction... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEBrain:
def compute_forward(self, batch, stage):
"""Forward computations from the waveform batches to the enhanced output."""
batch = batch.to(self.device)
noisy_wavs, lens = batch.noisy_sig
noisy_feats = self.compute_feats(noisy_wavs)
mask = self.modules.model(noisy_f... | the_stack_v2_python_sparse | recipes/Voicebank/enhance/spectral_mask/train.py | zycv/speechbrain | train | 2 | |
2124bd3ed69fc82ee59194f9ad1c26ce0e5d7d2e | [
"self.name = name\nself._implementation = None\nself._schema_name = schema_name\nself._arguments_coercer = arguments_coercer\nself._list_concurrently = list_concurrently\nself._parent_concurrently = parent_concurrently",
"if not self._implementation:\n raise MissingImplementation(f'No implementation given for ... | <|body_start_0|>
self.name = name
self._implementation = None
self._schema_name = schema_name
self._arguments_coercer = arguments_coercer
self._list_concurrently = list_concurrently
self._parent_concurrently = parent_concurrently
<|end_body_0|>
<|body_start_1|>
i... | This decorator allows you to link a GraphQL Schema subscription field to a subscription generator. For example, for the following SDL: type Subscription { countdown(startAt: Int!): Int! } Use the Subscription decorator the following way: @Subscription("Subscription.countdown") async def countdown_subscription(parent, a... | Subscription | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscription:
"""This decorator allows you to link a GraphQL Schema subscription field to a subscription generator. For example, for the following SDL: type Subscription { countdown(startAt: Int!): Int! } Use the Subscription decorator the following way: @Subscription("Subscription.countdown") as... | stack_v2_sparse_classes_36k_train_030850 | 4,069 | permissive | [
{
"docstring": ":param name: name of the subscription field :param schema_name: name of the schema to which link the subscription :param arguments_coercer: callable to use to coerce field arguments :param list_concurrently: whether or not list will be coerced concurrently :param parent_concurrently: whether or ... | 3 | stack_v2_sparse_classes_30k_train_002623 | Implement the Python class `Subscription` described below.
Class description:
This decorator allows you to link a GraphQL Schema subscription field to a subscription generator. For example, for the following SDL: type Subscription { countdown(startAt: Int!): Int! } Use the Subscription decorator the following way: @Su... | Implement the Python class `Subscription` described below.
Class description:
This decorator allows you to link a GraphQL Schema subscription field to a subscription generator. For example, for the following SDL: type Subscription { countdown(startAt: Int!): Int! } Use the Subscription decorator the following way: @Su... | 421c1e937f553d6a5bf2f30154022c0d77053cfb | <|skeleton|>
class Subscription:
"""This decorator allows you to link a GraphQL Schema subscription field to a subscription generator. For example, for the following SDL: type Subscription { countdown(startAt: Int!): Int! } Use the Subscription decorator the following way: @Subscription("Subscription.countdown") as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subscription:
"""This decorator allows you to link a GraphQL Schema subscription field to a subscription generator. For example, for the following SDL: type Subscription { countdown(startAt: Int!): Int! } Use the Subscription decorator the following way: @Subscription("Subscription.countdown") async def count... | the_stack_v2_python_sparse | tartiflette/subscription/subscription.py | tartiflette/tartiflette | train | 586 |
ad52fd6ebf003d56051a3d3f553df49511734707 | [
"res = []\n\ndef serialize_util(root):\n nonlocal res\n if not root:\n return\n res.append(root.val)\n serialize_util(root.left)\n serialize_util(root.right)\n return\nserialize_util(root)\nreturn ' '.join((str(s) for s in res))",
"data = [int(s) for s in data.split()]\n\ndef deserialize_... | <|body_start_0|>
res = []
def serialize_util(root):
nonlocal res
if not root:
return
res.append(root.val)
serialize_util(root.left)
serialize_util(root.right)
return
serialize_util(root)
return ' '.j... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030851 | 1,471 | permissive | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: Optional[TreeNode]) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> Optional[TreeNode... | 2 | stack_v2_sparse_classes_30k_val_000937 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree.
<... | c80dbb9f0d09cdde72e01a09fb44a512d3b7c30e | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
res = []
def serialize_util(root):
nonlocal res
if not root:
return
res.append(root.val)
serialize_util(root.left)
... | the_stack_v2_python_sparse | code/449.Serialize-and-Deserialize-BST.py | Aden-Q/LeetCode | train | 0 | |
b0318ead544eb822daeabf448618c2207589fa1a | [
"numLen = len(nums)\nfor i in range(k % numLen):\n nums.insert(0, nums.pop())",
"k %= len(nums)\nnums.reverse()\nnums[0:k].reverse()\nnums[k:len(nums)].reverse()"
] | <|body_start_0|>
numLen = len(nums)
for i in range(k % numLen):
nums.insert(0, nums.pop())
<|end_body_0|>
<|body_start_1|>
k %= len(nums)
nums.reverse()
nums[0:k].reverse()
nums[k:len(nums)].reverse()
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k_train_030852 | 668 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste... | 2 | stack_v2_sparse_classes_30k_train_015778 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[in... | b9b302841100551b837c01be4ea6ad3aaade748e | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
numLen = len(nums)
for i in range(k % numLen):
nums.insert(0, nums.pop())
def rotate2(self, nums, k):
""":type nums:... | the_stack_v2_python_sparse | 201611_Week1/20161103_2.py | Troy-Wang/LeetCode | train | 0 | |
06241e4c35defeba9f1619b8e71f4fb58b9eaf1d | [
"super(MlpPolicy, self).__init__(placeholders=placeholders)\nself.reuse = reuse\nself.name = name\nself._init(*args, **kwargs)\nself.scope = tf.get_variable_scope().name\nself.sess = sess",
"obs, pdtype = self.get_obs_and_pdtype(ob_space, ac_space)\nwith tf.variable_scope(self.name + '/obfilter', reuse=self.reuse... | <|body_start_0|>
super(MlpPolicy, self).__init__(placeholders=placeholders)
self.reuse = reuse
self.name = name
self._init(*args, **kwargs)
self.scope = tf.get_variable_scope().name
self.sess = sess
<|end_body_0|>
<|body_start_1|>
obs, pdtype = self.get_obs_and_p... | MlpPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MlpPolicy:
def __init__(self, name, *args, sess=None, reuse=False, placeholders=None, **kwargs):
"""A MLP policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment :param ac_space: (Gym Space) T... | stack_v2_sparse_classes_36k_train_030853 | 6,504 | permissive | [
{
"docstring": "A MLP policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment :param ac_space: (Gym Space) The action space of the environment :param hid_size: (int) the size of the hidden layers :param num_hid_layer... | 2 | stack_v2_sparse_classes_30k_train_019014 | Implement the Python class `MlpPolicy` described below.
Class description:
Implement the MlpPolicy class.
Method signatures and docstrings:
- def __init__(self, name, *args, sess=None, reuse=False, placeholders=None, **kwargs): A MLP policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :p... | Implement the Python class `MlpPolicy` described below.
Class description:
Implement the MlpPolicy class.
Method signatures and docstrings:
- def __init__(self, name, *args, sess=None, reuse=False, placeholders=None, **kwargs): A MLP policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :p... | 5f11927a4420b46bed873c4a8477a55153d37bcd | <|skeleton|>
class MlpPolicy:
def __init__(self, name, *args, sess=None, reuse=False, placeholders=None, **kwargs):
"""A MLP policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment :param ac_space: (Gym Space) T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MlpPolicy:
def __init__(self, name, *args, sess=None, reuse=False, placeholders=None, **kwargs):
"""A MLP policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment :param ac_space: (Gym Space) The action spac... | the_stack_v2_python_sparse | baselines/ppo1/mlp_policy.py | northtiger/stable-baselines | train | 0 | |
84cba4e2faf2159b7df116e8628a1d883b59e6fb | [
"self.current_nickname = TidyReqData.get_nickname()\nself.articles_list = get_collection_article(self.current_nickname, article={'$exists': False}, title={'$exists': True})\nself.crawler_begin_time = time()\nself.crawler_parse_counter = 0",
"for article in self.articles_list:\n if 'weixin' in article['content_... | <|body_start_0|>
self.current_nickname = TidyReqData.get_nickname()
self.articles_list = get_collection_article(self.current_nickname, article={'$exists': False}, title={'$exists': True})
self.crawler_begin_time = time()
self.crawler_parse_counter = 0
<|end_body_0|>
<|body_start_1|>
... | 公众号文章内容爬虫 | ArticleSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleSpider:
"""公众号文章内容爬虫"""
def __init__(self, *args, **kwargs):
""":param args: :param kwargs: 实例化爬虫需要调用的函数"""
<|body_0|>
def start_requests(self):
""":return:重新爬虫的入口函数, 否者直接请求start_urls中的各个url 重写之后手动调用Request并指定回调函数例如self.parse"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_030854 | 7,358 | no_license | [
{
"docstring": ":param args: :param kwargs: 实例化爬虫需要调用的函数",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": ":return:重新爬虫的入口函数, 否者直接请求start_urls中的各个url 重写之后手动调用Request并指定回调函数例如self.parse",
"name": "start_requests",
"signature": "def start_requests(... | 4 | null | Implement the Python class `ArticleSpider` described below.
Class description:
公众号文章内容爬虫
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :param args: :param kwargs: 实例化爬虫需要调用的函数
- def start_requests(self): :return:重新爬虫的入口函数, 否者直接请求start_urls中的各个url 重写之后手动调用Request并指定回调函数例如self.parse
- def par... | Implement the Python class `ArticleSpider` described below.
Class description:
公众号文章内容爬虫
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :param args: :param kwargs: 实例化爬虫需要调用的函数
- def start_requests(self): :return:重新爬虫的入口函数, 否者直接请求start_urls中的各个url 重写之后手动调用Request并指定回调函数例如self.parse
- def par... | 6d2b4db3d34183d729f6fd30555c6d6f04514260 | <|skeleton|>
class ArticleSpider:
"""公众号文章内容爬虫"""
def __init__(self, *args, **kwargs):
""":param args: :param kwargs: 实例化爬虫需要调用的函数"""
<|body_0|>
def start_requests(self):
""":return:重新爬虫的入口函数, 否者直接请求start_urls中的各个url 重写之后手动调用Request并指定回调函数例如self.parse"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleSpider:
"""公众号文章内容爬虫"""
def __init__(self, *args, **kwargs):
""":param args: :param kwargs: 实例化爬虫需要调用的函数"""
self.current_nickname = TidyReqData.get_nickname()
self.articles_list = get_collection_article(self.current_nickname, article={'$exists': False}, title={'$exists': Tr... | the_stack_v2_python_sparse | weixin_crawler/project/crawler/crawler/spiders/article.py | cassieeric/python_crawler | train | 322 |
02e17a753ee773477fcf2ba49621e108f262395a | [
"self.typology = 'Simple'\nself.trace = trace\nself.dip = dip\nself.upper_depth = upper_depth\nself.lower_depth = lower_depth\nself.surface = SimpleFaultSurface.from_fault_data(self.trace, self.upper_depth, self.lower_depth, self.dip, mesh_spacing)\nself.length = trace.get_length()\nself.downdip_width = None\nself.... | <|body_start_0|>
self.typology = 'Simple'
self.trace = trace
self.dip = dip
self.upper_depth = upper_depth
self.lower_depth = lower_depth
self.surface = SimpleFaultSurface.from_fault_data(self.trace, self.upper_depth, self.lower_depth, self.dip, mesh_spacing)
self... | Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic d... | SimpleFaultGeometry | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleFaultGeometry:
"""Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km... | stack_v2_sparse_classes_36k_train_030855 | 6,464 | permissive | [
{
"docstring": "Sets up the fault geometry parameters from the input fault definitions :param float mesh_spacing: Spacing (km) of the fault surface mesh",
"name": "__init__",
"signature": "def __init__(self, trace, dip, upper_depth, lower_depth, mesh_spacing=1.0)"
},
{
"docstring": "Calculates t... | 2 | null | Implement the Python class `SimpleFaultGeometry` described below.
Class description:
Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float u... | Implement the Python class `SimpleFaultGeometry` described below.
Class description:
Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float u... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class SimpleFaultGeometry:
"""Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleFaultGeometry:
"""Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km) :param floa... | the_stack_v2_python_sparse | openquake/hmtk/faults/fault_geometries.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
458a9c1bcfbad838e32131bc43236e48ecb6fd87 | [
"TESTS = [('', {}), ('native_id=deadbeef', {'native_id': 'deadbeef'}), ('native_id=%5edeadbeef', {'native_id': '^deadbeef'}), ('native_id=deadbeef%20biscuit', {'native_id': 'deadbeef biscuit'}), ('native_id=deadbeef%20OR%20bob', {'native_id': 'deadbeef|bob'}), ('native_id=tom%20dick%20harry', {'native_id': 'tom dic... | <|body_start_0|>
TESTS = [('', {}), ('native_id=deadbeef', {'native_id': 'deadbeef'}), ('native_id=%5edeadbeef', {'native_id': '^deadbeef'}), ('native_id=deadbeef%20biscuit', {'native_id': 'deadbeef biscuit'}), ('native_id=deadbeef%20OR%20bob', {'native_id': 'deadbeef|bob'}), ('native_id=tom%20dick%20harry', {'... | Test the query string parser. | ParseTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParseTests:
"""Test the query string parser."""
def test_one_variable(self):
"""Various forms of single-variable query strings that can be submitted to /core/resources/<uuid>/ or /core/resource_types/<unique_id>/."""
<|body_0|>
def test_multiple_variables(self):
... | stack_v2_sparse_classes_36k_train_030856 | 22,971 | permissive | [
{
"docstring": "Various forms of single-variable query strings that can be submitted to /core/resources/<uuid>/ or /core/resource_types/<unique_id>/.",
"name": "test_one_variable",
"signature": "def test_one_variable(self)"
},
{
"docstring": "Various forms of multi-variable query strings that ca... | 2 | stack_v2_sparse_classes_30k_test_000203 | Implement the Python class `ParseTests` described below.
Class description:
Test the query string parser.
Method signatures and docstrings:
- def test_one_variable(self): Various forms of single-variable query strings that can be submitted to /core/resources/<uuid>/ or /core/resource_types/<unique_id>/.
- def test_mu... | Implement the Python class `ParseTests` described below.
Class description:
Test the query string parser.
Method signatures and docstrings:
- def test_one_variable(self): Various forms of single-variable query strings that can be submitted to /core/resources/<uuid>/ or /core/resource_types/<unique_id>/.
- def test_mu... | 73d334a9f0df7c044c06989977a9a22dd2ff9b7a | <|skeleton|>
class ParseTests:
"""Test the query string parser."""
def test_one_variable(self):
"""Various forms of single-variable query strings that can be submitted to /core/resources/<uuid>/ or /core/resource_types/<unique_id>/."""
<|body_0|>
def test_multiple_variables(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParseTests:
"""Test the query string parser."""
def test_one_variable(self):
"""Various forms of single-variable query strings that can be submitted to /core/resources/<uuid>/ or /core/resource_types/<unique_id>/."""
TESTS = [('', {}), ('native_id=deadbeef', {'native_id': 'deadbeef'}), ('... | the_stack_v2_python_sparse | goldstone/core/tests.py | bhuvan-rk/goldstone-server | train | 0 |
02f7cbfdcd0850f287bea5aca534dde80e41c411 | [
"super().at_object_creation()\nself.db.puzzle_value = 1\nself.db.success_teleport_msg = 'You are successful!'\nself.db.success_teleport_to = 'treasure room'\nself.db.failure_teleport_msg = 'You fail!'\nself.db.failure_teleport_to = 'dark cell'",
"if not character.has_account:\n return\nis_success = str(charact... | <|body_start_0|>
super().at_object_creation()
self.db.puzzle_value = 1
self.db.success_teleport_msg = 'You are successful!'
self.db.success_teleport_to = 'treasure room'
self.db.failure_teleport_msg = 'You fail!'
self.db.failure_teleport_to = 'dark cell'
<|end_body_0|>
<... | Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to success failure_teleport_to - wh... | TeleportRoom | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeleportRoom:
"""Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while telepor... | stack_v2_sparse_classes_36k_train_030857 | 42,922 | permissive | [
{
"docstring": "Called at first creation",
"name": "at_object_creation",
"signature": "def at_object_creation(self)"
},
{
"docstring": "This hook is called by the engine whenever the player is moved into this room.",
"name": "at_object_receive",
"signature": "def at_object_receive(self, ... | 2 | stack_v2_sparse_classes_30k_train_015835 | Implement the Python class `TeleportRoom` described below.
Class description:
Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_telep... | Implement the Python class `TeleportRoom` described below.
Class description:
Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_telep... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TeleportRoom:
"""Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while telepor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeleportRoom:
"""Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to succe... | the_stack_v2_python_sparse | evennia/contrib/tutorials/tutorial_world/rooms.py | evennia/evennia | train | 1,781 |
37b746b6bb27e70352bd839476530cb6bf206e44 | [
"self.reason = reason\nself.privacy = privacy\nself.unknown = unknown\nself.orig_to = orig_to",
"if dictionary is None:\n return None\nreason = dictionary.get('reason')\nprivacy = dictionary.get('privacy')\nunknown = dictionary.get('unknown')\norig_to = dictionary.get('origTo')\nreturn cls(reason, privacy, unk... | <|body_start_0|>
self.reason = reason
self.privacy = privacy
self.unknown = unknown
self.orig_to = orig_to
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
reason = dictionary.get('reason')
privacy = dictionary.get('privacy')
... | Implementation of the 'Diversion' model. TODO: type model description here. Attributes: reason (string): TODO: type description here. privacy (string): TODO: type description here. unknown (string): TODO: type description here. orig_to (string): TODO: type description here. | Diversion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Diversion:
"""Implementation of the 'Diversion' model. TODO: type model description here. Attributes: reason (string): TODO: type description here. privacy (string): TODO: type description here. unknown (string): TODO: type description here. orig_to (string): TODO: type description here."""
... | stack_v2_sparse_classes_36k_train_030858 | 2,040 | permissive | [
{
"docstring": "Constructor for the Diversion class",
"name": "__init__",
"signature": "def __init__(self, reason=None, privacy=None, unknown=None, orig_to=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of ... | 2 | stack_v2_sparse_classes_30k_train_018617 | Implement the Python class `Diversion` described below.
Class description:
Implementation of the 'Diversion' model. TODO: type model description here. Attributes: reason (string): TODO: type description here. privacy (string): TODO: type description here. unknown (string): TODO: type description here. orig_to (string)... | Implement the Python class `Diversion` described below.
Class description:
Implementation of the 'Diversion' model. TODO: type model description here. Attributes: reason (string): TODO: type description here. privacy (string): TODO: type description here. unknown (string): TODO: type description here. orig_to (string)... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class Diversion:
"""Implementation of the 'Diversion' model. TODO: type model description here. Attributes: reason (string): TODO: type description here. privacy (string): TODO: type description here. unknown (string): TODO: type description here. orig_to (string): TODO: type description here."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Diversion:
"""Implementation of the 'Diversion' model. TODO: type model description here. Attributes: reason (string): TODO: type description here. privacy (string): TODO: type description here. unknown (string): TODO: type description here. orig_to (string): TODO: type description here."""
def __init__(... | the_stack_v2_python_sparse | bandwidth/voice/models/diversion.py | Bandwidth/python-sdk | train | 10 |
f77f2ac55b6324b327ced40b73807265531f2a4f | [
"self.year = year\nself.dupersids = dupersids\nself.OB_LOOKUPS = {2018: {'model': OfficeBasedVisits18, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR', 'OBDATEMM', 'SEEDOC_M18'}, 'see_doc': 'SEEDOC_M18'}, 2017: {'model': OfficeBasedVisits17, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR', 'OBDATEMM', 'SEEDOC'}, 'see_doc... | <|body_start_0|>
self.year = year
self.dupersids = dupersids
self.OB_LOOKUPS = {2018: {'model': OfficeBasedVisits18, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR', 'OBDATEMM', 'SEEDOC_M18'}, 'see_doc': 'SEEDOC_M18'}, 2017: {'model': OfficeBasedVisits17, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR... | Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types. | OfficeBasedVisitsEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficeBasedVisitsEncoder:
"""Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types."""
def __init__(self, year, dupersids=None):
"""Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively f... | stack_v2_sparse_classes_36k_train_030859 | 5,068 | permissive | [
{
"docstring": "Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively fetch data for",
"name": "__init__",
"signature": "def __init__(self, year, dupersids=None)"
},
{
"docstring": "Groups events by respondents. Classifies events th... | 2 | stack_v2_sparse_classes_30k_train_001240 | Implement the Python class `OfficeBasedVisitsEncoder` described below.
Class description:
Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types.
Method signatures and docstrings:
- def __init__(self, year, dupersids=None): Required_Inputs: year: Year to fetch data for Optional Inputs:... | Implement the Python class `OfficeBasedVisitsEncoder` described below.
Class description:
Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types.
Method signatures and docstrings:
- def __init__(self, year, dupersids=None): Required_Inputs: year: Year to fetch data for Optional Inputs:... | cd98ff6b484799fc0f2f447b3945621bd013bee6 | <|skeleton|>
class OfficeBasedVisitsEncoder:
"""Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types."""
def __init__(self, year, dupersids=None):
"""Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficeBasedVisitsEncoder:
"""Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types."""
def __init__(self, year, dupersids=None):
"""Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively fetch data for... | the_stack_v2_python_sparse | meps_db/processors/encoders/office_based_visits_encoder.py | explore-meps/meps_dev | train | 0 |
eb86da42e35090952e8c205885c9fd6b3f4df7c2 | [
"if self.request.method == 'GET':\n return (IsInActiveCommunity(), IsInPubliclyVisibleCommunity())\nelif self.request.method == 'DELETE':\n return (IsInActiveCommunity(), IsAbleToDeleteComment())\nreturn tuple()",
"queryset = self.filter_queryset(self.get_queryset())\nqueryset = filter_queryset_permission(q... | <|body_start_0|>
if self.request.method == 'GET':
return (IsInActiveCommunity(), IsInPubliclyVisibleCommunity())
elif self.request.method == 'DELETE':
return (IsInActiveCommunity(), IsAbleToDeleteComment())
return tuple()
<|end_body_0|>
<|body_start_1|>
queryset ... | Comment view set | CommentViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentViewSet:
"""Comment view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List comments"""
<|body_1|>
def destroy(self, request, *args, **kwargs):
"""Disable instance"""
... | stack_v2_sparse_classes_36k_train_030860 | 8,383 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "List comments",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Disable instance",
"name": "destroy",
"signa... | 3 | null | Implement the Python class `CommentViewSet` described below.
Class description:
Comment view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def list(self, request, *args, **kwargs): List comments
- def destroy(self, request, *args, **kwargs): Disable instance | Implement the Python class `CommentViewSet` described below.
Class description:
Comment view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def list(self, request, *args, **kwargs): List comments
- def destroy(self, request, *args, **kwargs): Disable instance
<|skeleton|>
class ... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class CommentViewSet:
"""Comment view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List comments"""
<|body_1|>
def destroy(self, request, *args, **kwargs):
"""Disable instance"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentViewSet:
"""Comment view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (IsInActiveCommunity(), IsInPubliclyVisibleCommunity())
elif self.request.method == 'DELETE':
return (IsInActiveCommunity(), IsAb... | the_stack_v2_python_sparse | asset/views.py | 810Teams/clubs-and-events-backend | train | 3 |
0245cd05a02d242871dace80def4f60f8c9c72d9 | [
"self.initial = initial\nself.ids = list()\nself.num_states = self._number_states(self.initial, 0, self.ids)",
"if state.number is None:\n state.number = next_number\n next_number += 1\n for diedge, target in state._all_transitions():\n if diedge is not None:\n if diedge.srcID not in id... | <|body_start_0|>
self.initial = initial
self.ids = list()
self.num_states = self._number_states(self.initial, 0, self.ids)
<|end_body_0|>
<|body_start_1|>
if state.number is None:
state.number = next_number
next_number += 1
for diedge, target in state... | A finite automaton. Attributes: initial -- The initial state of the automaton ids -- The list of node IDs of the motif in the automaton num_states -- The number of states in this automaton | Automaton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Automaton:
"""A finite automaton. Attributes: initial -- The initial state of the automaton ids -- The list of node IDs of the motif in the automaton num_states -- The number of states in this automaton"""
def __init__(self, initial):
"""Create a new automaton with the given initial ... | stack_v2_sparse_classes_36k_train_030861 | 5,139 | no_license | [
{
"docstring": "Create a new automaton with the given initial state. Arguments: initial -- The initial automaton state",
"name": "__init__",
"signature": "def __init__(self, initial)"
},
{
"docstring": "Number the given @state and all states reachable from it. At the same time, collect diedge's ... | 3 | stack_v2_sparse_classes_30k_train_012024 | Implement the Python class `Automaton` described below.
Class description:
A finite automaton. Attributes: initial -- The initial state of the automaton ids -- The list of node IDs of the motif in the automaton num_states -- The number of states in this automaton
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `Automaton` described below.
Class description:
A finite automaton. Attributes: initial -- The initial state of the automaton ids -- The list of node IDs of the motif in the automaton num_states -- The number of states in this automaton
Method signatures and docstrings:
- def __init__(self,... | f3366d6871678faa37cd78e83fba9cae4976b94c | <|skeleton|>
class Automaton:
"""A finite automaton. Attributes: initial -- The initial state of the automaton ids -- The list of node IDs of the motif in the automaton num_states -- The number of states in this automaton"""
def __init__(self, initial):
"""Create a new automaton with the given initial ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Automaton:
"""A finite automaton. Attributes: initial -- The initial state of the automaton ids -- The list of node IDs of the motif in the automaton num_states -- The number of states in this automaton"""
def __init__(self, initial):
"""Create a new automaton with the given initial state. Argume... | the_stack_v2_python_sparse | scripts/gregex/automaton.py | TinkerBellSystem/graph-matching | train | 0 |
896b24452e5940d52efd94a4bd14d067d67d32be | [
"if not exactly_one(directory_uri, file_uri):\n raise ETLInputError('One of file_uri or directory_uri needed')\nsuper(ExtractS3Step, self).__init__(**kwargs)\nif directory_uri:\n directory_uri = get_modified_s3_path(directory_uri)\n s3_path = S3Path(uri=directory_uri, is_directory=True)\nelse:\n file_ur... | <|body_start_0|>
if not exactly_one(directory_uri, file_uri):
raise ETLInputError('One of file_uri or directory_uri needed')
super(ExtractS3Step, self).__init__(**kwargs)
if directory_uri:
directory_uri = get_modified_s3_path(directory_uri)
s3_path = S3Path(ur... | ExtractS3 Step class that helps get data from S3 | ExtractS3Step | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractS3Step:
"""ExtractS3 Step class that helps get data from S3"""
def __init__(self, directory_uri=None, file_uri=None, **kwargs):
"""Constructor for the ExtractS3Step class Args: directory_uri(str): s3 path for s3 data directory file_uri(str): s3 path for s3 data file **kwargs(o... | stack_v2_sparse_classes_36k_train_030862 | 1,733 | permissive | [
{
"docstring": "Constructor for the ExtractS3Step class Args: directory_uri(str): s3 path for s3 data directory file_uri(str): s3 path for s3 data file **kwargs(optional): Keyword arguments directly passed to base class",
"name": "__init__",
"signature": "def __init__(self, directory_uri=None, file_uri=... | 2 | stack_v2_sparse_classes_30k_train_018885 | Implement the Python class `ExtractS3Step` described below.
Class description:
ExtractS3 Step class that helps get data from S3
Method signatures and docstrings:
- def __init__(self, directory_uri=None, file_uri=None, **kwargs): Constructor for the ExtractS3Step class Args: directory_uri(str): s3 path for s3 data dir... | Implement the Python class `ExtractS3Step` described below.
Class description:
ExtractS3 Step class that helps get data from S3
Method signatures and docstrings:
- def __init__(self, directory_uri=None, file_uri=None, **kwargs): Constructor for the ExtractS3Step class Args: directory_uri(str): s3 path for s3 data dir... | 797cb719e6c2abeda0751ada3339c72bfb19c8f2 | <|skeleton|>
class ExtractS3Step:
"""ExtractS3 Step class that helps get data from S3"""
def __init__(self, directory_uri=None, file_uri=None, **kwargs):
"""Constructor for the ExtractS3Step class Args: directory_uri(str): s3 path for s3 data directory file_uri(str): s3 path for s3 data file **kwargs(o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtractS3Step:
"""ExtractS3 Step class that helps get data from S3"""
def __init__(self, directory_uri=None, file_uri=None, **kwargs):
"""Constructor for the ExtractS3Step class Args: directory_uri(str): s3 path for s3 data directory file_uri(str): s3 path for s3 data file **kwargs(optional): Key... | the_stack_v2_python_sparse | dataduct/steps/extract_s3.py | EverFi/dataduct | train | 3 |
4c63fbd7c64251ffc4ab2e8b269460ee951a99fd | [
"queryset = model_admin.queryset(request)\nresults = queryset.values_list('ip__country').order_by('ip__country').distinct()\ndata = ((code[0] or 'none', dict(COUNTRIES).get(code[0], _('None'))) for code in results if code[0] not in ['None', ''])\nreturn data",
"value = self.value()\nif value == 'none':\n retur... | <|body_start_0|>
queryset = model_admin.queryset(request)
results = queryset.values_list('ip__country').order_by('ip__country').distinct()
data = ((code[0] or 'none', dict(COUNTRIES).get(code[0], _('None'))) for code in results if code[0] not in ['None', ''])
return data
<|end_body_0|>
... | Filtre admin des pays des IP des accès | AccessIPCountryFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessIPCountryFilter:
"""Filtre admin des pays des IP des accès"""
def lookups(self, request, model_admin):
"""Renvoyer les options de pays"""
<|body_0|>
def queryset(self, request, queryset):
"""Filtrer le queryset par le pays sélectionné"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_030863 | 1,802 | no_license | [
{
"docstring": "Renvoyer les options de pays",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Filtrer le queryset par le pays sélectionné",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017896 | Implement the Python class `AccessIPCountryFilter` described below.
Class description:
Filtre admin des pays des IP des accès
Method signatures and docstrings:
- def lookups(self, request, model_admin): Renvoyer les options de pays
- def queryset(self, request, queryset): Filtrer le queryset par le pays sélectionné | Implement the Python class `AccessIPCountryFilter` described below.
Class description:
Filtre admin des pays des IP des accès
Method signatures and docstrings:
- def lookups(self, request, model_admin): Renvoyer les options de pays
- def queryset(self, request, queryset): Filtrer le queryset par le pays sélectionné
... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class AccessIPCountryFilter:
"""Filtre admin des pays des IP des accès"""
def lookups(self, request, model_admin):
"""Renvoyer les options de pays"""
<|body_0|>
def queryset(self, request, queryset):
"""Filtrer le queryset par le pays sélectionné"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessIPCountryFilter:
"""Filtre admin des pays des IP des accès"""
def lookups(self, request, model_admin):
"""Renvoyer les options de pays"""
queryset = model_admin.queryset(request)
results = queryset.values_list('ip__country').order_by('ip__country').distinct()
data = ... | the_stack_v2_python_sparse | scoop/user/access/admin/filters.py | artscoop/scoop | train | 0 |
ed3864bdd9c1092bb3b30fdf0cc4941a64cb7437 | [
"if not model_response.get('text'):\n return\nresp = model_response['text']\nself.metrics.add('knowledge_f1_docs', F1Metric.compute(resp, teacher_action[CONST.SELECTED_DOCS]))\nself.metrics.add('knowledge_f1_sentences', F1Metric.compute(resp, teacher_action[CONST.SELECTED_SENTENCES]))\nself.metrics.add('f1_retri... | <|body_start_0|>
if not model_response.get('text'):
return
resp = model_response['text']
self.metrics.add('knowledge_f1_docs', F1Metric.compute(resp, teacher_action[CONST.SELECTED_DOCS]))
self.metrics.add('knowledge_f1_sentences', F1Metric.compute(resp, teacher_action[CONST.S... | Knowledge Teacher. Input is Context. Target is selected __knowledge__. | KnowledgeTeacher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnowledgeTeacher:
"""Knowledge Teacher. Input is Context. Target is selected __knowledge__."""
def custom_evaluation(self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message) -> None:
"""Various F1 metrics for the generated model response."""
<|bod... | stack_v2_sparse_classes_36k_train_030864 | 16,717 | permissive | [
{
"docstring": "Various F1 metrics for the generated model response.",
"name": "custom_evaluation",
"signature": "def custom_evaluation(self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message) -> None"
},
{
"docstring": "Remove knowledge component of message, and mov... | 2 | null | Implement the Python class `KnowledgeTeacher` described below.
Class description:
Knowledge Teacher. Input is Context. Target is selected __knowledge__.
Method signatures and docstrings:
- def custom_evaluation(self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message) -> None: Various F1 m... | Implement the Python class `KnowledgeTeacher` described below.
Class description:
Knowledge Teacher. Input is Context. Target is selected __knowledge__.
Method signatures and docstrings:
- def custom_evaluation(self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message) -> None: Various F1 m... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class KnowledgeTeacher:
"""Knowledge Teacher. Input is Context. Target is selected __knowledge__."""
def custom_evaluation(self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message) -> None:
"""Various F1 metrics for the generated model response."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KnowledgeTeacher:
"""Knowledge Teacher. Input is Context. Target is selected __knowledge__."""
def custom_evaluation(self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message) -> None:
"""Various F1 metrics for the generated model response."""
if not model_respo... | the_stack_v2_python_sparse | projects/seeker/tasks/lm.py | facebookresearch/ParlAI | train | 10,943 |
a9ab8a10e10a9b7cbc0b0af534e3be93085ed0e0 | [
"operStatus = False\nif systemCommand.commandType == ESysCommandType.AddSysTopic:\n operStatus = self.__addSysTopic(systemCommand)\nelif systemCommand.commandType == ESysCommandType.AddCommercialAd:\n pass\nelse:\n Logger.logInfo('__SystemCommandDigester.digest: undigested command type:', systemCommand.com... | <|body_start_0|>
operStatus = False
if systemCommand.commandType == ESysCommandType.AddSysTopic:
operStatus = self.__addSysTopic(systemCommand)
elif systemCommand.commandType == ESysCommandType.AddCommercialAd:
pass
else:
Logger.logInfo('__SystemComman... | __SystemCommandDigester | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class __SystemCommandDigester:
def digest(self, systemCommand):
""":type systemCommand: message.db.mongodb.utiltables.TSystemCommand :rtype: bool"""
<|body_0|>
def __addSysTopic(self, scmd):
""":type scmd: message.db.mongodb.utiltables.TSystemCommand :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_030865 | 1,514 | no_license | [
{
"docstring": ":type systemCommand: message.db.mongodb.utiltables.TSystemCommand :rtype: bool",
"name": "digest",
"signature": "def digest(self, systemCommand)"
},
{
"docstring": ":type scmd: message.db.mongodb.utiltables.TSystemCommand :rtype: bool",
"name": "__addSysTopic",
"signature... | 2 | null | Implement the Python class `__SystemCommandDigester` described below.
Class description:
Implement the __SystemCommandDigester class.
Method signatures and docstrings:
- def digest(self, systemCommand): :type systemCommand: message.db.mongodb.utiltables.TSystemCommand :rtype: bool
- def __addSysTopic(self, scmd): :ty... | Implement the Python class `__SystemCommandDigester` described below.
Class description:
Implement the __SystemCommandDigester class.
Method signatures and docstrings:
- def digest(self, systemCommand): :type systemCommand: message.db.mongodb.utiltables.TSystemCommand :rtype: bool
- def __addSysTopic(self, scmd): :ty... | 47811e2cfe67c3c0de4c4be7394dd30e48732799 | <|skeleton|>
class __SystemCommandDigester:
def digest(self, systemCommand):
""":type systemCommand: message.db.mongodb.utiltables.TSystemCommand :rtype: bool"""
<|body_0|>
def __addSysTopic(self, scmd):
""":type scmd: message.db.mongodb.utiltables.TSystemCommand :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class __SystemCommandDigester:
def digest(self, systemCommand):
""":type systemCommand: message.db.mongodb.utiltables.TSystemCommand :rtype: bool"""
operStatus = False
if systemCommand.commandType == ESysCommandType.AddSysTopic:
operStatus = self.__addSysTopic(systemCommand)
... | the_stack_v2_python_sparse | python/dbcache/background/digester.py | bropony/gamit | train | 0 | |
3ed348c665e9b394601ae7bb225801930d588d46 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None or len(list_dictionaries) == 0:\n return '[]'\nreturn json.dumps(list_dictionaries)",
"if json_string is None or len(json_string) == 0:\n return []\nreturn json.loads(j... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or len(list_dictionaries) == 0:
return '[]'
return json.dumps(list_dicti... | class Base | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""class Base"""
def __init__(self, id=None):
"""class constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""returns the JSON string representation of list_dictionaries"""
<|body_1|>
def from_json_string(json_string):
"""s... | stack_v2_sparse_classes_36k_train_030866 | 1,138 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "returns the JSON string representation of list_dictionaries",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "st... | 3 | stack_v2_sparse_classes_30k_train_008822 | Implement the Python class `Base` described below.
Class description:
class Base
Method signatures and docstrings:
- def __init__(self, id=None): class constructor
- def to_json_string(list_dictionaries): returns the JSON string representation of list_dictionaries
- def from_json_string(json_string): static method th... | Implement the Python class `Base` described below.
Class description:
class Base
Method signatures and docstrings:
- def __init__(self, id=None): class constructor
- def to_json_string(list_dictionaries): returns the JSON string representation of list_dictionaries
- def from_json_string(json_string): static method th... | 1e70a39d39ad6b02ff1169a957a0459d7c42f9fc | <|skeleton|>
class Base:
"""class Base"""
def __init__(self, id=None):
"""class constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""returns the JSON string representation of list_dictionaries"""
<|body_1|>
def from_json_string(json_string):
"""s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""class Base"""
def __init__(self, id=None):
"""class constructor"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_dictionaries):
"""returns the JSON string r... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | pichu185/holbertonschool-higher_level_programming | train | 0 |
3636341c233339424441796f61c66b741e349e81 | [
"body1 = {'reqId': get_uuid(), 'areaCode': 'atAJ-A', 'startTime': '20181010' + '06000000', 'endTime': '20181023' + '06000000'}\na = api_v1_analysis_channel_sec_peak(body1)\ndict_data = json.loads(a)\nself.assertLessEqual(11542, dict_data['results'][1]['num'])",
"body1 = {'reqId': get_uuid(), 'areaCode': 'atAJ-A',... | <|body_start_0|>
body1 = {'reqId': get_uuid(), 'areaCode': 'atAJ-A', 'startTime': '20181010' + '06000000', 'endTime': '20181023' + '06000000'}
a = api_v1_analysis_channel_sec_peak(body1)
dict_data = json.loads(a)
self.assertLessEqual(11542, dict_data['results'][1]['num'])
<|end_body_0|>
... | 2.4.9.2安检口人数峰值分析 | TestApiAnalysisChannelSecPeak | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestApiAnalysisChannelSecPeak:
"""2.4.9.2安检口人数峰值分析"""
def test_01(self):
"""验证正确传入参数时能返回安检口人数峰值数据"""
<|body_0|>
def test_02(self):
"""验证查询非有效时间内不能查询到安检口人数峰值数据"""
<|body_1|>
def test_03(self):
"""验证区域通道不存在时,不能查到安检口人数峰值数据"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_030867 | 2,805 | no_license | [
{
"docstring": "验证正确传入参数时能返回安检口人数峰值数据",
"name": "test_01",
"signature": "def test_01(self)"
},
{
"docstring": "验证查询非有效时间内不能查询到安检口人数峰值数据",
"name": "test_02",
"signature": "def test_02(self)"
},
{
"docstring": "验证区域通道不存在时,不能查到安检口人数峰值数据",
"name": "test_03",
"signature": "def... | 5 | stack_v2_sparse_classes_30k_train_016440 | Implement the Python class `TestApiAnalysisChannelSecPeak` described below.
Class description:
2.4.9.2安检口人数峰值分析
Method signatures and docstrings:
- def test_01(self): 验证正确传入参数时能返回安检口人数峰值数据
- def test_02(self): 验证查询非有效时间内不能查询到安检口人数峰值数据
- def test_03(self): 验证区域通道不存在时,不能查到安检口人数峰值数据
- def test_04(self): 验证startTime大于end... | Implement the Python class `TestApiAnalysisChannelSecPeak` described below.
Class description:
2.4.9.2安检口人数峰值分析
Method signatures and docstrings:
- def test_01(self): 验证正确传入参数时能返回安检口人数峰值数据
- def test_02(self): 验证查询非有效时间内不能查询到安检口人数峰值数据
- def test_03(self): 验证区域通道不存在时,不能查到安检口人数峰值数据
- def test_04(self): 验证startTime大于end... | aa0749f4a237ee76a61579dc5984635a7127a631 | <|skeleton|>
class TestApiAnalysisChannelSecPeak:
"""2.4.9.2安检口人数峰值分析"""
def test_01(self):
"""验证正确传入参数时能返回安检口人数峰值数据"""
<|body_0|>
def test_02(self):
"""验证查询非有效时间内不能查询到安检口人数峰值数据"""
<|body_1|>
def test_03(self):
"""验证区域通道不存在时,不能查到安检口人数峰值数据"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestApiAnalysisChannelSecPeak:
"""2.4.9.2安检口人数峰值分析"""
def test_01(self):
"""验证正确传入参数时能返回安检口人数峰值数据"""
body1 = {'reqId': get_uuid(), 'areaCode': 'atAJ-A', 'startTime': '20181010' + '06000000', 'endTime': '20181023' + '06000000'}
a = api_v1_analysis_channel_sec_peak(body1)
di... | the_stack_v2_python_sparse | Airport/Auto_return/TestCase/test_data_platform_092.py | jingshiyue/zhongkeyuan_workspace | train | 0 |
db8b773aca99167c2b0c06142b324d3ac0c5385a | [
"super(ModuleUIFrame, self).__init__(parent)\nself.columnconfigure(0, weight=1)\nself.rowconfigure(0, weight=1)\napi_frame = ttk.LabelFrame(self, padding=8, text='Google API')\napi_frame.grid(row=0, column=0, sticky='W E N S')\napi_frame.columnconfigure(0, weight=1)\nself.reddit_api_user_agent = tk.StringVar()\nttk... | <|body_start_0|>
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
api_frame = ttk.LabelFrame(self, padding=8, text='Google API')
api_frame.grid(row=0, column=0, sticky='W E N S')
api_frame.columnconfigure(0, weig... | The UI for the gamedeals module | ModuleUIFrame | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
<|body_0|>
def update_google_key(self):
"""Updates the Google API key with the text value"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_030868 | 2,701 | permissive | [
{
"docstring": "Create a new UI for the module Args: parent: A tk or ttk object",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Updates the Google API key with the text value",
"name": "update_google_key",
"signature": "def update_google_key(self)"
}
... | 2 | stack_v2_sparse_classes_30k_test_000441 | Implement the Python class `ModuleUIFrame` described below.
Class description:
The UI for the gamedeals module
Method signatures and docstrings:
- def __init__(self, parent): Create a new UI for the module Args: parent: A tk or ttk object
- def update_google_key(self): Updates the Google API key with the text value | Implement the Python class `ModuleUIFrame` described below.
Class description:
The UI for the gamedeals module
Method signatures and docstrings:
- def __init__(self, parent): Create a new UI for the module Args: parent: A tk or ttk object
- def update_google_key(self): Updates the Google API key with the text value
... | 3e044b7152a04ebf15e95bd332f476724b40c652 | <|skeleton|>
class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
<|body_0|>
def update_google_key(self):
"""Updates the Google API key with the text value"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
api_f... | the_stack_v2_python_sparse | modis/discord_modis/modules/gamedeals/_ui.py | OKEPlazmA/modis | train | 0 |
68ef1223d3022307efa878db16af851897523fd7 | [
"batch = cls(name=name, on_weekdays=on_weekdays, on_weekends=on_weekends, clazz=clazz, target_year=target_year, target_exam=target_exam, type=type, other=other, batch_timings=batch_timings, institute_id=institute_id)\ndb.session.add(batch)\ntry:\n db.session.commit()\nexcept IntegrityError:\n db.session.rollb... | <|body_start_0|>
batch = cls(name=name, on_weekdays=on_weekdays, on_weekends=on_weekends, clazz=clazz, target_year=target_year, target_exam=target_exam, type=type, other=other, batch_timings=batch_timings, institute_id=institute_id)
db.session.add(batch)
try:
db.session.commit()
... | Batch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Batch:
def create(cls, name, on_weekdays, on_weekends, clazz, target_year, target_exam, type, other, batch_timings, institute_id):
"""Create a new batch :param name: :param on_weekdays: :param on_weekends: :param clazz: :param target_year: :param target_exam: :param type: :param other: s... | stack_v2_sparse_classes_36k_train_030869 | 4,381 | no_license | [
{
"docstring": "Create a new batch :param name: :param on_weekdays: :param on_weekends: :param clazz: :param target_year: :param target_exam: :param type: :param other: some text about batch :param batch_timings: string in the form ``h1:m1-h2:m2`` :param institute_id: :return:",
"name": "create",
"signa... | 3 | stack_v2_sparse_classes_30k_train_007757 | Implement the Python class `Batch` described below.
Class description:
Implement the Batch class.
Method signatures and docstrings:
- def create(cls, name, on_weekdays, on_weekends, clazz, target_year, target_exam, type, other, batch_timings, institute_id): Create a new batch :param name: :param on_weekdays: :param o... | Implement the Python class `Batch` described below.
Class description:
Implement the Batch class.
Method signatures and docstrings:
- def create(cls, name, on_weekdays, on_weekends, clazz, target_year, target_exam, type, other, batch_timings, institute_id): Create a new batch :param name: :param on_weekdays: :param o... | c8af233693cd6a97489a2d73a85646b15220389c | <|skeleton|>
class Batch:
def create(cls, name, on_weekdays, on_weekends, clazz, target_year, target_exam, type, other, batch_timings, institute_id):
"""Create a new batch :param name: :param on_weekdays: :param on_weekends: :param clazz: :param target_year: :param target_exam: :param type: :param other: s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Batch:
def create(cls, name, on_weekdays, on_weekends, clazz, target_year, target_exam, type, other, batch_timings, institute_id):
"""Create a new batch :param name: :param on_weekdays: :param on_weekends: :param clazz: :param target_year: :param target_exam: :param type: :param other: some text about... | the_stack_v2_python_sparse | exam_app/models/batch.py | GraphicalDot/testrocketbackend | train | 0 | |
39c55b6abd96132265b026d4484734f85b2ee518 | [
"if not cls._repository_url:\n return None\nif not cls._repository_url.startswith('https://github.com/'):\n raise RuntimeError('Do not known how to handle this repository: %s' % cls._repository_url)\nlocal_repository_dir = cls.local_repository_location()\nif not local_repository_dir:\n return None\nreturn ... | <|body_start_0|>
if not cls._repository_url:
return None
if not cls._repository_url.startswith('https://github.com/'):
raise RuntimeError('Do not known how to handle this repository: %s' % cls._repository_url)
local_repository_dir = cls.local_repository_location()
... | Implements all methods needed to handle cache handling for git-repository-based adapters | GitRepositoryAdapter | [
"MIT",
"CC-BY-SA-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitRepositoryAdapter:
"""Implements all methods needed to handle cache handling for git-repository-based adapters"""
def fetch_command(cls):
"""Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not s... | stack_v2_sparse_classes_36k_train_030870 | 5,184 | permissive | [
{
"docstring": "Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not specified",
"name": "fetch_command",
"signature": "def fetch_command(cls)"
},
{
"docstring": "Update of the repository. Return cmdline that h... | 6 | stack_v2_sparse_classes_30k_test_001056 | Implement the Python class `GitRepositoryAdapter` described below.
Class description:
Implements all methods needed to handle cache handling for git-repository-based adapters
Method signatures and docstrings:
- def fetch_command(cls): Initial fetch of the repository. Return cmdline that has to be executed to fetch th... | Implement the Python class `GitRepositoryAdapter` described below.
Class description:
Implements all methods needed to handle cache handling for git-repository-based adapters
Method signatures and docstrings:
- def fetch_command(cls): Initial fetch of the repository. Return cmdline that has to be executed to fetch th... | 7a3c5c32d1a087770c65d765b546e3f6b856626e | <|skeleton|>
class GitRepositoryAdapter:
"""Implements all methods needed to handle cache handling for git-repository-based adapters"""
def fetch_command(cls):
"""Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitRepositoryAdapter:
"""Implements all methods needed to handle cache handling for git-repository-based adapters"""
def fetch_command(cls):
"""Initial fetch of the repository. Return cmdline that has to be executed to fetch the repository. Skipping if `self._repository_url` is not specified"""
... | the_stack_v2_python_sparse | lib/adapter/git_adapter.py | santoshakil/cheat.sh | train | 2 |
e45336dc06bdfc788358ce530f2d3e1e6645c4b0 | [
"self.news_dict = {}\nself.news_ls = []\nself.follow_dict = {}",
"if userId not in self.follow_dict.keys():\n self.follow_dict[userId] = [userId]\nif userId not in self.news_dict.keys():\n self.news_dict[userId] = [tweetId]\nelse:\n self.news_dict[userId].append(tweetId)\nself.news_ls.append([userId, twe... | <|body_start_0|>
self.news_dict = {}
self.news_ls = []
self.follow_dict = {}
<|end_body_0|>
<|body_start_1|>
if userId not in self.follow_dict.keys():
self.follow_dict[userId] = [userId]
if userId not in self.news_dict.keys():
self.news_dict[userId] = [tw... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. 发一条twitter时,将自己加为好友"""
<|body_1|>
def getNewsFeed(self, userId):
"""Retrieve the 10 most recent tweet... | stack_v2_sparse_classes_36k_train_030871 | 3,312 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. 发一条twitter时,将自己加为好友",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"docstring": "Retrieve the 10 m... | 5 | null | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. 发一条twitter时,将自己加为好友
- def getNewsFeed(self, userId): Retrieve ... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. 发一条twitter时,将自己加为好友
- def getNewsFeed(self, userId): Retrieve ... | a290361c3cf6420ae1f7951bb9bad1b8f7e2a829 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. 发一条twitter时,将自己加为好友"""
<|body_1|>
def getNewsFeed(self, userId):
"""Retrieve the 10 most recent tweet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.news_dict = {}
self.news_ls = []
self.follow_dict = {}
def postTweet(self, userId, tweetId):
"""Compose a new tweet. 发一条twitter时,将自己加为好友"""
if userId not in self.follow_dict.keys()... | the_stack_v2_python_sparse | leetcode/#355 design-twitter.py | maizijun/study | train | 1 | |
176f9c96473c91c95257a7fea9fbda20ab53ac5c | [
"self._historical_info = copy.deepcopy(historical_info)\nself._subtype = subtype\nself._epsilon = epsilon",
"if not arms_sampled:\n raise ValueError('arms_sampled is empty!')\navg_payoff_arm_name_list = []\nfor arm_name, sampled_arm in arms_sampled.iteritems():\n avg_payoff = numpy.float64(sampled_arm.win -... | <|body_start_0|>
self._historical_info = copy.deepcopy(historical_info)
self._subtype = subtype
self._epsilon = epsilon
<|end_body_0|>
<|body_start_1|>
if not arms_sampled:
raise ValueError('arms_sampled is empty!')
avg_payoff_arm_name_list = []
for arm_name,... | Implementation of the constructor and common methods of Epsilon. Abstract method allocate_arms implemented in subclass. A class to encapsulate the computation of bandit epsilon. Epsilon is the sole hyperparameter in this class. Subclasses may contain other hyperparameters. See :mod:`moe.bandit.bandit_interface` docs fo... | EpsilonInterface | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpsilonInterface:
"""Implementation of the constructor and common methods of Epsilon. Abstract method allocate_arms implemented in subclass. A class to encapsulate the computation of bandit epsilon. Epsilon is the sole hyperparameter in this class. Subclasses may contain other hyperparameters. Se... | stack_v2_sparse_classes_36k_train_030872 | 2,713 | permissive | [
{
"docstring": "Construct an Epsilon object. :param historical_info: a dictionary of arms sampled :type historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype: subtype of the epsilon bandit algorithm (default: None) :type subty... | 2 | stack_v2_sparse_classes_30k_train_016323 | Implement the Python class `EpsilonInterface` described below.
Class description:
Implementation of the constructor and common methods of Epsilon. Abstract method allocate_arms implemented in subclass. A class to encapsulate the computation of bandit epsilon. Epsilon is the sole hyperparameter in this class. Subclasse... | Implement the Python class `EpsilonInterface` described below.
Class description:
Implementation of the constructor and common methods of Epsilon. Abstract method allocate_arms implemented in subclass. A class to encapsulate the computation of bandit epsilon. Epsilon is the sole hyperparameter in this class. Subclasse... | 44143f25424c30d58321f8da8f60ce161bb83e67 | <|skeleton|>
class EpsilonInterface:
"""Implementation of the constructor and common methods of Epsilon. Abstract method allocate_arms implemented in subclass. A class to encapsulate the computation of bandit epsilon. Epsilon is the sole hyperparameter in this class. Subclasses may contain other hyperparameters. Se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EpsilonInterface:
"""Implementation of the constructor and common methods of Epsilon. Abstract method allocate_arms implemented in subclass. A class to encapsulate the computation of bandit epsilon. Epsilon is the sole hyperparameter in this class. Subclasses may contain other hyperparameters. See :mod:`moe.b... | the_stack_v2_python_sparse | moe/bandit/epsilon/epsilon_interface.py | melikavah/test | train | 2 |
d00dc0595f5fa7aacbd4cff9856c032dfccced00 | [
"\"\"\"\n 返回前缀遍历数组\n \"\"\"\nresult = []\n\ndef preorder(root):\n if not root:\n result.append('null')\n return\n result.append(root.val)\n preorder(root.left)\n preorder(root.right)\npreorder(root)\nreturn str(result)",
"tree_list = eval(data)\n\ndef preorder(tree_list):\n... | <|body_start_0|>
"""
返回前缀遍历数组
"""
result = []
def preorder(root):
if not root:
result.append('null')
return
result.append(root.val)
preorder(root.left)
preorder(root.right)
pr... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_030873 | 2,245 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
"""
返回前缀遍历数组
"""
result = []
def preorder(root):
if not root:
result.append('null')
return
... | the_stack_v2_python_sparse | datastructure/binary_tree/Codec.py | yinhuax/leet_code | train | 0 | |
b7aaf2b60fd64b6b2ea2585cd5e0e7c8e324906e | [
"s = 0\nfor x in self.help(root):\n s += int(x)\nreturn s",
"if root is None:\n return []\nif is_leaf(root):\n return [str(root.val)]\nlr = self.help(root.left) + self.help(root.right)\nreturn [str(root.val) + x for x in lr]"
] | <|body_start_0|>
s = 0
for x in self.help(root):
s += int(x)
return s
<|end_body_0|>
<|body_start_1|>
if root is None:
return []
if is_leaf(root):
return [str(root.val)]
lr = self.help(root.left) + self.help(root.right)
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def help(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = 0
for x in self.help(root):
s +... | stack_v2_sparse_classes_36k_train_030874 | 2,216 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers",
"signature": "def sumNumbers(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "help",
"signature": "def help(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000243 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers(self, root): :type root: TreeNode :rtype: int
- def help(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers(self, root): :type root: TreeNode :rtype: int
- def help(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumNumbers(self, root... | 911c6622448a4be041834bcab25051dd0f9209b2 | <|skeleton|>
class Solution:
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def help(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
s = 0
for x in self.help(root):
s += int(x)
return s
def help(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return []
if is_l... | the_stack_v2_python_sparse | leetcode/python/129/save | frankieliu/problems | train | 1 | |
a305b417802142ddb5444953fad966f1a7e2a30c | [
"self.X = X\nself.Y = pdist(X, metric=options['metric'])\nself.clustering_method = clustering_method\nself.options = options\nself.prototypes = None\nself.clusters = None",
"options = self.options\nif options['use_raw'] == False:\n agglo = AgglomerativeClustering.Agglomerative(self.Y, options['threshold'])\nel... | <|body_start_0|>
self.X = X
self.Y = pdist(X, metric=options['metric'])
self.clustering_method = clustering_method
self.options = options
self.prototypes = None
self.clusters = None
<|end_body_0|>
<|body_start_1|>
options = self.options
if options['use_ra... | Codebook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codebook:
def __init__(self, X, clustering_method='agglomerative', **options):
"""**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_met... | stack_v2_sparse_classes_36k_train_030875 | 4,078 | no_license | [
{
"docstring": "**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_method (optional): default *agglomerative*. Defines the clustering method to be used for find... | 3 | stack_v2_sparse_classes_30k_train_019810 | Implement the Python class `Codebook` described below.
Class description:
Implement the Codebook class.
Method signatures and docstrings:
- def __init__(self, X, clustering_method='agglomerative', **options): **Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Impleme... | Implement the Python class `Codebook` described below.
Class description:
Implement the Codebook class.
Method signatures and docstrings:
- def __init__(self, X, clustering_method='agglomerative', **options): **Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Impleme... | 90531055691a094dd271966b53c40b7a097df375 | <|skeleton|>
class Codebook:
def __init__(self, X, clustering_method='agglomerative', **options):
"""**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codebook:
def __init__(self, X, clustering_method='agglomerative', **options):
"""**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_method (optional)... | the_stack_v2_python_sparse | ImageRepresentation/codebook/CodebookGeneration.py | kmakantasis/CV-Tools | train | 0 | |
a23e509c9fac587b86e1984d4b8a20c7c64f3232 | [
"kwargs['input'] = ''\nsuper().__init__(work, **kwargs)\nself.audio = silence(self.delay)\nsuper().define_action()",
"text_ = kwargs.get(mc.VALUES, '')\nif text_ != '':\n raise mex.MMValueError(message_text(self.work, 'WA80101', (text_, '')))\nme = super().copy(**kwargs)\nreturn silence(me.delay)"
] | <|body_start_0|>
kwargs['input'] = ''
super().__init__(work, **kwargs)
self.audio = silence(self.delay)
super().define_action()
<|end_body_0|>
<|body_start_1|>
text_ = kwargs.get(mc.VALUES, '')
if text_ != '':
raise mex.MMValueError(message_text(self.work, 'W... | Definition of Wait object and waiting | Wait | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wait:
"""Definition of Wait object and waiting"""
def __init__(self, work, **kwargs):
"""Define Wait object"""
<|body_0|>
def do(self, **kwargs):
"""Do Wait object call :param kwargs: overriding parameters :return: None"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_030876 | 1,047 | permissive | [
{
"docstring": "Define Wait object",
"name": "__init__",
"signature": "def __init__(self, work, **kwargs)"
},
{
"docstring": "Do Wait object call :param kwargs: overriding parameters :return: None",
"name": "do",
"signature": "def do(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013918 | Implement the Python class `Wait` described below.
Class description:
Definition of Wait object and waiting
Method signatures and docstrings:
- def __init__(self, work, **kwargs): Define Wait object
- def do(self, **kwargs): Do Wait object call :param kwargs: overriding parameters :return: None | Implement the Python class `Wait` described below.
Class description:
Definition of Wait object and waiting
Method signatures and docstrings:
- def __init__(self, work, **kwargs): Define Wait object
- def do(self, **kwargs): Do Wait object call :param kwargs: overriding parameters :return: None
<|skeleton|>
class Wa... | 194bc6c7b899bb4ab61966af3ba1e619fc74c20c | <|skeleton|>
class Wait:
"""Definition of Wait object and waiting"""
def __init__(self, work, **kwargs):
"""Define Wait object"""
<|body_0|>
def do(self, **kwargs):
"""Do Wait object call :param kwargs: overriding parameters :return: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wait:
"""Definition of Wait object and waiting"""
def __init__(self, work, **kwargs):
"""Define Wait object"""
kwargs['input'] = ''
super().__init__(work, **kwargs)
self.audio = silence(self.delay)
super().define_action()
def do(self, **kwargs):
"""Do ... | the_stack_v2_python_sparse | manuscript/elements/wait.py | anterokangas/ManuscriptManagerOld | train | 0 |
2963d978adc7c224d24aa605754d7cdd4b95f3af | [
"self.__property1: str = property1\nself.__operation: str = operation\nself.__property2: str = property2",
"name = path or 'args'\nvalue1 = ObjectReader.get_property(value, self.__property1)\nvalue2 = ObjectReader.get_property(value, self.__property2)\nif not ObjectComparator.compare(value1, self.__operation, val... | <|body_start_0|>
self.__property1: str = property1
self.__operation: str = operation
self.__property2: str = property2
<|end_body_0|>
<|body_start_1|>
name = path or 'args'
value1 = ObjectReader.get_property(value, self.__property1)
value2 = ObjectReader.get_property(val... | Validation rule that compares two object properties. Example: .. code-block:: python schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2")) schema.validate({ field1: 1, field2: 2 }) # Result: no errors schema.validate({ field1: 1, field2: 1 }) # Result: field1 shall not be equal to field2 s... | PropertiesComparisonRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertiesComparisonRule:
"""Validation rule that compares two object properties. Example: .. code-block:: python schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2")) schema.validate({ field1: 1, field2: 2 }) # Result: no errors schema.validate({ field1: 1, field2: ... | stack_v2_sparse_classes_36k_train_030877 | 2,842 | permissive | [
{
"docstring": "Creates a new validation rule and sets its arguments. :param property1: a name of the first property to compare. :param operation: a comparison operation: \"==\" (\"=\", \"EQ\"), \"!= \" (\"<>\", \"NE\"); \"<\"/\">\" (\"LT\"/\"GT\"), \"<=\"/\">=\" (\"LE\"/\"GE\"); \"LIKE\". :param property2: a n... | 2 | stack_v2_sparse_classes_30k_train_006088 | Implement the Python class `PropertiesComparisonRule` described below.
Class description:
Validation rule that compares two object properties. Example: .. code-block:: python schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2")) schema.validate({ field1: 1, field2: 2 }) # Result: no error... | Implement the Python class `PropertiesComparisonRule` described below.
Class description:
Validation rule that compares two object properties. Example: .. code-block:: python schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2")) schema.validate({ field1: 1, field2: 2 }) # Result: no error... | 17f8a231fb75684032ec57b24025c9a3ca3dcdd6 | <|skeleton|>
class PropertiesComparisonRule:
"""Validation rule that compares two object properties. Example: .. code-block:: python schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2")) schema.validate({ field1: 1, field2: 2 }) # Result: no errors schema.validate({ field1: 1, field2: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertiesComparisonRule:
"""Validation rule that compares two object properties. Example: .. code-block:: python schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2")) schema.validate({ field1: 1, field2: 2 }) # Result: no errors schema.validate({ field1: 1, field2: 1 }) # Result... | the_stack_v2_python_sparse | pip_services3_commons/validate/PropertiesComparisonRule.py | pip-services3-python/pip-services3-commons-python | train | 0 |
31381aad5e917d9b8ff41b2af4452ae061562f69 | [
"self.x = x\nself.y = y\nself.tx = tx\nself.ty = ty\nself.chars = chars",
"chars = self.chars\nallrows = []\nfor yi in range(self.y):\n tiles = [Tile(self.tx, self.ty, chars[xi % len(chars)]) for xi in range(self.x)]\n tilerows = [''.join([tile.lines[tyi] for tile in tiles]) for tyi in range(self.ty)]\n ... | <|body_start_0|>
self.x = x
self.y = y
self.tx = tx
self.ty = ty
self.chars = chars
<|end_body_0|>
<|body_start_1|>
chars = self.chars
allrows = []
for yi in range(self.y):
tiles = [Tile(self.tx, self.ty, chars[xi % len(chars)]) for xi in rang... | A checkered grid, composed of alternating tiles of (possibly) different characters. The characters out of which tiles are alternatively composed can be defined as a string, or as a list of strings. A single string consisting of multiple characters and a list of single characters are functionally identical (see the firs... | CheckeredGrid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckeredGrid:
"""A checkered grid, composed of alternating tiles of (possibly) different characters. The characters out of which tiles are alternatively composed can be defined as a string, or as a list of strings. A single string consisting of multiple characters and a list of single characters... | stack_v2_sparse_classes_36k_train_030878 | 7,606 | no_license | [
{
"docstring": "Initialize a new checkered grid.",
"name": "__init__",
"signature": "def __init__(self, x, y, tx, ty, chars)"
},
{
"docstring": "Format a string representation of the checkered grid.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007397 | Implement the Python class `CheckeredGrid` described below.
Class description:
A checkered grid, composed of alternating tiles of (possibly) different characters. The characters out of which tiles are alternatively composed can be defined as a string, or as a list of strings. A single string consisting of multiple cha... | Implement the Python class `CheckeredGrid` described below.
Class description:
A checkered grid, composed of alternating tiles of (possibly) different characters. The characters out of which tiles are alternatively composed can be defined as a string, or as a list of strings. A single string consisting of multiple cha... | c80ea145c758f3b392f956e4311f11cfc099a149 | <|skeleton|>
class CheckeredGrid:
"""A checkered grid, composed of alternating tiles of (possibly) different characters. The characters out of which tiles are alternatively composed can be defined as a string, or as a list of strings. A single string consisting of multiple characters and a list of single characters... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckeredGrid:
"""A checkered grid, composed of alternating tiles of (possibly) different characters. The characters out of which tiles are alternatively composed can be defined as a string, or as a list of strings. A single string consisting of multiple characters and a list of single characters are function... | the_stack_v2_python_sparse | dailyprogrammer/plugins/asciiart.py | UltimateTimmeh/r-daily-programmer | train | 0 |
b91126c0c59cd2eaa760334f05622b6bc89e8d92 | [
"self.word2vec = gensim.models.KeyedVectors.load_word2vec_format(path_to_word2vec, binary=False)\nself.word2vec.init_sims(replace=True)\nself.dimensions = self.word2vec.vector_size",
"if word not in self.word2vec.vocab:\n return None\nreturn self.word2vec.syn0norm[self.word2vec.vocab[word].index]",
"if word1... | <|body_start_0|>
self.word2vec = gensim.models.KeyedVectors.load_word2vec_format(path_to_word2vec, binary=False)
self.word2vec.init_sims(replace=True)
self.dimensions = self.word2vec.vector_size
<|end_body_0|>
<|body_start_1|>
if word not in self.word2vec.vocab:
return None
... | Interface to provide word2vec interface access on top of gensim http://zablo.net/blog/post/twitter-sentiment-analysis-python-scikit-word2vec-nltk-xgboost | Word2VecProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Word2VecProvider:
"""Interface to provide word2vec interface access on top of gensim http://zablo.net/blog/post/twitter-sentiment-analysis-python-scikit-word2vec-nltk-xgboost"""
def load(self, path_to_word2vec):
"""Load a word2vec embeddings file :param path_to_word2vec: path to the ... | stack_v2_sparse_classes_36k_train_030879 | 6,383 | no_license | [
{
"docstring": "Load a word2vec embeddings file :param path_to_word2vec: path to the file :return: Nothing",
"name": "load",
"signature": "def load(self, path_to_word2vec)"
},
{
"docstring": "Get the vector associated to a given word. None if the word is not in vocabulary. :param word: word to g... | 3 | stack_v2_sparse_classes_30k_train_011642 | Implement the Python class `Word2VecProvider` described below.
Class description:
Interface to provide word2vec interface access on top of gensim http://zablo.net/blog/post/twitter-sentiment-analysis-python-scikit-word2vec-nltk-xgboost
Method signatures and docstrings:
- def load(self, path_to_word2vec): Load a word2... | Implement the Python class `Word2VecProvider` described below.
Class description:
Interface to provide word2vec interface access on top of gensim http://zablo.net/blog/post/twitter-sentiment-analysis-python-scikit-word2vec-nltk-xgboost
Method signatures and docstrings:
- def load(self, path_to_word2vec): Load a word2... | eb9eb133c97bb8585324b5e158f3d9d941c018b2 | <|skeleton|>
class Word2VecProvider:
"""Interface to provide word2vec interface access on top of gensim http://zablo.net/blog/post/twitter-sentiment-analysis-python-scikit-word2vec-nltk-xgboost"""
def load(self, path_to_word2vec):
"""Load a word2vec embeddings file :param path_to_word2vec: path to the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Word2VecProvider:
"""Interface to provide word2vec interface access on top of gensim http://zablo.net/blog/post/twitter-sentiment-analysis-python-scikit-word2vec-nltk-xgboost"""
def load(self, path_to_word2vec):
"""Load a word2vec embeddings file :param path_to_word2vec: path to the file :return:... | the_stack_v2_python_sparse | src/embeddings.py | elliotbart/SemTweet | train | 0 |
fff7b890da23348a6c8b6afa9e22bb9afec32872 | [
"article = ArticleInst.fetch(slug)\ncomment = request.data.get('comment', {})\nserializer = self.serializer_class(data=comment)\nserializer.is_valid(raise_exception=True)\nstatus_ = status.HTTP_201_CREATED\ntry:\n Comment.objects.get(article=article, body=comment.get('body'))\nexcept Comment.DoesNotExist:\n s... | <|body_start_0|>
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
serializer = self.serializer_class(data=comment)
serializer.is_valid(raise_exception=True)
status_ = status.HTTP_201_CREATED
try:
Comment.objects.get(article=article, ... | Handles listing of all comments and creation of new comments to an article | ListCommentsView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCommentsView:
"""Handles listing of all comments and creation of new comments to an article"""
def post(self, request, slug):
"""Posts a comment to an article"""
<|body_0|>
def get(self, request, slug):
"""Retrieves all comments associated with an article"""
... | stack_v2_sparse_classes_36k_train_030880 | 10,918 | permissive | [
{
"docstring": "Posts a comment to an article",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "Retrieves all comments associated with an article",
"name": "get",
"signature": "def get(self, request, slug)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012606 | Implement the Python class `ListCommentsView` described below.
Class description:
Handles listing of all comments and creation of new comments to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a comment to an article
- def get(self, request, slug): Retrieves all comments associate... | Implement the Python class `ListCommentsView` described below.
Class description:
Handles listing of all comments and creation of new comments to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a comment to an article
- def get(self, request, slug): Retrieves all comments associate... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class ListCommentsView:
"""Handles listing of all comments and creation of new comments to an article"""
def post(self, request, slug):
"""Posts a comment to an article"""
<|body_0|>
def get(self, request, slug):
"""Retrieves all comments associated with an article"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListCommentsView:
"""Handles listing of all comments and creation of new comments to an article"""
def post(self, request, slug):
"""Posts a comment to an article"""
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
serializer = self.serializer_cl... | the_stack_v2_python_sparse | authors/apps/comments/views.py | deferral/ah-django | train | 1 |
0bb3f99bd00d4dd913c9ad807c8ba7313258fcd2 | [
"if invoice.state in ('cancel', 'open', 'paid'):\n return True\nif invoice.state == 'draft':\n wf_service = netsvc.LocalService('workflow')\n wf_service.trg_validate(uid, 'account.invoice', invoice.id, 'invoice_open', cr)\n return True\nreturn False",
"if invoice.state in ('paid', 'cancel'):\n retu... | <|body_start_0|>
if invoice.state in ('cancel', 'open', 'paid'):
return True
if invoice.state == 'draft':
wf_service = netsvc.LocalService('workflow')
wf_service.trg_validate(uid, 'account.invoice', invoice.id, 'invoice_open', cr)
return True
retur... | account_invoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_invoice:
def auto_wkf_validate(self, cr, uid, invoice, context=None):
"""Interface method for the automatic worflow. Validate an invoice in draft state. :param browse_record invoice: the invoice to validate :return: True if the invoice have been opened, False if not"""
<|... | stack_v2_sparse_classes_36k_train_030881 | 15,477 | no_license | [
{
"docstring": "Interface method for the automatic worflow. Validate an invoice in draft state. :param browse_record invoice: the invoice to validate :return: True if the invoice have been opened, False if not",
"name": "auto_wkf_validate",
"signature": "def auto_wkf_validate(self, cr, uid, invoice, con... | 2 | null | Implement the Python class `account_invoice` described below.
Class description:
Implement the account_invoice class.
Method signatures and docstrings:
- def auto_wkf_validate(self, cr, uid, invoice, context=None): Interface method for the automatic worflow. Validate an invoice in draft state. :param browse_record in... | Implement the Python class `account_invoice` described below.
Class description:
Implement the account_invoice class.
Method signatures and docstrings:
- def auto_wkf_validate(self, cr, uid, invoice, context=None): Interface method for the automatic worflow. Validate an invoice in draft state. :param browse_record in... | 73c8a29a182460e6a8f7a97bbc15f1847dbdd63e | <|skeleton|>
class account_invoice:
def auto_wkf_validate(self, cr, uid, invoice, context=None):
"""Interface method for the automatic worflow. Validate an invoice in draft state. :param browse_record invoice: the invoice to validate :return: True if the invoice have been opened, False if not"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_invoice:
def auto_wkf_validate(self, cr, uid, invoice, context=None):
"""Interface method for the automatic worflow. Validate an invoice in draft state. :param browse_record invoice: the invoice to validate :return: True if the invoice have been opened, False if not"""
if invoice.state... | the_stack_v2_python_sparse | base_sale_multichannels/workflow_job.py | GoContractPro/Odoo-GCP | train | 1 | |
b7255f0e985453353a583103119cfe29c6bd2f8a | [
"Spectrum.__init__(self, *args, **kwargs)\nself._filename = filename\nif filename:\n try:\n data = fits.getdata(filename, 'SPECTRUM')\n self._wavelength = data.WAVE\n self.flux = data.FLUX\n except KeyError:\n data = fits.getdata(filename, 'SCI')\n self._wavelength = data.WA... | <|body_start_0|>
Spectrum.__init__(self, *args, **kwargs)
self._filename = filename
if filename:
try:
data = fits.getdata(filename, 'SPECTRUM')
self._wavelength = data.WAVE
self.flux = data.FLUX
except KeyError:
... | Handles spectra stored in FITS binary tables. | SpectrumBinTableFITS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrumBinTableFITS:
"""Handles spectra stored in FITS binary tables."""
def __init__(self, filename: str, *args, **kwargs):
"""Loads a spectrum from a FITS binary table. Args: filename: Name of file to load spectrum from."""
<|body_0|>
def save(self, filename: str):
... | stack_v2_sparse_classes_36k_train_030882 | 46,205 | permissive | [
{
"docstring": "Loads a spectrum from a FITS binary table. Args: filename: Name of file to load spectrum from.",
"name": "__init__",
"signature": "def __init__(self, filename: str, *args, **kwargs)"
},
{
"docstring": "Save spectrum to FITS file Args: filename: If given, save to this filename.",
... | 2 | null | Implement the Python class `SpectrumBinTableFITS` described below.
Class description:
Handles spectra stored in FITS binary tables.
Method signatures and docstrings:
- def __init__(self, filename: str, *args, **kwargs): Loads a spectrum from a FITS binary table. Args: filename: Name of file to load spectrum from.
- d... | Implement the Python class `SpectrumBinTableFITS` described below.
Class description:
Handles spectra stored in FITS binary tables.
Method signatures and docstrings:
- def __init__(self, filename: str, *args, **kwargs): Loads a spectrum from a FITS binary table. Args: filename: Name of file to load spectrum from.
- d... | 648eb1758e3744d9e3d6669edc4a0c4753559f17 | <|skeleton|>
class SpectrumBinTableFITS:
"""Handles spectra stored in FITS binary tables."""
def __init__(self, filename: str, *args, **kwargs):
"""Loads a spectrum from a FITS binary table. Args: filename: Name of file to load spectrum from."""
<|body_0|>
def save(self, filename: str):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpectrumBinTableFITS:
"""Handles spectra stored in FITS binary tables."""
def __init__(self, filename: str, *args, **kwargs):
"""Loads a spectrum from a FITS binary table. Args: filename: Name of file to load spectrum from."""
Spectrum.__init__(self, *args, **kwargs)
self._filenam... | the_stack_v2_python_sparse | spexxy/data/spectrum.py | thusser/spexxy | train | 4 |
d6787d664dbbbc47aae21014bfded5f9c918d483 | [
"dao = Dao()\nfrom main_index import Interface_Tasking\ninter_task = Interface_Tasking()\ntestees = []\nall_timings = dao.find_by_timing()\nfor all_timing in all_timings:\n gev = gevent.spawn(inter_task.give_one_mongo_params, all_timing)\n testees.append(gev)\ngevent.joinall(testees)\nglobal timer\ndelta_t = ... | <|body_start_0|>
dao = Dao()
from main_index import Interface_Tasking
inter_task = Interface_Tasking()
testees = []
all_timings = dao.find_by_timing()
for all_timing in all_timings:
gev = gevent.spawn(inter_task.give_one_mongo_params, all_timing)
t... | 定义定时类,只是面向对象罢了,没什么大不同的 | alarm_schedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class alarm_schedule:
"""定义定时类,只是面向对象罢了,没什么大不同的"""
def alarm_gogogo(self):
"""进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的"""
<|body_0|>
def input_one_time(self):
"""给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_030883 | 3,321 | no_license | [
{
"docstring": "进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的",
"name": "alarm_gogogo",
"signature": "def alarm_gogogo(self)"
},
{
"docstring": "给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE",
"name": "input_one_time",
"signature": "def input_one_time(self)"
}... | 3 | stack_v2_sparse_classes_30k_train_018089 | Implement the Python class `alarm_schedule` described below.
Class description:
定义定时类,只是面向对象罢了,没什么大不同的
Method signatures and docstrings:
- def alarm_gogogo(self): 进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的
- def input_one_time(self): 给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE
- def get... | Implement the Python class `alarm_schedule` described below.
Class description:
定义定时类,只是面向对象罢了,没什么大不同的
Method signatures and docstrings:
- def alarm_gogogo(self): 进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的
- def input_one_time(self): 给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE
- def get... | 2ec589d7267b03df8ae8b5df8d4d3ce8253d097c | <|skeleton|>
class alarm_schedule:
"""定义定时类,只是面向对象罢了,没什么大不同的"""
def alarm_gogogo(self):
"""进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的"""
<|body_0|>
def input_one_time(self):
"""给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class alarm_schedule:
"""定义定时类,只是面向对象罢了,没什么大不同的"""
def alarm_gogogo(self):
"""进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的"""
dao = Dao()
from main_index import Interface_Tasking
inter_task = Interface_Tasking()
testees = []
all_timings = dao.fi... | the_stack_v2_python_sparse | src/interface_tasking/alarm_scheduling.py | Ka1evi/Angular-SPA | train | 0 |
064d34919760ef23a672da3e7ba428cc92bd3727 | [
"self.db_client = db_client\nself.db = db\nself.dblist = dblist\nself.collection = collection\nself.collection_name = collection_name\nself.set_up_db()",
"try:\n gv.logger.info('Setting up DB connection... ')\n if self.db_client is None:\n self.establish_client_connection()\n if self.collectio... | <|body_start_0|>
self.db_client = db_client
self.db = db
self.dblist = dblist
self.collection = collection
self.collection_name = collection_name
self.set_up_db()
<|end_body_0|>
<|body_start_1|>
try:
gv.logger.info('Setting up DB connection... ')
... | This class represent a MongoDB connection handler. :param db: MongoDB database, defaults to None :type db: pymongo.database.Database, optional :param db_client: Pymongo client, defaults to None :type db_client: pymongo.MongoClient, optional :param dblist: List of databases in database, defaults to None :type dblist: Li... | DbConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbConnection:
"""This class represent a MongoDB connection handler. :param db: MongoDB database, defaults to None :type db: pymongo.database.Database, optional :param db_client: Pymongo client, defaults to None :type db_client: pymongo.MongoClient, optional :param dblist: List of databases in dat... | stack_v2_sparse_classes_36k_train_030884 | 4,005 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, db=None, db_client=None, dblist=None, collection=None, collection_name=None)"
},
{
"docstring": "Starts db connection",
"name": "set_up_db",
"signature": "def set_up_db(self)"
},
{
"docstring": "Co... | 6 | stack_v2_sparse_classes_30k_train_013897 | Implement the Python class `DbConnection` described below.
Class description:
This class represent a MongoDB connection handler. :param db: MongoDB database, defaults to None :type db: pymongo.database.Database, optional :param db_client: Pymongo client, defaults to None :type db_client: pymongo.MongoClient, optional ... | Implement the Python class `DbConnection` described below.
Class description:
This class represent a MongoDB connection handler. :param db: MongoDB database, defaults to None :type db: pymongo.database.Database, optional :param db_client: Pymongo client, defaults to None :type db_client: pymongo.MongoClient, optional ... | dc0d84e1f62be38868718410006fed98fb7763a5 | <|skeleton|>
class DbConnection:
"""This class represent a MongoDB connection handler. :param db: MongoDB database, defaults to None :type db: pymongo.database.Database, optional :param db_client: Pymongo client, defaults to None :type db_client: pymongo.MongoClient, optional :param dblist: List of databases in dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DbConnection:
"""This class represent a MongoDB connection handler. :param db: MongoDB database, defaults to None :type db: pymongo.database.Database, optional :param db_client: Pymongo client, defaults to None :type db_client: pymongo.MongoClient, optional :param dblist: List of databases in database, defaul... | the_stack_v2_python_sparse | data_manager/managers/db_connection.py | victorgrubio/sonda-data-manager | train | 0 |
4017def5247b985cdf2e853c537e1cdc89a566ed | [
"r2 = cloudflare.resource('s3')\nbucket_name, path = data_utils.split_r2_path(url)\nbucket = r2.Bucket(bucket_name)\nnum_objects = 0\nfor obj in bucket.objects.filter(Prefix=path):\n num_objects += 1\n if obj.key == path:\n return False\n if num_objects == 3:\n return True\nreturn True",
"e... | <|body_start_0|>
r2 = cloudflare.resource('s3')
bucket_name, path = data_utils.split_r2_path(url)
bucket = r2.Bucket(bucket_name)
num_objects = 0
for obj in bucket.objects.filter(Prefix=path):
num_objects += 1
if obj.key == path:
return Fal... | Cloudflare Cloud Storage. | R2CloudStorage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class R2CloudStorage:
"""Cloudflare Cloud Storage."""
def is_directory(self, url: str) -> bool:
"""Returns whether R2 'url' is a directory. In cloud object stores, a "directory" refers to a regular object whose name is a prefix of other objects."""
<|body_0|>
def make_sync_dir... | stack_v2_sparse_classes_36k_train_030885 | 11,806 | permissive | [
{
"docstring": "Returns whether R2 'url' is a directory. In cloud object stores, a \"directory\" refers to a regular object whose name is a prefix of other objects.",
"name": "is_directory",
"signature": "def is_directory(self, url: str) -> bool"
},
{
"docstring": "Downloads using AWS CLI.",
... | 3 | stack_v2_sparse_classes_30k_train_016692 | Implement the Python class `R2CloudStorage` described below.
Class description:
Cloudflare Cloud Storage.
Method signatures and docstrings:
- def is_directory(self, url: str) -> bool: Returns whether R2 'url' is a directory. In cloud object stores, a "directory" refers to a regular object whose name is a prefix of ot... | Implement the Python class `R2CloudStorage` described below.
Class description:
Cloudflare Cloud Storage.
Method signatures and docstrings:
- def is_directory(self, url: str) -> bool: Returns whether R2 'url' is a directory. In cloud object stores, a "directory" refers to a regular object whose name is a prefix of ot... | e58f33f315ca08c6e057ab9a2d00cd27476529a1 | <|skeleton|>
class R2CloudStorage:
"""Cloudflare Cloud Storage."""
def is_directory(self, url: str) -> bool:
"""Returns whether R2 'url' is a directory. In cloud object stores, a "directory" refers to a regular object whose name is a prefix of other objects."""
<|body_0|>
def make_sync_dir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class R2CloudStorage:
"""Cloudflare Cloud Storage."""
def is_directory(self, url: str) -> bool:
"""Returns whether R2 'url' is a directory. In cloud object stores, a "directory" refers to a regular object whose name is a prefix of other objects."""
r2 = cloudflare.resource('s3')
bucket_... | the_stack_v2_python_sparse | sky/cloud_stores.py | skypilot-org/skypilot | train | 3,416 |
407cefc3f44c7a0bab87186edcf12ca23bca9d64 | [
"url = get_table_url(self.URL)\ntry:\n password = Tables.objects.filter(url=url).first()\nexcept:\n raise NoSuchTable\nif not password and password.password == '':\n return False\nreturn True",
"is_added = Particip.objects.select_related().filter(user_id__username=self.USERNAME, table_id__url=self.table_... | <|body_start_0|>
url = get_table_url(self.URL)
try:
password = Tables.objects.filter(url=url).first()
except:
raise NoSuchTable
if not password and password.password == '':
return False
return True
<|end_body_0|>
<|body_start_1|>
is_ad... | permissions for allowing user read table content | CanReadTableContent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanReadTableContent:
"""permissions for allowing user read table content"""
def need_password(self) -> bool:
"""does table need password?"""
<|body_0|>
def already_added(self) -> bool:
"""check if user is added to table"""
<|body_1|>
def has_permissi... | stack_v2_sparse_classes_36k_train_030886 | 2,369 | no_license | [
{
"docstring": "does table need password?",
"name": "need_password",
"signature": "def need_password(self) -> bool"
},
{
"docstring": "check if user is added to table",
"name": "already_added",
"signature": "def already_added(self) -> bool"
},
{
"docstring": "main function",
... | 3 | stack_v2_sparse_classes_30k_train_014889 | Implement the Python class `CanReadTableContent` described below.
Class description:
permissions for allowing user read table content
Method signatures and docstrings:
- def need_password(self) -> bool: does table need password?
- def already_added(self) -> bool: check if user is added to table
- def has_permission(s... | Implement the Python class `CanReadTableContent` described below.
Class description:
permissions for allowing user read table content
Method signatures and docstrings:
- def need_password(self) -> bool: does table need password?
- def already_added(self) -> bool: check if user is added to table
- def has_permission(s... | 25e1bf7a3ae4a75c02f576582778bb259d7d8d4a | <|skeleton|>
class CanReadTableContent:
"""permissions for allowing user read table content"""
def need_password(self) -> bool:
"""does table need password?"""
<|body_0|>
def already_added(self) -> bool:
"""check if user is added to table"""
<|body_1|>
def has_permissi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanReadTableContent:
"""permissions for allowing user read table content"""
def need_password(self) -> bool:
"""does table need password?"""
url = get_table_url(self.URL)
try:
password = Tables.objects.filter(url=url).first()
except:
raise NoSuchTab... | the_stack_v2_python_sparse | api/permissions.py | RandomGuy090/taskmanager | train | 0 |
241d332c73dfc3d4cb9922b38484cb9b922e9cf6 | [
"output_types = output_types or ['pdf']\nfor t in output_types:\n t = t.replace('.', '')\n f_out = dot_filename.replace('.dot', '.' + t)\n exec_str = 'dot -T%s %s -o %s' % (t, dot_filename, f_out)\n os.system(exec_str)",
"from Cheetah.Template import Template\nif not component.is_flat() and flatten:\n... | <|body_start_0|>
output_types = output_types or ['pdf']
for t in output_types:
t = t.replace('.', '')
f_out = dot_filename.replace('.dot', '.' + t)
exec_str = 'dot -T%s %s -o %s' % (t, dot_filename, f_out)
os.system(exec_str)
<|end_body_0|>
<|body_start_1... | Dot Writer docstring | DotWriter | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DotWriter:
"""Dot Writer docstring"""
def build(cls, dot_filename, output_types=None):
"""Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced... | stack_v2_sparse_classes_36k_train_030887 | 4,675 | permissive | [
{
"docstring": "Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced, by default 'pdf' will be produced. This should be a list, for example, ['svg','pdf','png']",
"na... | 2 | stack_v2_sparse_classes_30k_train_005891 | Implement the Python class `DotWriter` described below.
Class description:
Dot Writer docstring
Method signatures and docstrings:
- def build(cls, dot_filename, output_types=None): Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params ... | Implement the Python class `DotWriter` described below.
Class description:
Dot Writer docstring
Method signatures and docstrings:
- def build(cls, dot_filename, output_types=None): Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params ... | 941ceb72e6cd26c55fd03f0029f84ab75ad18485 | <|skeleton|>
class DotWriter:
"""Dot Writer docstring"""
def build(cls, dot_filename, output_types=None):
"""Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DotWriter:
"""Dot Writer docstring"""
def build(cls, dot_filename, output_types=None):
"""Runs the commandline tool, ``dot`` on a filename to produce output figures. :params dot_filename: The filename of the .dot file. :params output_types: The types of output that should be produced, by default ... | the_stack_v2_python_sparse | lib9ml/python/nineml/abstraction_layer/dynamics/writers/dot_writer.py | iraikov/nineml | train | 0 |
d519d1be3d47490f7ebe23655aa2f602962555da | [
"if not isinstance(gate, Gate):\n raise TypeError(f'Expected Gate for gate, got {type(gate)}')\nself.gate = gate",
"if not isinstance(target, (UnitaryMatrix, StateVector, StateSystem)):\n raise TypeError('Expected unitary or state, got %s.' % type(target))\ninit_circuit = Circuit(target.num_qudits, target.r... | <|body_start_0|>
if not isinstance(gate, Gate):
raise TypeError(f'Expected Gate for gate, got {type(gate)}')
self.gate = gate
<|end_body_0|>
<|body_start_1|>
if not isinstance(target, (UnitaryMatrix, StateVector, StateSystem)):
raise TypeError('Expected unitary or state,... | Layer Generator for search that builds circuits from a single gate. | StairLayerGenerator | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StairLayerGenerator:
"""Layer Generator for search that builds circuits from a single gate."""
def __init__(self, gate: Gate) -> None:
"""Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from."""
<|body_0|>
def gen_initial_layer(self, target: Unitary... | stack_v2_sparse_classes_36k_train_030888 | 2,358 | permissive | [
{
"docstring": "Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.",
"name": "__init__",
"signature": "def __init__(self, gate: Gate) -> None"
},
{
"docstring": "Generate the initial layer, see LayerGenerator for more. Raises: ValueError: If `target` has a size or radix ... | 3 | null | Implement the Python class `StairLayerGenerator` described below.
Class description:
Layer Generator for search that builds circuits from a single gate.
Method signatures and docstrings:
- def __init__(self, gate: Gate) -> None: Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.
- def gen_ini... | Implement the Python class `StairLayerGenerator` described below.
Class description:
Layer Generator for search that builds circuits from a single gate.
Method signatures and docstrings:
- def __init__(self, gate: Gate) -> None: Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from.
- def gen_ini... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class StairLayerGenerator:
"""Layer Generator for search that builds circuits from a single gate."""
def __init__(self, gate: Gate) -> None:
"""Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from."""
<|body_0|>
def gen_initial_layer(self, target: Unitary... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StairLayerGenerator:
"""Layer Generator for search that builds circuits from a single gate."""
def __init__(self, gate: Gate) -> None:
"""Construct a StairLayerGenerator. Args: gate (Gate): The gate to build from."""
if not isinstance(gate, Gate):
raise TypeError(f'Expected Ga... | the_stack_v2_python_sparse | bqskit/passes/search/generators/stair.py | BQSKit/bqskit | train | 54 |
83d10a260d7fbb82f3a2307cc5fc2da1e3e7ea06 | [
"is_valid = True\ntry:\n fips = item[0]\n name = item[2]\n geoid = int(item[3])\nexcept:\n is_valid = False\nif is_valid and fips and name:\n return is_valid\nlogger.warning('Invalid Record: ({item})'.format(item=item))\nreturn False",
"division = self._get_division_cache(data['division_fips'])\nif... | <|body_start_0|>
is_valid = True
try:
fips = item[0]
name = item[2]
geoid = int(item[3])
except:
is_valid = False
if is_valid and fips and name:
return is_valid
logger.warning('Invalid Record: ({item})'.format(item=item)... | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
def is_entry_valid(self, item):
"""Checks for minimum subdivision requirements."""
<|body_0|>
def get_query_fields(self, data):
"""Fields to identify a subdivision record."""
<|body_1|>
def record_to_dict(self, item):
"""Given a division... | stack_v2_sparse_classes_36k_train_030889 | 2,957 | permissive | [
{
"docstring": "Checks for minimum subdivision requirements.",
"name": "is_entry_valid",
"signature": "def is_entry_valid(self, item)"
},
{
"docstring": "Fields to identify a subdivision record.",
"name": "get_query_fields",
"signature": "def get_query_fields(self, data)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_013949 | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def is_entry_valid(self, item): Checks for minimum subdivision requirements.
- def get_query_fields(self, data): Fields to identify a subdivision record.
- def record_to_dict(self,... | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def is_entry_valid(self, item): Checks for minimum subdivision requirements.
- def get_query_fields(self, data): Fields to identify a subdivision record.
- def record_to_dict(self,... | cd7c51e358e5b2d2c3ca92626edbdd7e4f573ab8 | <|skeleton|>
class Command:
def is_entry_valid(self, item):
"""Checks for minimum subdivision requirements."""
<|body_0|>
def get_query_fields(self, data):
"""Fields to identify a subdivision record."""
<|body_1|>
def record_to_dict(self, item):
"""Given a division... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
def is_entry_valid(self, item):
"""Checks for minimum subdivision requirements."""
is_valid = True
try:
fips = item[0]
name = item[2]
geoid = int(item[3])
except:
is_valid = False
if is_valid and fips and name:
... | the_stack_v2_python_sparse | geoware/management/commands/subdivision.py | un33k/django-geoware | train | 4 | |
2f41eb16eac8f161a6094394debe9ded16feec57 | [
"if not isinstance(new_impl, dict):\n raise TypeError('new_impl must be a dictionary')\nfor k, v in new_impl.items():\n if not isinstance(v, dict):\n raise TypeError('Every value of new_impl must be a dictionary. Item for key {key} has class {vclass}'.format(key=k, vclass=v))\ncls._LAYERS_RESHAPE_MAP.u... | <|body_start_0|>
if not isinstance(new_impl, dict):
raise TypeError('new_impl must be a dictionary')
for k, v in new_impl.items():
if not isinstance(v, dict):
raise TypeError('Every value of new_impl must be a dictionary. Item for key {key} has class {vclass}'.for... | The keys represent built-in keras layers and the values represent the strategy accoding to which clustering will be done. If the key is not present in the map, that means that there is nothing to work on, or the strategy is not currently supported | ClusteringLookupRegistry | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause-Open-MPI",
"LicenseRef-scancode-free-unknown",
"Libtool-exception",
"GCC-exception-3.1",
"LicenseRef-scancode-mit-old-style",
"OFL-1.1",
"JSON",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"ICU",
"LicenseRef-scancode-... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusteringLookupRegistry:
"""The keys represent built-in keras layers and the values represent the strategy accoding to which clustering will be done. If the key is not present in the map, that means that there is nothing to work on, or the strategy is not currently supported"""
def register... | stack_v2_sparse_classes_36k_train_030890 | 14,398 | permissive | [
{
"docstring": "For custom user-defined objects define the way how clusterable weights are going to be formed. If weights are any of these, 1D,2D or 4D, please consider using existing implementations: BiasWeightsCA, ConvolutionalWeightsCA and DenseWeightsCA. :param new_impl: dictionary. Keys are classes and val... | 2 | null | Implement the Python class `ClusteringLookupRegistry` described below.
Class description:
The keys represent built-in keras layers and the values represent the strategy accoding to which clustering will be done. If the key is not present in the map, that means that there is nothing to work on, or the strategy is not c... | Implement the Python class `ClusteringLookupRegistry` described below.
Class description:
The keys represent built-in keras layers and the values represent the strategy accoding to which clustering will be done. If the key is not present in the map, that means that there is nothing to work on, or the strategy is not c... | f74ddc6ed086ba949b791626638717e21505dba2 | <|skeleton|>
class ClusteringLookupRegistry:
"""The keys represent built-in keras layers and the values represent the strategy accoding to which clustering will be done. If the key is not present in the map, that means that there is nothing to work on, or the strategy is not currently supported"""
def register... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusteringLookupRegistry:
"""The keys represent built-in keras layers and the values represent the strategy accoding to which clustering will be done. If the key is not present in the map, that means that there is nothing to work on, or the strategy is not currently supported"""
def register_new_implemen... | the_stack_v2_python_sparse | src/vai_quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/clustering/keras/clustering_registry.py | Xilinx/Vitis-AI | train | 1,283 |
0ef7971de8b5e7700e3bf304c91ead69a8ac9971 | [
"if ws is None:\n self.tmp_folder = tempfile.TemporaryDirectory()\n ws = self.tmp_folder.name\nself.ws = ws",
"folder = path.join(self.ws, name)\nmakedirs(folder, exist_ok=True)\nmapping_path = path.join(folder, 'mapping.json')\nif path.exists(mapping_path):\n with open(mapping_path, 'r', encoding='utf-8... | <|body_start_0|>
if ws is None:
self.tmp_folder = tempfile.TemporaryDirectory()
ws = self.tmp_folder.name
self.ws = ws
<|end_body_0|>
<|body_start_1|>
folder = path.join(self.ws, name)
makedirs(folder, exist_ok=True)
mapping_path = path.join(folder, 'mapp... | Generate a folder name for caching intermediate variables | CachedWorkspace | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedWorkspace:
"""Generate a folder name for caching intermediate variables"""
def __init__(self, ws=None):
"""Initialization Args: ws (str, optional): Workspace folder If not given, will use a temporary folder."""
<|body_0|>
def get_path_for_name_and_kwargs(self, name... | stack_v2_sparse_classes_36k_train_030891 | 22,314 | permissive | [
{
"docstring": "Initialization Args: ws (str, optional): Workspace folder If not given, will use a temporary folder.",
"name": "__init__",
"signature": "def __init__(self, ws=None)"
},
{
"docstring": "Generate a hashed path in the workspace (self.ws) Args: name (str): a basename (e.g., the inter... | 2 | stack_v2_sparse_classes_30k_train_019805 | Implement the Python class `CachedWorkspace` described below.
Class description:
Generate a folder name for caching intermediate variables
Method signatures and docstrings:
- def __init__(self, ws=None): Initialization Args: ws (str, optional): Workspace folder If not given, will use a temporary folder.
- def get_pat... | Implement the Python class `CachedWorkspace` described below.
Class description:
Generate a folder name for caching intermediate variables
Method signatures and docstrings:
- def __init__(self, ws=None): Initialization Args: ws (str, optional): Workspace folder If not given, will use a temporary folder.
- def get_pat... | 9aefa13e1cc873cb68801cba49d4e9a48572eeb7 | <|skeleton|>
class CachedWorkspace:
"""Generate a folder name for caching intermediate variables"""
def __init__(self, ws=None):
"""Initialization Args: ws (str, optional): Workspace folder If not given, will use a temporary folder."""
<|body_0|>
def get_path_for_name_and_kwargs(self, name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CachedWorkspace:
"""Generate a folder name for caching intermediate variables"""
def __init__(self, ws=None):
"""Initialization Args: ws (str, optional): Workspace folder If not given, will use a temporary folder."""
if ws is None:
self.tmp_folder = tempfile.TemporaryDirectory... | the_stack_v2_python_sparse | pecos/apps/text2text/model.py | zusmani/pecos | train | 1 |
c8ee4933e68a2f9982b9275c472a6df0e654cc69 | [
"for task_item in self.tasks:\n if task_item.id == task_id:\n return True\nreturn False",
"if self.isExist(task_id):\n forbidden_abort(f\"Task '{task_id}' is already exist!\")\nif task_id[0] == '_':\n forbidden_abort(\"Task name can not start with '_'\")\ntitle = kwargs.get('title')\ndesc = kwargs... | <|body_start_0|>
for task_item in self.tasks:
if task_item.id == task_id:
return True
return False
<|end_body_0|>
<|body_start_1|>
if self.isExist(task_id):
forbidden_abort(f"Task '{task_id}' is already exist!")
if task_id[0] == '_':
f... | Index信息存入'.dicer2_base'的字段结构和操作方法 | BaseIndex | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseIndex:
"""Index信息存入'.dicer2_base'的字段结构和操作方法"""
def isExist(self, task_id):
"""判断'.dicer2_base'当前index对象中某个task是否存在 :param task_id: 目标task :return:"""
<|body_0|>
def add_task(self, task_id, **kwargs):
"""向'.dicer2_base'当前index对象中添加一个task :param task_id: 目标task... | stack_v2_sparse_classes_36k_train_030892 | 3,221 | permissive | [
{
"docstring": "判断'.dicer2_base'当前index对象中某个task是否存在 :param task_id: 目标task :return:",
"name": "isExist",
"signature": "def isExist(self, task_id)"
},
{
"docstring": "向'.dicer2_base'当前index对象中添加一个task :param task_id: 目标task :param kwargs: 添加task所需的其他字段 :return:",
"name": "add_task",
"sig... | 6 | stack_v2_sparse_classes_30k_val_001097 | Implement the Python class `BaseIndex` described below.
Class description:
Index信息存入'.dicer2_base'的字段结构和操作方法
Method signatures and docstrings:
- def isExist(self, task_id): 判断'.dicer2_base'当前index对象中某个task是否存在 :param task_id: 目标task :return:
- def add_task(self, task_id, **kwargs): 向'.dicer2_base'当前index对象中添加一个task :... | Implement the Python class `BaseIndex` described below.
Class description:
Index信息存入'.dicer2_base'的字段结构和操作方法
Method signatures and docstrings:
- def isExist(self, task_id): 判断'.dicer2_base'当前index对象中某个task是否存在 :param task_id: 目标task :return:
- def add_task(self, task_id, **kwargs): 向'.dicer2_base'当前index对象中添加一个task :... | 3d50d3854a087eecaf45a744ddfe2fa2e225951a | <|skeleton|>
class BaseIndex:
"""Index信息存入'.dicer2_base'的字段结构和操作方法"""
def isExist(self, task_id):
"""判断'.dicer2_base'当前index对象中某个task是否存在 :param task_id: 目标task :return:"""
<|body_0|>
def add_task(self, task_id, **kwargs):
"""向'.dicer2_base'当前index对象中添加一个task :param task_id: 目标task... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseIndex:
"""Index信息存入'.dicer2_base'的字段结构和操作方法"""
def isExist(self, task_id):
"""判断'.dicer2_base'当前index对象中某个task是否存在 :param task_id: 目标task :return:"""
for task_item in self.tasks:
if task_item.id == task_id:
return True
return False
def add_task... | the_stack_v2_python_sparse | App/models/BaseIndexMapping.py | PhenomingZ/dicer2 | train | 1 |
edd341cf38d80eab9ca807a05f446f5c68a3af50 | [
"self.n_actions = n_actions\nself.eps_initial = eps_initial\nself.eps_final = eps_final\nself.eps_final_frame = eps_final_frame\nself.eps_evaluation = eps_evaluation\nself.eps_annealing_frames = eps_annealing_frame\nself.replay_memory_start_size = replay_memory_start_size\nself.max_frames = max_frames\nself.slope =... | <|body_start_0|>
self.n_actions = n_actions
self.eps_initial = eps_initial
self.eps_final = eps_final
self.eps_final_frame = eps_final_frame
self.eps_evaluation = eps_evaluation
self.eps_annealing_frames = eps_annealing_frame
self.replay_memory_start_size = replay... | determines an action according to an epsilon greedy strategy with annealing epsilon Modify the annealing and exploration as desired.. | ActionGetter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionGetter:
"""determines an action according to an epsilon greedy strategy with annealing epsilon Modify the annealing and exploration as desired.."""
def __init__(self, n_actions, eps_initial=1, eps_final=0.1, eps_final_frame=0.01, eps_evaluation=0.0, eps_annealing_frame=1000000, replay_... | stack_v2_sparse_classes_36k_train_030893 | 33,346 | no_license | [
{
"docstring": ":param n_actions: int, number of possible actions :param eps_initial: float, initial exploration probability for replay_memory start size frames :param eps_final: exploration probability after replay_memory_start_size + eps_annealing_frames frames :param eps_final_frame: exploration probability ... | 2 | null | Implement the Python class `ActionGetter` described below.
Class description:
determines an action according to an epsilon greedy strategy with annealing epsilon Modify the annealing and exploration as desired..
Method signatures and docstrings:
- def __init__(self, n_actions, eps_initial=1, eps_final=0.1, eps_final_... | Implement the Python class `ActionGetter` described below.
Class description:
determines an action according to an epsilon greedy strategy with annealing epsilon Modify the annealing and exploration as desired..
Method signatures and docstrings:
- def __init__(self, n_actions, eps_initial=1, eps_final=0.1, eps_final_... | 5d4dbde8d570623fe785e78a3e45cd05ea80aa08 | <|skeleton|>
class ActionGetter:
"""determines an action according to an epsilon greedy strategy with annealing epsilon Modify the annealing and exploration as desired.."""
def __init__(self, n_actions, eps_initial=1, eps_final=0.1, eps_final_frame=0.01, eps_evaluation=0.0, eps_annealing_frame=1000000, replay_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionGetter:
"""determines an action according to an epsilon greedy strategy with annealing epsilon Modify the annealing and exploration as desired.."""
def __init__(self, n_actions, eps_initial=1, eps_final=0.1, eps_final_frame=0.01, eps_evaluation=0.0, eps_annealing_frame=1000000, replay_memory_start_... | the_stack_v2_python_sparse | Reinforcement-Learning/7-2-double_dueling_1stepDQN.py | behrouzmadahian/python | train | 1 |
a270609b1ebe28e50c39905b8ba7e6311ece8b83 | [
"manualLayout = self.manualLayout\nif manualLayout is None:\n return 0.0\nreturn manualLayout.horz_offset",
"if offset == 0.0:\n self._remove_manualLayout()\n return\nmanualLayout = self.get_or_add_manualLayout()\nmanualLayout.horz_offset = offset"
] | <|body_start_0|>
manualLayout = self.manualLayout
if manualLayout is None:
return 0.0
return manualLayout.horz_offset
<|end_body_0|>
<|body_start_1|>
if offset == 0.0:
self._remove_manualLayout()
return
manualLayout = self.get_or_add_manualLay... | ``<c:layout>`` custom element class | CT_Layout | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Layout:
"""``<c:layout>`` custom element class"""
def horz_offset(self):
"""The float value in ./c:manualLayout/c:x when c:layout/c:manualLayout/c:xMode@val == "factor". 0.0 if that XPath expression finds no match."""
<|body_0|>
def horz_offset(self, offset):
... | stack_v2_sparse_classes_36k_train_030894 | 5,875 | permissive | [
{
"docstring": "The float value in ./c:manualLayout/c:x when c:layout/c:manualLayout/c:xMode@val == \"factor\". 0.0 if that XPath expression finds no match.",
"name": "horz_offset",
"signature": "def horz_offset(self)"
},
{
"docstring": "Set the value of ./c:manualLayout/c:x@val to *offset* and ... | 2 | null | Implement the Python class `CT_Layout` described below.
Class description:
``<c:layout>`` custom element class
Method signatures and docstrings:
- def horz_offset(self): The float value in ./c:manualLayout/c:x when c:layout/c:manualLayout/c:xMode@val == "factor". 0.0 if that XPath expression finds no match.
- def hor... | Implement the Python class `CT_Layout` described below.
Class description:
``<c:layout>`` custom element class
Method signatures and docstrings:
- def horz_offset(self): The float value in ./c:manualLayout/c:x when c:layout/c:manualLayout/c:xMode@val == "factor". 0.0 if that XPath expression finds no match.
- def hor... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_Layout:
"""``<c:layout>`` custom element class"""
def horz_offset(self):
"""The float value in ./c:manualLayout/c:x when c:layout/c:manualLayout/c:xMode@val == "factor". 0.0 if that XPath expression finds no match."""
<|body_0|>
def horz_offset(self, offset):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_Layout:
"""``<c:layout>`` custom element class"""
def horz_offset(self):
"""The float value in ./c:manualLayout/c:x when c:layout/c:manualLayout/c:xMode@val == "factor". 0.0 if that XPath expression finds no match."""
manualLayout = self.manualLayout
if manualLayout is None:
... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/chart/shared.py | ryfeus/lambda-packs | train | 1,283 |
be145d69da147d8c0a117bd4ee974866ea1e8ea3 | [
"N = len(nums)\nW = (sum(nums) + S) // 2\nif (sum(nums) + S) % 2 == 1:\n return 0\nif sum(nums) < S or sum(nums) < -S:\n return 0\ndp = [0] * (W + 1)\ndp[0] = 1\nfor i in range(1, N + 1):\n for j in range(W, nums[i - 1] - 1, -1):\n dp[j] = dp[j] + dp[j - nums[i - 1]]\nprint(dp)\nreturn dp[W]",
"de... | <|body_start_0|>
N = len(nums)
W = (sum(nums) + S) // 2
if (sum(nums) + S) % 2 == 1:
return 0
if sum(nums) < S or sum(nums) < -S:
return 0
dp = [0] * (W + 1)
dp[0] = 1
for i in range(1, N + 1):
for j in range(W, nums[i - 1] - 1,... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
"""状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2"""
<|body_0|>
def findTargetSumWays1(self, nums: List[int], S: in... | stack_v2_sparse_classes_36k_train_030895 | 3,913 | permissive | [
{
"docstring": "状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2",
"name": "findTargetSumWays",
"signature": "def findTargetSumWays(self, nums: List[int], S: int) -> int"
},
{
"docstring": "回溯算法:二进制递归枚举",
... | 3 | stack_v2_sparse_classes_30k_train_014943 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums: List[int], S: int) -> int: 状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums: List[int], S: int) -> int: 状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
"""状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2"""
<|body_0|>
def findTargetSumWays1(self, nums: List[int], S: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
"""状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2"""
N = len(nums)
W = (sum(nums) + S) // 2
if (sum(nums) + S) % 2 == ... | the_stack_v2_python_sparse | 494-target-sum.py | yuenliou/leetcode | train | 0 | |
61f12ebe32d13b58dae2d65360d357215941f315 | [
"super(Particle, self).__init__(*groups)\nself.age = 30\nstartcolor = pygame.Color(*colorstart)\nendcolor = pygame.Color(*colorend)\nself.color = startcolor\nself.colorsteps = (startcolor - endcolor) // pygame.Color(*3 * [self.age])\nself.image = pygame.surface.Surface((2, 2))\nself.image.fill(self.color)\nself.ima... | <|body_start_0|>
super(Particle, self).__init__(*groups)
self.age = 30
startcolor = pygame.Color(*colorstart)
endcolor = pygame.Color(*colorend)
self.color = startcolor
self.colorsteps = (startcolor - endcolor) // pygame.Color(*3 * [self.age])
self.image = pygame.... | A Single Particle | Particle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Particle:
"""A Single Particle"""
def __init__(self, position, colorstart, colorend, speedx, speedy, tilemap, *groups):
"""Default constructor Keyword Arguments: - position: The initial position of the particle - colorstart: A 3-Tuple (RRR,GGG,BBB) representing the initial color of t... | stack_v2_sparse_classes_36k_train_030896 | 3,601 | permissive | [
{
"docstring": "Default constructor Keyword Arguments: - position: The initial position of the particle - colorstart: A 3-Tuple (RRR,GGG,BBB) representing the initial color of the particle - colorend: A 3-Tuple (RRR,GGG,BBB) representing the final color just before the particle dies - speedx: The horizontal spe... | 2 | null | Implement the Python class `Particle` described below.
Class description:
A Single Particle
Method signatures and docstrings:
- def __init__(self, position, colorstart, colorend, speedx, speedy, tilemap, *groups): Default constructor Keyword Arguments: - position: The initial position of the particle - colorstart: A ... | Implement the Python class `Particle` described below.
Class description:
A Single Particle
Method signatures and docstrings:
- def __init__(self, position, colorstart, colorend, speedx, speedy, tilemap, *groups): Default constructor Keyword Arguments: - position: The initial position of the particle - colorstart: A ... | 0363fc368af205d1e829b2556ad70797930c10bd | <|skeleton|>
class Particle:
"""A Single Particle"""
def __init__(self, position, colorstart, colorend, speedx, speedy, tilemap, *groups):
"""Default constructor Keyword Arguments: - position: The initial position of the particle - colorstart: A 3-Tuple (RRR,GGG,BBB) representing the initial color of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Particle:
"""A Single Particle"""
def __init__(self, position, colorstart, colorend, speedx, speedy, tilemap, *groups):
"""Default constructor Keyword Arguments: - position: The initial position of the particle - colorstart: A 3-Tuple (RRR,GGG,BBB) representing the initial color of the particle -... | the_stack_v2_python_sparse | Game/libs/particle.py | Penaz91/Glitch_Heaven | train | 2 |
5a40973521f22979e0c64bba9dff003bfca872e7 | [
"a = 0\nfor i in range(2, n):\n b = []\n for j in range(2, i):\n if i % j == 0:\n b.append(j)\n break\n if len(b) == 0:\n a += 1\nreturn a",
"if n < 3:\n return 0\np = [True] * n\np[0] = p[1] = False\nfor i in range(2, int(n ** 0.5) + 1):\n if p[i]:\n p[i ... | <|body_start_0|>
a = 0
for i in range(2, n):
b = []
for j in range(2, i):
if i % j == 0:
b.append(j)
break
if len(b) == 0:
a += 1
return a
<|end_body_0|>
<|body_start_1|>
if n < 3... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes1(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = 0
for i in range(2, n):
b = []
f... | stack_v2_sparse_classes_36k_train_030897 | 2,259 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes1",
"signature": "def countPrimes1(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013626 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def countPrimes1(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def countPrimes1(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def countPrimes(self, n):
""":... | 40bca64cf3ed2fbc670b9e2cdf4f88d6c7b68134 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes1(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
a = 0
for i in range(2, n):
b = []
for j in range(2, i):
if i % j == 0:
b.append(j)
break
if len(b) == 0:
a += ... | the_stack_v2_python_sparse | Math/Count Primes (two).py | okliou/lcode | train | 0 | |
8c12a9ff57fc9587185456f7bb4e9d1b03e004e6 | [
"tmp_nums = nums[:]\nn = len(nums)\nfor idx in range(n):\n new_idx = (idx + k) % n\n nums[new_idx] = tmp_nums[idx]",
"def reverse(i, j):\n while i < j:\n nums[i], nums[j] = (nums[j], nums[i])\n i += 1\n j -= 1\nn = len(nums)\nk %= n\nreverse(0, n - 1)\nreverse(0, k - 1)\nreverse(k, n... | <|body_start_0|>
tmp_nums = nums[:]
n = len(nums)
for idx in range(n):
new_idx = (idx + k) % n
nums[new_idx] = tmp_nums[idx]
<|end_body_0|>
<|body_start_1|>
def reverse(i, j):
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""使用额外的数组"""
<|body_0|>
def rotate_reverse(self, nums: List[int], k: int) -> None:
"""数组反转"""
<|body_1|>
def rotate_ring(self, nums: List[int], k: int) -> None:
"""环状替换"""
<|bo... | stack_v2_sparse_classes_36k_train_030898 | 1,634 | no_license | [
{
"docstring": "使用额外的数组",
"name": "rotate",
"signature": "def rotate(self, nums: List[int], k: int) -> None"
},
{
"docstring": "数组反转",
"name": "rotate_reverse",
"signature": "def rotate_reverse(self, nums: List[int], k: int) -> None"
},
{
"docstring": "环状替换",
"name": "rotate_... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: 使用额外的数组
- def rotate_reverse(self, nums: List[int], k: int) -> None: 数组反转
- def rotate_ring(self, nums: List[int], k: int) -> N... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: 使用额外的数组
- def rotate_reverse(self, nums: List[int], k: int) -> None: 数组反转
- def rotate_ring(self, nums: List[int], k: int) -> N... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""使用额外的数组"""
<|body_0|>
def rotate_reverse(self, nums: List[int], k: int) -> None:
"""数组反转"""
<|body_1|>
def rotate_ring(self, nums: List[int], k: int) -> None:
"""环状替换"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""使用额外的数组"""
tmp_nums = nums[:]
n = len(nums)
for idx in range(n):
new_idx = (idx + k) % n
nums[new_idx] = tmp_nums[idx]
def rotate_reverse(self, nums: List[int], k: int) -> None:
... | the_stack_v2_python_sparse | 189.旋转数组/solution.py | QtTao/daily_leetcode | train | 0 | |
74b26613aa5e69863760bfda100f0ba2940b51c4 | [
"super().__init__(**kwargs)\nself.dense = tf.keras.layers.Dense(config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name='dense')\nself.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='LayerNorm')\nself.dropout = tf.keras.layers.Dropout(config.hidden_... | <|body_start_0|>
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name='dense')
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='LayerNorm')
self.dropout... | Fastspeech output of self attention module. | TFFastSpeechSelfOutput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFFastSpeechSelfOutput:
"""Fastspeech output of self attention module."""
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs, training=False):
"""Call logic."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030899 | 17,606 | permissive | [
{
"docstring": "Init variables.",
"name": "__init__",
"signature": "def __init__(self, config, **kwargs)"
},
{
"docstring": "Call logic.",
"name": "call",
"signature": "def call(self, inputs, training=False)"
}
] | 2 | null | Implement the Python class `TFFastSpeechSelfOutput` described below.
Class description:
Fastspeech output of self attention module.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs, training=False): Call logic. | Implement the Python class `TFFastSpeechSelfOutput` described below.
Class description:
Fastspeech output of self attention module.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs, training=False): Call logic.
<|skeleton|>
class TFFastSpeechSelfOutput... | 4343c409340c608a426cc6f0926fbe2c1661783e | <|skeleton|>
class TFFastSpeechSelfOutput:
"""Fastspeech output of self attention module."""
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs, training=False):
"""Call logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFFastSpeechSelfOutput:
"""Fastspeech output of self attention module."""
def __init__(self, config, **kwargs):
"""Init variables."""
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), nam... | the_stack_v2_python_sparse | malaya_speech/train/model/fastspeech/model_aligner.py | Ariffleng/malaya-speech | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.