blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08383286f37f34f683898e2b0b196b1cc9d8de5a | [
"if len(chordProgression) < 4:\n print('ERROR IN ChordProgression 2')\n return None\nelse:\n keysForReturn = []\n tempChords = []\n for chord in chordProgression:\n tempChords.append(chord[0])\n tempChords = np.array(tempChords)\n chords = [[tempChords[0], tempChords[1]], [tempChords[2],... | <|body_start_0|>
if len(chordProgression) < 4:
print('ERROR IN ChordProgression 2')
return None
else:
keysForReturn = []
tempChords = []
for chord in chordProgression:
tempChords.append(chord[0])
tempChords = np.arra... | SubMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
<|body_0|>
def cherryB(self, keyProgression, chordProgression):
"""サビで使われているメソッド"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(chordProgression) < 4... | stack_v2_sparse_classes_10k_train_000000 | 12,440 | no_license | [
{
"docstring": "INTROで使われているメソッド",
"name": "cherryIntro",
"signature": "def cherryIntro(self, keyProgression, chordProgression)"
},
{
"docstring": "サビで使われているメソッド",
"name": "cherryB",
"signature": "def cherryB(self, keyProgression, chordProgression)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005988 | Implement the Python class `SubMethods` described below.
Class description:
Implement the SubMethods class.
Method signatures and docstrings:
- def cherryIntro(self, keyProgression, chordProgression): INTROで使われているメソッド
- def cherryB(self, keyProgression, chordProgression): サビで使われているメソッド | Implement the Python class `SubMethods` described below.
Class description:
Implement the SubMethods class.
Method signatures and docstrings:
- def cherryIntro(self, keyProgression, chordProgression): INTROで使われているメソッド
- def cherryB(self, keyProgression, chordProgression): サビで使われているメソッド
<|skeleton|>
class SubMethods:... | 172f486048825d989aac69945c463dd150b84a88 | <|skeleton|>
class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
<|body_0|>
def cherryB(self, keyProgression, chordProgression):
"""サビで使われているメソッド"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
if len(chordProgression) < 4:
print('ERROR IN ChordProgression 2')
return None
else:
keysForReturn = []
tempChords = []
for chord in c... | the_stack_v2_python_sparse | SongGenerator/mikakunin/Composer/ChordProgression.py | ku70t6h1k6r1/auto_music | train | 0 | |
582f5f7cc2cbdc26dc47ba28039f489fab195fb4 | [
"self.output_path = output_path\nself.max_concurrent_invocations_per_instance = max_concurrent_invocations_per_instance\nself.kms_key_id = kms_key_id\nself.notification_config = notification_config\nself.failure_path = failure_path",
"request_dict = {'OutputConfig': {'S3OutputPath': self.output_path, 'S3FailurePa... | <|body_start_0|>
self.output_path = output_path
self.max_concurrent_invocations_per_instance = max_concurrent_invocations_per_instance
self.kms_key_id = kms_key_id
self.notification_config = notification_config
self.failure_path = failure_path
<|end_body_0|>
<|body_start_1|>
... | Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to async endpoint. Use this configuration when trying to create async endpoint and make async inference | AsyncInferenceConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncInferenceConfig:
"""Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to async endpoint. Use this configuration when trying to create async endpoint and make async inference"""
def __init__(self, output_path=N... | stack_v2_sparse_classes_10k_train_000001 | 4,694 | permissive | [
{
"docstring": "Initialize an AsyncInferenceConfig object for async inference configuration. Args: output_path (str): Optional. The Amazon S3 location that endpoints upload inference responses to. If no value is provided, Amazon SageMaker will use default Amazon S3 Async Inference output path. (Default: None) m... | 2 | null | Implement the Python class `AsyncInferenceConfig` described below.
Class description:
Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to async endpoint. Use this configuration when trying to create async endpoint and make async inference
... | Implement the Python class `AsyncInferenceConfig` described below.
Class description:
Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to async endpoint. Use this configuration when trying to create async endpoint and make async inference
... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class AsyncInferenceConfig:
"""Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to async endpoint. Use this configuration when trying to create async endpoint and make async inference"""
def __init__(self, output_path=N... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AsyncInferenceConfig:
"""Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to async endpoint. Use this configuration when trying to create async endpoint and make async inference"""
def __init__(self, output_path=None, max_conc... | the_stack_v2_python_sparse | src/sagemaker/async_inference/async_inference_config.py | aws/sagemaker-python-sdk | train | 2,050 |
166e01d59ab41b7a1bc0e3e1ebd2ff273e943c2d | [
"\"\"\"\n 我的想法:\n Merge graph, 然後判斷此graph的toposort 是否唯一.\n\n a digraph has a unique topological ordering if and only if there is a\n (directed edge) between each pair of consecutive vertices in the\n topological order (i.e., the digraph has a Hamiltonian path).\n\n https://... | <|body_start_0|>
"""
我的想法:
Merge graph, 然後判斷此graph的toposort 是否唯一.
a digraph has a unique topological ordering if and only if there is a
(directed edge) between each pair of consecutive vertices in the
topological order (i.e., the d... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sequenceReconstruction(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_0|>
def rewrite(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k_train_000002 | 3,721 | no_license | [
{
"docstring": ":type org: List[int] :type seqs: List[List[int]] :rtype: bool",
"name": "sequenceReconstruction",
"signature": "def sequenceReconstruction(self, org, seqs)"
},
{
"docstring": ":type org: List[int] :type seqs: List[List[int]] :rtype: bool",
"name": "rewrite",
"signature": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sequenceReconstruction(self, org, seqs): :type org: List[int] :type seqs: List[List[int]] :rtype: bool
- def rewrite(self, org, seqs): :type org: List[int] :type seqs: List[L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sequenceReconstruction(self, org, seqs): :type org: List[int] :type seqs: List[List[int]] :rtype: bool
- def rewrite(self, org, seqs): :type org: List[int] :type seqs: List[L... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def sequenceReconstruction(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_0|>
def rewrite(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sequenceReconstruction(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
"""
我的想法:
Merge graph, 然後判斷此graph的toposort 是否唯一.
a digraph has a unique topological ordering if and only if there is a
... | the_stack_v2_python_sparse | graph/444_Sequence_Reconstruction.py | vsdrun/lc_public | train | 6 | |
bd0f1abfcf830758fb58ba5e12d93d44f79d7085 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = query.size(0)\nquery, key, va... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
... | Multi-headed attention block. | MultiHeadedAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-headed attention block."""
def __init__(self, h, d_model, dropout=0.1):
""":param h: number of attention heads :param d_model: input/output dimensionality :param dropout: dropout probability"""
<|body_0|>
def forward(self, query, key, value... | stack_v2_sparse_classes_10k_train_000003 | 21,238 | no_license | [
{
"docstring": ":param h: number of attention heads :param d_model: input/output dimensionality :param dropout: dropout probability",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Forward pass through the multi-head attention block. :param quer... | 2 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-headed attention block.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): :param h: number of attention heads :param d_model: input/output dimensionality :param dropout: dropout probability
- def... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-headed attention block.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): :param h: number of attention heads :param d_model: input/output dimensionality :param dropout: dropout probability
- def... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-headed attention block."""
def __init__(self, h, d_model, dropout=0.1):
""":param h: number of attention heads :param d_model: input/output dimensionality :param dropout: dropout probability"""
<|body_0|>
def forward(self, query, key, value... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
"""Multi-headed attention block."""
def __init__(self, h, d_model, dropout=0.1):
""":param h: number of attention heads :param d_model: input/output dimensionality :param dropout: dropout probability"""
super(MultiHeadedAttention, self).__init__()
assert d_mo... | the_stack_v2_python_sparse | generated/test_allegro_allRank.py | jansel/pytorch-jit-paritybench | train | 35 |
36535093f9dc5d03333aa1536ca60195e30bb2ea | [
"self._log_startup(input_dict, output_dict, exec_properties)\nexclude_splits = json_utils.loads(exec_properties.get(standard_component_specs.EXCLUDE_SPLITS_KEY, 'null')) or []\nif not isinstance(exclude_splits, list):\n raise ValueError('exclude_splits in execution properties needs to be a list. Got %s instead.'... | <|body_start_0|>
self._log_startup(input_dict, output_dict, exec_properties)
exclude_splits = json_utils.loads(exec_properties.get(standard_component_specs.EXCLUDE_SPLITS_KEY, 'null')) or []
if not isinstance(exclude_splits, list):
raise ValueError('exclude_splits in execution proper... | TensorFlow ExampleValidator component executor. | Executor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Executor:
"""TensorFlow ExampleValidator component executor."""
def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None:
"""TensorFlow ExampleValidator executor entrypoint. This validates statist... | stack_v2_sparse_classes_10k_train_000004 | 7,025 | permissive | [
{
"docstring": "TensorFlow ExampleValidator executor entrypoint. This validates statistics against the schema. Args: input_dict: Input dict from input key to a list of artifacts, including: - statistics: A list of type `standard_artifacts.ExampleStatistics` generated by StatisticsGen. - schema: A list of type `... | 2 | null | Implement the Python class `Executor` described below.
Class description:
TensorFlow ExampleValidator component executor.
Method signatures and docstrings:
- def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None: TensorFlow Exa... | Implement the Python class `Executor` described below.
Class description:
TensorFlow ExampleValidator component executor.
Method signatures and docstrings:
- def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None: TensorFlow Exa... | 1b328504fa08a70388691e4072df76f143631325 | <|skeleton|>
class Executor:
"""TensorFlow ExampleValidator component executor."""
def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None:
"""TensorFlow ExampleValidator executor entrypoint. This validates statist... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Executor:
"""TensorFlow ExampleValidator component executor."""
def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None:
"""TensorFlow ExampleValidator executor entrypoint. This validates statistics against t... | the_stack_v2_python_sparse | tfx/components/example_validator/executor.py | tensorflow/tfx | train | 2,116 |
b70e73edb101e6303b655e31f58aa1ebc22cac70 | [
"super(Decoder, self).__init__(parameters)\nself.num_layers = num_layers\nself.layer_list = add_conv_block(self.Conv, self.BatchNorm, in_channels=anatomy_factors, out_channels=self.base_filters)\nfor _ in range(self.num_layers - 2):\n self.layer_list += add_conv_block(self.Conv, self.BatchNorm, in_channels=self.... | <|body_start_0|>
super(Decoder, self).__init__(parameters)
self.num_layers = num_layers
self.layer_list = add_conv_block(self.Conv, self.BatchNorm, in_channels=anatomy_factors, out_channels=self.base_filters)
for _ in range(self.num_layers - 2):
self.layer_list += add_conv_bl... | Decoder | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
def __init__(self, parameters, anatomy_factors, num_layers=5):
"""Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of laye... | stack_v2_sparse_classes_10k_train_000005 | 14,834 | permissive | [
{
"docstring": "Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of layers in the Decoder. Defaults to 5. Attributes: num_layers (int): The number of layer... | 6 | stack_v2_sparse_classes_30k_train_005006 | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, parameters, anatomy_factors, num_layers=5): Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): T... | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, parameters, anatomy_factors, num_layers=5): Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): T... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class Decoder:
def __init__(self, parameters, anatomy_factors, num_layers=5):
"""Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of laye... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Decoder:
def __init__(self, parameters, anatomy_factors, num_layers=5):
"""Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of layers in the Deco... | the_stack_v2_python_sparse | GANDLF/models/sdnet.py | mlcommons/GaNDLF | train | 45 | |
eec45e2f079cf9cee3b69e75401bc71597575f0c | [
"available_taxon_slugs: List[str] = []\nfor attr in attributes:\n available_taxon_slugs.extend(attr.field_map)\nreturn available_taxon_slugs",
"if 'attributes' in values:\n attributes: List[FdqModelAttribute] = values['attributes']\n taxon_slugs = cls._get_available_attrs_taxon_slugs(attributes)\n tax... | <|body_start_0|>
available_taxon_slugs: List[str] = []
for attr in attributes:
available_taxon_slugs.extend(attr.field_map)
return available_taxon_slugs
<|end_body_0|>
<|body_start_1|>
if 'attributes' in values:
attributes: List[FdqModelAttribute] = values['attri... | FdqModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FdqModel:
def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]:
"""Gets list of available taxon slugs for given attributes"""
<|body_0|>
def validate_unique_taxon_slugs(cls, values):
"""Validate that each taxon slug is used at m... | stack_v2_sparse_classes_10k_train_000006 | 8,280 | permissive | [
{
"docstring": "Gets list of available taxon slugs for given attributes",
"name": "_get_available_attrs_taxon_slugs",
"signature": "def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]"
},
{
"docstring": "Validate that each taxon slug is used at most once i... | 5 | stack_v2_sparse_classes_30k_train_005494 | Implement the Python class `FdqModel` described below.
Class description:
Implement the FdqModel class.
Method signatures and docstrings:
- def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]: Gets list of available taxon slugs for given attributes
- def validate_unique_taxon_s... | Implement the Python class `FdqModel` described below.
Class description:
Implement the FdqModel class.
Method signatures and docstrings:
- def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]: Gets list of available taxon slugs for given attributes
- def validate_unique_taxon_s... | 210f037280793d5cb3b6d9d3e7ba3e22ca9b8bbc | <|skeleton|>
class FdqModel:
def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]:
"""Gets list of available taxon slugs for given attributes"""
<|body_0|>
def validate_unique_taxon_slugs(cls, values):
"""Validate that each taxon slug is used at m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FdqModel:
def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]:
"""Gets list of available taxon slugs for given attributes"""
available_taxon_slugs: List[str] = []
for attr in attributes:
available_taxon_slugs.extend(attr.field_map)
... | the_stack_v2_python_sparse | src/panoramic/cli/husky/core/federated/model/models.py | panoramichq/panoramic-cli | train | 5 | |
3bc49a85876c37d609f9dcebfa908b298719650a | [
"self.capacity = capacity\nself.dict = OrderedDict()\nself.curr_len = 0",
"try:\n val = self.dict[key]\n del self.dict[key]\n self.dict[key] = val\n return val\nexcept KeyError:\n return -1",
"try:\n del self.dict[key]\n self.dict[key] = value\nexcept KeyError:\n if self.curr_len == self... | <|body_start_0|>
self.capacity = capacity
self.dict = OrderedDict()
self.curr_len = 0
<|end_body_0|>
<|body_start_1|>
try:
val = self.dict[key]
del self.dict[key]
self.dict[key] = val
return val
except KeyError:
return ... | Implement with OrderedDict | LRUCache1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache1:
"""Implement with OrderedDict"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
... | stack_v2_sparse_classes_10k_train_000007 | 3,068 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache1` described below.
Class description:
Implement with OrderedDict
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache1` described below.
Class description:
Implement with OrderedDict
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
class... | a64bca9c07a7be8d4060c4b96e89d8d429a7f1a3 | <|skeleton|>
class LRUCache1:
"""Implement with OrderedDict"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache1:
"""Implement with OrderedDict"""
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.dict = OrderedDict()
self.curr_len = 0
def get(self, key):
""":rtype: int"""
try:
val = self.dict[key]
... | the_stack_v2_python_sparse | Company Interview/SC/LRU.py | geniousisme/CodingInterview | train | 0 |
a5bec19a18ad7ebeda6e191272e9ba4e471ce6d9 | [
"if not root:\n return ''\nres = []\nq = collections.deque([root])\nwhile q:\n node = q.popleft()\n if node:\n res.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n res.append(str(-1))\nreturn ','.join(res)",
"if not data:\n return None\ndata_q... | <|body_start_0|>
if not root:
return ''
res = []
q = collections.deque([root])
while q:
node = q.popleft()
if node:
res.append(str(node.val))
q.append(node.left)
q.append(node.right)
else:
... | Codec | [] | 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_10k_train_000008 | 1,442 | no_license | [
{
"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_train_006182 | 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.
<... | c7a42753b2b16c7b9c66b8d7c2e67b683a15e27d | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
res = []
q = collections.deque([root])
while q:
node = q.popleft()
if node:
res.append(str(no... | the_stack_v2_python_sparse | medium/449.py | brandoneng000/LeetCode | train | 0 | |
26aff93bc0df9aa22e1b2e111b25105004d5a7c8 | [
"self._DebugPrintValue('Unknown1', f'0x{user_assist_entry.unknown1:08x}')\nself._DebugPrintDecimalValue('Number of executions', user_assist_entry.number_of_executions)\nif format_version == 5:\n self._DebugPrintDecimalValue('Application focus count', user_assist_entry.application_focus_count)\n self._DebugPri... | <|body_start_0|>
self._DebugPrintValue('Unknown1', f'0x{user_assist_entry.unknown1:08x}')
self._DebugPrintDecimalValue('Number of executions', user_assist_entry.number_of_executions)
if format_version == 5:
self._DebugPrintDecimalValue('Application focus count', user_assist_entry.app... | UserAssist data parser. | UserAssistDataParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAssistDataParser:
"""UserAssist data parser."""
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist... | stack_v2_sparse_classes_10k_train_000009 | 7,377 | permissive | [
{
"docstring": "Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist entry.",
"name": "_DebugPrintEntry",
"signature": "def _DebugPrintEntry(self, format_version, user_assist_entry)"
},
... | 2 | stack_v2_sparse_classes_30k_train_006023 | Implement the Python class `UserAssistDataParser` described below.
Class description:
UserAssist data parser.
Method signatures and docstrings:
- def _DebugPrintEntry(self, format_version, user_assist_entry): Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entr... | Implement the Python class `UserAssistDataParser` described below.
Class description:
UserAssist data parser.
Method signatures and docstrings:
- def _DebugPrintEntry(self, format_version, user_assist_entry): Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entr... | d149aff1b8ff97e1cc8d7416fc583b964bad4ccd | <|skeleton|>
class UserAssistDataParser:
"""UserAssist data parser."""
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserAssistDataParser:
"""UserAssist data parser."""
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist entry."""
... | the_stack_v2_python_sparse | winregrc/userassist.py | libyal/winreg-kb | train | 129 |
5bdbf11c4cfcb9a0185228801e2ea77cc24271a0 | [
"self.directions = self._listify_input(input_string.lower())\nself.steps = [0, 0, 0, 0]\nself.facing = 0\nself.locations = [(0, 0)]\nself.new_loc = (0, 0)",
"stripped_string = re.sub('\\\\s+', '', input_string.strip())\nsplit_list = stripped_string.split(',')\nreturn [(x[0], int(x[1:])) for x in split_list]",
"... | <|body_start_0|>
self.directions = self._listify_input(input_string.lower())
self.steps = [0, 0, 0, 0]
self.facing = 0
self.locations = [(0, 0)]
self.new_loc = (0, 0)
<|end_body_0|>
<|body_start_1|>
stripped_string = re.sub('\\s+', '', input_string.strip())
split... | Class for turning walking directions into distance from start. | Walker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Walker:
"""Class for turning walking directions into distance from start."""
def __init__(self, input_string):
"""Initialize."""
<|body_0|>
def _listify_input(self, input_string):
"""Turn a string of inputs into a list."""
<|body_1|>
def make_rotatio... | stack_v2_sparse_classes_10k_train_000010 | 2,294 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, input_string)"
},
{
"docstring": "Turn a string of inputs into a list.",
"name": "_listify_input",
"signature": "def _listify_input(self, input_string)"
},
{
"docstring": "Turn left or right, and u... | 6 | stack_v2_sparse_classes_30k_train_003435 | Implement the Python class `Walker` described below.
Class description:
Class for turning walking directions into distance from start.
Method signatures and docstrings:
- def __init__(self, input_string): Initialize.
- def _listify_input(self, input_string): Turn a string of inputs into a list.
- def make_rotation(se... | Implement the Python class `Walker` described below.
Class description:
Class for turning walking directions into distance from start.
Method signatures and docstrings:
- def __init__(self, input_string): Initialize.
- def _listify_input(self, input_string): Turn a string of inputs into a list.
- def make_rotation(se... | 17c729af2af5f1d95ba6ff68771a82ca6d00b05d | <|skeleton|>
class Walker:
"""Class for turning walking directions into distance from start."""
def __init__(self, input_string):
"""Initialize."""
<|body_0|>
def _listify_input(self, input_string):
"""Turn a string of inputs into a list."""
<|body_1|>
def make_rotatio... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Walker:
"""Class for turning walking directions into distance from start."""
def __init__(self, input_string):
"""Initialize."""
self.directions = self._listify_input(input_string.lower())
self.steps = [0, 0, 0, 0]
self.facing = 0
self.locations = [(0, 0)]
... | the_stack_v2_python_sparse | 2016/day01_no_time_for_a_taxicab/python/src/part2.py | tlake/advent-of-code | train | 0 |
5460e94ca69e81da3dfbe356fc9545f03baab185 | [
"if target not in nums:\n return -1\nreturn nums.index(target)",
"left = 0\nright = len(nums) - 1\nif not nums:\n return -1\nwhile left + 1 < right:\n mid = (left + right) // 2\n if nums[mid] >= nums[left]:\n if nums[left] <= target <= nums[mid]:\n right = mid\n else:\n ... | <|body_start_0|>
if target not in nums:
return -1
return nums.index(target)
<|end_body_0|>
<|body_start_1|>
left = 0
right = len(nums) - 1
if not nums:
return -1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_binary(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_000011 | 2,370 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search_binary",
"signature": "def search_binary(self, nums, target)"
}... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_binary(self, nums, target): :type nums: List[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_binary(self, nums, target): :type nums: List[int] :type target: int :rtype: int
... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_binary(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
if target not in nums:
return -1
return nums.index(target)
def search_binary(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00033.Search in Rotated Sorted Array.py | roger6blog/LeetCode | train | 0 | |
6744895894e45ee7455520b2fbc0baa617c56ff9 | [
"if root is None:\n return ''\nreturn f'{root.val},{self.serialize(root.left)}{self.serialize(root.right)}'",
"def insert(node, val):\n if node is None:\n return TreeNode(val)\n if val < node.val:\n node.left = insert(node.left, val)\n else:\n node.right = insert(node.right, val)\... | <|body_start_0|>
if root is None:
return ''
return f'{root.val},{self.serialize(root.left)}{self.serialize(root.right)}'
<|end_body_0|>
<|body_start_1|>
def insert(node, val):
if node is None:
return TreeNode(val)
if val < node.val:
... | Codec | [] | 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_10k_train_000012 | 2,004 | no_license | [
{
"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 | null | 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.
<... | 157cbaeeff74130e5105e58a6b4cdf66403a8a6f | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
if root is None:
return ''
return f'{root.val},{self.serialize(root.left)}{self.serialize(root.right)}'
def deserialize(self, data: str) -> Optional[TreeNode]:
... | the_stack_v2_python_sparse | Leetcode/449. Serialize and Deserialize BST.py | xiaohuanlin/Algorithms | train | 1 | |
abee5b7ce469825ae16fb8fa2002ee71659ee035 | [
"self.policy = policy\nself.base_rate = base_rate\nself.gamma = gamma\nself.power = power\nself.max_steps = max_steps\nself.step_values = step_values\nif self.step_values:\n self.stepvalues_list = map(float, step_values.split(','))\nelse:\n self.stepvalues_list = []\nif self.max_steps < len(self.stepvalues_li... | <|body_start_0|>
self.policy = policy
self.base_rate = base_rate
self.gamma = gamma
self.power = power
self.max_steps = max_steps
self.step_values = step_values
if self.step_values:
self.stepvalues_list = map(float, step_values.split(','))
else... | This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp: return base_lr * gamma ^ iter - in... | LRPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRPolicy:
"""This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp... | stack_v2_sparse_classes_10k_train_000013 | 6,721 | permissive | [
{
"docstring": "Initialize a learning rate policy Args: policy: Learning rate policy base_rate: Base learning rate gamma: parameter to compute learning rate power: parameter to compute learning rate max_steps: parameter to compute learning rate step_values: parameter(s) to compute learning rate. should be a str... | 2 | stack_v2_sparse_classes_30k_train_005287 | Implement the Python class `LRPolicy` described below.
Class description:
This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_... | Implement the Python class `LRPolicy` described below.
Class description:
This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_... | ad44695a459adc389a886ec72ca92ae190b0d30a | <|skeleton|>
class LRPolicy:
"""This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRPolicy:
"""This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp: return base... | the_stack_v2_python_sparse | deepstacks/utils/lr_policy.py | guoxuesong/deepstacks | train | 2 |
2ef984b3a5210a5b63f2ef9e337335e054edf591 | [
"i = 0\nwhile i <= len(nums):\n if i + nums[i] >= len(nums) - 1:\n return True\n if i == len(nums) - 2 or nums[i] == 0:\n return False\n max = nums[i + 1] + i + 1\n temp = i + 1\n if nums[i] != 0:\n for j in range(1, nums[i] + 1):\n if nums[i + j] + i + j >= max:\n ... | <|body_start_0|>
i = 0
while i <= len(nums):
if i + nums[i] >= len(nums) - 1:
return True
if i == len(nums) - 2 or nums[i] == 0:
return False
max = nums[i + 1] + i + 1
temp = i + 1
if nums[i] != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
"""高端解法 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
while i <= len(nums):
if i + num... | stack_v2_sparse_classes_10k_train_000014 | 1,696 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": "高端解法 :param nums: :return:",
"name": "canJump2",
"signature": "def canJump2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004821 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): 高端解法 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): 高端解法 :param nums: :return:
<|skeleton|>
class Solution:
def canJump(self, nums):
... | beabfd31379f44ffd767fc676912db5022495b53 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
"""高端解法 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
i = 0
while i <= len(nums):
if i + nums[i] >= len(nums) - 1:
return True
if i == len(nums) - 2 or nums[i] == 0:
return False
max = nums[i + 1]... | the_stack_v2_python_sparse | leetCode/top100/055canJump.py | fatezy/Algorithm | train | 1 | |
ff14f9c959ef3a3497975e4138158316719050b0 | [
"T = len(self.x)\ndLdx = np.zeros((T, self.input_size))\nself.nodes.reset_error()\nfor t in xrange(T):\n dLdp = dLds[t] * self.acfun.derivate(self.s[t])\n self.nodes.dLdu += np.outer(dLdp, self.x[t])\n if self.en_bias:\n self.nodes.dLdb += dLdp\n dLdx[t] = np.dot(self.nodes.u.T, dLdp)\nself.nodes... | <|body_start_0|>
T = len(self.x)
dLdx = np.zeros((T, self.input_size))
self.nodes.reset_error()
for t in xrange(T):
dLdp = dLds[t] * self.acfun.derivate(self.s[t])
self.nodes.dLdu += np.outer(dLdp, self.x[t])
if self.en_bias:
self.nodes... | Feed-forward neural network. | FNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FNN:
"""Feed-forward neural network."""
def update(self, dLds, alpha, beta):
"""Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter"... | stack_v2_sparse_classes_10k_train_000015 | 1,800 | permissive | [
{
"docstring": "Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter",
"name": "update",
"signature": "def update(self, dLds, alpha, beta)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_001767 | Implement the Python class `FNN` described below.
Class description:
Feed-forward neural network.
Method signatures and docstrings:
- def update(self, dLds, alpha, beta): Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param al... | Implement the Python class `FNN` described below.
Class description:
Feed-forward neural network.
Method signatures and docstrings:
- def update(self, dLds, alpha, beta): Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param al... | 1a08b12767cf028626f0368b993933092390f28d | <|skeleton|>
class FNN:
"""Feed-forward neural network."""
def update(self, dLds, alpha, beta):
"""Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FNN:
"""Feed-forward neural network."""
def update(self, dLds, alpha, beta):
"""Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter"""
T ... | the_stack_v2_python_sparse | nnlm/nnm/fnn.py | dengliangshi/pynnlms | train | 11 |
bcd5d58a4b1789a205e03f69fe2458b9b4a5b5a2 | [
"while m > 0 and n > 0:\n if nums1[m - 1] > nums2[n - 1]:\n nums1[m + n - 1] = nums1[m - 1]\n m -= 1\n else:\n nums1[m + n - 1] = nums2[n - 1]\n n -= 1\nif m == 0:\n nums1[:n] = nums2[:n]\n nums1[m:] = nums2[j:]",
"i = 0\nj = 0\nwhile j < n:\n while i < m and nums1[i] <=... | <|body_start_0|>
while m > 0 and n > 0:
if nums1[m - 1] > nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
else:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
if m == 0:
nums1[:n] = nums2[:n]
num... | Do not return anything, modify nums1 in-place instead. | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Do not return anything, modify nums1 in-place instead."""
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge1(self, nums1, m, nums2, n):
"""Tw... | stack_v2_sparse_classes_10k_train_000016 | 2,069 | permissive | [
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature": "def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None"
},
{
"docstring": "Two Pointers",
"name": "merge1",
"signature": "def merge1(self, nums1, m, nums2, n)"
}... | 3 | stack_v2_sparse_classes_30k_train_003028 | Implement the Python class `Solution` described below.
Class description:
Do not return anything, modify nums1 in-place instead.
Method signatures and docstrings:
- def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge1(self, nu... | Implement the Python class `Solution` described below.
Class description:
Do not return anything, modify nums1 in-place instead.
Method signatures and docstrings:
- def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge1(self, nu... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
"""Do not return anything, modify nums1 in-place instead."""
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge1(self, nums1, m, nums2, n):
"""Tw... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Do not return anything, modify nums1 in-place instead."""
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
while m > 0 and n > 0:
if nums1[m - 1] > nums2[n - 1]:
... | the_stack_v2_python_sparse | leetcode/0088_merge_sorted_array.py | chaosWsF/Python-Practice | train | 1 |
fe86294cb26d6c8e26bfcd46f17bb2f43aabbd8b | [
"if _cfg.server_backend == 'cassandra':\n clear_graph()\nelse:\n Gremlin().gremlin_post('graph.truncateBackend();')\nInsertData(gremlin='gremlin_traverser.txt').gremlin_graph()",
"json = {'sources': {'ids': [], 'label': 'person', 'properties': {'name': 'marko'}}, 'steps': [{'direction': 'OUT', 'labels': ['k... | <|body_start_0|>
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_traverser.txt').gremlin_graph()
<|end_body_0|>
<|body_start_1|>
json = {'sources': {'ids': [], 'label': 'per... | 查询一批顶点符合条件的路径 | TestCustomizedPaths | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCustomizedPaths:
"""查询一批顶点符合条件的路径"""
def setup_class(self):
"""测试类开始"""
<|body_0|>
def test_reqiured_params(self):
"""source、max_depth :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if _cfg.server_backend == 'cassandra':
... | stack_v2_sparse_classes_10k_train_000017 | 2,712 | no_license | [
{
"docstring": "测试类开始",
"name": "setup_class",
"signature": "def setup_class(self)"
},
{
"docstring": "source、max_depth :return:",
"name": "test_reqiured_params",
"signature": "def test_reqiured_params(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002029 | Implement the Python class `TestCustomizedPaths` described below.
Class description:
查询一批顶点符合条件的路径
Method signatures and docstrings:
- def setup_class(self): 测试类开始
- def test_reqiured_params(self): source、max_depth :return: | Implement the Python class `TestCustomizedPaths` described below.
Class description:
查询一批顶点符合条件的路径
Method signatures and docstrings:
- def setup_class(self): 测试类开始
- def test_reqiured_params(self): source、max_depth :return:
<|skeleton|>
class TestCustomizedPaths:
"""查询一批顶点符合条件的路径"""
def setup_class(self):
... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class TestCustomizedPaths:
"""查询一批顶点符合条件的路径"""
def setup_class(self):
"""测试类开始"""
<|body_0|>
def test_reqiured_params(self):
"""source、max_depth :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCustomizedPaths:
"""查询一批顶点符合条件的路径"""
def setup_class(self):
"""测试类开始"""
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_traverser.txt').gremlin_graph()
... | the_stack_v2_python_sparse | src/graph_function_test/server/algorithm_oltp/test_customized_path.py | hugegraph/hugegraph-test | train | 1 |
b34dd614c6b7da0a6a80d608d0b45bca5a481470 | [
"dp = [[0 for _ in range(100)] for _ in range(100)]\ndp[0][0] = poured\ncur = [0, 1]\nrow = 0\nwhile cur[0] < cur[1] and row < 99:\n next_max = -1\n next_min = 100\n print(row, cur[0], cur[1])\n for i in range(cur[0], cur[1]):\n if dp[row][i] > 1:\n next_one = (dp[row][i] - 1) / 2.0\n ... | <|body_start_0|>
dp = [[0 for _ in range(100)] for _ in range(100)]
dp[0][0] = poured
cur = [0, 1]
row = 0
while cur[0] < cur[1] and row < 99:
next_max = -1
next_min = 100
print(row, cur[0], cur[1])
for i in range(cur[0], cur[1]):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def champagneTower(self, poured, query_row, query_glass):
""":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms"""
<|body_0|>
def champagneTower_1(self, poured, query_row, query_glass):
""":type poured: int :type query_row: in... | stack_v2_sparse_classes_10k_train_000018 | 4,193 | no_license | [
{
"docstring": ":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms",
"name": "champagneTower",
"signature": "def champagneTower(self, poured, query_row, query_glass)"
},
{
"docstring": ":type poured: int :type query_row: int :type query_glass: int :rtype: float 125... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def champagneTower(self, poured, query_row, query_glass): :type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms
- def champagneTower_1(self, poured, q... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def champagneTower(self, poured, query_row, query_glass): :type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms
- def champagneTower_1(self, poured, q... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def champagneTower(self, poured, query_row, query_glass):
""":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms"""
<|body_0|>
def champagneTower_1(self, poured, query_row, query_glass):
""":type poured: int :type query_row: in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def champagneTower(self, poured, query_row, query_glass):
""":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms"""
dp = [[0 for _ in range(100)] for _ in range(100)]
dp[0][0] = poured
cur = [0, 1]
row = 0
while cur[0] < c... | the_stack_v2_python_sparse | ChampagneTower_MID_799.py | 953250587/leetcode-python | train | 2 | |
010a5eda3d42169112042145140e28c0d5d19a12 | [
"room_list = []\nrooms = models.Room.objects.all()\nfor room in rooms:\n if room.state == 0:\n room_list.append(room.roomId)\nreturn render(request, 'usermgr/order/neworder.html', locals())",
"resultData = {'ret': None}\nif request.is_ajax():\n room = models.Room.objects.filter(roomId=request.POST.ge... | <|body_start_0|>
room_list = []
rooms = models.Room.objects.all()
for room in rooms:
if room.state == 0:
room_list.append(room.roomId)
return render(request, 'usermgr/order/neworder.html', locals())
<|end_body_0|>
<|body_start_1|>
resultData = {'ret':... | 处理新预约订单 | NewOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewOrder:
"""处理新预约订单"""
def get(self, request):
"""获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面"""
<|body_0|>
def post(self, request):
"""获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果"""
<|body_1|>
def databa... | stack_v2_sparse_classes_10k_train_000019 | 12,349 | no_license | [
{
"docstring": "获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果",
"name": "post",
"signature": "def post(self, request)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_005149 | Implement the Python class `NewOrder` described below.
Class description:
处理新预约订单
Method signatures and docstrings:
- def get(self, request): 获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面
- def post(self, request): 获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果
- def database_u... | Implement the Python class `NewOrder` described below.
Class description:
处理新预约订单
Method signatures and docstrings:
- def get(self, request): 获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面
- def post(self, request): 获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果
- def database_u... | 26c49e8f525ca57dca27f8de53d15bcab24d00e4 | <|skeleton|>
class NewOrder:
"""处理新预约订单"""
def get(self, request):
"""获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面"""
<|body_0|>
def post(self, request):
"""获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果"""
<|body_1|>
def databa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NewOrder:
"""处理新预约订单"""
def get(self, request):
"""获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面"""
room_list = []
rooms = models.Room.objects.all()
for room in rooms:
if room.state == 0:
room_list.append(room.roomId)
... | the_stack_v2_python_sparse | iframe_api/views.py | A35-Zhou/Rental-House-Manager | train | 0 |
a1239f4ed517661675af6b8785004ce7bff3af9a | [
"letters = 'abcdefghijklmnopqrstuvwxyz'\ncnt = collections.Counter()\nn = 0\nfor s in licensePlate:\n if s.lower() in letters:\n cnt[s.lower()] += 1\n n += 1\nres, leng = ('', float('inf'))\nfor each in words:\n if len(each) >= n:\n flag = 1\n for key in cnt:\n if cnt[ke... | <|body_start_0|>
letters = 'abcdefghijklmnopqrstuvwxyz'
cnt = collections.Counter()
n = 0
for s in licensePlate:
if s.lower() in letters:
cnt[s.lower()] += 1
n += 1
res, leng = ('', float('inf'))
for each in words:
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
<|body_0|>
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
... | stack_v2_sparse_classes_10k_train_000020 | 2,799 | no_license | [
{
"docstring": ":type licensePlate: str :type words: List[str] :rtype: str",
"name": "shortestCompletingWord",
"signature": "def shortestCompletingWord(self, licensePlate, words)"
},
{
"docstring": ":type licensePlate: str :type words: List[str] :rtype: str",
"name": "shortestCompletingWord"... | 2 | stack_v2_sparse_classes_30k_train_002348 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestCompletingWord(self, licensePlate, words): :type licensePlate: str :type words: List[str] :rtype: str
- def shortestCompletingWord(self, licensePlate, words): :type l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestCompletingWord(self, licensePlate, words): :type licensePlate: str :type words: List[str] :rtype: str
- def shortestCompletingWord(self, licensePlate, words): :type l... | 8bb17099be02d997d554519be360ef4aa1c028e3 | <|skeleton|>
class Solution:
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
<|body_0|>
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
letters = 'abcdefghijklmnopqrstuvwxyz'
cnt = collections.Counter()
n = 0
for s in licensePlate:
if s.lower() in letters:
... | the_stack_v2_python_sparse | Google/2. medium/749. Shortest Completing Word.py | yemao616/summer18 | train | 0 | |
1b307bb242d4f2e0085c286024ddc959dab980c9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.accessPackageAssignmentRequestWorkflowExten... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | CustomCalloutExtension | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomCalloutExtension:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomCalloutExtension:
"""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 ... | stack_v2_sparse_classes_10k_train_000021 | 6,532 | 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: CustomCalloutExtension",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_002836 | Implement the Python class `CustomCalloutExtension` described below.
Class description:
Implement the CustomCalloutExtension class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomCalloutExtension: Creates a new instance of the appropriate class b... | Implement the Python class `CustomCalloutExtension` described below.
Class description:
Implement the CustomCalloutExtension class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomCalloutExtension: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CustomCalloutExtension:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomCalloutExtension:
"""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 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomCalloutExtension:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomCalloutExtension:
"""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 Ret... | the_stack_v2_python_sparse | msgraph/generated/models/custom_callout_extension.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d561dd6ad0557cda488cff9082d1654f11b012ae | [
"self._nhc = nhc\nself.hass = hass\nself.available = True\nself.data = {}\nself._system_info = None",
"_LOGGER.debug('Fetching async state in bulk')\ntry:\n self.data = await self.hass.async_add_executor_job(self._nhc.list_actions_raw)\n self.available = True\nexcept OSError as ex:\n _LOGGER.error('Unabl... | <|body_start_0|>
self._nhc = nhc
self.hass = hass
self.available = True
self.data = {}
self._system_info = None
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug('Fetching async state in bulk')
try:
self.data = await self.hass.async_add_executor_job(self.... | The class for handling data retrieval. | NikoHomeControlData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NikoHomeControlData:
"""The class for handling data retrieval."""
def __init__(self, hass, nhc):
"""Set up Niko Home Control Data object."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the NikoHomeControl API."""
<|body_1|>
d... | stack_v2_sparse_classes_10k_train_000022 | 4,084 | permissive | [
{
"docstring": "Set up Niko Home Control Data object.",
"name": "__init__",
"signature": "def __init__(self, hass, nhc)"
},
{
"docstring": "Get the latest data from the NikoHomeControl API.",
"name": "async_update",
"signature": "async def async_update(self)"
},
{
"docstring": "F... | 3 | stack_v2_sparse_classes_30k_train_003206 | Implement the Python class `NikoHomeControlData` described below.
Class description:
The class for handling data retrieval.
Method signatures and docstrings:
- def __init__(self, hass, nhc): Set up Niko Home Control Data object.
- async def async_update(self): Get the latest data from the NikoHomeControl API.
- def g... | Implement the Python class `NikoHomeControlData` described below.
Class description:
The class for handling data retrieval.
Method signatures and docstrings:
- def __init__(self, hass, nhc): Set up Niko Home Control Data object.
- async def async_update(self): Get the latest data from the NikoHomeControl API.
- def g... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NikoHomeControlData:
"""The class for handling data retrieval."""
def __init__(self, hass, nhc):
"""Set up Niko Home Control Data object."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the NikoHomeControl API."""
<|body_1|>
d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NikoHomeControlData:
"""The class for handling data retrieval."""
def __init__(self, hass, nhc):
"""Set up Niko Home Control Data object."""
self._nhc = nhc
self.hass = hass
self.available = True
self.data = {}
self._system_info = None
async def async_... | the_stack_v2_python_sparse | homeassistant/components/niko_home_control/light.py | home-assistant/core | train | 35,501 |
7abe1af354a1bfafcfd00b03325031dba680c060 | [
"if len(strs) == 0:\n return ''\nminstrlenghth = 10 ** 9\nfor s in strs:\n if len(s) < minstrlenghth:\n minstrlenghth = len(s)\nprint(minstrlenghth)\nfor i in range(minstrlenghth):\n temp = strs[0][i]\n for j in range(1, len(strs)):\n if strs[j][i] != temp:\n return strs[0][:i]\... | <|body_start_0|>
if len(strs) == 0:
return ''
minstrlenghth = 10 ** 9
for s in strs:
if len(s) < minstrlenghth:
minstrlenghth = len(s)
print(minstrlenghth)
for i in range(minstrlenghth):
temp = strs[0][i]
for j in ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix1(self, strs: List[str]) -> str:
"""我这里做纵向扫描,也就是从前向后遍历所有字符串的每一列, 比较相同列行的字符是否相同,如果相同则继续对下一列的字符进行比较 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀 复杂度分析: 时间复杂度:O(nm) 其中m为字符串数组的长度,n为列表长度(即字符串的数量) 最坏的情况下,字符串数组中每个字符串的每个字符都要被比较一次 空间复杂度:O(1)"""
<|body_0|>
def lo... | stack_v2_sparse_classes_10k_train_000023 | 1,993 | no_license | [
{
"docstring": "我这里做纵向扫描,也就是从前向后遍历所有字符串的每一列, 比较相同列行的字符是否相同,如果相同则继续对下一列的字符进行比较 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀 复杂度分析: 时间复杂度:O(nm) 其中m为字符串数组的长度,n为列表长度(即字符串的数量) 最坏的情况下,字符串数组中每个字符串的每个字符都要被比较一次 空间复杂度:O(1)",
"name": "longestCommonPrefix1",
"signature": "def longestCommonPrefix1(self, strs: List[str]) -> str... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix1(self, strs: List[str]) -> str: 我这里做纵向扫描,也就是从前向后遍历所有字符串的每一列, 比较相同列行的字符是否相同,如果相同则继续对下一列的字符进行比较 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀 复杂度分析: 时间复杂度:O(nm) 其中m为字符串... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix1(self, strs: List[str]) -> str: 我这里做纵向扫描,也就是从前向后遍历所有字符串的每一列, 比较相同列行的字符是否相同,如果相同则继续对下一列的字符进行比较 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀 复杂度分析: 时间复杂度:O(nm) 其中m为字符串... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def longestCommonPrefix1(self, strs: List[str]) -> str:
"""我这里做纵向扫描,也就是从前向后遍历所有字符串的每一列, 比较相同列行的字符是否相同,如果相同则继续对下一列的字符进行比较 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀 复杂度分析: 时间复杂度:O(nm) 其中m为字符串数组的长度,n为列表长度(即字符串的数量) 最坏的情况下,字符串数组中每个字符串的每个字符都要被比较一次 空间复杂度:O(1)"""
<|body_0|>
def lo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix1(self, strs: List[str]) -> str:
"""我这里做纵向扫描,也就是从前向后遍历所有字符串的每一列, 比较相同列行的字符是否相同,如果相同则继续对下一列的字符进行比较 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀 复杂度分析: 时间复杂度:O(nm) 其中m为字符串数组的长度,n为列表长度(即字符串的数量) 最坏的情况下,字符串数组中每个字符串的每个字符都要被比较一次 空间复杂度:O(1)"""
if len(strs) == 0:
retur... | the_stack_v2_python_sparse | LeetCode_practice/0014_LongestCommonPrefix.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
8fed59678ddeabe8b7060bdccc4745817cd442ab | [
"self.expression_data = expression_data\nself.calculator = calculator\nself.rm_outliers = rm_outliers",
"data = None\nif isinstance(measurments, dict):\n data = measurments\n measurments = list(measurments.values())\nmeasurments = np.array(measurments)\nupper_quartile = np.percentile(measurments, 75)\nlower... | <|body_start_0|>
self.expression_data = expression_data
self.calculator = calculator
self.rm_outliers = rm_outliers
<|end_body_0|>
<|body_start_1|>
data = None
if isinstance(measurments, dict):
data = measurments
measurments = list(measurments.values())
... | Base class for navigation of similarity calculation between specified genes. | SimilarityCalculatorNavigator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimilarityCalculatorNavigator:
"""Base class for navigation of similarity calculation between specified genes."""
def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):
""":param expression_data: Data for all genes :param calcul... | stack_v2_sparse_classes_10k_train_000024 | 43,977 | no_license | [
{
"docstring": ":param expression_data: Data for all genes :param calculator: SimilarityCalculator used in all calculations :param rm_outliers: should outliers be removed before similarity statistics calculation",
"name": "__init__",
"signature": "def __init__(self, expression_data: GeneExpression, calc... | 2 | stack_v2_sparse_classes_30k_train_005795 | Implement the Python class `SimilarityCalculatorNavigator` described below.
Class description:
Base class for navigation of similarity calculation between specified genes.
Method signatures and docstrings:
- def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):... | Implement the Python class `SimilarityCalculatorNavigator` described below.
Class description:
Base class for navigation of similarity calculation between specified genes.
Method signatures and docstrings:
- def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):... | 6d11df5e8ca37e53e048d261ac287f859ba6e9b9 | <|skeleton|>
class SimilarityCalculatorNavigator:
"""Base class for navigation of similarity calculation between specified genes."""
def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):
""":param expression_data: Data for all genes :param calcul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimilarityCalculatorNavigator:
"""Base class for navigation of similarity calculation between specified genes."""
def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):
""":param expression_data: Data for all genes :param calculator: Similar... | the_stack_v2_python_sparse | correlation_enrichment/library_correlation_enrichment.py | biolab/baylor-dicty | train | 0 |
965614a8a704d6161c20932dff7cb13c1b8b0d81 | [
"OGLDrawable.__init__(self)\nlength = wingspan / 2.0\nfuseLen = length / 2.0\ndepth = fuseLen / 2.0\nfuseHalf = fuseLen / 2.0\ndpthHalf = depth / 2.0\nwingHalf = wingspan / 2.0\nfront = [fuseHalf, 0.0, 0.0]\nbottom = [0.0, 0.0, -dpthHalf]\nback = [-fuseHalf, 0.0, 0.0]\ntop = [0.0, 0.0, dpthHalf]\nrghtWTip = [-lengt... | <|body_start_0|>
OGLDrawable.__init__(self)
length = wingspan / 2.0
fuseLen = length / 2.0
depth = fuseLen / 2.0
fuseHalf = fuseLen / 2.0
dpthHalf = depth / 2.0
wingHalf = wingspan / 2.0
front = [fuseHalf, 0.0, 0.0]
bottom = [0.0, 0.0, -dpthHalf]
... | Little Wing | StarGlider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarGlider:
"""Little Wing"""
def __init__(self, wingspan=1.0):
"""Set up as drawable"""
<|body_0|>
def draw(self):
"""Render the StarGlider"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
OGLDrawable.__init__(self)
length = wingspan / 2... | stack_v2_sparse_classes_10k_train_000025 | 5,966 | no_license | [
{
"docstring": "Set up as drawable",
"name": "__init__",
"signature": "def __init__(self, wingspan=1.0)"
},
{
"docstring": "Render the StarGlider",
"name": "draw",
"signature": "def draw(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002057 | Implement the Python class `StarGlider` described below.
Class description:
Little Wing
Method signatures and docstrings:
- def __init__(self, wingspan=1.0): Set up as drawable
- def draw(self): Render the StarGlider | Implement the Python class `StarGlider` described below.
Class description:
Little Wing
Method signatures and docstrings:
- def __init__(self, wingspan=1.0): Set up as drawable
- def draw(self): Render the StarGlider
<|skeleton|>
class StarGlider:
"""Little Wing"""
def __init__(self, wingspan=1.0):
... | 7f3b2aaeb24e41002e9dee2f2af669006e1cbd5c | <|skeleton|>
class StarGlider:
"""Little Wing"""
def __init__(self, wingspan=1.0):
"""Set up as drawable"""
<|body_0|>
def draw(self):
"""Render the StarGlider"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StarGlider:
"""Little Wing"""
def __init__(self, wingspan=1.0):
"""Set up as drawable"""
OGLDrawable.__init__(self)
length = wingspan / 2.0
fuseLen = length / 2.0
depth = fuseLen / 2.0
fuseHalf = fuseLen / 2.0
dpthHalf = depth / 2.0
wingHalf... | the_stack_v2_python_sparse | Games/OGL_test.py | jwatson-CO-edu/py_toybox | train | 0 |
d2928c15b2c3fe50a6daec8a2883581c7172d86f | [
"data = [{'name': 'Normal string', 'item_num': 1}, {'name': 'String, with, commas', 'item_num': 2}, {'name': 'String with \" quote', 'item_num': 3}]\ntable = TableReportForTesting(data)\nresponse = table.as_csv(HttpRequest())\nself.assertEqual(response.status_code, 200)\ncontent = response.content\nif PY3:\n con... | <|body_start_0|>
data = [{'name': 'Normal string', 'item_num': 1}, {'name': 'String, with, commas', 'item_num': 2}, {'name': 'String with " quote', 'item_num': 3}]
table = TableReportForTesting(data)
response = table.as_csv(HttpRequest())
self.assertEqual(response.status_code, 200)
... | Test csv generation on sample table data. | TestCsvGeneration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCsvGeneration:
"""Test csv generation on sample table data."""
def test_csv_simple_input(self):
"""Test ability to generate csv with simple input data."""
<|body_0|>
def test_csv_with_unicode(self):
"""Test that unicode cell values are converted correctly to ... | stack_v2_sparse_classes_10k_train_000026 | 7,242 | no_license | [
{
"docstring": "Test ability to generate csv with simple input data.",
"name": "test_csv_simple_input",
"signature": "def test_csv_simple_input(self)"
},
{
"docstring": "Test that unicode cell values are converted correctly to csv.",
"name": "test_csv_with_unicode",
"signature": "def tes... | 4 | stack_v2_sparse_classes_30k_train_005237 | Implement the Python class `TestCsvGeneration` described below.
Class description:
Test csv generation on sample table data.
Method signatures and docstrings:
- def test_csv_simple_input(self): Test ability to generate csv with simple input data.
- def test_csv_with_unicode(self): Test that unicode cell values are co... | Implement the Python class `TestCsvGeneration` described below.
Class description:
Test csv generation on sample table data.
Method signatures and docstrings:
- def test_csv_simple_input(self): Test ability to generate csv with simple input data.
- def test_csv_with_unicode(self): Test that unicode cell values are co... | 0fcdb4becd8e25559819e877e77078c0cf17b6cd | <|skeleton|>
class TestCsvGeneration:
"""Test csv generation on sample table data."""
def test_csv_simple_input(self):
"""Test ability to generate csv with simple input data."""
<|body_0|>
def test_csv_with_unicode(self):
"""Test that unicode cell values are converted correctly to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCsvGeneration:
"""Test csv generation on sample table data."""
def test_csv_simple_input(self):
"""Test ability to generate csv with simple input data."""
data = [{'name': 'Normal string', 'item_num': 1}, {'name': 'String, with, commas', 'item_num': 2}, {'name': 'String with " quote',... | the_stack_v2_python_sparse | django_tables2_reports/tests.py | goinnn/django-tables2-reports | train | 48 |
390b55ad55a201edb5db7cb6bbd8448294d25856 | [
"super(NeuralProcess, self).__init__()\nself._num_latents = num_latents\nself._latent_encoder_sizes = latent_encoder_sizes\nself._deterministic_encoder_sizes = deterministic_encoder_sizes\nself._decoder_sizes = decoder_sizes\nself._use_deterministic_path = use_deterministic_path\nself._attention = attention_wrapper... | <|body_start_0|>
super(NeuralProcess, self).__init__()
self._num_latents = num_latents
self._latent_encoder_sizes = latent_encoder_sizes
self._deterministic_encoder_sizes = deterministic_encoder_sizes
self._decoder_sizes = decoder_sizes
self._use_deterministic_path = use_... | Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018). | NeuralProcess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model... | stack_v2_sparse_classes_10k_train_000027 | 32,302 | permissive | [
{
"docstring": "Initializes the Neural Process model. Args: latent_encoder_sizes: (list of ints) Hidden layer sizes for latent encoder. num_latents: (int) Dimensionality of global latent variable. decoder_sizes: (list of ints) Hidden layer sizes for decoder use_deterministic_path: (bool) Uses deterministic enco... | 5 | null | Implement the Python class `NeuralProcess` described below.
Class description:
Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018).
Method signatures and docstrings:
- def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, atte... | Implement the Python class `NeuralProcess` described below.
Class description:
Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018).
Method signatures and docstrings:
- def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, atte... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model. Args: laten... | the_stack_v2_python_sparse | t2t_bert/utils/tensor2tensor/layers/gaussian_process.py | yyht/BERT | train | 37 |
561471ab045e389d791bab7bf4968b71143294b6 | [
"super().__init__()\nif not components:\n raise ValueError('At least one (weight, loss_function) pair must be supplied.')\nself.components = components",
"result = None\nfor weight, loss_function in self.components:\n loss = weight * loss_function(output, target, **kwargs)\n if result is None:\n r... | <|body_start_0|>
super().__init__()
if not components:
raise ValueError('At least one (weight, loss_function) pair must be supplied.')
self.components = components
<|end_body_0|>
<|body_start_1|>
result = None
for weight, loss_function in self.components:
... | MixtureLoss | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixtureLoss:
def __init__(self, components: List[Tuple[float, SupervisedLearningCriterion]]):
"""Loss function defined as a weighted mixture (interpolation) of other loss functions. :param components: a non-empty list of weights and loss function instances."""
<|body_0|>
def... | stack_v2_sparse_classes_10k_train_000028 | 1,825 | permissive | [
{
"docstring": "Loss function defined as a weighted mixture (interpolation) of other loss functions. :param components: a non-empty list of weights and loss function instances.",
"name": "__init__",
"signature": "def __init__(self, components: List[Tuple[float, SupervisedLearningCriterion]])"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_000751 | Implement the Python class `MixtureLoss` described below.
Class description:
Implement the MixtureLoss class.
Method signatures and docstrings:
- def __init__(self, components: List[Tuple[float, SupervisedLearningCriterion]]): Loss function defined as a weighted mixture (interpolation) of other loss functions. :param... | Implement the Python class `MixtureLoss` described below.
Class description:
Implement the MixtureLoss class.
Method signatures and docstrings:
- def __init__(self, components: List[Tuple[float, SupervisedLearningCriterion]]): Loss function defined as a weighted mixture (interpolation) of other loss functions. :param... | 2877002d50d3a34d80f647c18cb561025d9066cc | <|skeleton|>
class MixtureLoss:
def __init__(self, components: List[Tuple[float, SupervisedLearningCriterion]]):
"""Loss function defined as a weighted mixture (interpolation) of other loss functions. :param components: a non-empty list of weights and loss function instances."""
<|body_0|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MixtureLoss:
def __init__(self, components: List[Tuple[float, SupervisedLearningCriterion]]):
"""Loss function defined as a weighted mixture (interpolation) of other loss functions. :param components: a non-empty list of weights and loss function instances."""
super().__init__()
if not... | the_stack_v2_python_sparse | InnerEye/ML/models/losses/mixture.py | microsoft/InnerEye-DeepLearning | train | 511 | |
7929cd678260c83e3ef6142c56b17ab169d28e72 | [
"requestor = Requestor(local_api_key=api_key)\nurl = cls.class_url()\nwrapped_params = {cls.snakecase_name(): params}\nif verify:\n wrapped_params['verify'] = verify\nif verify_strict:\n wrapped_params['verify_strict'] = verify_strict\nresponse, api_key = requestor.request(method=RequestMethod.POST, url=url, ... | <|body_start_0|>
requestor = Requestor(local_api_key=api_key)
url = cls.class_url()
wrapped_params = {cls.snakecase_name(): params}
if verify:
wrapped_params['verify'] = verify
if verify_strict:
wrapped_params['verify_strict'] = verify_strict
respo... | Address | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Address:
def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address':
"""Create an address."""
<|body_0|>
def create_and_verify(cls, api_key: Opti... | stack_v2_sparse_classes_10k_train_000029 | 1,988 | permissive | [
{
"docstring": "Create an address.",
"name": "create",
"signature": "def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address'"
},
{
"docstring": "Create and verify ... | 3 | stack_v2_sparse_classes_30k_test_000124 | Implement the Python class `Address` described below.
Class description:
Implement the Address class.
Method signatures and docstrings:
- def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> '... | Implement the Python class `Address` described below.
Class description:
Implement the Address class.
Method signatures and docstrings:
- def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> '... | c8f7a3f2472ae5fea13a5b596b4618bd55f3be0c | <|skeleton|>
class Address:
def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address':
"""Create an address."""
<|body_0|>
def create_and_verify(cls, api_key: Opti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Address:
def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address':
"""Create an address."""
requestor = Requestor(local_api_key=api_key)
url = cls.class_u... | the_stack_v2_python_sparse | easypost/address.py | dsanders11/easypost-python | train | 0 | |
85eabc921a215db7dcf82dc69f0cd928cc1f43f7 | [
"if not asnode:\n self.translate_coding_to_rule(rule)\nelse:\n self.rule = rule\n self.human_read = self.rule.visit_easy_read()\n self.polish_notation = self.rule.visit_with_polish_notation()\n self.coding = self.rule.visit_make_coding()\n self.find_needed_premises()\n self.find_conclusions()",... | <|body_start_0|>
if not asnode:
self.translate_coding_to_rule(rule)
else:
self.rule = rule
self.human_read = self.rule.visit_easy_read()
self.polish_notation = self.rule.visit_with_polish_notation()
self.coding = self.rule.visit_make_coding()
... | This class represents a Rule for the rule approach. It has its Coding which is a string of its binary coding, a node named rule which is the starting node of the rule in its tree representation, a string representation of the polish notation of the Rule and an easily human readable representation of the rule. | Rule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""This class represents a Rule for the rule approach. It has its Coding which is a string of its binary coding, a node named rule which is the starting node of the rule in its tree representation, a string representation of the polish notation of the Rule and an easily human readable repre... | stack_v2_sparse_classes_10k_train_000030 | 3,168 | permissive | [
{
"docstring": ":param rule: the rule :param asnode: change it to false if you are only passing a lib which should be transformed to a rule. This constructor takes either a Node which represents the starting node of a rule and fills in all other needed information. Or an coding which represents a rule in its bi... | 5 | stack_v2_sparse_classes_30k_train_001128 | Implement the Python class `Rule` described below.
Class description:
This class represents a Rule for the rule approach. It has its Coding which is a string of its binary coding, a node named rule which is the starting node of the rule in its tree representation, a string representation of the polish notation of the ... | Implement the Python class `Rule` described below.
Class description:
This class represents a Rule for the rule approach. It has its Coding which is a string of its binary coding, a node named rule which is the starting node of the rule in its tree representation, a string representation of the polish notation of the ... | ac73fb60387aad37d3b3fb823f9b2c205c6cb458 | <|skeleton|>
class Rule:
"""This class represents a Rule for the rule approach. It has its Coding which is a string of its binary coding, a node named rule which is the starting node of the rule in its tree representation, a string representation of the polish notation of the Rule and an easily human readable repre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Rule:
"""This class represents a Rule for the rule approach. It has its Coding which is a string of its binary coding, a node named rule which is the starting node of the rule in its tree representation, a string representation of the polish notation of the Rule and an easily human readable representation of ... | the_stack_v2_python_sparse | relational/student_projects/2019_guth/models/Rule_Genetic/Rule.py | CognitiveComputationLab/cogmods | train | 1 |
9e6635cb59bd73a2f7b0812c705bffed39ee8d8f | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\naux = np.linspace(bounds[0], bounds[1], num=ac_samples)\nself.X_s = aux.reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu_s, sigma_s = self.gp.predict(self.X_s)\nif self.minimize is True:\n Y_s_opt = np.min(self.gp.Y)\n imp = Y_s_opt - mu_s... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
aux = np.linspace(bounds[0], bounds[1], num=ac_samples)
self.X_s = aux.reshape(-1, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu_s, sigma_s = self.gp.predict(self... | Represents a noiseless 1D Gaussian process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of sha... | stack_v2_sparse_classes_10k_train_000031 | 3,331 | no_license | [
{
"docstring": "Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function :param Y_init: is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for eac... | 3 | stack_v2_sparse_classes_30k_train_006801 | Implement the Python class `BayesianOptimization` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor :param f: is the black-box function... | Implement the Python class `BayesianOptimization` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor :param f: is the black-box function... | 975f7e23906b7416e78489f6ad6331ea408c8709 | <|skeleton|>
class BayesianOptimization:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of sha... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BayesianOptimization:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of shape (t, 1) rep... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py | julgachancipa/holbertonschool-machine_learning | train | 1 |
c042f42d783c5e61ec6d6e7ae7f488a725e2ae6f | [
"self.carrier_direct_port = carrier_direct_port\nself.http_direct_port = http_direct_port\nself.requires_ssl = requires_ssl\nself.seeds = seeds",
"if dictionary is None:\n return None\ncarrier_direct_port = dictionary.get('carrierDirectPort')\nhttp_direct_port = dictionary.get('httpDirectPort')\nrequires_ssl =... | <|body_start_0|>
self.carrier_direct_port = carrier_direct_port
self.http_direct_port = http_direct_port
self.requires_ssl = requires_ssl
self.seeds = seeds
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
carrier_direct_port = dictionary.ge... | Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port. requires_ssl (bool): Specifies whether this clus... | CouchbaseConnectParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouchbaseConnectParams:
"""Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port... | stack_v2_sparse_classes_10k_train_000032 | 2,287 | permissive | [
{
"docstring": "Constructor for the CouchbaseConnectParams class",
"name": "__init__",
"signature": "def __init__(self, carrier_direct_port=None, http_direct_port=None, requires_ssl=None, seeds=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | stack_v2_sparse_classes_30k_train_001357 | Implement the Python class `CouchbaseConnectParams` described below.
Class description:
Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (i... | Implement the Python class `CouchbaseConnectParams` described below.
Class description:
Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (i... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CouchbaseConnectParams:
"""Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CouchbaseConnectParams:
"""Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port. requires_ss... | the_stack_v2_python_sparse | cohesity_management_sdk/models/couchbase_connect_params.py | cohesity/management-sdk-python | train | 24 |
fd94796047c557b42d455180121d18b4c96ee72f | [
"from scoop.content.models.link import Link\nidentifier = self.value\ncontents = Link.objects.filter(uuid=identifier)\ncontent = contents[0] if contents.exists() else None\nreturn {'link': content}",
"base = super(LinkInline, self).get_template_name()[0]\npath = 'content/{}'.format(base)\nreturn path"
] | <|body_start_0|>
from scoop.content.models.link import Link
identifier = self.value
contents = Link.objects.filter(uuid=identifier)
content = contents[0] if contents.exists() else None
return {'link': content}
<|end_body_0|>
<|body_start_1|>
base = super(LinkInline, self... | Inline d'insertion de liens Format : {{link uuid}} | LinkInline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkInline:
"""Inline d'insertion de liens Format : {{link uuid}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
<|body_0|>
def get_template_name(self):
"""Renvoyer le chemin du template"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_000033 | 6,816 | no_license | [
{
"docstring": "Renvoyer le contexte de rendu de l'inline",
"name": "get_context",
"signature": "def get_context(self)"
},
{
"docstring": "Renvoyer le chemin du template",
"name": "get_template_name",
"signature": "def get_template_name(self)"
}
] | 2 | null | Implement the Python class `LinkInline` described below.
Class description:
Inline d'insertion de liens Format : {{link uuid}}
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte de rendu de l'inline
- def get_template_name(self): Renvoyer le chemin du template | Implement the Python class `LinkInline` described below.
Class description:
Inline d'insertion de liens Format : {{link uuid}}
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte de rendu de l'inline
- def get_template_name(self): Renvoyer le chemin du template
<|skeleton|>
class LinkInli... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class LinkInline:
"""Inline d'insertion de liens Format : {{link uuid}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
<|body_0|>
def get_template_name(self):
"""Renvoyer le chemin du template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinkInline:
"""Inline d'insertion de liens Format : {{link uuid}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
from scoop.content.models.link import Link
identifier = self.value
contents = Link.objects.filter(uuid=identifier)
content = ... | the_stack_v2_python_sparse | scoop/content/util/inlines.py | artscoop/scoop | train | 0 |
32a1945cb0fa6d32a08f4222b261daed7ff59956 | [
"self.cluster_name = cluster_name\nself.cluster_size = cluster_size\nself.encryption_config = encryption_config\nself.ip_preference = ip_preference\nself.metadata_fault_tolerance = metadata_fault_tolerance\nself.network_config = network_config\nself.node_ips = node_ips",
"if dictionary is None:\n return None\n... | <|body_start_0|>
self.cluster_name = cluster_name
self.cluster_size = cluster_size
self.encryption_config = encryption_config
self.ip_preference = ip_preference
self.metadata_fault_tolerance = metadata_fault_tolerance
self.network_config = network_config
self.node... | Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the cluster. It is set as Large by default if the parameter... | CreateCloudClusterParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateCloudClusterParameters:
"""Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the... | stack_v2_sparse_classes_10k_train_000034 | 3,779 | permissive | [
{
"docstring": "Constructor for the CreateCloudClusterParameters class",
"name": "__init__",
"signature": "def __init__(self, cluster_name=None, cluster_size=None, encryption_config=None, ip_preference=None, metadata_fault_tolerance=None, network_config=None, node_ips=None)"
},
{
"docstring": "C... | 2 | null | Implement the Python class `CreateCloudClusterParameters` described below.
Class description:
Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (Clus... | Implement the Python class `CreateCloudClusterParameters` described below.
Class description:
Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (Clus... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CreateCloudClusterParameters:
"""Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateCloudClusterParameters:
"""Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the cluster. It ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/create_cloud_cluster_parameters.py | cohesity/management-sdk-python | train | 24 |
b3a8afe6d1659b3bfdd80b86d00701856ce6e712 | [
"from random import choice\nif name == 'ip':\n result = choice(['127.0.0.1', '192.168.0.1'])\nelif name == 'user':\n result = choice(['jim', 'fred2', 'sheila'])\nelse:\n result = self.__dict__.get(name, '?')\nreturn result",
"keys = ['ip', 'user']\nkeys.extend(self.__dict__.keys())\nreturn keys.__iter__(... | <|body_start_0|>
from random import choice
if name == 'ip':
result = choice(['127.0.0.1', '192.168.0.1'])
elif name == 'user':
result = choice(['jim', 'fred2', 'sheila'])
else:
result = self.__dict__.get(name, '?')
return result
<|end_body_0|>
... | An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter. | ConnInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnInfo:
"""An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter."""
def __getitem__(self, name):
"""To allow this instance to look like a dict."""
<|body_0|>
def __iter__(self):
... | stack_v2_sparse_classes_10k_train_000035 | 1,615 | no_license | [
{
"docstring": "To allow this instance to look like a dict.",
"name": "__getitem__",
"signature": "def __getitem__(self, name)"
},
{
"docstring": "To allow iteration over keys, which will be merged into the LogRecord dict before formatting and output.",
"name": "__iter__",
"signature": "... | 2 | null | Implement the Python class `ConnInfo` described below.
Class description:
An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter.
Method signatures and docstrings:
- def __getitem__(self, name): To allow this instance to look like a dict... | Implement the Python class `ConnInfo` described below.
Class description:
An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter.
Method signatures and docstrings:
- def __getitem__(self, name): To allow this instance to look like a dict... | bbb64dcfd581c30eddb210c647db5b5864b59166 | <|skeleton|>
class ConnInfo:
"""An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter."""
def __getitem__(self, name):
"""To allow this instance to look like a dict."""
<|body_0|>
def __iter__(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConnInfo:
"""An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter."""
def __getitem__(self, name):
"""To allow this instance to look like a dict."""
from random import choice
if name == 'ip':
... | the_stack_v2_python_sparse | configurations/i09-config/scripts/utils/ContextualInfo.py | openGDA/gda-diamond | train | 4 |
7c3468c1036066a2fceabc8abd2cbb06a707d7e0 | [
"if lang in self.ASIAN_TYPED_LANGUAGES:\n super(sppasNumAsianType, self).__init__(lang, dictionary)\nelse:\n raise sppasValueError(lang, str(sppasNumBase.ASIAN_TYPED_LANGUAGES))\nfor i in sppasNumAsianType.NUMBER_LIST:\n if self._lang_dict.is_unk(str(i)):\n raise sppasValueError(self._lang_dict, str... | <|body_start_0|>
if lang in self.ASIAN_TYPED_LANGUAGES:
super(sppasNumAsianType, self).__init__(lang, dictionary)
else:
raise sppasValueError(lang, str(sppasNumBase.ASIAN_TYPED_LANGUAGES))
for i in sppasNumAsianType.NUMBER_LIST:
if self._lang_dict.is_unk(str(i... | sppasNumAsianType | [
"MIT",
"GFDL-1.1-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasNumAsianType:
def __init__(self, lang=None, dictionary=None):
"""Create an instance of sppasNumAsianType :param lang: (str) name of the language"""
<|body_0|>
def _tenth_of_thousands(self, number):
"""Return the "wordified" version of a tenth of a thousand numbe... | stack_v2_sparse_classes_10k_train_000036 | 4,832 | permissive | [
{
"docstring": "Create an instance of sppasNumAsianType :param lang: (str) name of the language",
"name": "__init__",
"signature": "def __init__(self, lang=None, dictionary=None)"
},
{
"docstring": "Return the \"wordified\" version of a tenth of a thousand number Returns the word corresponding t... | 3 | stack_v2_sparse_classes_30k_train_004443 | Implement the Python class `sppasNumAsianType` described below.
Class description:
Implement the sppasNumAsianType class.
Method signatures and docstrings:
- def __init__(self, lang=None, dictionary=None): Create an instance of sppasNumAsianType :param lang: (str) name of the language
- def _tenth_of_thousands(self, ... | Implement the Python class `sppasNumAsianType` described below.
Class description:
Implement the sppasNumAsianType class.
Method signatures and docstrings:
- def __init__(self, lang=None, dictionary=None): Create an instance of sppasNumAsianType :param lang: (str) name of the language
- def _tenth_of_thousands(self, ... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasNumAsianType:
def __init__(self, lang=None, dictionary=None):
"""Create an instance of sppasNumAsianType :param lang: (str) name of the language"""
<|body_0|>
def _tenth_of_thousands(self, number):
"""Return the "wordified" version of a tenth of a thousand numbe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class sppasNumAsianType:
def __init__(self, lang=None, dictionary=None):
"""Create an instance of sppasNumAsianType :param lang: (str) name of the language"""
if lang in self.ASIAN_TYPED_LANGUAGES:
super(sppasNumAsianType, self).__init__(lang, dictionary)
else:
raise ... | the_stack_v2_python_sparse | sppas/sppas/src/annotations/TextNorm/num2text/num_asian_lang.py | mirfan899/MTTS | train | 0 | |
1ec298c2d7a17d99819f79975aa1d550328f4b91 | [
"my_player_id = current_user['player_id']\npg = get_playergroup(group_name, player_id)\nif player_id != my_player_id:\n secret_ok = pg['secret'] == args.get('secret')\n is_service = 'service' in current_user['roles']\n if not secret_ok and (not is_service):\n message = \"'player_id' does not match c... | <|body_start_0|>
my_player_id = current_user['player_id']
pg = get_playergroup(group_name, player_id)
if player_id != my_player_id:
secret_ok = pg['secret'] == args.get('secret')
is_service = 'service' in current_user['roles']
if not secret_ok and (not is_serv... | Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session). | PlayerGroupsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, args, player_id, group_name):
"""Get group f... | stack_v2_sparse_classes_10k_train_000037 | 5,033 | permissive | [
{
"docstring": "Get group for player Returns user identities group 'group_name' associated with 'player_id'.",
"name": "get",
"signature": "def get(self, args, player_id, group_name)"
},
{
"docstring": "Create a player group Creates a new player group for the player. Can only be called by the pl... | 2 | stack_v2_sparse_classes_30k_train_006721 | Implement the Python class `PlayerGroupsAPI` described below.
Class description:
Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session).
Method signatures and docstrings:
... | Implement the Python class `PlayerGroupsAPI` described below.
Class description:
Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session).
Method signatures and docstrings:
... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, args, player_id, group_name):
"""Get group f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, args, player_id, group_name):
"""Get group for player Ret... | the_stack_v2_python_sparse | driftbase/api/players/playergroups.py | dgnorth/drift-base | train | 1 |
a7bf9580e8f5b8118276c2adea987f196dd59018 | [
"show_uncategorized = request.GET.get('show_uncategorized', False)\nif show_uncategorized is True or show_uncategorized == 'true':\n return True\nreturn False",
"stats_datasets = StatsMakerDataverses(**request.GET.dict())\nif self.is_show_uncategorized(request):\n exclude_uncategorized = False\nelse:\n e... | <|body_start_0|>
show_uncategorized = request.GET.get('show_uncategorized', False)
if show_uncategorized is True or show_uncategorized == 'true':
return True
return False
<|end_body_0|>
<|body_start_1|>
stats_datasets = StatsMakerDataverses(**request.GET.dict())
if s... | DataverseTypeCounts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataverseTypeCounts:
def is_show_uncategorized(self, request):
"""Return the result of the "?show_uncategorized" query string param"""
<|body_0|>
def get_stats_result(self, request):
"""Return the StatsResult object for this statistic"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k_train_000038 | 6,085 | no_license | [
{
"docstring": "Return the result of the \"?show_uncategorized\" query string param",
"name": "is_show_uncategorized",
"signature": "def is_show_uncategorized(self, request)"
},
{
"docstring": "Return the StatsResult object for this statistic",
"name": "get_stats_result",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_001651 | Implement the Python class `DataverseTypeCounts` described below.
Class description:
Implement the DataverseTypeCounts class.
Method signatures and docstrings:
- def is_show_uncategorized(self, request): Return the result of the "?show_uncategorized" query string param
- def get_stats_result(self, request): Return th... | Implement the Python class `DataverseTypeCounts` described below.
Class description:
Implement the DataverseTypeCounts class.
Method signatures and docstrings:
- def is_show_uncategorized(self, request): Return the result of the "?show_uncategorized" query string param
- def get_stats_result(self, request): Return th... | 2a17e5ba918d6d1c7d38c192e0504e6cd96b32d2 | <|skeleton|>
class DataverseTypeCounts:
def is_show_uncategorized(self, request):
"""Return the result of the "?show_uncategorized" query string param"""
<|body_0|>
def get_stats_result(self, request):
"""Return the StatsResult object for this statistic"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataverseTypeCounts:
def is_show_uncategorized(self, request):
"""Return the result of the "?show_uncategorized" query string param"""
show_uncategorized = request.GET.get('show_uncategorized', False)
if show_uncategorized is True or show_uncategorized == 'true':
return Tru... | the_stack_v2_python_sparse | dv_apps/metrics/stats_views_dataverses.py | IQSS/miniverse | train | 3 | |
5e8b9932734bec2eac26839189e7c997956ec95b | [
"if request.version == 'v6':\n return self.retrieve_impl(request, file_id)\nelif request.version == 'v7':\n return self.retrieve_impl(request, file_id)\nraise Http404()",
"try:\n scale_file = ScaleFile.objects.get_details(file_id)\nexcept ScaleFile.DoesNotExist:\n raise Http404\nserializer = self.get_... | <|body_start_0|>
if request.version == 'v6':
return self.retrieve_impl(request, file_id)
elif request.version == 'v7':
return self.retrieve_impl(request, file_id)
raise Http404()
<|end_body_0|>
<|body_start_1|>
try:
scale_file = ScaleFile.objects.get_... | This view is the endpoint for retrieving details of a scale file. | FileDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDetailsView:
"""This view is the endpoint for retrieving details of a scale file."""
def retrieve(self, request, file_id):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id... | stack_v2_sparse_classes_10k_train_000039 | 19,677 | permissive | [
{
"docstring": "Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id: The id of the file :type file_id: int encoded as a string :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to s... | 2 | stack_v2_sparse_classes_30k_train_003708 | Implement the Python class `FileDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a scale file.
Method signatures and docstrings:
- def retrieve(self, request, file_id): Determine api version and call specific method :param request: the HTTP POST request :type reques... | Implement the Python class `FileDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a scale file.
Method signatures and docstrings:
- def retrieve(self, request, file_id): Determine api version and call specific method :param request: the HTTP POST request :type reques... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class FileDetailsView:
"""This view is the endpoint for retrieving details of a scale file."""
def retrieve(self, request, file_id):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileDetailsView:
"""This view is the endpoint for retrieving details of a scale file."""
def retrieve(self, request, file_id):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id: The id of t... | the_stack_v2_python_sparse | scale/storage/views.py | kfconsultant/scale | train | 0 |
0138a77c06865245c98d99bfcf47fb0b1ce9d11e | [
"super().__init__(device=device)\nxyz = _handle_input(x, y, z, dtype, device, 'Translate')\nN = xyz.shape[0]\nmat = torch.eye(4, dtype=dtype, device=device)\nmat = mat.view(1, 4, 4).repeat(N, 1, 1)\nmat[:, 3, :3] = xyz\nself._matrix = mat",
"inv_mask = self._matrix.new_ones([1, 4, 4])\ninv_mask[0, 3, :3] = -1.0\n... | <|body_start_0|>
super().__init__(device=device)
xyz = _handle_input(x, y, z, dtype, device, 'Translate')
N = xyz.shape[0]
mat = torch.eye(4, dtype=dtype, device=device)
mat = mat.view(1, 4, 4).repeat(N, 1, 1)
mat[:, 3, :3] = xyz
self._matrix = mat
<|end_body_0|>
... | Translate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Translate:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.floa... | stack_v2_sparse_classes_10k_train_000040 | 43,607 | permissive | [
{
"docstring": "Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.float32, device='cpu') Here x, y, and z will be broadcast against each other and concatenated to for... | 2 | stack_v2_sparse_classes_30k_train_006647 | Implement the Python class `Translate` described below.
Class description:
Implement the Translate class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'): Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, d... | Implement the Python class `Translate` described below.
Class description:
Implement the Translate class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'): Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, d... | 1d240f60a99682e8409363c5829aba14869ba140 | <|skeleton|>
class Translate:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.floa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Translate:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.float32, device='c... | the_stack_v2_python_sparse | soft_intro_vae_3d/datasets/transforms3d.py | LearnerLYH/soft-intro-vae-pytorch | train | 1 | |
64e533586c7071fd91ca81903cd3a1fa77ebd982 | [
"if not digits:\n return [1]\nelif digits[-1] == 9:\n digits[-1] = 0\n digits[:-1] = self.plusOne(digits[:-1])\nelse:\n digits[-1] += 1\nreturn digits",
"if len(digits) == 0:\n return [1]\nif digits[-1] == 9:\n return self.plusOne(digits[:-1]) + [0]\nreturn digits[:-1] + [digits[-1] + 1]",
"n ... | <|body_start_0|>
if not digits:
return [1]
elif digits[-1] == 9:
digits[-1] = 0
digits[:-1] = self.plusOne(digits[:-1])
else:
digits[-1] += 1
return digits
<|end_body_0|>
<|body_start_1|>
if len(digits) == 0:
return [1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: ... | stack_v2_sparse_classes_10k_train_000041 | 1,164 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne1",
"signature": "def plusOne1(self, digits)"
},
{
"docstring": ":type digits: Li... | 3 | stack_v2_sparse_classes_30k_train_002360 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type d... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
if not digits:
return [1]
elif digits[-1] == 9:
digits[-1] = 0
digits[:-1] = self.plusOne(digits[:-1])
else:
digits[-1] += 1
return digit... | the_stack_v2_python_sparse | q66_Plus_One.py | Ryuya1995/leetcode | train | 0 | |
258d4ca6708b129c3c5368422e04d5a5bfa7dd9d | [
"if not costs:\n return 0\nn = len(costs)\nk = len(costs[0])\ndp = [[0] * k for _ in range(n)]\ndp[0] = costs[0]\nfor i in range(1, n):\n for j in range(k):\n dp[i][j] = costs[i][j] + min((dp[i - 1][k] for k in range(k) if k != j))\nreturn min((dp[n - 1][j] for j in range(k)))",
"n = len(costs)\nif n... | <|body_start_0|>
if not costs:
return 0
n = len(costs)
k = len(costs[0])
dp = [[0] * k for _ in range(n)]
dp[0] = costs[0]
for i in range(1, n):
for j in range(k):
dp[i][j] = costs[i][j] + min((dp[i - 1][k] for k in range(k) if k !=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCostII(self, costs):
""":type costs: List[List[int]] :rtype: int"""
<|body_0|>
def minCostII(self, costs):
""":type costs: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not costs:
return ... | stack_v2_sparse_classes_10k_train_000042 | 3,301 | no_license | [
{
"docstring": ":type costs: List[List[int]] :rtype: int",
"name": "minCostII",
"signature": "def minCostII(self, costs)"
},
{
"docstring": ":type costs: List[List[int]] :rtype: int",
"name": "minCostII",
"signature": "def minCostII(self, costs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostII(self, costs): :type costs: List[List[int]] :rtype: int
- def minCostII(self, costs): :type costs: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostII(self, costs): :type costs: List[List[int]] :rtype: int
- def minCostII(self, costs): :type costs: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def minCostII(self, costs):
""":type costs: List[List[int]] :rtype: int"""
<|body_0|>
def minCostII(self, costs):
""":type costs: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minCostII(self, costs):
""":type costs: List[List[int]] :rtype: int"""
if not costs:
return 0
n = len(costs)
k = len(costs[0])
dp = [[0] * k for _ in range(n)]
dp[0] = costs[0]
for i in range(1, n):
for j in range(k)... | the_stack_v2_python_sparse | python_leetcode_2020/Python_Leetcode_2020/265_paint_house.py | xiangcao/Leetcode | train | 0 | |
ed4d63809b4817112b8d962de2b129f42a9ecdf8 | [
"self.w0 = w0\nself.wa = wa\nDarkEnergyModel.__init__(self)",
"if isinstance(z, np.ndarray) and z.size > 1:\n assert np.all(np.diff(z) > 0.0)\nreturn self.w0 + (1.0 - 1.0 / (1.0 + z)) * self.wa",
"if isinstance(z, np.ndarray) and z.size > 1:\n assert np.all(np.diff(z) > 0.0)\nreturn np.exp(-3.0 * self.wa ... | <|body_start_0|>
self.w0 = w0
self.wa = wa
DarkEnergyModel.__init__(self)
<|end_body_0|>
<|body_start_1|>
if isinstance(z, np.ndarray) and z.size > 1:
assert np.all(np.diff(z) > 0.0)
return self.w0 + (1.0 - 1.0 / (1.0 + z)) * self.wa
<|end_body_1|>
<|body_start_2|>
... | w(z)=constant dark energy model | DarkEnergyW0Wa | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkEnergyW0Wa:
"""w(z)=constant dark energy model"""
def __init__(self, w0, wa):
"""w(z)=w0+(1-a)wa"""
<|body_0|>
def w_of_z(self, z):
"""w(z)=w0+(1-a)wa"""
<|body_1|>
def de_mult(self, z):
"""w(z)=w0+(1-a)wa multiplier"""
<|body_2|>... | stack_v2_sparse_classes_10k_train_000043 | 4,757 | no_license | [
{
"docstring": "w(z)=w0+(1-a)wa",
"name": "__init__",
"signature": "def __init__(self, w0, wa)"
},
{
"docstring": "w(z)=w0+(1-a)wa",
"name": "w_of_z",
"signature": "def w_of_z(self, z)"
},
{
"docstring": "w(z)=w0+(1-a)wa multiplier",
"name": "de_mult",
"signature": "def d... | 3 | stack_v2_sparse_classes_30k_train_006312 | Implement the Python class `DarkEnergyW0Wa` described below.
Class description:
w(z)=constant dark energy model
Method signatures and docstrings:
- def __init__(self, w0, wa): w(z)=w0+(1-a)wa
- def w_of_z(self, z): w(z)=w0+(1-a)wa
- def de_mult(self, z): w(z)=w0+(1-a)wa multiplier | Implement the Python class `DarkEnergyW0Wa` described below.
Class description:
w(z)=constant dark energy model
Method signatures and docstrings:
- def __init__(self, w0, wa): w(z)=w0+(1-a)wa
- def w_of_z(self, z): w(z)=w0+(1-a)wa
- def de_mult(self, z): w(z)=w0+(1-a)wa multiplier
<|skeleton|>
class DarkEnergyW0Wa:
... | f6cb3014a55942a751ae53f8bb0fc2ea62c6442b | <|skeleton|>
class DarkEnergyW0Wa:
"""w(z)=constant dark energy model"""
def __init__(self, w0, wa):
"""w(z)=w0+(1-a)wa"""
<|body_0|>
def w_of_z(self, z):
"""w(z)=w0+(1-a)wa"""
<|body_1|>
def de_mult(self, z):
"""w(z)=w0+(1-a)wa multiplier"""
<|body_2|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DarkEnergyW0Wa:
"""w(z)=constant dark energy model"""
def __init__(self, w0, wa):
"""w(z)=w0+(1-a)wa"""
self.w0 = w0
self.wa = wa
DarkEnergyModel.__init__(self)
def w_of_z(self, z):
"""w(z)=w0+(1-a)wa"""
if isinstance(z, np.ndarray) and z.size > 1:
... | the_stack_v2_python_sparse | dark_energy_model.py | mcdigman/SuperSCRAM | train | 1 |
fe418098dead5b83336d00fe93e645aca3e7ee34 | [
"super().__init__()\nself.base = base\nassert isinstance(self.base, ValueFunctionBase)\nself.outputs = namedtuple('Outputs', ['value', 'state_out'])",
"outs = self.base(ob) if state_in is None else self.base(ob, state_in)\nif isinstance(outs, tuple):\n value, state_out = outs\nelse:\n value, state_out = (ou... | <|body_start_0|>
super().__init__()
self.base = base
assert isinstance(self.base, ValueFunctionBase)
self.outputs = namedtuple('Outputs', ['value', 'state_out'])
<|end_body_0|>
<|body_start_1|>
outs = self.base(ob) if state_in is None else self.base(ob, state_in)
if isin... | Value function module. | ValueFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
<|body_0|>
def forward(self, ob, state_in=None):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.base = base
as... | stack_v2_sparse_classes_10k_train_000044 | 1,416 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, base)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, ob, state_in=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003546 | Implement the Python class `ValueFunction` described below.
Class description:
Value function module.
Method signatures and docstrings:
- def __init__(self, base): Init.
- def forward(self, ob, state_in=None): Forward. | Implement the Python class `ValueFunction` described below.
Class description:
Value function module.
Method signatures and docstrings:
- def __init__(self, base): Init.
- def forward(self, ob, state_in=None): Forward.
<|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
... | e71c4b12955b01bfb907aa31c91ded6bcd8aaec8 | <|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
<|body_0|>
def forward(self, ob, state_in=None):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
super().__init__()
self.base = base
assert isinstance(self.base, ValueFunctionBase)
self.outputs = namedtuple('Outputs', ['value', 'state_out'])
def forward(self, ob, state_in=No... | the_stack_v2_python_sparse | dl/rl/modules/value_function.py | cbschaff/dl | train | 1 |
7bc75e72dfb1bcf1d3e302368fca234537fc45fc | [
"self.SetTitle('This is an example Dialog')\nself.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)\nreturn True",
"if messageId == c4d.DLG_OK:\n print('User Click on Ok')\n return True\nelif messageId == c4d.DLG_CANCEL:\n print('User Click on Cancel')\n self.Close()\n return True\nreturn True"
] | <|body_start_0|>
self.SetTitle('This is an example Dialog')
self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)
return True
<|end_body_0|>
<|body_start_1|>
if messageId == c4d.DLG_OK:
print('User Click on Ok')
return True
elif messageId == c4d.DLG_CANCEL:
... | ExampleDialog | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_10k_train_000045 | 1,800 | permissive | [
{
"docstring": "This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.",
"name": "CreateLayout",
"signature": "def CreateLayout(self)"
},
{
"docstring": "This Method is called automatically when the user clicks on a gadget and/or changes its value this func... | 2 | null | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
self.SetTitle('This is an example Dialog')
self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)
return True
def Command(self, messageId, bc):... | the_stack_v2_python_sparse | scripts/03_application_development/gui/dialog/gedialog_modal_r13.py | PluginCafe/cinema4d_py_sdk_extended | train | 112 | |
c883e2a4c9d6a4881787f4f7cdae953c6e82070f | [
"self._tbirth = tbirth\nself._mass = mass\nself._metal = metal\nself._radiation = radiation\nself._wind = wind\nself._star = stars.Star(mass, metal, rotating=rotating)",
"integrator = weltgeist.integrator.Integrator()\nt = integrator.time\ndt = integrator.dt\nage = t - self._tbirth\nTeff = 0.0\nstar = self._star\... | <|body_start_0|>
self._tbirth = tbirth
self._mass = mass
self._metal = metal
self._radiation = radiation
self._wind = wind
self._star = stars.Star(mass, metal, rotating=rotating)
<|end_body_0|>
<|body_start_1|>
integrator = weltgeist.integrator.Integrator()
... | Source of energy & photons based on a lookup table | StellarSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StellarSource:
"""Source of energy & photons based on a lookup table"""
def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True):
"""Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in secon... | stack_v2_sparse_classes_10k_train_000046 | 3,252 | no_license | [
{
"docstring": "Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in seconds radiation : bool Turn radiation on? wind : bool Turn winds on? rotating : bool Use the Geneva rotating tracks?",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_001955 | Implement the Python class `StellarSource` described below.
Class description:
Source of energy & photons based on a lookup table
Method signatures and docstrings:
- def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True): Constructor Parameters ---------- mass : float Mass of star in so... | Implement the Python class `StellarSource` described below.
Class description:
Source of energy & photons based on a lookup table
Method signatures and docstrings:
- def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True): Constructor Parameters ---------- mass : float Mass of star in so... | d1ecb297daabc559e2a0ef045e5c032d4e492fb0 | <|skeleton|>
class StellarSource:
"""Source of energy & photons based on a lookup table"""
def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True):
"""Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in secon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StellarSource:
"""Source of energy & photons based on a lookup table"""
def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True):
"""Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in seconds radiation ... | the_stack_v2_python_sparse | Shells/scripts/stellarsource.py | samgeen/mcrtscripts | train | 0 |
2b9ee447adfbf4f246bacde3fe8c34229d957ec0 | [
"base.Action.__init__(self, self.__doMakeGif)\nself.__name = '{}_{}'.format(type(self).__name__, id(self))\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx\nself.__panel = panel\nself.__overlayList.addListener('overlays', self.__name, self.__selectedOverlayChanged)\nself.__displayCtx.addListener('s... | <|body_start_0|>
base.Action.__init__(self, self.__doMakeGif)
self.__name = '{}_{}'.format(type(self).__name__, id(self))
self.__overlayList = overlayList
self.__displayCtx = displayCtx
self.__panel = panel
self.__overlayList.addListener('overlays', self.__name, self.__se... | The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings. | MovieGifAction | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieGifAction:
"""The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings."""
def __init__(self, overlayList, displayCtx, panel):
"""Create a ``MovieGifAction``. :arg ov... | stack_v2_sparse_classes_10k_train_000047 | 9,924 | permissive | [
{
"docstring": "Create a ``MovieGifAction``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The :class:`.DisplayContext`. :arg panel: The :class:`.CanvasPanel` to generate the animated GIF for.",
"name": "__init__",
"signature": "def __init__(self, overlayList, displayCtx, panel)"
},
... | 4 | null | Implement the Python class `MovieGifAction` described below.
Class description:
The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings.
Method signatures and docstrings:
- def __init__(self, overlayList,... | Implement the Python class `MovieGifAction` described below.
Class description:
The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings.
Method signatures and docstrings:
- def __init__(self, overlayList,... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class MovieGifAction:
"""The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings."""
def __init__(self, overlayList, displayCtx, panel):
"""Create a ``MovieGifAction``. :arg ov... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovieGifAction:
"""The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings."""
def __init__(self, overlayList, displayCtx, panel):
"""Create a ``MovieGifAction``. :arg overlayList: Th... | the_stack_v2_python_sparse | fsleyes/actions/moviegif.py | sanjayankur31/fsleyes | train | 1 |
4b653de11fba1d6aa8bfc0f0e14ea998358939b0 | [
"super(DecodeImage, self).__init__()\nself.to_rgb = to_rgb\nself.with_mixup = with_mixup\nif not isinstance(self.to_rgb, bool):\n raise TypeError('{}: input type is invalid.'.format(self))\nif not isinstance(self.with_mixup, bool):\n raise TypeError('{}: input type is invalid.'.format(self))",
"if 'image' n... | <|body_start_0|>
super(DecodeImage, self).__init__()
self.to_rgb = to_rgb
self.with_mixup = with_mixup
if not isinstance(self.to_rgb, bool):
raise TypeError('{}: input type is invalid.'.format(self))
if not isinstance(self.with_mixup, bool):
raise TypeErro... | DecodeImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodeImage:
def __init__(self, to_rgb=True, with_mixup=False):
"""Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score"""
<|body_0|>
def __call__(self, sample, con... | stack_v2_sparse_classes_10k_train_000048 | 19,057 | permissive | [
{
"docstring": "Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score",
"name": "__init__",
"signature": "def __init__(self, to_rgb=True, with_mixup=False)"
},
{
"docstring": "load image... | 2 | stack_v2_sparse_classes_30k_train_006452 | Implement the Python class `DecodeImage` described below.
Class description:
Implement the DecodeImage class.
Method signatures and docstrings:
- def __init__(self, to_rgb=True, with_mixup=False): Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether o... | Implement the Python class `DecodeImage` described below.
Class description:
Implement the DecodeImage class.
Method signatures and docstrings:
- def __init__(self, to_rgb=True, with_mixup=False): Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether o... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class DecodeImage:
def __init__(self, to_rgb=True, with_mixup=False):
"""Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score"""
<|body_0|>
def __call__(self, sample, con... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DecodeImage:
def __init__(self, to_rgb=True, with_mixup=False):
"""Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score"""
super(DecodeImage, self).__init__()
self.to_rgb = to... | the_stack_v2_python_sparse | CV/PaddleReid/reid/data/transform/operators.py | sserdoubleh/Research | train | 10 | |
ae214b5ea2107f11399ec116af749a09cf22f958 | [
"searchtemplate = SearchTemplate.query.get(searchtemplate_id)\nif not searchtemplate:\n abort(HTTP_STATUS_CODE_NOT_FOUND, 'Search template was not found')\nreturn self.to_json(searchtemplate)",
"searchtemplate = SearchTemplate.query.get(searchtemplate_id)\nif not searchtemplate:\n abort(HTTP_STATUS_CODE_NOT... | <|body_start_0|>
searchtemplate = SearchTemplate.query.get(searchtemplate_id)
if not searchtemplate:
abort(HTTP_STATUS_CODE_NOT_FOUND, 'Search template was not found')
return self.to_json(searchtemplate)
<|end_body_0|>
<|body_start_1|>
searchtemplate = SearchTemplate.query.g... | Resource to get a search template. | SearchTemplateResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchTemplateResource:
"""Resource to get a search template."""
def get(self, searchtemplate_id):
"""Handles GET request to the resource. Args: searchtemplate_id: Primary key for a search template database model Returns: Search template in JSON (instance of flask.wrappers.Response)"... | stack_v2_sparse_classes_10k_train_000049 | 7,889 | permissive | [
{
"docstring": "Handles GET request to the resource. Args: searchtemplate_id: Primary key for a search template database model Returns: Search template in JSON (instance of flask.wrappers.Response)",
"name": "get",
"signature": "def get(self, searchtemplate_id)"
},
{
"docstring": "Handles DELETE... | 2 | null | Implement the Python class `SearchTemplateResource` described below.
Class description:
Resource to get a search template.
Method signatures and docstrings:
- def get(self, searchtemplate_id): Handles GET request to the resource. Args: searchtemplate_id: Primary key for a search template database model Returns: Searc... | Implement the Python class `SearchTemplateResource` described below.
Class description:
Resource to get a search template.
Method signatures and docstrings:
- def get(self, searchtemplate_id): Handles GET request to the resource. Args: searchtemplate_id: Primary key for a search template database model Returns: Searc... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class SearchTemplateResource:
"""Resource to get a search template."""
def get(self, searchtemplate_id):
"""Handles GET request to the resource. Args: searchtemplate_id: Primary key for a search template database model Returns: Search template in JSON (instance of flask.wrappers.Response)"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SearchTemplateResource:
"""Resource to get a search template."""
def get(self, searchtemplate_id):
"""Handles GET request to the resource. Args: searchtemplate_id: Primary key for a search template database model Returns: Search template in JSON (instance of flask.wrappers.Response)"""
se... | the_stack_v2_python_sparse | timesketch/api/v1/resources/searchtemplate.py | google/timesketch | train | 2,263 |
764da55932a024173f71a6da9a09b6ab3a639f6d | [
"self.return_urls = return_urls\nself.identity_provider = identity_provider\nself.i_frame = i_frame\nself.language = language\nself.get_social_security_number = get_social_security_number\nself.pre_filled_social_security_number = pre_filled_social_security_number\nself.page_title = page_title\nself.external_referen... | <|body_start_0|>
self.return_urls = return_urls
self.identity_provider = identity_provider
self.i_frame = i_frame
self.language = language
self.get_social_security_number = get_social_security_number
self.pre_filled_social_security_number = pre_filled_social_security_numb... | Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to use for the identification, if not set the user will get ... | CreateIdentificationRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateIdentificationRequest:
"""Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to us... | stack_v2_sparse_classes_10k_train_000050 | 5,767 | permissive | [
{
"docstring": "Constructor for the CreateIdentificationRequest class",
"name": "__init__",
"signature": "def __init__(self, return_urls=None, identity_provider=None, i_frame=None, language=None, get_social_security_number=None, pre_filled_social_security_number=None, page_title=None, external_reference... | 2 | stack_v2_sparse_classes_30k_train_000679 | Implement the Python class `CreateIdentificationRequest` described below.
Class description:
Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (Identi... | Implement the Python class `CreateIdentificationRequest` described below.
Class description:
Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (Identi... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class CreateIdentificationRequest:
"""Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to us... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateIdentificationRequest:
"""Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to use for the ide... | the_stack_v2_python_sparse | idfy_rest_client/models/create_identification_request.py | dealflowteam/Idfy | train | 0 |
4c308c06c751e5f143037c31c71b45ff8c37d022 | [
"array = self.format_and_eval_string(self.target_array)\nif self.column_name:\n array = array[self.column_name]\nif self.mode == 'Max' or self.mode == 'Max & min':\n ind = np.argmax(array)\n val = array[ind]\n self.write_in_database('max_ind', ind)\n self.write_in_database('max_value', val)\nif self.... | <|body_start_0|>
array = self.format_and_eval_string(self.target_array)
if self.column_name:
array = array[self.column_name]
if self.mode == 'Max' or self.mode == 'Max & min':
ind = np.argmax(array)
val = array[ind]
self.write_in_database('max_ind'... | Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution. | ArrayExtremaTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayExtremaTask:
"""Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find extrema of database array and store index/value pairs."""
<|body_0|>
def check(self, *args, **kwargs):
... | stack_v2_sparse_classes_10k_train_000051 | 6,289 | permissive | [
{
"docstring": "Find extrema of database array and store index/value pairs.",
"name": "perform",
"signature": "def perform(self)"
},
{
"docstring": "Check the target array can be found and has the right column.",
"name": "check",
"signature": "def check(self, *args, **kwargs)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000544 | Implement the Python class `ArrayExtremaTask` described below.
Class description:
Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution.
Method signatures and docstrings:
- def perform(self): Find extrema of database array and store index/value pairs.
- def ... | Implement the Python class `ArrayExtremaTask` described below.
Class description:
Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution.
Method signatures and docstrings:
- def perform(self): Find extrema of database array and store index/value pairs.
- def ... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class ArrayExtremaTask:
"""Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find extrema of database array and store index/value pairs."""
<|body_0|>
def check(self, *args, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArrayExtremaTask:
"""Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find extrema of database array and store index/value pairs."""
array = self.format_and_eval_string(self.target_array)
if... | the_stack_v2_python_sparse | exopy_hqc_legacy/tasks/tasks/util/array_tasks.py | Exopy/exopy_hqc_legacy | train | 0 |
f9d3c7f1e9ffe1e3c38cee5eeafd17c93abe2304 | [
"self._alphabet = alphabet\nself._min_size = min_size\nself._max_size = max_size",
"motif_size = random.randrange(self._min_size, self._max_size)\nmotif = ''\nfor letter_num in range(motif_size):\n cur_letter = random.choice(self._alphabet.letters)\n motif += cur_letter\nreturn MutableSeq(motif, self._alpha... | <|body_start_0|>
self._alphabet = alphabet
self._min_size = min_size
self._max_size = max_size
<|end_body_0|>
<|body_start_1|>
motif_size = random.randrange(self._min_size, self._max_size)
motif = ''
for letter_num in range(motif_size):
cur_letter = random.ch... | Generate a random motif within given parameters. | RandomMotifGenerator | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomMotifGenerator:
"""Generate a random motif within given parameters."""
def __init__(self, alphabet, min_size=12, max_size=17):
"""Initialize with the motif parameters. Arguments: o alphabet - An alphabet specifying what letters can be inserted in a motif. o min_size, max_size -... | stack_v2_sparse_classes_10k_train_000052 | 26,199 | permissive | [
{
"docstring": "Initialize with the motif parameters. Arguments: o alphabet - An alphabet specifying what letters can be inserted in a motif. o min_size, max_size - Specify the range of sizes for motifs.",
"name": "__init__",
"signature": "def __init__(self, alphabet, min_size=12, max_size=17)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_003061 | Implement the Python class `RandomMotifGenerator` described below.
Class description:
Generate a random motif within given parameters.
Method signatures and docstrings:
- def __init__(self, alphabet, min_size=12, max_size=17): Initialize with the motif parameters. Arguments: o alphabet - An alphabet specifying what l... | Implement the Python class `RandomMotifGenerator` described below.
Class description:
Generate a random motif within given parameters.
Method signatures and docstrings:
- def __init__(self, alphabet, min_size=12, max_size=17): Initialize with the motif parameters. Arguments: o alphabet - An alphabet specifying what l... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class RandomMotifGenerator:
"""Generate a random motif within given parameters."""
def __init__(self, alphabet, min_size=12, max_size=17):
"""Initialize with the motif parameters. Arguments: o alphabet - An alphabet specifying what letters can be inserted in a motif. o min_size, max_size -... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomMotifGenerator:
"""Generate a random motif within given parameters."""
def __init__(self, alphabet, min_size=12, max_size=17):
"""Initialize with the motif parameters. Arguments: o alphabet - An alphabet specifying what letters can be inserted in a motif. o min_size, max_size - Specify the ... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/NeuralNetwork/Gene/Schema.py | LyonsLab/coge | train | 41 |
b64d71f4b6e74e3322f4c66f923e10847d27158e | [
"d = set(''.join(wordDict))\nfor c in set(s):\n if c not in d:\n return False\n\ndef help(s, wordDict):\n if not s:\n return True\n for i, w in enumerate(wordDict):\n if s.startswith(w):\n if help(s[len(w):], wordDict):\n return True\n return False\nreturn ... | <|body_start_0|>
d = set(''.join(wordDict))
for c in set(s):
if c not in d:
return False
def help(s, wordDict):
if not s:
return True
for i, w in enumerate(wordDict):
if s.startswith(w):
if h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_000053 | 1,399 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak1",
"signature": "def wordBreak1(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002728 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
<|... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
d = set(''.join(wordDict))
for c in set(s):
if c not in d:
return False
def help(s, wordDict):
if not s:
return True
... | the_stack_v2_python_sparse | py/leetcode/139.py | wfeng1991/learnpy | train | 0 | |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(MaskingModule, self).__init__()\nself.N = N\nself.in_N = N + N // 2 if partial_input else N\nself.norm_1 = GroupNormWrapper(generated, E_1, E_2, 8, self.in_N, eps=1e-08)\nself.prelu_1 = nn.PReLU()\nself.in_conv = Conv1dWrapper(generated, E_1, E_2, self.in_N, B, 1, bias=False)\nself.norm_2 = GroupNormWrapper(... | <|body_start_0|>
super(MaskingModule, self).__init__()
self.N = N
self.in_N = N + N // 2 if partial_input else N
self.norm_1 = GroupNormWrapper(generated, E_1, E_2, 8, self.in_N, eps=1e-08)
self.prelu_1 = nn.PReLU()
self.in_conv = Conv1dWrapper(generated, E_1, E_2, self.i... | Creates a [0,1] mask of the four instruments on the latent matrix | MaskingModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskingModule:
"""Creates a [0,1] mask of the four instruments on the latent matrix"""
def __init__(self, generated, E_1, E_2, N, B, H, layer, stack, kernel=3, residual_bias=False, partial_input=False):
"""Arguments: generated {bool} -- True if you want to use the generated weights E... | stack_v2_sparse_classes_10k_train_000054 | 37,269 | no_license | [
{
"docstring": "Arguments: generated {bool} -- True if you want to use the generated weights E_1 {int} -- Dimension of the instrument embedding E_2 {int} -- Dimension of the instrument embedding bottleneck N {int} -- Dimension of the latent matrix B {int} -- Dimension of the bottleneck convolution H {int} -- Hi... | 2 | stack_v2_sparse_classes_30k_train_000973 | Implement the Python class `MaskingModule` described below.
Class description:
Creates a [0,1] mask of the four instruments on the latent matrix
Method signatures and docstrings:
- def __init__(self, generated, E_1, E_2, N, B, H, layer, stack, kernel=3, residual_bias=False, partial_input=False): Arguments: generated ... | Implement the Python class `MaskingModule` described below.
Class description:
Creates a [0,1] mask of the four instruments on the latent matrix
Method signatures and docstrings:
- def __init__(self, generated, E_1, E_2, N, B, H, layer, stack, kernel=3, residual_bias=False, partial_input=False): Arguments: generated ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MaskingModule:
"""Creates a [0,1] mask of the four instruments on the latent matrix"""
def __init__(self, generated, E_1, E_2, N, B, H, layer, stack, kernel=3, residual_bias=False, partial_input=False):
"""Arguments: generated {bool} -- True if you want to use the generated weights E... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MaskingModule:
"""Creates a [0,1] mask of the four instruments on the latent matrix"""
def __init__(self, generated, E_1, E_2, N, B, H, layer, stack, kernel=3, residual_bias=False, partial_input=False):
"""Arguments: generated {bool} -- True if you want to use the generated weights E_1 {int} -- D... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
35d88e8923e9d0bbb66a45df3b66939759d0a77b | [
"self._datafolder = datafolder\nself._tectonic_grid = os.path.join(datafolder, 'tectonic_global.grd')\nself._oceanic_grid = os.path.join(datafolder, 'oceanic_global.grd')",
"config = get_config()\ndatadir = config['DATA']['folder']\nreturn cls(datadir)",
"regions = OrderedDict()\ngd = GeoDict.createDictFromCent... | <|body_start_0|>
self._datafolder = datafolder
self._tectonic_grid = os.path.join(datafolder, 'tectonic_global.grd')
self._oceanic_grid = os.path.join(datafolder, 'oceanic_global.grd')
<|end_body_0|>
<|body_start_1|>
config = get_config()
datadir = config['DATA']['folder']
... | Regionalizer | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regionalizer:
def __init__(self, datafolder):
"""Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions."""
<|body_0|>
def load(cls):
"""Load regionalizer data from data ... | stack_v2_sparse_classes_10k_train_000055 | 7,330 | permissive | [
{
"docstring": "Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions.",
"name": "__init__",
"signature": "def __init__(self, datafolder)"
},
{
"docstring": "Load regionalizer data from data in the ... | 3 | stack_v2_sparse_classes_30k_train_000034 | Implement the Python class `Regionalizer` described below.
Class description:
Implement the Regionalizer class.
Method signatures and docstrings:
- def __init__(self, datafolder): Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tec... | Implement the Python class `Regionalizer` described below.
Class description:
Implement the Regionalizer class.
Method signatures and docstrings:
- def __init__(self, datafolder): Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tec... | 6e13af7f76d52adfeefbd74dbe647705e92db7d0 | <|skeleton|>
class Regionalizer:
def __init__(self, datafolder):
"""Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions."""
<|body_0|>
def load(cls):
"""Load regionalizer data from data ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Regionalizer:
def __init__(self, datafolder):
"""Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions."""
self._datafolder = datafolder
self._tectonic_grid = os.path.join(datafolder, 'tec... | the_stack_v2_python_sparse | strec/gmreg.py | emthompson-usgs/strec | train | 0 | |
a1d16f974aac0fa1a42d7330830ddb2b6dcdbef4 | [
"self.identifier = identifier\nself.name = name\nself.created_at = created_at\nself.last_modified_at = last_modified_at\nself.workflows = workflows",
"name = None\nfor prop in obj['properties']:\n if prop['key'] == 'name':\n name = prop['value']\n break\nworkflows = None\nif 'workflows' in obj:\n... | <|body_start_0|>
self.identifier = identifier
self.name = name
self.created_at = created_at
self.last_modified_at = last_modified_at
self.workflows = workflows
<|end_body_0|>
<|body_start_1|>
name = None
for prop in obj['properties']:
if prop['key'] =... | A project branch in a remote vizier instance. | BranchResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BranchResource:
"""A project branch in a remote vizier instance."""
def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None):
"""Initialize the branch attributes."""
<|body_0|>... | stack_v2_sparse_classes_10k_train_000056 | 2,603 | permissive | [
{
"docstring": "Initialize the branch attributes.",
"name": "__init__",
"signature": "def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None)"
},
{
"docstring": "Get a branch resource instance fr... | 2 | stack_v2_sparse_classes_30k_train_006582 | Implement the Python class `BranchResource` described below.
Class description:
A project branch in a remote vizier instance.
Method signatures and docstrings:
- def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None)... | Implement the Python class `BranchResource` described below.
Class description:
A project branch in a remote vizier instance.
Method signatures and docstrings:
- def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None)... | e99f43df3df80ad5647f57d805c339257336ac73 | <|skeleton|>
class BranchResource:
"""A project branch in a remote vizier instance."""
def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None):
"""Initialize the branch attributes."""
<|body_0|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BranchResource:
"""A project branch in a remote vizier instance."""
def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None):
"""Initialize the branch attributes."""
self.identifier = ident... | the_stack_v2_python_sparse | vizier/api/client/resources/branch.py | VizierDB/web-api-async | train | 2 |
30e5137cf2187e467f5c5c96817ee5633bc973f0 | [
"self.height = height\nself.length = length\nself.weight = weight\nself.width = width",
"if dictionary is None:\n return None\nheight = awsecommerceservice.models.decimal_with_units.DecimalWithUnits.from_dictionary(dictionary.get('Height')) if dictionary.get('Height') else None\nlength = awsecommerceservice.mo... | <|body_start_0|>
self.height = height
self.length = length
self.weight = weight
self.width = width
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
height = awsecommerceservice.models.decimal_with_units.DecimalWithUnits.from_dictionary(dicti... | Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (DecimalWithUnits): TODO: type description here. | PackageDimensions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageDimensions:
"""Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (Deci... | stack_v2_sparse_classes_10k_train_000057 | 2,533 | permissive | [
{
"docstring": "Constructor for the PackageDimensions class",
"name": "__init__",
"signature": "def __init__(self, height=None, length=None, weight=None, width=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation... | 2 | stack_v2_sparse_classes_30k_val_000236 | Implement the Python class `PackageDimensions` described below.
Class description:
Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): T... | Implement the Python class `PackageDimensions` described below.
Class description:
Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): T... | 26ea1019115a1de3b1b37a4b830525e164ac55ce | <|skeleton|>
class PackageDimensions:
"""Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (Deci... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PackageDimensions:
"""Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (DecimalWithUnits)... | the_stack_v2_python_sparse | awsecommerceservice/models/package_dimensions.py | nidaizamir/Test-PY | train | 0 |
86606bc769437f84b37de8eb1be2a52e0111826a | [
"for key in intemplates:\n if not key.startswith('text search template '):\n raise KeyError('Unrecognized object type: %s' % key)\n tst = key[21:]\n self[schema.name, tst] = template = TSTemplate(schema=schema.name, name=tst)\n intemplate = intemplates[key]\n if intemplate:\n for attr, ... | <|body_start_0|>
for key in intemplates:
if not key.startswith('text search template '):
raise KeyError('Unrecognized object type: %s' % key)
tst = key[21:]
self[schema.name, tst] = template = TSTemplate(schema=schema.name, name=tst)
intemplate = i... | The collection of text search templates in a database | TSTemplateDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSTemplateDict:
"""The collection of text search templates in a database"""
def from_map(self, schema, intemplates):
"""Initialize the dictionary of templates by examining the input map :param schema: schema owning the templates :param intemplates: input YAML map defining the templat... | stack_v2_sparse_classes_10k_train_000058 | 15,925 | permissive | [
{
"docstring": "Initialize the dictionary of templates by examining the input map :param schema: schema owning the templates :param intemplates: input YAML map defining the templates",
"name": "from_map",
"signature": "def from_map(self, schema, intemplates)"
},
{
"docstring": "Generate SQL to t... | 2 | stack_v2_sparse_classes_30k_train_001890 | Implement the Python class `TSTemplateDict` described below.
Class description:
The collection of text search templates in a database
Method signatures and docstrings:
- def from_map(self, schema, intemplates): Initialize the dictionary of templates by examining the input map :param schema: schema owning the template... | Implement the Python class `TSTemplateDict` described below.
Class description:
The collection of text search templates in a database
Method signatures and docstrings:
- def from_map(self, schema, intemplates): Initialize the dictionary of templates by examining the input map :param schema: schema owning the template... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class TSTemplateDict:
"""The collection of text search templates in a database"""
def from_map(self, schema, intemplates):
"""Initialize the dictionary of templates by examining the input map :param schema: schema owning the templates :param intemplates: input YAML map defining the templat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TSTemplateDict:
"""The collection of text search templates in a database"""
def from_map(self, schema, intemplates):
"""Initialize the dictionary of templates by examining the input map :param schema: schema owning the templates :param intemplates: input YAML map defining the templates"""
... | the_stack_v2_python_sparse | pyrseas/dbobject/textsearch.py | vayerx/Pyrseas | train | 1 |
1cb7153d1eafd5bbdbdf63a3392606b7f8712ef6 | [
"customer = order_data.get('customer')\nflavour = order_data.get('flavour')\nsize = order_data.get('size')\nmobile_number = customer.get('mobile_number')\nif self.model.objects.filter(flavour=flavour, size=size, customer__mobile_number=mobile_number).exists():\n raise DuplicateOrderException",
"self._check_dup... | <|body_start_0|>
customer = order_data.get('customer')
flavour = order_data.get('flavour')
size = order_data.get('size')
mobile_number = customer.get('mobile_number')
if self.model.objects.filter(flavour=flavour, size=size, customer__mobile_number=mobile_number).exists():
... | Order Service | OrderService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderService:
"""Order Service"""
def _check_duplicate_order(self, order_data):
"""Check Duplicate Order :param order_data: Order payload :return: None"""
<|body_0|>
def create_order(self, order_data):
"""Create Order :param order_data: Order payload :return: ord... | stack_v2_sparse_classes_10k_train_000059 | 4,498 | no_license | [
{
"docstring": "Check Duplicate Order :param order_data: Order payload :return: None",
"name": "_check_duplicate_order",
"signature": "def _check_duplicate_order(self, order_data)"
},
{
"docstring": "Create Order :param order_data: Order payload :return: order: Order object",
"name": "create... | 5 | stack_v2_sparse_classes_30k_val_000009 | Implement the Python class `OrderService` described below.
Class description:
Order Service
Method signatures and docstrings:
- def _check_duplicate_order(self, order_data): Check Duplicate Order :param order_data: Order payload :return: None
- def create_order(self, order_data): Create Order :param order_data: Order... | Implement the Python class `OrderService` described below.
Class description:
Order Service
Method signatures and docstrings:
- def _check_duplicate_order(self, order_data): Check Duplicate Order :param order_data: Order payload :return: None
- def create_order(self, order_data): Create Order :param order_data: Order... | 787e67788359521a188b9ca4fad58c216fec387d | <|skeleton|>
class OrderService:
"""Order Service"""
def _check_duplicate_order(self, order_data):
"""Check Duplicate Order :param order_data: Order payload :return: None"""
<|body_0|>
def create_order(self, order_data):
"""Create Order :param order_data: Order payload :return: ord... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrderService:
"""Order Service"""
def _check_duplicate_order(self, order_data):
"""Check Duplicate Order :param order_data: Order payload :return: None"""
customer = order_data.get('customer')
flavour = order_data.get('flavour')
size = order_data.get('size')
mobile... | the_stack_v2_python_sparse | pizza_ordering/orders/services/order_service.py | solaman-raji/pizza-ordering | train | 0 |
546da4336aab8bb0e83a3be2303b77c6baa21bcd | [
"if kw.get('interleaved_gate', None) is not None:\n self.default_experiment_name = 'SingleQubitIRB'\nkw['dim_hilbert'] = 2\nsuper().__init__(task_list, sweep_points=sweep_points, nr_seeds=nr_seeds, cliffords=cliffords, **kw)",
"interleaved_gate = kw.get('interleaved_gate', None)\npulse_op_codes_list = []\ntl =... | <|body_start_0|>
if kw.get('interleaved_gate', None) is not None:
self.default_experiment_name = 'SingleQubitIRB'
kw['dim_hilbert'] = 2
super().__init__(task_list, sweep_points=sweep_points, nr_seeds=nr_seeds, cliffords=cliffords, **kw)
<|end_body_0|>
<|body_start_1|>
interl... | Class for running the single qubit randomized benchmarking experiment on several qubits in parallel. | SingleQubitRandomizedBenchmarking | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleQubitRandomizedBenchmarking:
"""Class for running the single qubit randomized benchmarking experiment on several qubits in parallel."""
def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **kw):
"""Init of the SingleQubitRandomizedBenchmarking class.... | stack_v2_sparse_classes_10k_train_000060 | 38,263 | permissive | [
{
"docstring": "Init of the SingleQubitRandomizedBenchmarking class. Args: nr_seeds (int): the number of times the Clifford group should be sampled for each Clifford sequence length. cliffords(list/array): integers specifying the number of cliffords to apply. Keyword args: passed to parent class interleaved_gat... | 2 | stack_v2_sparse_classes_30k_train_000381 | Implement the Python class `SingleQubitRandomizedBenchmarking` described below.
Class description:
Class for running the single qubit randomized benchmarking experiment on several qubits in parallel.
Method signatures and docstrings:
- def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **... | Implement the Python class `SingleQubitRandomizedBenchmarking` described below.
Class description:
Class for running the single qubit randomized benchmarking experiment on several qubits in parallel.
Method signatures and docstrings:
- def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class SingleQubitRandomizedBenchmarking:
"""Class for running the single qubit randomized benchmarking experiment on several qubits in parallel."""
def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **kw):
"""Init of the SingleQubitRandomizedBenchmarking class.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SingleQubitRandomizedBenchmarking:
"""Class for running the single qubit randomized benchmarking experiment on several qubits in parallel."""
def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **kw):
"""Init of the SingleQubitRandomizedBenchmarking class. Args: nr_see... | the_stack_v2_python_sparse | pycqed/measurement/benchmarking/randomized_benchmarking.py | QudevETH/PycQED_py3 | train | 8 |
65e156ce4e5dfb4474607b009d4a81dcd7204be5 | [
"ObjectManager.__init__(self)\nself.getters.update({'session_template': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general', 'resource_type': 'get_foreign_key'})\nself.setters.update({'session_template': 'set_foreign_key', 'max': 'set_general', 'min': 'set_general', 'resource_type': 'set_foreign_key'})\ns... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'session_template': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general', 'resource_type': 'get_foreign_key'})
self.setters.update({'session_template': 'set_foreign_key', 'max': 'set_general', 'min': 'set_general', 'reso... | Manage SessionTemplateResourceTypeRequirements in the Power Reg system | SessionTemplateResourceTypeRequirementManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionTemplateResourceTypeRequirementManager:
"""Manage SessionTemplateResourceTypeRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, session_template_id, resource_type_id, min, max):
"""Create a... | stack_v2_sparse_classes_10k_train_000061 | 2,098 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new SessionTemplateResourceTypeRequirement @param session_template_id Foreign key for an session_template @param resource_type_id Foreign key for an resource_type @param min Minimum nu... | 2 | stack_v2_sparse_classes_30k_train_006998 | Implement the Python class `SessionTemplateResourceTypeRequirementManager` described below.
Class description:
Manage SessionTemplateResourceTypeRequirements in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, session_template_id, resource_type_id... | Implement the Python class `SessionTemplateResourceTypeRequirementManager` described below.
Class description:
Manage SessionTemplateResourceTypeRequirements in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, session_template_id, resource_type_id... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class SessionTemplateResourceTypeRequirementManager:
"""Manage SessionTemplateResourceTypeRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, session_template_id, resource_type_id, min, max):
"""Create a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SessionTemplateResourceTypeRequirementManager:
"""Manage SessionTemplateResourceTypeRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'session_template': 'get_foreign_key', 'max': 'get_general', 'min': '... | the_stack_v2_python_sparse | pr_services/event_system/session_template_resource_type_requirement_manager.py | ninemoreminutes/openassign-server | train | 0 |
b992550f26593f09a6912f5c91970c7aecfde264 | [
"for x in range(len(nums)):\n for y in range(len(nums)):\n if x != y and nums[x] + nums[y] == target:\n return [x, y]",
"if len(nums) <= 1:\n return False\nbuff_dict = {}\nfor i in range(len(nums)):\n if nums[i] in buff_dict:\n return [buff_dict[nums[i]], i]\n else:\n b... | <|body_start_0|>
for x in range(len(nums)):
for y in range(len(nums)):
if x != y and nums[x] + nums[y] == target:
return [x, y]
<|end_body_0|>
<|body_start_1|>
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(n... | Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].""... | stack_v2_sparse_classes_10k_train_000062 | 1,292 | permissive | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int] O(n^2)",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": "O(n)",
"name": "twoSumBest",
"signature": "def twoSumBest(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006016 | Implement the Python class `Solution` described below.
Class description:
Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] ... | Implement the Python class `Solution` described below.
Class description:
Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] ... | 0420fbcbebad3b746db63b9e9a5878b4af8ad6ac | <|skeleton|>
class Solution:
"""Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]."""
def tw... | the_stack_v2_python_sparse | leetcode/array/easy/twoSum.py | joway/PyAlgorithm | train | 1 |
1b092a95b449c370c424c99435276797fe30572d | [
"super(GradientAccumulationOptimizer, self).__init__(opt, name)\nif num_mini_batches < 1:\n raise ValueError('num_mini_batches must be a positive number.')\nself._num_mini_batches = num_mini_batches\nself._verify_usage = verify_usage",
"summed_grads_and_vars = []\nfor grad, var in grads_and_vars:\n if grad ... | <|body_start_0|>
super(GradientAccumulationOptimizer, self).__init__(opt, name)
if num_mini_batches < 1:
raise ValueError('num_mini_batches must be a positive number.')
self._num_mini_batches = num_mini_batches
self._verify_usage = verify_usage
<|end_body_0|>
<|body_start_1|... | An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural networks allows us to simulate bigger batch sizes. For exam... | GradientAccumulationOptimizer | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientAccumulationOptimizer:
"""An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural ne... | stack_v2_sparse_classes_10k_train_000063 | 18,009 | permissive | [
{
"docstring": "Construct a Gradient Accumulation Optimizer. Args: opt: An existing `Optimizer` to encapsulate. num_mini_batches: Number of mini-batches the gradients will be accumulated for. verify_usage: The current gradient accumulation supports the `GradientDescentOptimizer` and `MomentumOptimizer` optimize... | 2 | null | Implement the Python class `GradientAccumulationOptimizer` described below.
Class description:
An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the w... | Implement the Python class `GradientAccumulationOptimizer` described below.
Class description:
An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the w... | 085b20a4b6287eff8c0b792425d52422ab8cbab3 | <|skeleton|>
class GradientAccumulationOptimizer:
"""An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural ne... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GradientAccumulationOptimizer:
"""An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural networks allows... | the_stack_v2_python_sparse | tensorflow/python/ipu/optimizers/gradient_accumulation_optimizer.py | graphcore/tensorflow | train | 84 |
2b7082a9a5b3a7653cafb2a882fbaca59cedd053 | [
"if not A or len(A) <= 0:\n return\nnum = len(A)\nB = [1] * num\nfor i in range(num):\n for j in range(num):\n if j == i:\n continue\n else:\n B[i] = B[i] * A[j]\n print(B[i])\nreturn B",
"if A is None or len(A) <= 0:\n return\nlength = len(A)\nB = [1] * len... | <|body_start_0|>
if not A or len(A) <= 0:
return
num = len(A)
B = [1] * num
for i in range(num):
for j in range(num):
if j == i:
continue
else:
B[i] = B[i] * A[j]
print(B[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def multiply_1(self, A):
"""暴力法 :param A: :return:"""
<|body_0|>
def multiply_2(self, A):
"""将B写成一个n*n的矩阵,观察得到一个上三角和下三角,可以分别求得 需要注意的是,返回数组B的初始化,为[1] * length :param A: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not A or le... | stack_v2_sparse_classes_10k_train_000064 | 1,402 | no_license | [
{
"docstring": "暴力法 :param A: :return:",
"name": "multiply_1",
"signature": "def multiply_1(self, A)"
},
{
"docstring": "将B写成一个n*n的矩阵,观察得到一个上三角和下三角,可以分别求得 需要注意的是,返回数组B的初始化,为[1] * length :param A: :return:",
"name": "multiply_2",
"signature": "def multiply_2(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005839 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply_1(self, A): 暴力法 :param A: :return:
- def multiply_2(self, A): 将B写成一个n*n的矩阵,观察得到一个上三角和下三角,可以分别求得 需要注意的是,返回数组B的初始化,为[1] * length :param A: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply_1(self, A): 暴力法 :param A: :return:
- def multiply_2(self, A): 将B写成一个n*n的矩阵,观察得到一个上三角和下三角,可以分别求得 需要注意的是,返回数组B的初始化,为[1] * length :param A: :return:
<|skeleton|>
class... | 746d77e9bfbcb3877fefae9a915004b3bfbcc612 | <|skeleton|>
class Solution:
def multiply_1(self, A):
"""暴力法 :param A: :return:"""
<|body_0|>
def multiply_2(self, A):
"""将B写成一个n*n的矩阵,观察得到一个上三角和下三角,可以分别求得 需要注意的是,返回数组B的初始化,为[1] * length :param A: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def multiply_1(self, A):
"""暴力法 :param A: :return:"""
if not A or len(A) <= 0:
return
num = len(A)
B = [1] * num
for i in range(num):
for j in range(num):
if j == i:
continue
else:
... | the_stack_v2_python_sparse | 剑指offer/第一遍/构建乘积数组.py | leilalu/algorithm | train | 0 | |
1551cf21b02340673adabca151988a906dc0f1ae | [
"length = len(array) - 1\nfor _ in range(length):\n for i in range(length):\n if array[i] > array[i + 1]:\n array[i], array[i + 1] = (array[i + 1], array[i])",
"for passes in range(len(array) - 1, 0, -1):\n for i in range(passes):\n if array[i] > array[i + 1]:\n array[i],... | <|body_start_0|>
length = len(array) - 1
for _ in range(length):
for i in range(length):
if array[i] > array[i + 1]:
array[i], array[i + 1] = (array[i + 1], array[i])
<|end_body_0|>
<|body_start_1|>
for passes in range(len(array) - 1, 0, -1):
... | Contains various bubble sort implementations. http://en.wikipedia.org/wiki/Bubble_sort | Bubble | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bubble:
"""Contains various bubble sort implementations. http://en.wikipedia.org/wiki/Bubble_sort"""
def bubble_naive(array):
"""A standard bubble sort implementation with no optimizations. Very bad and very slow. Inplace: Yes Time complexity: always O(n^2)"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_000065 | 14,101 | no_license | [
{
"docstring": "A standard bubble sort implementation with no optimizations. Very bad and very slow. Inplace: Yes Time complexity: always O(n^2)",
"name": "bubble_naive",
"signature": "def bubble_naive(array)"
},
{
"docstring": "Performs much better than the naive implementation by itterating th... | 4 | stack_v2_sparse_classes_30k_train_002917 | Implement the Python class `Bubble` described below.
Class description:
Contains various bubble sort implementations. http://en.wikipedia.org/wiki/Bubble_sort
Method signatures and docstrings:
- def bubble_naive(array): A standard bubble sort implementation with no optimizations. Very bad and very slow. Inplace: Yes ... | Implement the Python class `Bubble` described below.
Class description:
Contains various bubble sort implementations. http://en.wikipedia.org/wiki/Bubble_sort
Method signatures and docstrings:
- def bubble_naive(array): A standard bubble sort implementation with no optimizations. Very bad and very slow. Inplace: Yes ... | c88059dc66297af577ad2b8afa4e0ac0ad622915 | <|skeleton|>
class Bubble:
"""Contains various bubble sort implementations. http://en.wikipedia.org/wiki/Bubble_sort"""
def bubble_naive(array):
"""A standard bubble sort implementation with no optimizations. Very bad and very slow. Inplace: Yes Time complexity: always O(n^2)"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Bubble:
"""Contains various bubble sort implementations. http://en.wikipedia.org/wiki/Bubble_sort"""
def bubble_naive(array):
"""A standard bubble sort implementation with no optimizations. Very bad and very slow. Inplace: Yes Time complexity: always O(n^2)"""
length = len(array) - 1
... | the_stack_v2_python_sparse | codes/BuildLinks1.02/test_input/sort_codes/pysort.py | DaHuO/Supergraph | train | 2 |
c6ca08765c9a4de633916902e384d1b66479a6bb | [
"if self.isEmpty():\n self._head = self._Item(k, v)\n self._tail = self._head\n return\nitem = self._Item(k, v)\nwalk = self._head\nwhile walk.getNext():\n if walk.getNext().getVal() >= item.getVal():\n break\n walk = walk.getNext()\nitem.setNext(walk.getNext())\nwalk.setNext(item)",
"item =... | <|body_start_0|>
if self.isEmpty():
self._head = self._Item(k, v)
self._tail = self._head
return
item = self._Item(k, v)
walk = self._head
while walk.getNext():
if walk.getNext().getVal() >= item.getVal():
break
... | A min-oriented priority queue implemented with an unsorted list | SortedPriorityQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SortedPriorityQueue:
"""A min-oriented priority queue implemented with an unsorted list"""
def add(self, k, v):
"""Add a key-value pair (unsorted order)"""
<|body_0|>
def min_(self):
"""Return but do not remove (k,v) tuple with minimun key"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_000066 | 4,764 | no_license | [
{
"docstring": "Add a key-value pair (unsorted order)",
"name": "add",
"signature": "def add(self, k, v)"
},
{
"docstring": "Return but do not remove (k,v) tuple with minimun key",
"name": "min_",
"signature": "def min_(self)"
},
{
"docstring": "Remove and return (k,v) tuple with... | 3 | stack_v2_sparse_classes_30k_train_005704 | Implement the Python class `SortedPriorityQueue` described below.
Class description:
A min-oriented priority queue implemented with an unsorted list
Method signatures and docstrings:
- def add(self, k, v): Add a key-value pair (unsorted order)
- def min_(self): Return but do not remove (k,v) tuple with minimun key
- ... | Implement the Python class `SortedPriorityQueue` described below.
Class description:
A min-oriented priority queue implemented with an unsorted list
Method signatures and docstrings:
- def add(self, k, v): Add a key-value pair (unsorted order)
- def min_(self): Return but do not remove (k,v) tuple with minimun key
- ... | 783daaca7c9b716f080df43c7aa581add3b86a46 | <|skeleton|>
class SortedPriorityQueue:
"""A min-oriented priority queue implemented with an unsorted list"""
def add(self, k, v):
"""Add a key-value pair (unsorted order)"""
<|body_0|>
def min_(self):
"""Return but do not remove (k,v) tuple with minimun key"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SortedPriorityQueue:
"""A min-oriented priority queue implemented with an unsorted list"""
def add(self, k, v):
"""Add a key-value pair (unsorted order)"""
if self.isEmpty():
self._head = self._Item(k, v)
self._tail = self._head
return
item = se... | the_stack_v2_python_sparse | labs/P-QueueBase.py | pithecuse527/Algorithms-MUN | train | 4 |
2287f1a5337db874b0f9b0517964cb13ec1341c7 | [
"if not isinstance(text, list):\n text = [text]\nfor i in text:\n assert_that(page).contains(i)",
"if not isinstance(text, list):\n text = [text]\nfor i in text:\n assert_that(page).does_not_contain(i)",
"page = elem.text\nif not text:\n pass\nif mode not in ('vague', 'accurate'):\n raise Exce... | <|body_start_0|>
if not isinstance(text, list):
text = [text]
for i in text:
assert_that(page).contains(i)
<|end_body_0|>
<|body_start_1|>
if not isinstance(text, list):
text = [text]
for i in text:
assert_that(page).does_not_contain(i)
<|... | BaseAssert | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseAssert:
def assert_text_in_page(self, text, page):
"""判断文本在页面中存在,支持多个文本"""
<|body_0|>
def assert_text_not_in_page(self, text, page):
"""判断文本在页面中不存在,支持多个文本"""
<|body_1|>
def assert_text_in_elem(self, text, elem, mode='vague'):
"""判断元素包含文本,支持多个... | stack_v2_sparse_classes_10k_train_000067 | 3,059 | no_license | [
{
"docstring": "判断文本在页面中存在,支持多个文本",
"name": "assert_text_in_page",
"signature": "def assert_text_in_page(self, text, page)"
},
{
"docstring": "判断文本在页面中不存在,支持多个文本",
"name": "assert_text_not_in_page",
"signature": "def assert_text_not_in_page(self, text, page)"
},
{
"docstring": "判... | 5 | stack_v2_sparse_classes_30k_test_000152 | Implement the Python class `BaseAssert` described below.
Class description:
Implement the BaseAssert class.
Method signatures and docstrings:
- def assert_text_in_page(self, text, page): 判断文本在页面中存在,支持多个文本
- def assert_text_not_in_page(self, text, page): 判断文本在页面中不存在,支持多个文本
- def assert_text_in_elem(self, text, elem, m... | Implement the Python class `BaseAssert` described below.
Class description:
Implement the BaseAssert class.
Method signatures and docstrings:
- def assert_text_in_page(self, text, page): 判断文本在页面中存在,支持多个文本
- def assert_text_not_in_page(self, text, page): 判断文本在页面中不存在,支持多个文本
- def assert_text_in_elem(self, text, elem, m... | 0025cc46fa84db658987c9df109de4e5c3c4f5b9 | <|skeleton|>
class BaseAssert:
def assert_text_in_page(self, text, page):
"""判断文本在页面中存在,支持多个文本"""
<|body_0|>
def assert_text_not_in_page(self, text, page):
"""判断文本在页面中不存在,支持多个文本"""
<|body_1|>
def assert_text_in_elem(self, text, elem, mode='vague'):
"""判断元素包含文本,支持多个... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseAssert:
def assert_text_in_page(self, text, page):
"""判断文本在页面中存在,支持多个文本"""
if not isinstance(text, list):
text = [text]
for i in text:
assert_that(page).contains(i)
def assert_text_not_in_page(self, text, page):
"""判断文本在页面中不存在,支持多个文本"""
... | the_stack_v2_python_sparse | uiplatform/utils/common/BaseAssert.py | abao0713/erybjp | train | 0 | |
cc38e48cb8b5603abdfca0d2efe7236cc18a449c | [
"msg.bold('pyro ...')\nif solver_name not in valid_solvers:\n msg.fail(f'ERROR: {solver_name} is not a valid solver')\nself.pyro_home = os.path.dirname(os.path.realpath(__file__)) + '/'\nif not solver_name.startswith('pyro.'):\n solver_import = 'pyro.' + solver_name\nelse:\n solver_import = solver_name\nse... | <|body_start_0|>
msg.bold('pyro ...')
if solver_name not in valid_solvers:
msg.fail(f'ERROR: {solver_name} is not a valid solver')
self.pyro_home = os.path.dirname(os.path.realpath(__file__)) + '/'
if not solver_name.startswith('pyro.'):
solver_import = 'pyro.' + ... | The main driver to run pyro. | Pyro | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pyro:
"""The main driver to run pyro."""
def __init__(self, solver_name):
"""Constructor Parameters ---------- solver_name : str Name of solver to use"""
<|body_0|>
def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=None, other_commands=None):
... | stack_v2_sparse_classes_10k_train_000068 | 11,814 | permissive | [
{
"docstring": "Constructor Parameters ---------- solver_name : str Name of solver to use",
"name": "__init__",
"signature": "def __init__(self, solver_name)"
},
{
"docstring": "Initialize the specific problem Parameters ---------- problem_name : str Name of the problem inputs_file : str Filenam... | 6 | stack_v2_sparse_classes_30k_train_007085 | Implement the Python class `Pyro` described below.
Class description:
The main driver to run pyro.
Method signatures and docstrings:
- def __init__(self, solver_name): Constructor Parameters ---------- solver_name : str Name of solver to use
- def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=N... | Implement the Python class `Pyro` described below.
Class description:
The main driver to run pyro.
Method signatures and docstrings:
- def __init__(self, solver_name): Constructor Parameters ---------- solver_name : str Name of solver to use
- def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=N... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class Pyro:
"""The main driver to run pyro."""
def __init__(self, solver_name):
"""Constructor Parameters ---------- solver_name : str Name of solver to use"""
<|body_0|>
def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=None, other_commands=None):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Pyro:
"""The main driver to run pyro."""
def __init__(self, solver_name):
"""Constructor Parameters ---------- solver_name : str Name of solver to use"""
msg.bold('pyro ...')
if solver_name not in valid_solvers:
msg.fail(f'ERROR: {solver_name} is not a valid solver')
... | the_stack_v2_python_sparse | pyro/pyro_sim.py | python-hydro/pyro2 | train | 202 |
d5cf253c5ca3072b0d037a4218dd411aa9224505 | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('DescribeFraudBase', params, headers=headers)\n response = json.loads(body)\n model = models.DescribeFraudBaseResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n if... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('DescribeFraudBase', params, headers=headers)
response = json.loads(body)
model = models.DescribeFraudBaseResponse()
model._deserialize(response[... | TdsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TdsClient:
def DescribeFraudBase(self, request):
"""查询设备风险 :param request: Request instance for DescribeFraudBase. :type request: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseRequest` :rtype: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseResponse`"""
<|... | stack_v2_sparse_classes_10k_train_000069 | 4,548 | permissive | [
{
"docstring": "查询设备风险 :param request: Request instance for DescribeFraudBase. :type request: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseRequest` :rtype: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseResponse`",
"name": "DescribeFraudBase",
"signature": "def DescribeFraudBas... | 4 | stack_v2_sparse_classes_30k_train_000219 | Implement the Python class `TdsClient` described below.
Class description:
Implement the TdsClient class.
Method signatures and docstrings:
- def DescribeFraudBase(self, request): 查询设备风险 :param request: Request instance for DescribeFraudBase. :type request: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseR... | Implement the Python class `TdsClient` described below.
Class description:
Implement the TdsClient class.
Method signatures and docstrings:
- def DescribeFraudBase(self, request): 查询设备风险 :param request: Request instance for DescribeFraudBase. :type request: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseR... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class TdsClient:
def DescribeFraudBase(self, request):
"""查询设备风险 :param request: Request instance for DescribeFraudBase. :type request: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseRequest` :rtype: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseResponse`"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TdsClient:
def DescribeFraudBase(self, request):
"""查询设备风险 :param request: Request instance for DescribeFraudBase. :type request: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseRequest` :rtype: :class:`tencentcloud.tds.v20220801.models.DescribeFraudBaseResponse`"""
try:
... | the_stack_v2_python_sparse | tencentcloud/tds/v20220801/tds_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
8e478993ed439e058d0df69121db484f8c936899 | [
"if not nums:\n return 0\ndp = [1] * len(nums)\nfor i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"if not nums:\n return 0\ntail = [nums[0]]\nfor num in nums:\n if num > tail[-1]:\n tail.append(num)\n e... | <|body_start_0|>
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1|>
if not nums:
... | 详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/ | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/"""
def lengthOfLIS1(self, nums: List[int]) -> int:
"""DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个... | stack_v2_sparse_classes_10k_train_000070 | 2,709 | no_license | [
{
"docstring": "DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个更长的子序列 3. 状态转移:dp[i] = max(dp[i], dp[j] + 1) if nums[i] > nums[j]",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums: List[int]) -> int"
},
{
"docstring": "贪心+二分查找:维护tail数组 tai... | 2 | null | Implement the Python class `Solution` described below.
Class description:
详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/
Method signatures and docstrings:
- def lengthOfLIS1(self, nums: List[int]) -> int: DP: 1. 定义状态:dp[i] 表示以 nums[i]结... | Implement the Python class `Solution` described below.
Class description:
详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/
Method signatures and docstrings:
- def lengthOfLIS1(self, nums: List[int]) -> int: DP: 1. 定义状态:dp[i] 表示以 nums[i]结... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
"""详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/"""
def lengthOfLIS1(self, nums: List[int]) -> int:
"""DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/"""
def lengthOfLIS1(self, nums: List[int]) -> int:
"""DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个更长的子序列 3. 状态转... | the_stack_v2_python_sparse | 300_longest-increasing-subsequence.py | helloocc/algorithm | train | 1 |
cbc5743646eb423991c6867d038d171293c07813 | [
"self.append_documents = append_documents\nself.ddl_only_recovery = ddl_only_recovery\nself.documents_filter_type = documents_filter_type\nself.filter_expression = filter_expression\nself.id_regex = id_regex\nself.overwrite_users = overwrite_users\nself.suffix = suffix",
"if dictionary is None:\n return None\n... | <|body_start_0|>
self.append_documents = append_documents
self.ddl_only_recovery = ddl_only_recovery
self.documents_filter_type = documents_filter_type
self.filter_expression = filter_expression
self.id_regex = id_regex
self.overwrite_users = overwrite_users
self.... | Implementation of the 'CouchbaseRecoverJobParams' model. Contains any additional couchbase environment specific params for the recover job. Attributes: append_documents (bool): Whether to append documents into the bucket at the destination ddl_only_recovery (bool): Whether to recover only the bucket configuration docum... | CouchbaseRecoverJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouchbaseRecoverJobParams:
"""Implementation of the 'CouchbaseRecoverJobParams' model. Contains any additional couchbase environment specific params for the recover job. Attributes: append_documents (bool): Whether to append documents into the bucket at the destination ddl_only_recovery (bool): W... | stack_v2_sparse_classes_10k_train_000071 | 3,341 | permissive | [
{
"docstring": "Constructor for the CouchbaseRecoverJobParams class",
"name": "__init__",
"signature": "def __init__(self, append_documents=None, ddl_only_recovery=None, documents_filter_type=None, filter_expression=None, id_regex=None, overwrite_users=None, suffix=None)"
},
{
"docstring": "Crea... | 2 | null | Implement the Python class `CouchbaseRecoverJobParams` described below.
Class description:
Implementation of the 'CouchbaseRecoverJobParams' model. Contains any additional couchbase environment specific params for the recover job. Attributes: append_documents (bool): Whether to append documents into the bucket at the ... | Implement the Python class `CouchbaseRecoverJobParams` described below.
Class description:
Implementation of the 'CouchbaseRecoverJobParams' model. Contains any additional couchbase environment specific params for the recover job. Attributes: append_documents (bool): Whether to append documents into the bucket at the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CouchbaseRecoverJobParams:
"""Implementation of the 'CouchbaseRecoverJobParams' model. Contains any additional couchbase environment specific params for the recover job. Attributes: append_documents (bool): Whether to append documents into the bucket at the destination ddl_only_recovery (bool): W... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CouchbaseRecoverJobParams:
"""Implementation of the 'CouchbaseRecoverJobParams' model. Contains any additional couchbase environment specific params for the recover job. Attributes: append_documents (bool): Whether to append documents into the bucket at the destination ddl_only_recovery (bool): Whether to rec... | the_stack_v2_python_sparse | cohesity_management_sdk/models/couchbase_recover_job_params.py | cohesity/management-sdk-python | train | 24 |
e0487270a3bd5c3a5a2aa74ff0726e1758f4ae4b | [
"features = []\ncount = len(request.feature) - 1\nwhile count >= 0:\n features.append(str(request.feature[count]))\n count -= 1\nprepped_features = Pairwise.prepare_features(request.cohort_id, features)\noutputs = Pairwise.run_pairwise(prepped_features)\nresults = PairwiseResults(result_vectors=[], filter_mes... | <|body_start_0|>
features = []
count = len(request.feature) - 1
while count >= 0:
features.append(str(request.feature[count]))
count -= 1
prepped_features = Pairwise.prepare_features(request.cohort_id, features)
outputs = Pairwise.run_pairwise(prepped_feat... | Pairwise API v1 | PairwiseApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
<|body_0|>
def precomputed_results(self, request):
"""Used by the web application."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
features = []
... | stack_v2_sparse_classes_10k_train_000072 | 7,340 | permissive | [
{
"docstring": "Used by the web application.",
"name": "run_job",
"signature": "def run_job(self, request)"
},
{
"docstring": "Used by the web application.",
"name": "precomputed_results",
"signature": "def precomputed_results(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003067 | Implement the Python class `PairwiseApi` described below.
Class description:
Pairwise API v1
Method signatures and docstrings:
- def run_job(self, request): Used by the web application.
- def precomputed_results(self, request): Used by the web application. | Implement the Python class `PairwiseApi` described below.
Class description:
Pairwise API v1
Method signatures and docstrings:
- def run_job(self, request): Used by the web application.
- def precomputed_results(self, request): Used by the web application.
<|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
... | 1c1809eb5b3ab7ec8a7d028df878ce8b0de9854f | <|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
<|body_0|>
def precomputed_results(self, request):
"""Used by the web application."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
features = []
count = len(request.feature) - 1
while count >= 0:
features.append(str(request.feature[count]))
count -= 1
prepped_features = Pai... | the_stack_v2_python_sparse | api/pairwise_api.py | Angiotension/ISB-CGC-Webapp | train | 0 |
38481d6316a0f892011ed1c8ac82536246d50d2d | [
"super().__init__(connections, dev_cfg)\nself.log.info('Configuring LogicOr %s', self.name)\nself.log.debug('%s has following configured connections: \\n%s', self.name, yaml.dump(self.comm))\nself.log.debug('%s configured values: \\n%s', self.name, yaml.dump(self.values))\nverify_connections_layout(self.comm, self.... | <|body_start_0|>
super().__init__(connections, dev_cfg)
self.log.info('Configuring LogicOr %s', self.name)
self.log.debug('%s has following configured connections: \n%s', self.name, yaml.dump(self.comm))
self.log.debug('%s configured values: \n%s', self.name, yaml.dump(self.values))
... | Logical OR gate, can receive from multiple sensors and will trigger all configured receivers | LogicOr | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogicOr:
"""Logical OR gate, can receive from multiple sensors and will trigger all configured receivers"""
def __init__(self, connections, dev_cfg):
"""Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given... | stack_v2_sparse_classes_10k_train_000073 | 9,274 | permissive | [
{
"docstring": "Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given connections Arguments: - connections: List of the connections - dev_cfg: lambda that returns value for the passed in key \"Values\": Alternative values to publish i... | 2 | stack_v2_sparse_classes_30k_train_000277 | Implement the Python class `LogicOr` described below.
Class description:
Logical OR gate, can receive from multiple sensors and will trigger all configured receivers
Method signatures and docstrings:
- def __init__(self, connections, dev_cfg): Initializes the Actuator by storing the passed in arguments as data member... | Implement the Python class `LogicOr` described below.
Class description:
Logical OR gate, can receive from multiple sensors and will trigger all configured receivers
Method signatures and docstrings:
- def __init__(self, connections, dev_cfg): Initializes the Actuator by storing the passed in arguments as data member... | 6f8888ddef413fb8d58ef0ebc8fe89144c914a22 | <|skeleton|>
class LogicOr:
"""Logical OR gate, can receive from multiple sensors and will trigger all configured receivers"""
def __init__(self, connections, dev_cfg):
"""Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogicOr:
"""Logical OR gate, can receive from multiple sensors and will trigger all configured receivers"""
def __init__(self, connections, dev_cfg):
"""Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given connections ... | the_stack_v2_python_sparse | local/local_logic.py | rkoshak/sensorReporter | train | 104 |
471f4eded8f0544aee26a138ae1cfcbdfabfc60e | [
"super(ComposePromoter, self).__init__(client, working_dir)\nself.compose_url = compose_url\nself.supported_promotions = [{'candidate': 'latest-compose', 'target': 'centos-ci-testing'}]",
"try:\n latest_compose_id = urllib.request.urlopen(self.compose_url).readline().decode('utf-8')\nexcept Exception:\n msg... | <|body_start_0|>
super(ComposePromoter, self).__init__(client, working_dir)
self.compose_url = compose_url
self.supported_promotions = [{'candidate': 'latest-compose', 'target': 'centos-ci-testing'}]
<|end_body_0|>
<|body_start_1|>
try:
latest_compose_id = urllib.request.url... | CentOS compose promoter class. | ComposePromoter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComposePromoter:
"""CentOS compose promoter class."""
def __init__(self, client, working_dir, compose_url=None):
"""Instantiate a new compose promoter. :param client: client to be used for file operations :param working_dir: working directory to perform file operations :param compose... | stack_v2_sparse_classes_10k_train_000074 | 1,989 | permissive | [
{
"docstring": "Instantiate a new compose promoter. :param client: client to be used for file operations :param working_dir: working directory to perform file operations :param compose_url: url used to fetch latest compose-id for an specific distro.",
"name": "__init__",
"signature": "def __init__(self,... | 3 | stack_v2_sparse_classes_30k_train_003158 | Implement the Python class `ComposePromoter` described below.
Class description:
CentOS compose promoter class.
Method signatures and docstrings:
- def __init__(self, client, working_dir, compose_url=None): Instantiate a new compose promoter. :param client: client to be used for file operations :param working_dir: wo... | Implement the Python class `ComposePromoter` described below.
Class description:
CentOS compose promoter class.
Method signatures and docstrings:
- def __init__(self, client, working_dir, compose_url=None): Instantiate a new compose promoter. :param client: client to be used for file operations :param working_dir: wo... | b50bfb6ad52300243876113b1a247e7cff2c0805 | <|skeleton|>
class ComposePromoter:
"""CentOS compose promoter class."""
def __init__(self, client, working_dir, compose_url=None):
"""Instantiate a new compose promoter. :param client: client to be used for file operations :param working_dir: working directory to perform file operations :param compose... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ComposePromoter:
"""CentOS compose promoter class."""
def __init__(self, client, working_dir, compose_url=None):
"""Instantiate a new compose promoter. :param client: client to be used for file operations :param working_dir: working directory to perform file operations :param compose_url: url use... | the_stack_v2_python_sparse | ci-scripts/infra-setup/roles/artifact_promoter/module_utils/artifact_promoter/compose_promoter.py | rdo-infra/ci-config | train | 8 |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(ClassificationTaskModel, self).__init__()\nmodel_type = model_config.get('model_type', 'transformer')\nhidden_size = model_config.get('hidden_size', 512)\nin_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size\nself.fc_decoder = nn.Sequential(nn.Linear(in_features=in_channels, out_features=51... | <|body_start_0|>
super(ClassificationTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
self.fc_decoder = nn.Sequential(nn... | ClassificationTaskModel | ClassificationTaskModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationTaskModel:
"""ClassificationTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Classifi... | stack_v2_sparse_classes_10k_train_000075 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, class_num, model_config, encoder_model)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | null | Implement the Python class `ClassificationTaskModel` described below.
Class description:
ClassificationTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward | Implement the Python class `ClassificationTaskModel` described below.
Class description:
ClassificationTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward
<|skeleton|>
class ClassificationTaskModel:
"""Classif... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class ClassificationTaskModel:
"""ClassificationTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClassificationTaskModel:
"""ClassificationTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
super(ClassificationTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidd... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
1a62c91cdcdb50eec307a072555f87befa931953 | [
"size = len(entities)\nif size > 0:\n store = get_current_store()\n chunk = options.get('chunk_size', None)\n entity_type = type(entities[0])\n serialized_values = serializer_services.serialize(entities, **options)\n if chunk is None:\n chunk = 0\n chunk = int(chunk)\n if size <= chunk o... | <|body_start_0|>
size = len(entities)
if size > 0:
store = get_current_store()
chunk = options.get('chunk_size', None)
entity_type = type(entities[0])
serialized_values = serializer_services.serialize(entities, **options)
if chunk is None:
... | database bulk manager class. | DatabaseBulkManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseBulkManager:
"""database bulk manager class."""
def insert(self, *entities, **options):
"""bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inserted. :keyword int chunk_size: chunk size to insert values... | stack_v2_sparse_classes_10k_train_000076 | 20,839 | permissive | [
{
"docstring": "bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inserted. :keyword int chunk_size: chunk size to insert values. after each chunk, store will be committed. if not provided, all values will be inserted in a single call and ... | 2 | null | Implement the Python class `DatabaseBulkManager` described below.
Class description:
database bulk manager class.
Method signatures and docstrings:
- def insert(self, *entities, **options): bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inser... | Implement the Python class `DatabaseBulkManager` described below.
Class description:
database bulk manager class.
Method signatures and docstrings:
- def insert(self, *entities, **options): bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inser... | 9d4776498225de4f3d16a4600b5b19212abe8562 | <|skeleton|>
class DatabaseBulkManager:
"""database bulk manager class."""
def insert(self, *entities, **options):
"""bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inserted. :keyword int chunk_size: chunk size to insert values... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DatabaseBulkManager:
"""database bulk manager class."""
def insert(self, *entities, **options):
"""bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inserted. :keyword int chunk_size: chunk size to insert values. after each ... | the_stack_v2_python_sparse | src/pyrin/database/bulk/manager.py | mononobi/pyrin | train | 20 |
f6a7f300706a53bca5b4ad4711ab8b6ec2d46f42 | [
"if kwargs.get('handler', 0) == 0:\n return (f'{url}', ComponentHandler, self.get_dict(**kwargs))\nelse:\n return (f'{url}', kwargs['handler'], self.get_dict(**kwargs))",
"result = kwargs\nif not kwargs.get('kind'):\n result['kind'] = 'default'\nreturn result"
] | <|body_start_0|>
if kwargs.get('handler', 0) == 0:
return (f'{url}', ComponentHandler, self.get_dict(**kwargs))
else:
return (f'{url}', kwargs['handler'], self.get_dict(**kwargs))
<|end_body_0|>
<|body_start_1|>
result = kwargs
if not kwargs.get('kind'):
... | ComponentFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentFactory:
def get_handler(self, url, **kwargs):
"""Return a handler to be packaged with tornado app"""
<|body_0|>
def get_dict(self, **kwargs):
"""Default values if desired"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if kwargs.get('handl... | stack_v2_sparse_classes_10k_train_000077 | 2,456 | no_license | [
{
"docstring": "Return a handler to be packaged with tornado app",
"name": "get_handler",
"signature": "def get_handler(self, url, **kwargs)"
},
{
"docstring": "Default values if desired",
"name": "get_dict",
"signature": "def get_dict(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002737 | Implement the Python class `ComponentFactory` described below.
Class description:
Implement the ComponentFactory class.
Method signatures and docstrings:
- def get_handler(self, url, **kwargs): Return a handler to be packaged with tornado app
- def get_dict(self, **kwargs): Default values if desired | Implement the Python class `ComponentFactory` described below.
Class description:
Implement the ComponentFactory class.
Method signatures and docstrings:
- def get_handler(self, url, **kwargs): Return a handler to be packaged with tornado app
- def get_dict(self, **kwargs): Default values if desired
<|skeleton|>
cla... | f70def8691c84150818c40ccc9d4cdceeb276d46 | <|skeleton|>
class ComponentFactory:
def get_handler(self, url, **kwargs):
"""Return a handler to be packaged with tornado app"""
<|body_0|>
def get_dict(self, **kwargs):
"""Default values if desired"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ComponentFactory:
def get_handler(self, url, **kwargs):
"""Return a handler to be packaged with tornado app"""
if kwargs.get('handler', 0) == 0:
return (f'{url}', ComponentHandler, self.get_dict(**kwargs))
else:
return (f'{url}', kwargs['handler'], self.get_dict... | the_stack_v2_python_sparse | peak/component.py | connorjrice/OSS | train | 1 | |
b09ba37888da8baf3ee1fcb3a04d9df6fa46c02e | [
"n = len(nums)\nfor i in range(1, n):\n nums[i] = max(nums[i - 1], 0) + nums[i]\nreturn max(nums)",
"n = len(nums)\ndp = [0] * n\ndp[0] = nums[0]\nfor i in range(1, n):\n if dp[i - 1] > 0:\n dp[i] = max(dp[i - 1], dp[i - 1] + nums[i])\n else:\n dp[i] = nums[i]\nreturn max(dp)"
] | <|body_start_0|>
n = len(nums)
for i in range(1, n):
nums[i] = max(nums[i - 1], 0) + nums[i]
return max(nums)
<|end_body_0|>
<|body_start_1|>
n = len(nums)
dp = [0] * n
dp[0] = nums[0]
for i in range(1, n):
if dp[i - 1] > 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""状态转移方程: 当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i] ; 当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ; 时间复杂度:O(n) 空间复杂度:O(1) :param nums: :return:"""
<|body_0|>
def maxSubArray2(self, nums: List[int]) -> int:
"""dp模板写法,题解同上 :par... | stack_v2_sparse_classes_10k_train_000078 | 1,258 | no_license | [
{
"docstring": "状态转移方程: 当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i] ; 当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ; 时间复杂度:O(n) 空间复杂度:O(1) :param nums: :return:",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums: List[int]) -> int"
},
{
"docstring": "dp模板写法,题解同上 :param nums: :return:",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_000868 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums: List[int]) -> int: 状态转移方程: 当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i] ; 当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ; 时间复杂度:O(n) 空间复杂度:O(1) :param nums: :return:
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums: List[int]) -> int: 状态转移方程: 当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i] ; 当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ; 时间复杂度:O(n) 空间复杂度:O(1) :param nums: :return:
- def... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""状态转移方程: 当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i] ; 当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ; 时间复杂度:O(n) 空间复杂度:O(1) :param nums: :return:"""
<|body_0|>
def maxSubArray2(self, nums: List[int]) -> int:
"""dp模板写法,题解同上 :par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""状态转移方程: 当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i] ; 当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ; 时间复杂度:O(n) 空间复杂度:O(1) :param nums: :return:"""
n = len(nums)
for i in range(1, n):
nums[i] = max(nums[i - 1], 0) + nums[i]
r... | the_stack_v2_python_sparse | 剑指offer/连续子数组的最大和.py | cjrzs/MyLeetCode | train | 8 | |
dff8c659a78b13b7c40142b0f425f25e09025211 | [
"from sklearn.datasets import fetch_mldata\nmnist = fetch_mldata('MNIST original', data_home='.')\nself.X = mnist['data']\nself.y = mnist['target']\nprint('Loaded {} images which contain {} pixels'.format(self.X.shape[0], self.X.shape[1]))",
"import random\nfor digit in digit_list:\n digit_idx = np.where(self.... | <|body_start_0|>
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original', data_home='.')
self.X = mnist['data']
self.y = mnist['target']
print('Loaded {} images which contain {} pixels'.format(self.X.shape[0], self.X.shape[1]))
<|end_body_0|>
<|body_start... | MnistProcesser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MnistProcesser:
def __init__(self):
"""Incarcati setul de date MNIST. Acesta este format din 70000 de imagini cu cifre scrise de mana. Dimensiunea imaginilor este 28x28. Datele pe care le veti gasi in mnist['data'] sunt efectiv pixelii imaginilor, iar target-ul fiecarei imagini este de f... | stack_v2_sparse_classes_10k_train_000079 | 4,018 | no_license | [
{
"docstring": "Incarcati setul de date MNIST. Acesta este format din 70000 de imagini cu cifre scrise de mana. Dimensiunea imaginilor este 28x28. Datele pe care le veti gasi in mnist['data'] sunt efectiv pixelii imaginilor, iar target-ul fiecarei imagini este de fapt cifra. Inainte de a incepe lucrul, va indem... | 5 | null | Implement the Python class `MnistProcesser` described below.
Class description:
Implement the MnistProcesser class.
Method signatures and docstrings:
- def __init__(self): Incarcati setul de date MNIST. Acesta este format din 70000 de imagini cu cifre scrise de mana. Dimensiunea imaginilor este 28x28. Datele pe care ... | Implement the Python class `MnistProcesser` described below.
Class description:
Implement the MnistProcesser class.
Method signatures and docstrings:
- def __init__(self): Incarcati setul de date MNIST. Acesta este format din 70000 de imagini cu cifre scrise de mana. Dimensiunea imaginilor este 28x28. Datele pe care ... | e8ce18fad97b1207545e933ed0947347ed09c536 | <|skeleton|>
class MnistProcesser:
def __init__(self):
"""Incarcati setul de date MNIST. Acesta este format din 70000 de imagini cu cifre scrise de mana. Dimensiunea imaginilor este 28x28. Datele pe care le veti gasi in mnist['data'] sunt efectiv pixelii imaginilor, iar target-ul fiecarei imagini este de f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MnistProcesser:
def __init__(self):
"""Incarcati setul de date MNIST. Acesta este format din 70000 de imagini cu cifre scrise de mana. Dimensiunea imaginilor este 28x28. Datele pe care le veti gasi in mnist['data'] sunt efectiv pixelii imaginilor, iar target-ul fiecarei imagini este de fapt cifra. Ina... | the_stack_v2_python_sparse | 01_tests/06_laurentiu_repository/python_tests_ioan&erik/2/2_mnist_rez.py | Cloudifier/CLOUDIFIER_WORK | train | 0 | |
6525f29ac4e3b19423711836644310771b71a7dc | [
"j, lhp = (0, [0] * len(t))\nfor i in range(1, len(t)):\n while j > 0 and t[i] != t[j]:\n j = lhp[j - 1]\n if t[i] == t[j]:\n j += 1\n lhp[i] = j\nreturn lhp",
"j = 0\nlhp, res = (self.get_lhp(pat), [])\nfor i in range(len(text)):\n while j > 0 and text[i] != pat[j]:\n j = lhp... | <|body_start_0|>
j, lhp = (0, [0] * len(t))
for i in range(1, len(t)):
while j > 0 and t[i] != t[j]:
j = lhp[j - 1]
if t[i] == t[j]:
j += 1
lhp[i] = j
return lhp
<|end_body_0|>
<|body_start_1|>
j = 0
lhp, re... | KMP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KMP:
def get_lhp(self, t: str) -> List[int]:
"""Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t"""
<|body_0|>
def pattern... | stack_v2_sparse_classes_10k_train_000080 | 2,412 | no_license | [
{
"docstring": "Compute the length of LHP for each t[:i], i \\\\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t",
"name": "get_lhp",
"signature": "def get_lhp(self, t: str) -> List[int]"
},
{
... | 2 | null | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def get_lhp(self, t: str) -> List[int]: Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswit... | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def get_lhp(self, t: str) -> List[int]: Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswit... | 9e4f6f1a2830bd9aab1bba374c98f0464825d435 | <|skeleton|>
class KMP:
def get_lhp(self, t: str) -> List[int]:
"""Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t"""
<|body_0|>
def pattern... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KMP:
def get_lhp(self, t: str) -> List[int]:
"""Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t"""
j, lhp = (0, [0] * len(t))
for i ... | the_stack_v2_python_sparse | python_solutions/28.implement-strstr.py | h4hany/leetcode | train | 0 | |
24a5c20820c4b55a9eb5e28e9056f7203ce70c56 | [
"self.alternate_restore_base_directory = alternate_restore_base_directory\nself.continue_on_error = continue_on_error\nself.encryption_enabled = encryption_enabled\nself.generate_ssh_keys = generate_ssh_keys\nself.override_originals = override_originals\nself.preserve_acls = preserve_acls\nself.preserve_attributes ... | <|body_start_0|>
self.alternate_restore_base_directory = alternate_restore_base_directory
self.continue_on_error = continue_on_error
self.encryption_enabled = encryption_enabled
self.generate_ssh_keys = generate_ssh_keys
self.override_originals = override_originals
self.p... | Implementation of the 'RestoreFilesPreferences' model. This message captures preferences from the user while restoring the files on the target. Attributes: alternate_restore_base_directory (string): This must be set to a directory path if restore_to_original_paths is false. All the files and directories restored will b... | RestoreFilesPreferences | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreFilesPreferences:
"""Implementation of the 'RestoreFilesPreferences' model. This message captures preferences from the user while restoring the files on the target. Attributes: alternate_restore_base_directory (string): This must be set to a directory path if restore_to_original_paths is f... | stack_v2_sparse_classes_10k_train_000081 | 5,610 | permissive | [
{
"docstring": "Constructor for the RestoreFilesPreferences class",
"name": "__init__",
"signature": "def __init__(self, alternate_restore_base_directory=None, continue_on_error=None, encryption_enabled=None, generate_ssh_keys=None, override_originals=None, preserve_acls=None, preserve_attributes=None, ... | 2 | stack_v2_sparse_classes_30k_val_000141 | Implement the Python class `RestoreFilesPreferences` described below.
Class description:
Implementation of the 'RestoreFilesPreferences' model. This message captures preferences from the user while restoring the files on the target. Attributes: alternate_restore_base_directory (string): This must be set to a directory... | Implement the Python class `RestoreFilesPreferences` described below.
Class description:
Implementation of the 'RestoreFilesPreferences' model. This message captures preferences from the user while restoring the files on the target. Attributes: alternate_restore_base_directory (string): This must be set to a directory... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreFilesPreferences:
"""Implementation of the 'RestoreFilesPreferences' model. This message captures preferences from the user while restoring the files on the target. Attributes: alternate_restore_base_directory (string): This must be set to a directory path if restore_to_original_paths is f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreFilesPreferences:
"""Implementation of the 'RestoreFilesPreferences' model. This message captures preferences from the user while restoring the files on the target. Attributes: alternate_restore_base_directory (string): This must be set to a directory path if restore_to_original_paths is false. All the... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_files_preferences.py | cohesity/management-sdk-python | train | 24 |
4b2af1b09f9eab5edf36653f2fcdbf4d46479c60 | [
"date_format = get_date_format(range_type)\nhealth = cls.objects.filter(user=user).order_by('related_date')\nif range_type in (ChartTimeRange.YEAR, ChartTimeRange.MONTH):\n date = datetime.strptime(date_str, date_format)\n health = health.filter(related_date__year=date.strftime('%Y'))\n if range_type == Ch... | <|body_start_0|>
date_format = get_date_format(range_type)
health = cls.objects.filter(user=user).order_by('related_date')
if range_type in (ChartTimeRange.YEAR, ChartTimeRange.MONTH):
date = datetime.strptime(date_str, date_format)
health = health.filter(related_date__ye... | Health | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Health:
def get_health_by_date(cls, user, range_type, date_str):
"""Get queryset of health datas by range :param user: user object :param range_type: dates range type - week, month or year :param date_str: date string :return: queryset of health datas :rtype: queryset"""
<|body_0... | stack_v2_sparse_classes_10k_train_000082 | 5,178 | no_license | [
{
"docstring": "Get queryset of health datas by range :param user: user object :param range_type: dates range type - week, month or year :param date_str: date string :return: queryset of health datas :rtype: queryset",
"name": "get_health_by_date",
"signature": "def get_health_by_date(cls, user, range_t... | 3 | stack_v2_sparse_classes_30k_val_000353 | Implement the Python class `Health` described below.
Class description:
Implement the Health class.
Method signatures and docstrings:
- def get_health_by_date(cls, user, range_type, date_str): Get queryset of health datas by range :param user: user object :param range_type: dates range type - week, month or year :par... | Implement the Python class `Health` described below.
Class description:
Implement the Health class.
Method signatures and docstrings:
- def get_health_by_date(cls, user, range_type, date_str): Get queryset of health datas by range :param user: user object :param range_type: dates range type - week, month or year :par... | 3e2cf3b28ebcb6f87aa8db4073813eed7b7e3b8b | <|skeleton|>
class Health:
def get_health_by_date(cls, user, range_type, date_str):
"""Get queryset of health datas by range :param user: user object :param range_type: dates range type - week, month or year :param date_str: date string :return: queryset of health datas :rtype: queryset"""
<|body_0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Health:
def get_health_by_date(cls, user, range_type, date_str):
"""Get queryset of health datas by range :param user: user object :param range_type: dates range type - week, month or year :param date_str: date string :return: queryset of health datas :rtype: queryset"""
date_format = get_date... | the_stack_v2_python_sparse | app/health/models.py | v0y/sport-tracker-with-acziwments | train | 1 | |
6d254cd959bb9b5fa458d862289f585bc6f063a2 | [
"L = list(map(int, str(N + 1)))\nres, n = (0, len(L))\n\ndef A(m, n):\n return 1 if n == 0 else A(m, n - 1) * (m - n + 1)\nfor i in range(1, n):\n res += 9 * A(9, i - 1)\ns = set()\nfor i, x in enumerate(L):\n for y in range(0 if i else 1, x):\n if y not in s:\n res += A(9 - i, n - i - 1)... | <|body_start_0|>
L = list(map(int, str(N + 1)))
res, n = (0, len(L))
def A(m, n):
return 1 if n == 0 else A(m, n - 1) * (m - n + 1)
for i in range(1, n):
res += 9 * A(9, i - 1)
s = set()
for i, x in enumerate(L):
for y in range(0 if i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDupDigitsAtMostN(self, N):
""":param N: :return:"""
<|body_0|>
def numDupDigitsAtMostN2(self, N):
"""超时 :param N: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
L = list(map(int, str(N + 1)))
res, n = (0, len(L))
... | stack_v2_sparse_classes_10k_train_000083 | 2,023 | no_license | [
{
"docstring": ":param N: :return:",
"name": "numDupDigitsAtMostN",
"signature": "def numDupDigitsAtMostN(self, N)"
},
{
"docstring": "超时 :param N: :return:",
"name": "numDupDigitsAtMostN2",
"signature": "def numDupDigitsAtMostN2(self, N)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000147 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDupDigitsAtMostN(self, N): :param N: :return:
- def numDupDigitsAtMostN2(self, N): 超时 :param N: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDupDigitsAtMostN(self, N): :param N: :return:
- def numDupDigitsAtMostN2(self, N): 超时 :param N: :return:
<|skeleton|>
class Solution:
def numDupDigitsAtMostN(self, N... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def numDupDigitsAtMostN(self, N):
""":param N: :return:"""
<|body_0|>
def numDupDigitsAtMostN2(self, N):
"""超时 :param N: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numDupDigitsAtMostN(self, N):
""":param N: :return:"""
L = list(map(int, str(N + 1)))
res, n = (0, len(L))
def A(m, n):
return 1 if n == 0 else A(m, n - 1) * (m - n + 1)
for i in range(1, n):
res += 9 * A(9, i - 1)
s = set(... | the_stack_v2_python_sparse | 1012_至少有 1 位重复的数字.py | lovehhf/LeetCode | train | 0 | |
df88988a47b2ecf8fc7e57e0f507b9bc2d8d86ba | [
"N = len(Profits)\n\ndef dfs(i, k, c):\n if k == 0 or i == N:\n return c\n ret = [dfs(i + 1, k, c)]\n if Capital[i] <= c:\n ret.append(dfs(i + 1, k - 1, c + Profits[i]))\n return max(ret)\nreturn dfs(0, k, W)",
"N = len(Profits)\nmemo = {k: W}\ncp = list(sorted(zip(Capital, Profits)))\nf... | <|body_start_0|>
N = len(Profits)
def dfs(i, k, c):
if k == 0 or i == N:
return c
ret = [dfs(i + 1, k, c)]
if Capital[i] <= c:
ret.append(dfs(i + 1, k - 1, c + Profits[i]))
return max(ret)
return dfs(0, k, W)
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 12:26"""
<|body_0|>
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 13:05"""
... | stack_v2_sparse_classes_10k_train_000084 | 12,781 | no_license | [
{
"docstring": "Nov 01, 2020 12:26",
"name": "findMaximizedCapital",
"signature": "def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int"
},
{
"docstring": "Nov 01, 2020 13:05",
"name": "findMaximizedCapital",
"signature": "def findMaximizedCapital... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int: Nov 01, 2020 12:26
- def findMaximizedCapital(self, k: int, W: int, Profits: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int: Nov 01, 2020 12:26
- def findMaximizedCapital(self, k: int, W: int, Profits: List[i... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 12:26"""
<|body_0|>
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 13:05"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 12:26"""
N = len(Profits)
def dfs(i, k, c):
if k == 0 or i == N:
return c
ret = [dfs(i + 1, k, c)]
if Capital[i]... | the_stack_v2_python_sparse | leetcode/solved/502_IPO/solution.py | sungminoh/algorithms | train | 0 | |
44f41e3e839b55150b22276b164efbab1993629d | [
"name = 'test name'\nblock = Block(name)\nself.assertIsNotNone(block)\nself.assertEqual(block.get_name(), name)",
"name = 'test_name'\ndata = ['gamma', 'alpha', 'beta']\ndata_repr = '\\n\\t'.join([str(item) for item in data])\ntarget = 'block {0}:\\n\\t{1}'.format(name, data_repr)\nblock = Block(name)\nfor item i... | <|body_start_0|>
name = 'test name'
block = Block(name)
self.assertIsNotNone(block)
self.assertEqual(block.get_name(), name)
<|end_body_0|>
<|body_start_1|>
name = 'test_name'
data = ['gamma', 'alpha', 'beta']
data_repr = '\n\t'.join([str(item) for item in data])... | Tests for the block class | BlockTest | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockTest:
"""Tests for the block class"""
def test_constructor(self):
"""create an object, tests its name"""
<|body_0|>
def test_repr(self):
"""create a Block object, add some data, check its representation"""
<|body_1|>
def test_str(self):
... | stack_v2_sparse_classes_10k_train_000085 | 8,702 | permissive | [
{
"docstring": "create an object, tests its name",
"name": "test_constructor",
"signature": "def test_constructor(self)"
},
{
"docstring": "create a Block object, add some data, check its representation",
"name": "test_repr",
"signature": "def test_repr(self)"
},
{
"docstring": "... | 4 | null | Implement the Python class `BlockTest` described below.
Class description:
Tests for the block class
Method signatures and docstrings:
- def test_constructor(self): create an object, tests its name
- def test_repr(self): create a Block object, add some data, check its representation
- def test_str(self): create a Blo... | Implement the Python class `BlockTest` described below.
Class description:
Tests for the block class
Method signatures and docstrings:
- def test_constructor(self): create an object, tests its name
- def test_repr(self): create a Block object, add some data, check its representation
- def test_str(self): create a Blo... | e748466a2af9f3388a8b0ed091aa061dbfc752d6 | <|skeleton|>
class BlockTest:
"""Tests for the block class"""
def test_constructor(self):
"""create an object, tests its name"""
<|body_0|>
def test_repr(self):
"""create a Block object, add some data, check its representation"""
<|body_1|>
def test_str(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BlockTest:
"""Tests for the block class"""
def test_constructor(self):
"""create an object, tests its name"""
name = 'test name'
block = Block(name)
self.assertIsNotNone(block)
self.assertEqual(block.get_name(), name)
def test_repr(self):
"""create a B... | the_stack_v2_python_sparse | Python/FiniteStateParser/block.py | gjbex/training-material | train | 130 |
7839938c10c11e00708856e0dc9081aa58c7c434 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | AccionList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccionList:
def get(self):
"""Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una Acción"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
veri... | stack_v2_sparse_classes_10k_train_000086 | 6,129 | no_license | [
{
"docstring": "Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Crear una Acción",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001846 | Implement the Python class `AccionList` described below.
Class description:
Implement the AccionList class.
Method signatures and docstrings:
- def get(self): Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una Acción | Implement the Python class `AccionList` described below.
Class description:
Implement the AccionList class.
Method signatures and docstrings:
- def get(self): Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una Acción
<|skeleton|>
class Acci... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class AccionList:
def get(self):
"""Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una Acción"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccionList:
def get(self):
"""Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset'... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/acciones.py | Telematica/knight-rider | train | 1 | |
f05da35244090f1558fb2b45819531dd1e8f202b | [
"numerOfLists = len(lists)\ninterval = 1\nwhile interval < numerOfLists:\n for idx in range(0, numerOfLists - interval, interval * 2):\n lists[idx] = self.mergeTwoLists(lists[idx], lists[idx + interval])\n interval *= 2\nreturn lists[0] if numerOfLists > 0 else None",
"if not l1 or not l2:\n retur... | <|body_start_0|>
numerOfLists = len(lists)
interval = 1
while interval < numerOfLists:
for idx in range(0, numerOfLists - interval, interval * 2):
lists[idx] = self.mergeTwoLists(lists[idx], lists[idx + interval])
interval *= 2
return lists[0] if n... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
numerOfL... | stack_v2_sparse_classes_10k_train_000087 | 4,614 | permissive | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>... | 20ae1a048eddbc9a32c819cf61258e2b57572f05 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
numerOfLists = len(lists)
interval = 1
while interval < numerOfLists:
for idx in range(0, numerOfLists - interval, interval * 2):
lists[idx] = self.mergeTwoLis... | the_stack_v2_python_sparse | leetcode.com/python/23_Merge_k_Sorted_Lists.py | partho-maple/coding-interview-gym | train | 862 | |
181e254549a4346a3fc907bbc5cd16627bf4660a | [
"self.required_queries, self._enc, self._dec, self.key_len = (required_queries, encrypt, decrypt, key_len)\nself.key = ''\nself.ciphertexts = []",
"self.answered_queries = 0\nself.key = random_string(self.key_len)\nself.ciphertexts = []\nself.win = False",
"self.answered_queries += 1\nc = self._enc(self.key, m)... | <|body_start_0|>
self.required_queries, self._enc, self._dec, self.key_len = (required_queries, encrypt, decrypt, key_len)
self.key = ''
self.ciphertexts = []
<|end_body_0|>
<|body_start_1|>
self.answered_queries = 0
self.key = random_string(self.key_len)
self.ciphertext... | This game tests the integrity of a ciphertext. It is to be used to test to see if the decryption algorithm only decrypts authentic messages that have been sent by the sender. The Adversary has access to an encryption oracle (enc) and a decryption oracle (dec) that it uses to see if it won. | GameINTCTXT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameINTCTXT:
"""This game tests the integrity of a ciphertext. It is to be used to test to see if the decryption algorithm only decrypts authentic messages that have been sent by the sender. The Adversary has access to an encryption oracle (enc) and a decryption oracle (dec) that it uses to see i... | stack_v2_sparse_classes_10k_train_000088 | 2,233 | no_license | [
{
"docstring": ":param encrypt: Encryption function that takes inputs, a key k of key_len length and a message. :param decrypt: Decryption function to match encryption function. :param key_len: Length of key used by encrypt and decrypt.",
"name": "__init__",
"signature": "def __init__(self, required_que... | 4 | stack_v2_sparse_classes_30k_train_002193 | Implement the Python class `GameINTCTXT` described below.
Class description:
This game tests the integrity of a ciphertext. It is to be used to test to see if the decryption algorithm only decrypts authentic messages that have been sent by the sender. The Adversary has access to an encryption oracle (enc) and a decryp... | Implement the Python class `GameINTCTXT` described below.
Class description:
This game tests the integrity of a ciphertext. It is to be used to test to see if the decryption algorithm only decrypts authentic messages that have been sent by the sender. The Adversary has access to an encryption oracle (enc) and a decryp... | 9014f5a9bf7021bef9f5cc4aa5b16424ca83dee9 | <|skeleton|>
class GameINTCTXT:
"""This game tests the integrity of a ciphertext. It is to be used to test to see if the decryption algorithm only decrypts authentic messages that have been sent by the sender. The Adversary has access to an encryption oracle (enc) and a decryption oracle (dec) that it uses to see i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GameINTCTXT:
"""This game tests the integrity of a ciphertext. It is to be used to test to see if the decryption algorithm only decrypts authentic messages that have been sent by the sender. The Adversary has access to an encryption oracle (enc) and a decryption oracle (dec) that it uses to see if it won."""
... | the_stack_v2_python_sparse | src/playcrypt/games/game_int_ctxt.py | UCSDCSE107/playcrypt | train | 2 |
10ecbaf1cfa151fa8a537c81efc3d9b7f87b0d7b | [
"dist = []\nfor i in range(len(points)):\n dist.append(abs(math.sqrt((points[i][0] - 0) ** 2 + (points[i][1] - 0) ** 2)))\ncount = 0\nres = []\nusedIdx = set()\nwhile count < K:\n minSoFar = float('inf')\n selectedIdx = -1\n for m in range(len(dist)):\n if dist[m] < minSoFar and m not in usedIdx:... | <|body_start_0|>
dist = []
for i in range(len(points)):
dist.append(abs(math.sqrt((points[i][0] - 0) ** 2 + (points[i][1] - 0) ** 2)))
count = 0
res = []
usedIdx = set()
while count < K:
minSoFar = float('inf')
selectedIdx = -1
... | https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)"""
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]]"""
<|body_0|>
def kClosest2(self, points, K):
""... | stack_v2_sparse_classes_10k_train_000089 | 1,531 | no_license | [
{
"docstring": ":type points: List[List[int]] :type K: int :rtype: List[List[int]]",
"name": "kClosest",
"signature": "def kClosest(self, points, K)"
},
{
"docstring": ":type points: List[List[int]] :type K: int :rtype: List[List[int]]",
"name": "kClosest2",
"signature": "def kClosest2(s... | 2 | stack_v2_sparse_classes_30k_train_006072 | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)
Method signatures and docstrings:
- def kClosest(self, points, K): :type points: List[List[int]] :type K: int :rtype: List[List[int]]
- def kClose... | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)
Method signatures and docstrings:
- def kClosest(self, points, K): :type points: List[List[int]] :type K: int :rtype: List[List[int]]
- def kClose... | 54d3d9530b25272d4a2e5dc33e7035c44f506dc5 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)"""
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]]"""
<|body_0|>
def kClosest2(self, points, K):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)"""
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]]"""
dist = []
for i in range(len(points)):
dist.append(... | the_stack_v2_python_sparse | old/Session002/General/KClosestPointstoOrigin.py | MaxIakovliev/algorithms | train | 0 |
bc81200a2e2b2f7dba09d85ff95f67f5d367c4ec | [
"self.driver.get(url)\nself.driver.max_window()\nself.driver.find_element(locator.HeaderLocator.about_button).click()\nself.driver.pause(3)\nself.driver.switch_to_window()\nabout_is_dispayed = self.driver.is_display(locator.HeaderLocator.about_title)\nself.driver.pause(3)\ntt_check.assertTrue(about_is_dispayed, '关于... | <|body_start_0|>
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.about_button).click()
self.driver.pause(3)
self.driver.switch_to_window()
about_is_dispayed = self.driver.is_display(locator.HeaderLocator.about_title)
se... | about | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class about:
def test_about(self):
"""测试首页底部关于淘车-跳转,@author:xulanzhong"""
<|body_0|>
def test_contact(self):
"""测试首页底部联系我们-跳转,@author:xulanzhong"""
<|body_1|>
def test_B_lisence(self):
"""测试首页底部营业执照-跳转,@author:xulanzhong"""
<|body_2|>
def ... | stack_v2_sparse_classes_10k_train_000090 | 2,780 | no_license | [
{
"docstring": "测试首页底部关于淘车-跳转,@author:xulanzhong",
"name": "test_about",
"signature": "def test_about(self)"
},
{
"docstring": "测试首页底部联系我们-跳转,@author:xulanzhong",
"name": "test_contact",
"signature": "def test_contact(self)"
},
{
"docstring": "测试首页底部营业执照-跳转,@author:xulanzhong",
... | 5 | stack_v2_sparse_classes_30k_train_001658 | Implement the Python class `about` described below.
Class description:
Implement the about class.
Method signatures and docstrings:
- def test_about(self): 测试首页底部关于淘车-跳转,@author:xulanzhong
- def test_contact(self): 测试首页底部联系我们-跳转,@author:xulanzhong
- def test_B_lisence(self): 测试首页底部营业执照-跳转,@author:xulanzhong
- def tes... | Implement the Python class `about` described below.
Class description:
Implement the about class.
Method signatures and docstrings:
- def test_about(self): 测试首页底部关于淘车-跳转,@author:xulanzhong
- def test_contact(self): 测试首页底部联系我们-跳转,@author:xulanzhong
- def test_B_lisence(self): 测试首页底部营业执照-跳转,@author:xulanzhong
- def tes... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class about:
def test_about(self):
"""测试首页底部关于淘车-跳转,@author:xulanzhong"""
<|body_0|>
def test_contact(self):
"""测试首页底部联系我们-跳转,@author:xulanzhong"""
<|body_1|>
def test_B_lisence(self):
"""测试首页底部营业执照-跳转,@author:xulanzhong"""
<|body_2|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class about:
def test_about(self):
"""测试首页底部关于淘车-跳转,@author:xulanzhong"""
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.about_button).click()
self.driver.pause(3)
self.driver.switch_to_window()
about_is_dispayed =... | the_stack_v2_python_sparse | mc/taochePC/test_crawler/test_homepage/test_about.py | boeai/mc | train | 0 | |
821c348e83d4d88302a77dd12f7e8affaaae89f4 | [
"if counter.probe in probeMap:\n probeMap[counter.probe].append(index)\nelse:\n probeMap.update({counter.probe: [index]})",
"route = Route((counter.probe for counter in counters))\nindex = ProbeIndexFactory.cache.get(route, None)\nif not index:\n probeMap = ProbeMap()\n for i, counter in enumerate(cou... | <|body_start_0|>
if counter.probe in probeMap:
probeMap[counter.probe].append(index)
else:
probeMap.update({counter.probe: [index]})
<|end_body_0|>
<|body_start_1|>
route = Route((counter.probe for counter in counters))
index = ProbeIndexFactory.cache.get(route, ... | Utility class to intern probe map generation | ProbeIndexFactory | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProbeIndexFactory:
"""Utility class to intern probe map generation"""
def _addCounterToMap(probeMap, counter, index):
"""Inserts or updates the gvien counter to the probe map :param counter: Counter to be added :param index: relative index for probes, that got hit many times"""
... | stack_v2_sparse_classes_10k_train_000091 | 4,156 | permissive | [
{
"docstring": "Inserts or updates the gvien counter to the probe map :param counter: Counter to be added :param index: relative index for probes, that got hit many times",
"name": "_addCounterToMap",
"signature": "def _addCounterToMap(probeMap, counter, index)"
},
{
"docstring": "Builds an inst... | 2 | stack_v2_sparse_classes_30k_train_003749 | Implement the Python class `ProbeIndexFactory` described below.
Class description:
Utility class to intern probe map generation
Method signatures and docstrings:
- def _addCounterToMap(probeMap, counter, index): Inserts or updates the gvien counter to the probe map :param counter: Counter to be added :param index: re... | Implement the Python class `ProbeIndexFactory` described below.
Class description:
Utility class to intern probe map generation
Method signatures and docstrings:
- def _addCounterToMap(probeMap, counter, index): Inserts or updates the gvien counter to the probe map :param counter: Counter to be added :param index: re... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class ProbeIndexFactory:
"""Utility class to intern probe map generation"""
def _addCounterToMap(probeMap, counter, index):
"""Inserts or updates the gvien counter to the probe map :param counter: Counter to be added :param index: relative index for probes, that got hit many times"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProbeIndexFactory:
"""Utility class to intern probe map generation"""
def _addCounterToMap(probeMap, counter, index):
"""Inserts or updates the gvien counter to the probe map :param counter: Counter to be added :param index: relative index for probes, that got hit many times"""
if counter... | the_stack_v2_python_sparse | scripts/lib/xpedite/util/probeFactory.py | dendisuhubdy/Xpedite | train | 1 |
3b2535750640970e72fae433871919098381024b | [
"name = name or 'interpolation_2d'\nwith tf.name_scope(name):\n self._xdata = tf.convert_to_tensor(x_data, dtype=dtype, name='x_data')\n self._dtype = dtype or self._xdata.dtype\n self._ydata = tf.convert_to_tensor(y_data, dtype=self._dtype, name='y_data')\n self._zdata = tf.convert_to_tensor(z_data, dt... | <|body_start_0|>
name = name or 'interpolation_2d'
with tf.name_scope(name):
self._xdata = tf.convert_to_tensor(x_data, dtype=dtype, name='x_data')
self._dtype = dtype or self._xdata.dtype
self._ydata = tf.convert_to_tensor(y_data, dtype=self._dtype, name='y_data')
... | Performs interpolation in a 2-dimensional space. For input `x_data` in x-direction we assume that values in y-direction are given by `y_data` and the corresponding function values by `z_data`. For given `x` and `y` along x- and y- direction respectively, the interpolated function values are computed on grid `[x, y]`. T... | Interpolation2D | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interpolation2D:
"""Performs interpolation in a 2-dimensional space. For input `x_data` in x-direction we assume that values in y-direction are given by `y_data` and the corresponding function values by `z_data`. For given `x` and `y` along x- and y- direction respectively, the interpolated funct... | stack_v2_sparse_classes_10k_train_000092 | 6,894 | permissive | [
{
"docstring": "Initialize the 2d-interpolation object. Args: x_data: A `Tensor` of real `dtype` and shape `batch_shape + [num_x_data_points]`. Defines the x-coordinates of the input data. `num_x_data_points` should be >= 2. The elements of `x_data` should be in a non-decreasing order. y_data: A `Tensor` of the... | 2 | null | Implement the Python class `Interpolation2D` described below.
Class description:
Performs interpolation in a 2-dimensional space. For input `x_data` in x-direction we assume that values in y-direction are given by `y_data` and the corresponding function values by `z_data`. For given `x` and `y` along x- and y- directi... | Implement the Python class `Interpolation2D` described below.
Class description:
Performs interpolation in a 2-dimensional space. For input `x_data` in x-direction we assume that values in y-direction are given by `y_data` and the corresponding function values by `z_data`. For given `x` and `y` along x- and y- directi... | 0d3a2193c0f2d320b65e602cf01d7a617da484df | <|skeleton|>
class Interpolation2D:
"""Performs interpolation in a 2-dimensional space. For input `x_data` in x-direction we assume that values in y-direction are given by `y_data` and the corresponding function values by `z_data`. For given `x` and `y` along x- and y- direction respectively, the interpolated funct... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Interpolation2D:
"""Performs interpolation in a 2-dimensional space. For input `x_data` in x-direction we assume that values in y-direction are given by `y_data` and the corresponding function values by `z_data`. For given `x` and `y` along x- and y- direction respectively, the interpolated function values ar... | the_stack_v2_python_sparse | tf_quant_finance/math/interpolation/interpolation_2d/interpolation_2d.py | google/tf-quant-finance | train | 4,165 |
91f925c0e4c58ba9917fab7f24a322f19a3d1c88 | [
"for row in matrix:\n for col in range(1, len(row)):\n row[col] += row[col - 1]\nself.matrix = matrix",
"original = self.matrix[row][col]\nif col != 0:\n original -= self.matrix[row][col - 1]\ndiff = original - val\nfor y in range(col, len(self.matrix[0])):\n self.matrix[row][y] -= diff",
"sum =... | <|body_start_0|>
for row in matrix:
for col in range(1, len(row)):
row[col] += row[col - 1]
self.matrix = matrix
<|end_body_0|>
<|body_start_1|>
original = self.matrix[row][col]
if col != 0:
original -= self.matrix[row][col - 1]
diff = ori... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void"""
... | stack_v2_sparse_classes_10k_train_000093 | 1,212 | permissive | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void",
"name": "update",
... | 3 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def update(self, row, col, val): update the element at matrix[row,col] to val. ... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def update(self, row, col, val): update the element at matrix[row,col] to val. ... | 0de1af607557d95856f0e4c2a12a56c8c57d731d | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
for row in matrix:
for col in range(1, len(row)):
row[col] += row[col - 1]
self.matrix = matrix
def update(self, row, col, val):
"""u... | the_stack_v2_python_sparse | solutions/python3/308.py | jxhangithub/leetcode | train | 1 | |
76f9b2dabf8e91810c16c02f10edc48858557929 | [
"input_shapes = [input_shape] if isinstance(input_shape, tuple) else input_shape\nrand_min, rand_max = rand_range\nself.sample_input = tuple([((rand_max - rand_min) * torch.rand(*input_shape) + rand_min).type(input_dtype) for input_shape in input_shapes])\nself.num_trials = num_trials\nself.num_input_per_trial = nu... | <|body_start_0|>
input_shapes = [input_shape] if isinstance(input_shape, tuple) else input_shape
rand_min, rand_max = rand_range
self.sample_input = tuple([((rand_max - rand_min) * torch.rand(*input_shape) + rand_min).type(input_dtype) for input_shape in input_shapes])
self.num_trials = ... | AvgOnnxLatency | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvgOnnxLatency:
def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None):
"""Measure the... | stack_v2_sparse_classes_10k_train_000094 | 4,455 | permissive | [
{
"docstring": "Measure the average ONNX Latency (in millseconds) of a model Args: input_shape (Union[Tuple, List[Tuple]]): Model Input shape or list of model input shapes. num_trials (int, optional): Number of trials. Defaults to 15. num_input (int, optional): Number of input per trial. Defaults to 15. input_d... | 3 | null | Implement the Python class `AvgOnnxLatency` described below.
Class description:
Implement the AvgOnnxLatency class.
Method signatures and docstrings:
- def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float... | Implement the Python class `AvgOnnxLatency` described below.
Class description:
Implement the AvgOnnxLatency class.
Method signatures and docstrings:
- def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float... | 95d6e19a1523a701b3fbc249dd1a7d1e7ba44aee | <|skeleton|>
class AvgOnnxLatency:
def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None):
"""Measure the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AvgOnnxLatency:
def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None):
"""Measure the average ONNX ... | the_stack_v2_python_sparse | tasks/facial_landmark_detection/latency.py | microsoft/archai | train | 439 | |
daa3f6113876514e274699cd404d39b40f3807da | [
"result = []\nfor a in A:\n al, ar = (a[0], a[1])\n for b in B:\n bl, br = (b[0], b[1])\n if bl > ar:\n break\n if br < al:\n continue\n l = max(al, bl)\n r = min(ar, br)\n result.append([l, r])\nreturn result",
"i = 0\nj = 0\nresult = []\nwhil... | <|body_start_0|>
result = []
for a in A:
al, ar = (a[0], a[1])
for b in B:
bl, br = (b[0], b[1])
if bl > ar:
break
if br < al:
continue
l = max(al, bl)
r = min(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
<|body_0|>
def rewrite(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)"""
<... | stack_v2_sparse_classes_10k_train_000095 | 2,879 | no_license | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)",
"name": "intervalIntersection",
"signature": "def intervalIntersection(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)",
"name":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intervalIntersection(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)
- def rewrite(self, A, B): :type A: List[List[int]] :type B... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intervalIntersection(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)
- def rewrite(self, A, B): :type A: List[List[int]] :type B... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
<|body_0|>
def rewrite(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)"""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
result = []
for a in A:
al, ar = (a[0], a[1])
for b in B:
bl, br = (b[0], b[1])
if bl > ar:
... | the_stack_v2_python_sparse | two-pointers/986_Interval_List_Intersections.py | vsdrun/lc_public | train | 6 | |
5f35675176be57dcdab55b546f372315a571762a | [
"super().__init__()\nutils.check_file_readable(model_file)\nself.model = None\nwith open(model_file, 'rb') as icstream:\n try:\n self.model = pickle.load(icstream)\n except Exception as e:\n raise CaughtException('Exception encountered when loading the classifier: {}'.format(e))\nself.name = typ... | <|body_start_0|>
super().__init__()
utils.check_file_readable(model_file)
self.model = None
with open(model_file, 'rb') as icstream:
try:
self.model = pickle.load(icstream)
except Exception as e:
raise CaughtException('Exception enc... | Class used to load classification models and to predict class and class-probability for new documents. | LoadClassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadClassifier:
"""Class used to load classification models and to predict class and class-probability for new documents."""
def __init__(self, model_file):
"""Load classifier model from binary file"""
<|body_0|>
def classify_doc(self, feat):
"""Test the classifi... | stack_v2_sparse_classes_10k_train_000096 | 3,842 | permissive | [
{
"docstring": "Load classifier model from binary file",
"name": "__init__",
"signature": "def __init__(self, model_file)"
},
{
"docstring": "Test the classifier on a new document",
"name": "classify_doc",
"signature": "def classify_doc(self, feat)"
},
{
"docstring": "Test the cl... | 4 | stack_v2_sparse_classes_30k_train_005605 | Implement the Python class `LoadClassifier` described below.
Class description:
Class used to load classification models and to predict class and class-probability for new documents.
Method signatures and docstrings:
- def __init__(self, model_file): Load classifier model from binary file
- def classify_doc(self, fea... | Implement the Python class `LoadClassifier` described below.
Class description:
Class used to load classification models and to predict class and class-probability for new documents.
Method signatures and docstrings:
- def __init__(self, model_file): Load classifier model from binary file
- def classify_doc(self, fea... | 38dc998e0cf4ef7572d542aafe80f8b95865c464 | <|skeleton|>
class LoadClassifier:
"""Class used to load classification models and to predict class and class-probability for new documents."""
def __init__(self, model_file):
"""Load classifier model from binary file"""
<|body_0|>
def classify_doc(self, feat):
"""Test the classifi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoadClassifier:
"""Class used to load classification models and to predict class and class-probability for new documents."""
def __init__(self, model_file):
"""Load classifier model from binary file"""
super().__init__()
utils.check_file_readable(model_file)
self.model = N... | the_stack_v2_python_sparse | python/lib/xi/ml/classify/load_classifier.py | lorosanu/xi-ml-topicdiscovery | train | 0 |
89d851a8294be9c9e34f072b6714fbb1d600c0d6 | [
"self.keys = keys\nself.default_key = default_key\nself.token_mapping = token_mapping",
"args, kwargs = parse_args(text)\nif len(kwargs) and len(args):\n raise MixOfNamedAndOrderedArgs(text)\nif len(args):\n return self.apply_token_mapping(args, text)\nreturn self.validate_kwargs(kwargs, text)",
"if len(a... | <|body_start_0|>
self.keys = keys
self.default_key = default_key
self.token_mapping = token_mapping
<|end_body_0|>
<|body_start_1|>
args, kwargs = parse_args(text)
if len(kwargs) and len(args):
raise MixOfNamedAndOrderedArgs(text)
if len(args):
re... | Parser for options | Parser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser for options"""
def __init__(self, keys, default_key, token_mapping):
""".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default"""
<|body_0|>
def parse(self, text):
"""Parse argument s... | stack_v2_sparse_classes_10k_train_000097 | 8,680 | permissive | [
{
"docstring": ".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default",
"name": "__init__",
"signature": "def __init__(self, keys, default_key, token_mapping)"
},
{
"docstring": "Parse argument string Args: text (string): argument na... | 4 | stack_v2_sparse_classes_30k_train_007352 | Implement the Python class `Parser` described below.
Class description:
Parser for options
Method signatures and docstrings:
- def __init__(self, keys, default_key, token_mapping): .ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default
- def parse(self, te... | Implement the Python class `Parser` described below.
Class description:
Parser for options
Method signatures and docstrings:
- def __init__(self, keys, default_key, token_mapping): .ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default
- def parse(self, te... | d09e36f0319f5d3ac0b83ee84b8848d2b2e8e481 | <|skeleton|>
class Parser:
"""Parser for options"""
def __init__(self, keys, default_key, token_mapping):
""".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default"""
<|body_0|>
def parse(self, text):
"""Parse argument s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser for options"""
def __init__(self, keys, default_key, token_mapping):
""".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default"""
self.keys = keys
self.default_key = default_key
self.token_mapp... | the_stack_v2_python_sparse | tml/rules/options.py | translationexchange/tml-python | train | 2 |
2144e368dedf96f67f29546dc369bfa62b96a157 | [
"self.op = op\nself.e = e\nself.n = 1\nwhile self.n < length:\n self.n *= 2\nself.dat = [e()] * (2 * self.n - 1)",
"assert len(x_list) <= self.n\nfor i, x in enumerate(x_list):\n self.dat[self.n - 1 + i] = x\nfor i in range(self.n - 2, -1, -1):\n self.dat[i] = self.op(self.dat[2 * i + 1], self.dat[2 * i ... | <|body_start_0|>
self.op = op
self.e = e
self.n = 1
while self.n < length:
self.n *= 2
self.dat = [e()] * (2 * self.n - 1)
<|end_body_0|>
<|body_start_1|>
assert len(x_list) <= self.n
for i, x in enumerate(x_list):
self.dat[self.n - 1 + i]... | SegmentTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentTree:
def __init__(self, length, op=min, e=lambda: 0):
""":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op"""
<|body_0|>
def initialize(self, x_list):
"""initialize data :param x_... | stack_v2_sparse_classes_10k_train_000098 | 3,410 | no_license | [
{
"docstring": ":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op",
"name": "__init__",
"signature": "def __init__(self, length, op=min, e=lambda: 0)"
},
{
"docstring": "initialize data :param x_list: initial values ... | 6 | null | Implement the Python class `SegmentTree` described below.
Class description:
Implement the SegmentTree class.
Method signatures and docstrings:
- def __init__(self, length, op=min, e=lambda: 0): :param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element ... | Implement the Python class `SegmentTree` described below.
Class description:
Implement the SegmentTree class.
Method signatures and docstrings:
- def __init__(self, length, op=min, e=lambda: 0): :param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element ... | 02b0a6c92a05c6858b87cb22623ce877c1039f8f | <|skeleton|>
class SegmentTree:
def __init__(self, length, op=min, e=lambda: 0):
""":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op"""
<|body_0|>
def initialize(self, x_list):
"""initialize data :param x_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SegmentTree:
def __init__(self, length, op=min, e=lambda: 0):
""":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op"""
self.op = op
self.e = e
self.n = 1
while self.n < length:
se... | the_stack_v2_python_sparse | other_contests/abl001/D.py | k-harada/AtCoder | train | 9 | |
558fafbfdeaf967c101e2685d9dce79aea5a5ecc | [
"if data is not None:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) <= 2:\n raise ValueError('data must contain multiple values')\n self.lambtha = float(sum(data) / len(data))\nelse:\n if lambtha <= 0:\n raise ValueError('lambtha must be a ... | <|body_start_0|>
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data must contain multiple values')
self.lambtha = float(sum(data) / len(data))
else:
... | Class Poisson | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Class Poisson"""
def __init__(self, data=None, lambtha=1.0):
"""Constructor"""
<|body_0|>
def pmf(self, k):
"""Calculates the value of the PMF for a given number of successes"""
<|body_1|>
def cdf(self, k):
"""Calculates the value... | stack_v2_sparse_classes_10k_train_000099 | 1,340 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculates the value of the PMF for a given number of successes",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "Calculates the value ... | 3 | stack_v2_sparse_classes_30k_train_003636 | Implement the Python class `Poisson` described below.
Class description:
Class Poisson
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor
- def pmf(self, k): Calculates the value of the PMF for a given number of successes
- def cdf(self, k): Calculates the value of the CDF for... | Implement the Python class `Poisson` described below.
Class description:
Class Poisson
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor
- def pmf(self, k): Calculates the value of the PMF for a given number of successes
- def cdf(self, k): Calculates the value of the CDF for... | f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7 | <|skeleton|>
class Poisson:
"""Class Poisson"""
def __init__(self, data=None, lambtha=1.0):
"""Constructor"""
<|body_0|>
def pmf(self, k):
"""Calculates the value of the PMF for a given number of successes"""
<|body_1|>
def cdf(self, k):
"""Calculates the value... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Poisson:
"""Class Poisson"""
def __init__(self, data=None, lambtha=1.0):
"""Constructor"""
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data must cont... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | jalondono/holbertonschool-machine_learning | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.