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 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d8de9db16b066c37a8d25a442a351a2af76df07 | [
"self.gen = ObservationMetaDataGenerator(database=opsim_db, driver='sqlite')\nif db_config is not None:\n self.db_config = db_config\nelse:\n self.db_config = dict(database='LSSTCATSIM', port=1433, host='fatboy.phys.washington.edu', driver='mssql+pymssql')\nif logger is None:\n logging.basicConfig(format='... | <|body_start_0|>
self.gen = ObservationMetaDataGenerator(database=opsim_db, driver='sqlite')
if db_config is not None:
self.db_config = db_config
else:
self.db_config = dict(database='LSSTCATSIM', port=1433, host='fatboy.phys.washington.edu', driver='mssql+pymssql')
... | Class for creating instance catalogs. Attributes ---------- gen : lsst.sims.catUtils.utils.ObservationMetaDataGenerator db_config : dict Dictionary of database connection parameters. logger : logging.logger Logger object. | InstanceCatalogMaker | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceCatalogMaker:
"""Class for creating instance catalogs. Attributes ---------- gen : lsst.sims.catUtils.utils.ObservationMetaDataGenerator db_config : dict Dictionary of database connection parameters. logger : logging.logger Logger object."""
def __init__(self, opsim_db, db_config=Non... | stack_v2_sparse_classes_75kplus_train_008500 | 4,395 | permissive | [
{
"docstring": "Constructor. Parameters ---------- opsim_db : str sqlite3 db file containing observing plan. db_config : dict, optional Dictionary of database connection parameters. Parameters for connecting to fatboy.phys.washington.edu from a whitelisted machine will be used. logger : logging.logger, optional... | 2 | null | Implement the Python class `InstanceCatalogMaker` described below.
Class description:
Class for creating instance catalogs. Attributes ---------- gen : lsst.sims.catUtils.utils.ObservationMetaDataGenerator db_config : dict Dictionary of database connection parameters. logger : logging.logger Logger object.
Method sig... | Implement the Python class `InstanceCatalogMaker` described below.
Class description:
Class for creating instance catalogs. Attributes ---------- gen : lsst.sims.catUtils.utils.ObservationMetaDataGenerator db_config : dict Dictionary of database connection parameters. logger : logging.logger Logger object.
Method sig... | faf7fb09801408c9abc3b03790cf4b8cc6ac10c1 | <|skeleton|>
class InstanceCatalogMaker:
"""Class for creating instance catalogs. Attributes ---------- gen : lsst.sims.catUtils.utils.ObservationMetaDataGenerator db_config : dict Dictionary of database connection parameters. logger : logging.logger Logger object."""
def __init__(self, opsim_db, db_config=Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceCatalogMaker:
"""Class for creating instance catalogs. Attributes ---------- gen : lsst.sims.catUtils.utils.ObservationMetaDataGenerator db_config : dict Dictionary of database connection parameters. logger : logging.logger Logger object."""
def __init__(self, opsim_db, db_config=None, logger=Non... | the_stack_v2_python_sparse | python/desc/imsimdeep/InstanceCatalogMaker.py | jchiang87/ImSimDeep | train | 1 |
932a276a316295b79aac852162ae8b144dfd4f27 | [
"super().__init__(initial_class_observations, max_features, random_state)\nself._mc_correct_weight = 0.0\nself._nb_correct_weight = 0.0",
"if self._observed_class_distribution == {}:\n if 0 == y:\n self._mc_correct_weight += weight\nelif max(self._observed_class_distribution, key=self._observed_class_di... | <|body_start_0|>
super().__init__(initial_class_observations, max_features, random_state)
self._mc_correct_weight = 0.0
self._nb_correct_weight = 0.0
<|end_body_0|>
<|body_start_1|>
if self._observed_class_distribution == {}:
if 0 == y:
self._mc_correct_weigh... | Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instance or None, optional (default=None) If int, random_state ... | RandomLearningNodeNBAdaptive | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomLearningNodeNBAdaptive:
"""Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instanc... | stack_v2_sparse_classes_75kplus_train_008501 | 2,832 | permissive | [
{
"docstring": "LearningNodeNBAdaptive class constructor.",
"name": "__init__",
"signature": "def __init__(self, initial_class_observations, max_features, random_state)"
},
{
"docstring": "Update the node with the provided instance. Parameters ---------- X: numpy.ndarray of length equal to the n... | 3 | stack_v2_sparse_classes_30k_train_006788 | Implement the Python class `RandomLearningNodeNBAdaptive` described below.
Class description:
Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split.... | Implement the Python class `RandomLearningNodeNBAdaptive` described below.
Class description:
Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split.... | bfe504b4ca24b77e211fd55dc42844fc494671d7 | <|skeleton|>
class RandomLearningNodeNBAdaptive:
"""Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instanc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomLearningNodeNBAdaptive:
"""Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instance or None, op... | the_stack_v2_python_sparse | src/skmultiflow/trees/nodes/random_learning_node_nb_adaptive.py | jacobmontiel/scikit-multiflow | train | 1 |
d05e415bd767d5bb4af4da244278ab6cac05b01f | [
"if root.left == None and root.right == None:\n if partial_sum + root.val == target:\n res.append(partial_path + [root.val])\n return\nif root.left:\n self._pathSum(root.left, target, partial_path + [root.val], partial_sum + root.val, res)\nif root.right:\n self._pathSum(root.right, target, parti... | <|body_start_0|>
if root.left == None and root.right == None:
if partial_sum + root.val == target:
res.append(partial_path + [root.val])
return
if root.left:
self._pathSum(root.left, target, partial_path + [root.val], partial_sum + root.val, res)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _pathSum(self, root, target, partial_path, partial_sum, res):
""":type root: TreeNode :type target: int :type partial_path: List(int) :type partial_sum: int"""
<|body_0|>
def pathSum(self, root, target):
""":type root: TreeNode :type sum: int :rtype: Li... | stack_v2_sparse_classes_75kplus_train_008502 | 1,369 | no_license | [
{
"docstring": ":type root: TreeNode :type target: int :type partial_path: List(int) :type partial_sum: int",
"name": "_pathSum",
"signature": "def _pathSum(self, root, target, partial_path, partial_sum, res)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]",
"... | 2 | stack_v2_sparse_classes_30k_test_001852 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _pathSum(self, root, target, partial_path, partial_sum, res): :type root: TreeNode :type target: int :type partial_path: List(int) :type partial_sum: int
- def pathSum(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _pathSum(self, root, target, partial_path, partial_sum, res): :type root: TreeNode :type target: int :type partial_path: List(int) :type partial_sum: int
- def pathSum(self, ... | cd3900a7d91d1d94d308bc7a65533b8262781ee9 | <|skeleton|>
class Solution:
def _pathSum(self, root, target, partial_path, partial_sum, res):
""":type root: TreeNode :type target: int :type partial_path: List(int) :type partial_sum: int"""
<|body_0|>
def pathSum(self, root, target):
""":type root: TreeNode :type sum: int :rtype: Li... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _pathSum(self, root, target, partial_path, partial_sum, res):
""":type root: TreeNode :type target: int :type partial_path: List(int) :type partial_sum: int"""
if root.left == None and root.right == None:
if partial_sum + root.val == target:
res.append... | the_stack_v2_python_sparse | lc0113_PathSumII/lc0113.py | cgi0911/LeetCodePractice | train | 0 | |
c9105be84266e37810cd3ec86e9823d77b0504cb | [
"super().__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(target_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"seq_len = x.s... | <|body_start_0|>
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(target_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, dm)
self.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
self.d... | Decoder class | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder class"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""Init method Args: N: number of blocks in the encode dm: dimensionality of the model h: number of heads hidden: number of hidden units in the fully connected layer target_vo... | stack_v2_sparse_classes_75kplus_train_008503 | 2,350 | no_license | [
{
"docstring": "Init method Args: N: number of blocks in the encode dm: dimensionality of the model h: number of heads hidden: number of hidden units in the fully connected layer target_vocab: size of the target vocabulary max_seq_len: maximum sequence length possible drop_rate: dropout rate",
"name": "__in... | 2 | stack_v2_sparse_classes_30k_train_028052 | Implement the Python class `Decoder` described below.
Class description:
Decoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): Init method Args: N: number of blocks in the encode dm: dimensionality of the model h: number of heads hidden: numb... | Implement the Python class `Decoder` described below.
Class description:
Decoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): Init method Args: N: number of blocks in the encode dm: dimensionality of the model h: number of heads hidden: numb... | 7f9a040f23eda32c5aa154c991c930a01b490f0f | <|skeleton|>
class Decoder:
"""Decoder class"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""Init method Args: N: number of blocks in the encode dm: dimensionality of the model h: number of heads hidden: number of hidden units in the fully connected layer target_vo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""Decoder class"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""Init method Args: N: number of blocks in the encode dm: dimensionality of the model h: number of heads hidden: number of hidden units in the fully connected layer target_vocab: size of ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/10-transformer_decoder.py | dbaroli/holbertonschool-machine_learning | train | 0 |
2d6c9660aa12c47b11e1c9855ea4c35387fb17b7 | [
"self.exact_dates = exact_dates\nself.granularity = granularity\nself.multiplier = multiplier",
"if dictionary is None:\n return None\nexact_dates = cohesity_management_sdk.models.granularity_bucket_exact_dates_info.GranularityBucket_ExactDatesInfo.from_dictionary(dictionary.get('exactDates')) if dictionary.ge... | <|body_start_0|>
self.exact_dates = exact_dates
self.granularity = granularity
self.multiplier = multiplier
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
exact_dates = cohesity_management_sdk.models.granularity_bucket_exact_dates_info.Granularity... | Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequence of specific dates on which snapshots need ... | GranularityBucket | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GranularityBucket:
"""Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequen... | stack_v2_sparse_classes_75kplus_train_008504 | 2,889 | permissive | [
{
"docstring": "Constructor for the GranularityBucket class",
"name": "__init__",
"signature": "def __init__(self, exact_dates=None, granularity=None, multiplier=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representati... | 2 | stack_v2_sparse_classes_30k_train_054267 | Implement the Python class `GranularityBucket` described below.
Class description:
Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for ... | Implement the Python class `GranularityBucket` described below.
Class description:
Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GranularityBucket:
"""Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GranularityBucket:
"""Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequence of specifi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/granularity_bucket.py | cohesity/management-sdk-python | train | 24 |
c762a5a20d89ef6ab11fe292d2a37ae12ede3ca4 | [
"self._hass = hass\nself._store = Store[dict[str, dict[str, bool | Orientation]]](hass, STORAGE_VERSION, STORAGE_KEY)\nself._dynamic_stream_settings_by_entity_id: dict[str, DynamicStreamSettings] = {}",
"dynamic_stream_settings = self._dynamic_stream_settings_by_entity_id.get(entity_id)\nif preload_stream is not ... | <|body_start_0|>
self._hass = hass
self._store = Store[dict[str, dict[str, bool | Orientation]]](hass, STORAGE_VERSION, STORAGE_KEY)
self._dynamic_stream_settings_by_entity_id: dict[str, DynamicStreamSettings] = {}
<|end_body_0|>
<|body_start_1|>
dynamic_stream_settings = self._dynamic_... | Handle camera preferences. | CameraPreferences | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraPreferences:
"""Handle camera preferences."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize camera prefs."""
<|body_0|>
async def async_update(self, entity_id: str, *, preload_stream: bool | UndefinedType=UNDEFINED, orientation: Orientation | Undef... | stack_v2_sparse_classes_75kplus_train_008505 | 4,020 | permissive | [
{
"docstring": "Initialize camera prefs.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Update camera preferences. Also update the DynamicStreamSettings if they exist. preload_stream is stored in a Store orientation is stored in the Entity... | 3 | stack_v2_sparse_classes_30k_val_000634 | Implement the Python class `CameraPreferences` described below.
Class description:
Handle camera preferences.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize camera prefs.
- async def async_update(self, entity_id: str, *, preload_stream: bool | UndefinedType=UNDEFINED, ... | Implement the Python class `CameraPreferences` described below.
Class description:
Handle camera preferences.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize camera prefs.
- async def async_update(self, entity_id: str, *, preload_stream: bool | UndefinedType=UNDEFINED, ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class CameraPreferences:
"""Handle camera preferences."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize camera prefs."""
<|body_0|>
async def async_update(self, entity_id: str, *, preload_stream: bool | UndefinedType=UNDEFINED, orientation: Orientation | Undef... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CameraPreferences:
"""Handle camera preferences."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize camera prefs."""
self._hass = hass
self._store = Store[dict[str, dict[str, bool | Orientation]]](hass, STORAGE_VERSION, STORAGE_KEY)
self._dynamic_stream_sett... | the_stack_v2_python_sparse | homeassistant/components/camera/prefs.py | home-assistant/core | train | 35,501 |
e81dcade28143069fea74dcfb74840813b0735bd | [
"assert ConfHelper.loaded\nif method.upper() not in HTTP.METHOD:\n return cls.DUMMY_RESPONSE\nelse:\n args['method'] = method.upper()\n return BaseHelper.forward(cls, url, args, ConfHelper.GF_SENDER_CONF.url, HTTP.METHOD.POST)",
"assert ConfHelper.loaded\n\ndef _callback(response):\n if isinstance(res... | <|body_start_0|>
assert ConfHelper.loaded
if method.upper() not in HTTP.METHOD:
return cls.DUMMY_RESPONSE
else:
args['method'] = method.upper()
return BaseHelper.forward(cls, url, args, ConfHelper.GF_SENDER_CONF.url, HTTP.METHOD.POST)
<|end_body_0|>
<|body_st... | GFSenderHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GFSenderHelper:
def forward(cls, url, args, method=HTTP.METHOD.POST):
"""Forward the request in block most (sync mode) to sender. This means I will wait for the response from sender, which would block following requests. This should be avoided in uweb."""
<|body_0|>
def asyn... | stack_v2_sparse_classes_75kplus_train_008506 | 3,703 | no_license | [
{
"docstring": "Forward the request in block most (sync mode) to sender. This means I will wait for the response from sender, which would block following requests. This should be avoided in uweb.",
"name": "forward",
"signature": "def forward(cls, url, args, method=HTTP.METHOD.POST)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_032414 | Implement the Python class `GFSenderHelper` described below.
Class description:
Implement the GFSenderHelper class.
Method signatures and docstrings:
- def forward(cls, url, args, method=HTTP.METHOD.POST): Forward the request in block most (sync mode) to sender. This means I will wait for the response from sender, wh... | Implement the Python class `GFSenderHelper` described below.
Class description:
Implement the GFSenderHelper class.
Method signatures and docstrings:
- def forward(cls, url, args, method=HTTP.METHOD.POST): Forward the request in block most (sync mode) to sender. This means I will wait for the response from sender, wh... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class GFSenderHelper:
def forward(cls, url, args, method=HTTP.METHOD.POST):
"""Forward the request in block most (sync mode) to sender. This means I will wait for the response from sender, which would block following requests. This should be avoided in uweb."""
<|body_0|>
def asyn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GFSenderHelper:
def forward(cls, url, args, method=HTTP.METHOD.POST):
"""Forward the request in block most (sync mode) to sender. This means I will wait for the response from sender, which would block following requests. This should be avoided in uweb."""
assert ConfHelper.loaded
if me... | the_stack_v2_python_sparse | libs/helpers/gfsenderhelper.py | jcsy521/ydws | train | 0 | |
35e30564beee711248356674df33105bfab06daa | [
"bitstream_timestamp = PL.timestamp\nif bitstream_timestamp != _InterruptController._last_timestamp:\n _InterruptController._controllers.clear()\n _InterruptController._last_timestamp = bitstream_timestamp\nfor con in _InterruptController._controllers:\n if con.name == name:\n return con\nret = _Int... | <|body_start_0|>
bitstream_timestamp = PL.timestamp
if bitstream_timestamp != _InterruptController._last_timestamp:
_InterruptController._controllers.clear()
_InterruptController._last_timestamp = bitstream_timestamp
for con in _InterruptController._controllers:
... | Class that interacts with an AXI interrupt controller This class is not designed to be interacted with by end users directly - most uses will be via the register_interrupt API which will handle the creation and registration of _InterruptController instances | _InterruptController | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _InterruptController:
"""Class that interacts with an AXI interrupt controller This class is not designed to be interacted with by end users directly - most uses will be via the register_interrupt API which will handle the creation and registration of _InterruptController instances"""
def ge... | stack_v2_sparse_classes_75kplus_train_008507 | 9,140 | permissive | [
{
"docstring": "Returns the _InterruptController corresponding to the AXI interrupt controller with the specified name. Will invalidate all interrupt controllers if the Overlay has been changed. Should not be accessed by user code. Parameters ---------- name : str Name of the interrupt controller to return",
... | 5 | stack_v2_sparse_classes_30k_train_000740 | Implement the Python class `_InterruptController` described below.
Class description:
Class that interacts with an AXI interrupt controller This class is not designed to be interacted with by end users directly - most uses will be via the register_interrupt API which will handle the creation and registration of _Inter... | Implement the Python class `_InterruptController` described below.
Class description:
Class that interacts with an AXI interrupt controller This class is not designed to be interacted with by end users directly - most uses will be via the register_interrupt API which will handle the creation and registration of _Inter... | 38e9fcee46f0839e83e123cf22af76b13671a574 | <|skeleton|>
class _InterruptController:
"""Class that interacts with an AXI interrupt controller This class is not designed to be interacted with by end users directly - most uses will be via the register_interrupt API which will handle the creation and registration of _InterruptController instances"""
def ge... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _InterruptController:
"""Class that interacts with an AXI interrupt controller This class is not designed to be interacted with by end users directly - most uses will be via the register_interrupt API which will handle the creation and registration of _InterruptController instances"""
def get_controller(... | the_stack_v2_python_sparse | pynq/interrupt.py | yunqu/PYNQ | train | 8 |
443f5ddf5ef4a27803bc4e521401554eab237717 | [
"user_attribute = is_user_attribute('facebook_id')\nif user_attribute:\n user = self.user_authenticate(facebook_id, facebook_email)\nelse:\n user = self.profile_authenticate(facebook_id, facebook_email)\nreturn user",
"user_model = get_user_model()\nif facebook_id or facebook_email:\n auth_conditions = [... | <|body_start_0|>
user_attribute = is_user_attribute('facebook_id')
if user_attribute:
user = self.user_authenticate(facebook_id, facebook_email)
else:
user = self.profile_authenticate(facebook_id, facebook_email)
return user
<|end_body_0|>
<|body_start_1|>
... | Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid) | FacebookBackend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacebookBackend:
"""Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid)"""
def authenticate(... | stack_v2_sparse_classes_75kplus_train_008508 | 5,121 | permissive | [
{
"docstring": "Route to either the user or profile table depending on which type of user customization we are using (profile was used in Django < 1.5, user is the new way in 1.5 and up)",
"name": "authenticate",
"signature": "def authenticate(self, facebook_id=None, facebook_email=None)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_009916 | Implement the Python class `FacebookBackend` described below.
Class description:
Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(face... | Implement the Python class `FacebookBackend` described below.
Class description:
Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(face... | 89ddaae491a5110bb707567df41479f650f22f81 | <|skeleton|>
class FacebookBackend:
"""Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid)"""
def authenticate(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FacebookBackend:
"""Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid)"""
def authenticate(self, faceboo... | the_stack_v2_python_sparse | django_facebook/auth_backends.py | RebelTat/Django-facebook | train | 1 |
34715680dae98590f8067879e02bd96b78a0e62e | [
"if config['type'] != 'periodic':\n raise IncorrectConfig('Не верный тип анимации, должен быть periodic, а передан {}'.format(config['type']))\nsource = load_image(config['file'])\ntry:\n return PeriodicAnimation(crop_image(source, config['coords'], flip_x, flip_y), config['period'], adaptive_width=adaptive_w... | <|body_start_0|>
if config['type'] != 'periodic':
raise IncorrectConfig('Не верный тип анимации, должен быть periodic, а передан {}'.format(config['type']))
source = load_image(config['file'])
try:
return PeriodicAnimation(crop_image(source, config['coords'], flip_x, flip... | Загрузчик анимаций Содержит много статических методов, которые загружают разные анимации TODO: дописать загрузчики :raises : | AnimationLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnimationLoader:
"""Загрузчик анимаций Содержит много статических методов, которые загружают разные анимации TODO: дописать загрузчики :raises :"""
def load_periodic_animation(config, flip_x=False, flip_y=True, adaptive_width=True, adaptive_height=False, name=''):
"""Конфигурация дол... | stack_v2_sparse_classes_75kplus_train_008509 | 31,579 | no_license | [
{
"docstring": "Конфигурация должна быть словарём со следущими ключами: 'type': 'periodic' # вот тут строго 'locking': true/false # определяет, является ли анимация блокирующей 'file': путь до файла со спрайтами 'period': период анимации 'coords': список кропов картинки :param name: Название анимации :param con... | 3 | null | Implement the Python class `AnimationLoader` described below.
Class description:
Загрузчик анимаций Содержит много статических методов, которые загружают разные анимации TODO: дописать загрузчики :raises :
Method signatures and docstrings:
- def load_periodic_animation(config, flip_x=False, flip_y=True, adaptive_widt... | Implement the Python class `AnimationLoader` described below.
Class description:
Загрузчик анимаций Содержит много статических методов, которые загружают разные анимации TODO: дописать загрузчики :raises :
Method signatures and docstrings:
- def load_periodic_animation(config, flip_x=False, flip_y=True, adaptive_widt... | 55e5b4bdadaf713ee0365da880e1bd000ed0bc33 | <|skeleton|>
class AnimationLoader:
"""Загрузчик анимаций Содержит много статических методов, которые загружают разные анимации TODO: дописать загрузчики :raises :"""
def load_periodic_animation(config, flip_x=False, flip_y=True, adaptive_width=True, adaptive_height=False, name=''):
"""Конфигурация дол... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnimationLoader:
"""Загрузчик анимаций Содержит много статических методов, которые загружают разные анимации TODO: дописать загрузчики :raises :"""
def load_periodic_animation(config, flip_x=False, flip_y=True, adaptive_width=True, adaptive_height=False, name=''):
"""Конфигурация должна быть слов... | the_stack_v2_python_sparse | Engine/Scene/animations.py | dimon58/NeedForOtl10 | train | 3 |
e89f669ef8fc4c950b6a3d70901a9dbfa4b24c0e | [
"dp = [[math.inf] * (N + 1) for _ in range(K + 1)]\nfor i in range(1, K + 1):\n dp[i][0] = 0\n dp[i][1] = 1\nfor j in range(1, N + 1):\n dp[1][j] = j\nfor i in range(2, K + 1):\n for j in range(2, N + 1):\n for k in range(1, j + 1):\n dp[i][j] = min(dp[i][j], 1 + max(dp[i - 1][k - 1], ... | <|body_start_0|>
dp = [[math.inf] * (N + 1) for _ in range(K + 1)]
for i in range(1, K + 1):
dp[i][0] = 0
dp[i][1] = 1
for j in range(1, N + 1):
dp[1][j] = j
for i in range(2, K + 1):
for j in range(2, N + 1):
for k in range... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def superEggDrop_solution_1_brute_force(self, K: int, N: int) -> int:
""":type K: int :type N: int :rtype: int"""
<|body_0|>
def superEggDrop_solution_2_optimization_one(self, K: int, N: int) -> int:
""":type K: int :type N: int :rtype: int"""
<|bod... | stack_v2_sparse_classes_75kplus_train_008510 | 7,392 | no_license | [
{
"docstring": ":type K: int :type N: int :rtype: int",
"name": "superEggDrop_solution_1_brute_force",
"signature": "def superEggDrop_solution_1_brute_force(self, K: int, N: int) -> int"
},
{
"docstring": ":type K: int :type N: int :rtype: int",
"name": "superEggDrop_solution_2_optimization_... | 4 | stack_v2_sparse_classes_30k_train_032972 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def superEggDrop_solution_1_brute_force(self, K: int, N: int) -> int: :type K: int :type N: int :rtype: int
- def superEggDrop_solution_2_optimization_one(self, K: int, N: int) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def superEggDrop_solution_1_brute_force(self, K: int, N: int) -> int: :type K: int :type N: int :rtype: int
- def superEggDrop_solution_2_optimization_one(self, K: int, N: int) -... | f2621cd76822a922c49b60f32931f26cce1c571d | <|skeleton|>
class Solution:
def superEggDrop_solution_1_brute_force(self, K: int, N: int) -> int:
""":type K: int :type N: int :rtype: int"""
<|body_0|>
def superEggDrop_solution_2_optimization_one(self, K: int, N: int) -> int:
""":type K: int :type N: int :rtype: int"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def superEggDrop_solution_1_brute_force(self, K: int, N: int) -> int:
""":type K: int :type N: int :rtype: int"""
dp = [[math.inf] * (N + 1) for _ in range(K + 1)]
for i in range(1, K + 1):
dp[i][0] = 0
dp[i][1] = 1
for j in range(1, N + 1):
... | the_stack_v2_python_sparse | Dynamic_Programming/019_leetcode_P_887_SuperEggDrop/Solution.py | Keshav1506/competitive_programming | train | 0 | |
a3da3f9721ed5ac40759f4bd0db2597a7dc0655a | [
"if _refstate[self.atomicnumber]['symmetry'] != self.xtal_name:\n raise ValueError(('Cannot guess the %s lattice constant of' + ' an element with crystal structure %s.') % (self.xtal_name, _refstate[self.atomicnumber]['symmetry']))\nreturn _refstate[self.atomicnumber].copy()",
"lattice = self.latticeconstant\n... | <|body_start_0|>
if _refstate[self.atomicnumber]['symmetry'] != self.xtal_name:
raise ValueError(('Cannot guess the %s lattice constant of' + ' an element with crystal structure %s.') % (self.xtal_name, _refstate[self.atomicnumber]['symmetry']))
return _refstate[self.atomicnumber].copy()
<|e... | A factory for creating simple orthorhombic lattices. | SimpleOrthorhombicFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleOrthorhombicFactory:
"""A factory for creating simple orthorhombic lattices."""
def get_lattice_constant(self):
"""Get the lattice constant of an element with orhtorhombic crystal structure."""
<|body_0|>
def make_crystal_basis(self):
"""Make the basis matr... | stack_v2_sparse_classes_75kplus_train_008511 | 5,433 | no_license | [
{
"docstring": "Get the lattice constant of an element with orhtorhombic crystal structure.",
"name": "get_lattice_constant",
"signature": "def get_lattice_constant(self)"
},
{
"docstring": "Make the basis matrix for the crystal unit cell and the system unit cell.",
"name": "make_crystal_bas... | 3 | stack_v2_sparse_classes_30k_train_046525 | Implement the Python class `SimpleOrthorhombicFactory` described below.
Class description:
A factory for creating simple orthorhombic lattices.
Method signatures and docstrings:
- def get_lattice_constant(self): Get the lattice constant of an element with orhtorhombic crystal structure.
- def make_crystal_basis(self)... | Implement the Python class `SimpleOrthorhombicFactory` described below.
Class description:
A factory for creating simple orthorhombic lattices.
Method signatures and docstrings:
- def get_lattice_constant(self): Get the lattice constant of an element with orhtorhombic crystal structure.
- def make_crystal_basis(self)... | 6299b76c0504c5a7f7e94271aba9907a8ce77719 | <|skeleton|>
class SimpleOrthorhombicFactory:
"""A factory for creating simple orthorhombic lattices."""
def get_lattice_constant(self):
"""Get the lattice constant of an element with orhtorhombic crystal structure."""
<|body_0|>
def make_crystal_basis(self):
"""Make the basis matr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleOrthorhombicFactory:
"""A factory for creating simple orthorhombic lattices."""
def get_lattice_constant(self):
"""Get the lattice constant of an element with orhtorhombic crystal structure."""
if _refstate[self.atomicnumber]['symmetry'] != self.xtal_name:
raise ValueErr... | the_stack_v2_python_sparse | venv/Lib/site-packages/ase/lattice/orthorhombic.py | Pratiksha1317/e-shop | train | 0 |
0105d22c35fb6a050827be8722e358b377736591 | [
"query_builder = Configuration.BASE_URI\nquery_builder += '/ws/explore/endemic/species.csv'\nquery_builder = APIHelper.append_url_with_query_parameters(query_builder, {'facets': options.get('facets', None), 'fq': options.get('fq', None), 'q': options.get('q', None), 'wkt': options.get('wkt', None) if options.get('w... | <|body_start_0|>
query_builder = Configuration.BASE_URI
query_builder += '/ws/explore/endemic/species.csv'
query_builder = APIHelper.append_url_with_query_parameters(query_builder, {'facets': options.get('facets', None), 'fq': options.get('fq', None), 'q': options.get('q', None), 'wkt': options.... | A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API. | EndemismController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EndemismController:
"""A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API."""
def get_endemic_species_list__csv(self, options=dict()):
"""Does a GET request to /ws/explore/endemic/species.csv. List endemic species within an area Args: options (dict, opti... | stack_v2_sparse_classes_75kplus_train_008512 | 7,512 | no_license | [
{
"docstring": "Does a GET request to /ws/explore/endemic/species.csv. List endemic species within an area Args: options (dict, optional): Key-value pairs for any of the parameters to this API Endpoint. All parameters to the endpoint are supplied through the dictionary with their names being the key and their d... | 2 | null | Implement the Python class `EndemismController` described below.
Class description:
A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API.
Method signatures and docstrings:
- def get_endemic_species_list__csv(self, options=dict()): Does a GET request to /ws/explore/endemic/species.csv. List... | Implement the Python class `EndemismController` described below.
Class description:
A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API.
Method signatures and docstrings:
- def get_endemic_species_list__csv(self, options=dict()): Does a GET request to /ws/explore/endemic/species.csv. List... | a9f803ea42bef4eb3720d5dd92a53dc98e8f2678 | <|skeleton|>
class EndemismController:
"""A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API."""
def get_endemic_species_list__csv(self, options=dict()):
"""Does a GET request to /ws/explore/endemic/species.csv. List endemic species within an area Args: options (dict, opti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EndemismController:
"""A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API."""
def get_endemic_species_list__csv(self, options=dict()):
"""Does a GET request to /ws/explore/endemic/species.csv. List endemic species within an area Args: options (dict, optional): Key-va... | the_stack_v2_python_sparse | AtlasOfLivingAustraliaOccurrencesLib/Controllers/EndemismController.py | chm052/naturehack | train | 2 |
bf6033ee35a8ce3a33014d6cee07289ddb0e7606 | [
"params = kwargs\nresult = self._client.post('{}/configs'.format(NodeBalancer.api_endpoint), model=self, data=params)\nself.invalidate()\nif not 'id' in result:\n raise UnexpectedResponseError('Unexpected response creating config!', json=result)\nc = NodeBalancerConfig(self._client, result['id'], self.id, result... | <|body_start_0|>
params = kwargs
result = self._client.post('{}/configs'.format(NodeBalancer.api_endpoint), model=self, data=params)
self.invalidate()
if not 'id' in result:
raise UnexpectedResponseError('Unexpected response creating config!', json=result)
c = NodeBal... | A single NodeBalancer you can access. API documentation: https://www.linode.com/docs/api/nodebalancers/#nodebalancer-view | NodeBalancer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeBalancer:
"""A single NodeBalancer you can access. API documentation: https://www.linode.com/docs/api/nodebalancers/#nodebalancer-view"""
def config_create(self, **kwargs):
"""Creates a NodeBalancer Config, which allows the NodeBalancer to accept traffic on a new port. You will n... | stack_v2_sparse_classes_75kplus_train_008513 | 10,592 | permissive | [
{
"docstring": "Creates a NodeBalancer Config, which allows the NodeBalancer to accept traffic on a new port. You will need to add NodeBalancer Nodes to the new Config before it can actually serve requests. API documentation: https://www.linode.com/docs/api/nodebalancers/#config-create :returns: The config that... | 3 | stack_v2_sparse_classes_30k_train_000298 | Implement the Python class `NodeBalancer` described below.
Class description:
A single NodeBalancer you can access. API documentation: https://www.linode.com/docs/api/nodebalancers/#nodebalancer-view
Method signatures and docstrings:
- def config_create(self, **kwargs): Creates a NodeBalancer Config, which allows the... | Implement the Python class `NodeBalancer` described below.
Class description:
A single NodeBalancer you can access. API documentation: https://www.linode.com/docs/api/nodebalancers/#nodebalancer-view
Method signatures and docstrings:
- def config_create(self, **kwargs): Creates a NodeBalancer Config, which allows the... | 7415f28e1e1ca1dc6de9f2c2fa16d5f898413355 | <|skeleton|>
class NodeBalancer:
"""A single NodeBalancer you can access. API documentation: https://www.linode.com/docs/api/nodebalancers/#nodebalancer-view"""
def config_create(self, **kwargs):
"""Creates a NodeBalancer Config, which allows the NodeBalancer to accept traffic on a new port. You will n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeBalancer:
"""A single NodeBalancer you can access. API documentation: https://www.linode.com/docs/api/nodebalancers/#nodebalancer-view"""
def config_create(self, **kwargs):
"""Creates a NodeBalancer Config, which allows the NodeBalancer to accept traffic on a new port. You will need to add No... | the_stack_v2_python_sparse | linode_api4/objects/nodebalancer.py | linode/linode_api4-python | train | 88 |
994444cad185b10934ebbd2fdad4cf1af1d8a5c1 | [
"BasePool.__init__(self, fetcher, parser, saver, url_filter=url_filter)\nself.fetch_queue = queue.PriorityQueue()\nself.parse_queue = queue.PriorityQueue()\nself.save_queue = queue.Queue()\nself.lock = threading.Lock()\nself.monitor_stop = False\nself.monitor = MonitorThread('monitor', self, sleep_time=monitor_slee... | <|body_start_0|>
BasePool.__init__(self, fetcher, parser, saver, url_filter=url_filter)
self.fetch_queue = queue.PriorityQueue()
self.parse_queue = queue.PriorityQueue()
self.save_queue = queue.Queue()
self.lock = threading.Lock()
self.monitor_stop = False
self.mo... | class of ThreadPool, as the subclass of BasePool | ThreadPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadPool:
"""class of ThreadPool, as the subclass of BasePool"""
def __init__(self, fetcher, parser, saver, url_filter=None, monitor_sleep_time=5):
"""constructor"""
<|body_0|>
def start_work_and_wait_done(self, fetcher_num=5, parser_num=1, is_over=True):
"""st... | stack_v2_sparse_classes_75kplus_train_008514 | 1,947 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, fetcher, parser, saver, url_filter=None, monitor_sleep_time=5)"
},
{
"docstring": "start this ThreadPool, and wait for finishing",
"name": "start_work_and_wait_done",
"signature": "def start_work_and_wait_... | 2 | stack_v2_sparse_classes_30k_train_039476 | Implement the Python class `ThreadPool` described below.
Class description:
class of ThreadPool, as the subclass of BasePool
Method signatures and docstrings:
- def __init__(self, fetcher, parser, saver, url_filter=None, monitor_sleep_time=5): constructor
- def start_work_and_wait_done(self, fetcher_num=5, parser_num... | Implement the Python class `ThreadPool` described below.
Class description:
class of ThreadPool, as the subclass of BasePool
Method signatures and docstrings:
- def __init__(self, fetcher, parser, saver, url_filter=None, monitor_sleep_time=5): constructor
- def start_work_and_wait_done(self, fetcher_num=5, parser_num... | 8d40508a568fcdeb091c51c95050bb936621613f | <|skeleton|>
class ThreadPool:
"""class of ThreadPool, as the subclass of BasePool"""
def __init__(self, fetcher, parser, saver, url_filter=None, monitor_sleep_time=5):
"""constructor"""
<|body_0|>
def start_work_and_wait_done(self, fetcher_num=5, parser_num=1, is_over=True):
"""st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadPool:
"""class of ThreadPool, as the subclass of BasePool"""
def __init__(self, fetcher, parser, saver, url_filter=None, monitor_sleep_time=5):
"""constructor"""
BasePool.__init__(self, fetcher, parser, saver, url_filter=url_filter)
self.fetch_queue = queue.PriorityQueue()
... | the_stack_v2_python_sparse | spider/concurrent/concur_thread.py | Java-via/AppSpider | train | 0 |
4790acb182db18c32e13c52bc41fa74df0891b55 | [
"super(LSTM, self).__init__()\nself.emb = nn.Embedding(vocab_size, emb_size)\nself.lstm = nn.LSTM(emb_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional)\nself.fc = nn.Linear(hidden_size, num_classes)",
"batch_size = x.shape[0]\nx = self.emb(x)\nx = x.transpose(0, 1)\nif (hStat... | <|body_start_0|>
super(LSTM, self).__init__()
self.emb = nn.Embedding(vocab_size, emb_size)
self.lstm = nn.LSTM(emb_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional)
self.fc = nn.Linear(hidden_size, num_classes)
<|end_body_0|>
<|body_start_1|>
... | LSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTM:
def __init__(self, vocab_size, emb_size, hidden_size, num_classes, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional):
"""@doc: LSTM 模型细节 @author: Alpaca-Man @date: 2021/2/16 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 hidden_size: 隐藏层维度 num_classes: 标签种类数量 num_lay... | stack_v2_sparse_classes_75kplus_train_008515 | 2,325 | no_license | [
{
"docstring": "@doc: LSTM 模型细节 @author: Alpaca-Man @date: 2021/2/16 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 hidden_size: 隐藏层维度 num_classes: 标签种类数量 num_layers: LSTM 层数 dropout: 失活率 bidirectional: LSTM 是否双向 } @return: { }",
"name": "__init__",
"signature": "def __init__(self, vocab_size, emb_size, hid... | 2 | stack_v2_sparse_classes_30k_train_036134 | Implement the Python class `LSTM` described below.
Class description:
Implement the LSTM class.
Method signatures and docstrings:
- def __init__(self, vocab_size, emb_size, hidden_size, num_classes, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional): @doc: LSTM 模型细节 @author: Alpaca-Man @date: 2021/2... | Implement the Python class `LSTM` described below.
Class description:
Implement the LSTM class.
Method signatures and docstrings:
- def __init__(self, vocab_size, emb_size, hidden_size, num_classes, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional): @doc: LSTM 模型细节 @author: Alpaca-Man @date: 2021/2... | 49824925970f0439634dc66a7f19edc512f18a5f | <|skeleton|>
class LSTM:
def __init__(self, vocab_size, emb_size, hidden_size, num_classes, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional):
"""@doc: LSTM 模型细节 @author: Alpaca-Man @date: 2021/2/16 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 hidden_size: 隐藏层维度 num_classes: 标签种类数量 num_lay... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTM:
def __init__(self, vocab_size, emb_size, hidden_size, num_classes, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional):
"""@doc: LSTM 模型细节 @author: Alpaca-Man @date: 2021/2/16 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 hidden_size: 隐藏层维度 num_classes: 标签种类数量 num_layers: LSTM 层数 d... | the_stack_v2_python_sparse | LSTM/demo/LSTM.py | Alpaca-Man/NLP-Newcomer | train | 1 | |
a1d2c8505b438eb5ef62eda28897ca3853b5edb9 | [
"Editeur.__init__(self, pere, objet, attribut)\nself.ajouter_option('n', self.opt_creer_element)\nself.ajouter_option('d', self.opt_supprimer_element)",
"prototype = self.objet\nmsg = '| |tit|' + 'Edition des éléments de {}'.format(prototype).ljust(76)\nmsg += '|ff||\\n' + self.opts.separateur + '\\n'\nmsg += 'Op... | <|body_start_0|>
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('n', self.opt_creer_element)
self.ajouter_option('d', self.opt_supprimer_element)
<|end_body_0|>
<|body_start_1|>
prototype = self.objet
msg = '| |tit|' + 'Edition des éléments de {}'.format(proto... | Contexte-éditeur d'édition des éléments. | EdtElements | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdtElements:
"""Contexte-éditeur d'édition des éléments."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def accueil(self):
"""Message d'accueil du contexte"""
<|body_1|>
def opt_creer_element(self, ... | stack_v2_sparse_classes_75kplus_train_008516 | 4,266 | permissive | [
{
"docstring": "Constructeur de l'éditeur",
"name": "__init__",
"signature": "def __init__(self, pere, objet=None, attribut=None)"
},
{
"docstring": "Message d'accueil du contexte",
"name": "accueil",
"signature": "def accueil(self)"
},
{
"docstring": "Crée un nouvel élément. Syn... | 5 | stack_v2_sparse_classes_30k_train_051901 | Implement the Python class `EdtElements` described below.
Class description:
Contexte-éditeur d'édition des éléments.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def accueil(self): Message d'accueil du contexte
- def opt_creer_element(self, argu... | Implement the Python class `EdtElements` described below.
Class description:
Contexte-éditeur d'édition des éléments.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def accueil(self): Message d'accueil du contexte
- def opt_creer_element(self, argu... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class EdtElements:
"""Contexte-éditeur d'édition des éléments."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def accueil(self):
"""Message d'accueil du contexte"""
<|body_1|>
def opt_creer_element(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EdtElements:
"""Contexte-éditeur d'édition des éléments."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('n', self.opt_creer_element)
self.ajouter_option('d', self.opt... | the_stack_v2_python_sparse | src/primaires/salle/editeurs/sbedit/edt_elements.py | vincent-lg/tsunami | train | 5 |
aa51143a248d2d8ede1a136f2ebd47c755777768 | [
"self.file_name = file_name\nself.vocab_size = vocab_size\nself.text_encoder_type = text_encoder_type\nself.cache_dir = cache_dir\nself.encoder = encoder\nself.corpus = corpus\nself.max_seq_length = max_seq_length\nif self.corpus is None:\n self.corpus = read_file(file_name)\nself.corpus = preprocessing.add_star... | <|body_start_0|>
self.file_name = file_name
self.vocab_size = vocab_size
self.text_encoder_type = text_encoder_type
self.cache_dir = cache_dir
self.encoder = encoder
self.corpus = corpus
self.max_seq_length = max_seq_length
if self.corpus is None:
... | Dataloader used for a single unaligned dataset. | UnalignedDataloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnalignedDataloader:
"""Dataloader used for a single unaligned dataset."""
def __init__(self, file_name: str, vocab_size: int, text_encoder_type: text_encoder.TextEncoderType, cache_dir='.cache', encoder=None, corpus=None, max_seq_length=None):
"""Create the UnalignedDataloader. If n... | stack_v2_sparse_classes_75kplus_train_008517 | 6,307 | no_license | [
{
"docstring": "Create the UnalignedDataloader. If no corpus of encoder are passed, new ones are created.",
"name": "__init__",
"signature": "def __init__(self, file_name: str, vocab_size: int, text_encoder_type: text_encoder.TextEncoderType, cache_dir='.cache', encoder=None, corpus=None, max_seq_length... | 2 | null | Implement the Python class `UnalignedDataloader` described below.
Class description:
Dataloader used for a single unaligned dataset.
Method signatures and docstrings:
- def __init__(self, file_name: str, vocab_size: int, text_encoder_type: text_encoder.TextEncoderType, cache_dir='.cache', encoder=None, corpus=None, m... | Implement the Python class `UnalignedDataloader` described below.
Class description:
Dataloader used for a single unaligned dataset.
Method signatures and docstrings:
- def __init__(self, file_name: str, vocab_size: int, text_encoder_type: text_encoder.TextEncoderType, cache_dir='.cache', encoder=None, corpus=None, m... | 4502d9e7461520664e72165a91bedd8e65464bae | <|skeleton|>
class UnalignedDataloader:
"""Dataloader used for a single unaligned dataset."""
def __init__(self, file_name: str, vocab_size: int, text_encoder_type: text_encoder.TextEncoderType, cache_dir='.cache', encoder=None, corpus=None, max_seq_length=None):
"""Create the UnalignedDataloader. If n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnalignedDataloader:
"""Dataloader used for a single unaligned dataset."""
def __init__(self, file_name: str, vocab_size: int, text_encoder_type: text_encoder.TextEncoderType, cache_dir='.cache', encoder=None, corpus=None, max_seq_length=None):
"""Create the UnalignedDataloader. If no corpus of e... | the_stack_v2_python_sparse | src/dataloader.py | nathanielsimard/Low-Resource-Machine-Translation | train | 0 |
9dec40dadc125caeb3f504abbcc62bbf2645d2c3 | [
"vertex = set(range(1, N + 1))\nedge_out = []\nedge_in = []\nfor vo, vi in trust:\n edge_out.append(vo)\n edge_in.append(vi)\nedge_zero_outdegree = vertex.difference(edge_out)\nif len(edge_zero_outdegree) == 1:\n town_judge = edge_zero_outdegree.pop()\nelse:\n return -1\nif edge_in.count(town_judge) == ... | <|body_start_0|>
vertex = set(range(1, N + 1))
edge_out = []
edge_in = []
for vo, vi in trust:
edge_out.append(vo)
edge_in.append(vi)
edge_zero_outdegree = vertex.difference(edge_out)
if len(edge_zero_outdegree) == 1:
town_judge = edge_... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findJudge(self, N, trust):
"""direct modelling a graph"""
<|body_0|>
def findJudge2(self, N, trust):
"""calculate deg_diff = in_deg - out_dig"""
<|body_1|>
def findJudge3(self, N, trust):
"""calculate indegree firstly by adjacency m... | stack_v2_sparse_classes_75kplus_train_008518 | 2,581 | permissive | [
{
"docstring": "direct modelling a graph",
"name": "findJudge",
"signature": "def findJudge(self, N, trust)"
},
{
"docstring": "calculate deg_diff = in_deg - out_dig",
"name": "findJudge2",
"signature": "def findJudge2(self, N, trust)"
},
{
"docstring": "calculate indegree firstl... | 3 | stack_v2_sparse_classes_30k_train_024053 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findJudge(self, N, trust): direct modelling a graph
- def findJudge2(self, N, trust): calculate deg_diff = in_deg - out_dig
- def findJudge3(self, N, trust): calculate indegr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findJudge(self, N, trust): direct modelling a graph
- def findJudge2(self, N, trust): calculate deg_diff = in_deg - out_dig
- def findJudge3(self, N, trust): calculate indegr... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def findJudge(self, N, trust):
"""direct modelling a graph"""
<|body_0|>
def findJudge2(self, N, trust):
"""calculate deg_diff = in_deg - out_dig"""
<|body_1|>
def findJudge3(self, N, trust):
"""calculate indegree firstly by adjacency m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findJudge(self, N, trust):
"""direct modelling a graph"""
vertex = set(range(1, N + 1))
edge_out = []
edge_in = []
for vo, vi in trust:
edge_out.append(vo)
edge_in.append(vi)
edge_zero_outdegree = vertex.difference(edge_out)... | the_stack_v2_python_sparse | leetcode/0997_find_the_town_judge.py | chaosWsF/Python-Practice | train | 1 | |
7fc230d306fb7ecc41b69562be02291089cadfce | [
"urls = ['http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/']\nfor url in urls:\n yield scrapy.Request(url=url, callback=self.parse)",
"page = response.url.split('/')[-2]\nfilename = 'quotes-%s.html' % page\nwith open(filename, 'wb') as f:\n f.write(response.body)\nself.log('Saved fil... | <|body_start_0|>
urls = ['http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
<|end_body_0|>
<|body_start_1|>
page = response.url.split('/')[-2]
filename = 'quotes-%s.html' % page
... | QuotesSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuotesSpider:
def start_requests(self):
"""This function must return an iterable of Requests (scrapy.Request). :return:"""
<|body_0|>
def parse(self, response):
"""It will be called by scrapy.Request to handle the response. :param response: the type is the TextRespon... | stack_v2_sparse_classes_75kplus_train_008519 | 3,832 | no_license | [
{
"docstring": "This function must return an iterable of Requests (scrapy.Request). :return:",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "It will be called by scrapy.Request to handle the response. :param response: the type is the TextResponse class. :re... | 2 | stack_v2_sparse_classes_30k_train_018579 | Implement the Python class `QuotesSpider` described below.
Class description:
Implement the QuotesSpider class.
Method signatures and docstrings:
- def start_requests(self): This function must return an iterable of Requests (scrapy.Request). :return:
- def parse(self, response): It will be called by scrapy.Request to... | Implement the Python class `QuotesSpider` described below.
Class description:
Implement the QuotesSpider class.
Method signatures and docstrings:
- def start_requests(self): This function must return an iterable of Requests (scrapy.Request). :return:
- def parse(self, response): It will be called by scrapy.Request to... | ad2651872c43dd0442048289101dbbbdd31bc056 | <|skeleton|>
class QuotesSpider:
def start_requests(self):
"""This function must return an iterable of Requests (scrapy.Request). :return:"""
<|body_0|>
def parse(self, response):
"""It will be called by scrapy.Request to handle the response. :param response: the type is the TextRespon... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuotesSpider:
def start_requests(self):
"""This function must return an iterable of Requests (scrapy.Request). :return:"""
urls = ['http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)... | the_stack_v2_python_sparse | test_scrapy/quotes_spider.py | hobin2017/Webapp | train | 0 | |
4e14494c39e07fdb249b6713aeaff254abe817f3 | [
"r = x\nwhile r * r > x:\n r = (r + x / r) / 2\nreturn int(r)",
"if not x:\n return 0\nleft, right = (1, x)\nwhile left <= right:\n mid = (left + right) // 2\n if mid * mid == x:\n return mid\n elif mid * mid < x:\n left = mid + 1\n else:\n right = mid - 1\nreturn right if r... | <|body_start_0|>
r = x
while r * r > x:
r = (r + x / r) / 2
return int(r)
<|end_body_0|>
<|body_start_1|>
if not x:
return 0
left, right = (1, x)
while left <= right:
mid = (left + right) // 2
if mid * mid == x:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r = x
while r * r > x:
r = (r + x / r) / 2
return ... | stack_v2_sparse_classes_75kplus_train_008520 | 1,002 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt2",
"signature": "def mySqrt2(self, x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rt... | baa3342ebe2600f365b9348455f6342e19866a44 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
r = x
while r * r > x:
r = (r + x / r) / 2
return int(r)
def mySqrt2(self, x):
""":type x: int :rtype: int"""
if not x:
return 0
left, right = (1, x)
while... | the_stack_v2_python_sparse | easy/sqrt_x.py | ChrisLiu95/Leetcode | train | 0 | |
b64610041e600ced4c44ee6ad5fc573f08dd32a8 | [
"self.curline = ''\nself.gui = gui\nself.contents = []\nself.outdict = {}\nself.currout = None\nself.next_title = None",
"if re.match('^--+$', text.strip()) or re.match('^==+$', text.strip()):\n if self.currout:\n self.outdict[self.currout].remove(self.next_title)\n self.outdict[self.currout].pop... | <|body_start_0|>
self.curline = ''
self.gui = gui
self.contents = []
self.outdict = {}
self.currout = None
self.next_title = None
<|end_body_0|>
<|body_start_1|>
if re.match('^--+$', text.strip()) or re.match('^==+$', text.strip()):
if self.currout:
... | used in gui reporter instead of writing to stdout, it is written to this stream and saved in contents | BasicStream | [
"GPL-2.0-only",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicStream:
"""used in gui reporter instead of writing to stdout, it is written to this stream and saved in contents"""
def __init__(self, gui):
"""init"""
<|body_0|>
def write(self, text):
"""write text to the stream"""
<|body_1|>
def fix_contents(... | stack_v2_sparse_classes_75kplus_train_008521 | 19,674 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, gui)"
},
{
"docstring": "write text to the stream",
"name": "write",
"signature": "def write(self, text)"
},
{
"docstring": "finalize what the contents of the dict should look like before output",
"na... | 4 | null | Implement the Python class `BasicStream` described below.
Class description:
used in gui reporter instead of writing to stdout, it is written to this stream and saved in contents
Method signatures and docstrings:
- def __init__(self, gui): init
- def write(self, text): write text to the stream
- def fix_contents(self... | Implement the Python class `BasicStream` described below.
Class description:
used in gui reporter instead of writing to stdout, it is written to this stream and saved in contents
Method signatures and docstrings:
- def __init__(self, gui): init
- def write(self, text): write text to the stream
- def fix_contents(self... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class BasicStream:
"""used in gui reporter instead of writing to stdout, it is written to this stream and saved in contents"""
def __init__(self, gui):
"""init"""
<|body_0|>
def write(self, text):
"""write text to the stream"""
<|body_1|>
def fix_contents(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicStream:
"""used in gui reporter instead of writing to stdout, it is written to this stream and saved in contents"""
def __init__(self, gui):
"""init"""
self.curline = ''
self.gui = gui
self.contents = []
self.outdict = {}
self.currout = None
se... | the_stack_v2_python_sparse | third_party/pylint/pylint/gui.py | chromium/chromium | train | 17,408 |
d14f8beeb9e8e03cbbb7f62f5d364e9578d23aa4 | [
"ReconstFit.__init__(self, fiber_model, vox_data)\nself.life_matrix = life_matrix\nself.vox_coords = vox_coords\nself.fit_data = to_fit\nself.beta = beta\nself.weighted_signal = weighted_signal\nself.b0_signal = b0_signal\nself.relative_signal = relative_signal\nself.mean_signal = mean_sig\nself.streamline = stream... | <|body_start_0|>
ReconstFit.__init__(self, fiber_model, vox_data)
self.life_matrix = life_matrix
self.vox_coords = vox_coords
self.fit_data = to_fit
self.beta = beta
self.weighted_signal = weighted_signal
self.b0_signal = b0_signal
self.relative_signal = r... | A fit of the LiFE model to diffusion data | FiberFit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FiberFit:
"""A fit of the LiFE model to diffusion data"""
def __init__(self, fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mean_sig, vox_data, streamline, affine, evals):
"""Parameters ---------- fiber_model : A FiberModel class inst... | stack_v2_sparse_classes_75kplus_train_008522 | 20,065 | permissive | [
{
"docstring": "Parameters ---------- fiber_model : A FiberModel class instance params : the parameters derived from a fit of the model to the data.",
"name": "__init__",
"signature": "def __init__(self, fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mea... | 2 | stack_v2_sparse_classes_30k_train_046221 | Implement the Python class `FiberFit` described below.
Class description:
A fit of the LiFE model to diffusion data
Method signatures and docstrings:
- def __init__(self, fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mean_sig, vox_data, streamline, affine, evals): Pa... | Implement the Python class `FiberFit` described below.
Class description:
A fit of the LiFE model to diffusion data
Method signatures and docstrings:
- def __init__(self, fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mean_sig, vox_data, streamline, affine, evals): Pa... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class FiberFit:
"""A fit of the LiFE model to diffusion data"""
def __init__(self, fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mean_sig, vox_data, streamline, affine, evals):
"""Parameters ---------- fiber_model : A FiberModel class inst... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FiberFit:
"""A fit of the LiFE model to diffusion data"""
def __init__(self, fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mean_sig, vox_data, streamline, affine, evals):
"""Parameters ---------- fiber_model : A FiberModel class instance params :... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/dipy/tracking/life.py | Raniac/NEURO-LEARN | train | 9 |
99c58e84b8f4739ae6f1c44654c687c14c7c0057 | [
"if data['status'] == JSendStatus.SUCCESS or data['status'] == JSendStatus.FAIL:\n if 'data' not in data:\n raise ValidationError(f\"When status is {data['status']}, the data field must be populated.\")\nif data['status'] == JSendStatus.FAIL:\n if 'message' not in data['data']:\n raise Validatio... | <|body_start_0|>
if data['status'] == JSendStatus.SUCCESS or data['status'] == JSendStatus.FAIL:
if 'data' not in data:
raise ValidationError(f"When status is {data['status']}, the data field must be populated.")
if data['status'] == JSendStatus.FAIL:
if 'message'... | A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend | JSendSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSendSchema:
"""A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend"""
def assert_fields(self, data, **kwargs):
"""Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`... | stack_v2_sparse_classes_75kplus_train_008523 | 2,641 | permissive | [
{
"docstring": "Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`~JSendStatus.SUCCESS` or :attr:`~JSendStatus.FAIL` - the ``message`` field is included when the status is :attr:`~JSendStatus.ERROR`",
"name": "assert_fields",
"signature": "def asser... | 2 | stack_v2_sparse_classes_30k_train_046670 | Implement the Python class `JSendSchema` described below.
Class description:
A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend
Method signatures and docstrings:
- def assert_fields(self, data, **kwargs): Asserts that, according to the specification: - ... | Implement the Python class `JSendSchema` described below.
Class description:
A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend
Method signatures and docstrings:
- def assert_fields(self, data, **kwargs): Asserts that, according to the specification: - ... | fc6f9230e4701cbddcb16d7257fddb9ff08bddb9 | <|skeleton|>
class JSendSchema:
"""A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend"""
def assert_fields(self, data, **kwargs):
"""Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSendSchema:
"""A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend"""
def assert_fields(self, data, **kwargs):
"""Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`~JSendStatus.... | the_stack_v2_python_sparse | server/serializer/jsend.py | dragorhast/server | train | 6 |
f15f3adb7320f791c345b4ba5dc9de997d6194b4 | [
"super().__init__(preprocess, postprocess, allow_none)\nself._dtype = dtype\nself._shape = shape\nself._order = order",
"typed_and_ordered = np.array(arr, dtype=self._dtype, order=self._order)\nif len(typed_and_ordered.shape) != len(self._shape):\n raise ValueError(f'Expected array of {len(self._shape)} dimens... | <|body_start_0|>
super().__init__(preprocess, postprocess, allow_none)
self._dtype = dtype
self._shape = shape
self._order = order
<|end_body_0|>
<|body_start_1|>
typed_and_ordered = np.array(arr, dtype=self._dtype, order=self._order)
if len(typed_and_ordered.shape) != l... | Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is specified by the value. A value of ``None`` i... | NDArrayValidator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NDArrayValidator:
"""Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is s... | stack_v2_sparse_classes_75kplus_train_008524 | 20,632 | permissive | [
{
"docstring": "Create a NDArrayValidator object.",
"name": "__init__",
"signature": "def __init__(self, dtype, shape=(None,), order='K', preprocess=None, postprocess=None, allow_none=False)"
},
{
"docstring": "Validate an array or array-like object.",
"name": "_validate",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_042107 | Implement the Python class `NDArrayValidator` described below.
Class description:
Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the t... | Implement the Python class `NDArrayValidator` described below.
Class description:
Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the t... | abdd76bc854358426e4cf055badd27f80df6ec85 | <|skeleton|>
class NDArrayValidator:
"""Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NDArrayValidator:
"""Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is specified by t... | the_stack_v2_python_sparse | hoomd/data/typeconverter.py | glotzerlab/hoomd-blue | train | 287 |
0ad660815c6829521aed8af197ef30548402e594 | [
"Parametre.__init__(self, 'voir', 'view')\nself.schema = '<nombre>'\nself.aide_courte = \"affiche le détail d'une news letter\"\nself.aide_longue = \"Cette commande permet d'afficher le détail d'une news letter (si elle est envyée, la date d'envoi est affichée).\"",
"id = dic_masques['nombre'].nombre\ntry:\n n... | <|body_start_0|>
Parametre.__init__(self, 'voir', 'view')
self.schema = '<nombre>'
self.aide_courte = "affiche le détail d'une news letter"
self.aide_longue = "Cette commande permet d'afficher le détail d'une news letter (si elle est envyée, la date d'envoi est affichée)."
<|end_body_0|>... | Commande 'newsletter voir'. | PrmVoir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmVoir:
"""Commande 'newsletter voir'."""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre._... | stack_v2_sparse_classes_75kplus_train_008525 | 3,039 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'newsletter voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'newsletter voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmVoir:
"""Commande 'newsletter... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmVoir:
"""Commande 'newsletter voir'."""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmVoir:
"""Commande 'newsletter voir'."""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'voir', 'view')
self.schema = '<nombre>'
self.aide_courte = "affiche le détail d'une news letter"
self.aide_longue = "Cette commande permet d'af... | the_stack_v2_python_sparse | src/primaires/information/commandes/newsletter/voir.py | vincent-lg/tsunami | train | 5 |
0dbb563dc5e7ac920c597c3a48abb2fc84c0c2bf | [
"self.assertEqual(D20Coin.pp(1), 1000)\nself.assertEqual(D20Coin.gp(1), 100)\nself.assertEqual(D20Coin.sp(1), 10)\nself.assertEqual(D20Coin.cp(1), 1)",
"treasure = D20Coin(pp=1, gp=2, sp=3, cp=4)\nself.assertEqual(treasure.value, 1234)\nself.assertEqual(treasure.sale_value, 1234)\nself.assertEqual(treasure.name, ... | <|body_start_0|>
self.assertEqual(D20Coin.pp(1), 1000)
self.assertEqual(D20Coin.gp(1), 100)
self.assertEqual(D20Coin.sp(1), 10)
self.assertEqual(D20Coin.cp(1), 1)
<|end_body_0|>
<|body_start_1|>
treasure = D20Coin(pp=1, gp=2, sp=3, cp=4)
self.assertEqual(treasure.value, ... | A test suite for the D20Coin class | TestD20Coin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestD20Coin:
"""A test suite for the D20Coin class"""
def test_convert_coin_types(self):
"""Try the four coin type conversions"""
<|body_0|>
def test_coin_treasure(self):
"""Create a coin-only treasure object"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_008526 | 3,068 | permissive | [
{
"docstring": "Try the four coin type conversions",
"name": "test_convert_coin_types",
"signature": "def test_convert_coin_types(self)"
},
{
"docstring": "Create a coin-only treasure object",
"name": "test_coin_treasure",
"signature": "def test_coin_treasure(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000328 | Implement the Python class `TestD20Coin` described below.
Class description:
A test suite for the D20Coin class
Method signatures and docstrings:
- def test_convert_coin_types(self): Try the four coin type conversions
- def test_coin_treasure(self): Create a coin-only treasure object | Implement the Python class `TestD20Coin` described below.
Class description:
A test suite for the D20Coin class
Method signatures and docstrings:
- def test_convert_coin_types(self): Try the four coin type conversions
- def test_coin_treasure(self): Create a coin-only treasure object
<|skeleton|>
class TestD20Coin:
... | 75504d2443cdc80db120c5dcdc14db379d15396e | <|skeleton|>
class TestD20Coin:
"""A test suite for the D20Coin class"""
def test_convert_coin_types(self):
"""Try the four coin type conversions"""
<|body_0|>
def test_coin_treasure(self):
"""Create a coin-only treasure object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestD20Coin:
"""A test suite for the D20Coin class"""
def test_convert_coin_types(self):
"""Try the four coin type conversions"""
self.assertEqual(D20Coin.pp(1), 1000)
self.assertEqual(D20Coin.gp(1), 100)
self.assertEqual(D20Coin.sp(1), 10)
self.assertEqual(D20Coin... | the_stack_v2_python_sparse | games/d20/pathfinder/test_pathfindertreasure.py | ajs/tools | train | 5 |
8c71fcca09d6bee9c8df0998162ccbaf03d788c3 | [
"errors = []\nif not HAS_TEXTFSM:\n errors.append(missing_required_lib('textfsm'))\nreturn {'errors': errors}",
"cli_output = self._task_args.get('text')\nres = self._check_reqs()\nif res.get('errors'):\n return {'errors': res.get('errors')}\ntemplate_path = self._task_args.get('parser').get('template_path'... | <|body_start_0|>
errors = []
if not HAS_TEXTFSM:
errors.append(missing_required_lib('textfsm'))
return {'errors': errors}
<|end_body_0|>
<|body_start_1|>
cli_output = self._task_args.get('text')
res = self._check_reqs()
if res.get('errors'):
retur... | The textfsm parser class Convert raw text to structured data using textfsm | CliParser | [
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
... | stack_v2_sparse_classes_75kplus_train_008527 | 3,264 | permissive | [
{
"docstring": "Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path",
"name": "_check_reqs",
"signature": "def _check_reqs()"
},
{
"docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype... | 2 | stack_v2_sparse_classes_30k_train_010021 | Implement the Python class `CliParser` described below.
Class description:
The textfsm parser class Convert raw text to structured data using textfsm
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path
- def parse(se... | Implement the Python class `CliParser` described below.
Class description:
The textfsm parser class Convert raw text to structured data using textfsm
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path
- def parse(se... | 2ea7d4f00212f502bc684ac257371ada73da1ca9 | <|skeleton|>
class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
errors = []
if not HAS_TEXTFSM:
errors.append(missing... | the_stack_v2_python_sparse | intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/utils/plugins/sub_plugins/cli_parser/textfsm_parser.py | SimonFangCisco/dne-dna-code | train | 0 |
0290a92556c5673e928357ce5d0adeb5f13cec4f | [
"self._connect = connect\nself._resource = resource\nself.data = initial_data\nself._is_full = is_full\nself._can_refresh = can_refresh",
"if not self._is_full:\n self.refresh()\nreturn self.data",
"if self._can_refresh:\n self.data = self._connect.get(self._resource)\n self._is_full = True"
] | <|body_start_0|>
self._connect = connect
self._resource = resource
self.data = initial_data
self._is_full = is_full
self._can_refresh = can_refresh
<|end_body_0|>
<|body_start_1|>
if not self._is_full:
self.refresh()
return self.data
<|end_body_1|>
<... | RestBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestBase:
def __init__(self, connect, resource, initial_data=None, is_full=False, can_refresh=True):
"""Constructor Parameters connect - the Connect object used to send/receive Skytap REST requests resource - the relative URI to the resource represented by this object initial_data - a di... | stack_v2_sparse_classes_75kplus_train_008528 | 14,866 | no_license | [
{
"docstring": "Constructor Parameters connect - the Connect object used to send/receive Skytap REST requests resource - the relative URI to the resource represented by this object initial_data - a dictionary containing attribute/value pairs for this object. It can be a partial set. For instance if this is temp... | 3 | stack_v2_sparse_classes_30k_train_002647 | Implement the Python class `RestBase` described below.
Class description:
Implement the RestBase class.
Method signatures and docstrings:
- def __init__(self, connect, resource, initial_data=None, is_full=False, can_refresh=True): Constructor Parameters connect - the Connect object used to send/receive Skytap REST re... | Implement the Python class `RestBase` described below.
Class description:
Implement the RestBase class.
Method signatures and docstrings:
- def __init__(self, connect, resource, initial_data=None, is_full=False, can_refresh=True): Constructor Parameters connect - the Connect object used to send/receive Skytap REST re... | 18bf051bd03128ea0f72fae3d9e63e94d3a71479 | <|skeleton|>
class RestBase:
def __init__(self, connect, resource, initial_data=None, is_full=False, can_refresh=True):
"""Constructor Parameters connect - the Connect object used to send/receive Skytap REST requests resource - the relative URI to the resource represented by this object initial_data - a di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestBase:
def __init__(self, connect, resource, initial_data=None, is_full=False, can_refresh=True):
"""Constructor Parameters connect - the Connect object used to send/receive Skytap REST requests resource - the relative URI to the resource represented by this object initial_data - a dictionary conta... | the_stack_v2_python_sparse | dxskytap/restobject.py | careyrp/dxskytap | train | 0 | |
884e8b46a578412b236916b1de8a115205cc4990 | [
"self.ostype = self.NOSUPPORT\nself.version = self.ERRORVERS\nself.dist = platform.dist()\nself.system = platform.system()\nself.platform = platform.platform()\nself.uname = platform.uname()\nself.cpu_supported = self.uname[-1] in WhatOS.SUPPORTED_CPU_TYPES\nself.os_class_map = {WhatOS.LINUX_CLASS: self.linux, What... | <|body_start_0|>
self.ostype = self.NOSUPPORT
self.version = self.ERRORVERS
self.dist = platform.dist()
self.system = platform.system()
self.platform = platform.platform()
self.uname = platform.uname()
self.cpu_supported = self.uname[-1] in WhatOS.SUPPORTED_CPU_TY... | Determine OS-type and version of the system we run on and whether we run on a system that is supported. Only x86 systems are supported. All methods will return False if we are on another platform. On supported CPU platforms, the following methods are available: linux: determine OS-type and version for (some) Linux dist... | WhatOS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhatOS:
"""Determine OS-type and version of the system we run on and whether we run on a system that is supported. Only x86 systems are supported. All methods will return False if we are on another platform. On supported CPU platforms, the following methods are available: linux: determine OS-type... | stack_v2_sparse_classes_75kplus_train_008529 | 13,877 | no_license | [
{
"docstring": "AnyOS instance creation",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Find Linux OS-type and major OS version",
"name": "linux",
"signature": "def linux(self)"
},
{
"docstring": "Find Solaris OS-type and major OS version",
"name": ... | 5 | stack_v2_sparse_classes_30k_train_020599 | Implement the Python class `WhatOS` described below.
Class description:
Determine OS-type and version of the system we run on and whether we run on a system that is supported. Only x86 systems are supported. All methods will return False if we are on another platform. On supported CPU platforms, the following methods ... | Implement the Python class `WhatOS` described below.
Class description:
Determine OS-type and version of the system we run on and whether we run on a system that is supported. Only x86 systems are supported. All methods will return False if we are on another platform. On supported CPU platforms, the following methods ... | 5e4a177ffb42018cf0626381f26990f55caf9a34 | <|skeleton|>
class WhatOS:
"""Determine OS-type and version of the system we run on and whether we run on a system that is supported. Only x86 systems are supported. All methods will return False if we are on another platform. On supported CPU platforms, the following methods are available: linux: determine OS-type... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhatOS:
"""Determine OS-type and version of the system we run on and whether we run on a system that is supported. Only x86 systems are supported. All methods will return False if we are on another platform. On supported CPU platforms, the following methods are available: linux: determine OS-type and version ... | the_stack_v2_python_sparse | urb-core/tools/whatos.py | UnivaCorporation/urb-k8s | train | 21 |
b20b53f7ed8945e1ef6b537ba9c1b09d34d79924 | [
"success = False\ntry:\n registration_profile = self.get(user=user)\n if registration_profile.verification_code == verification_code and (not registration_profile.verification_code_expired()):\n user.is_active = True\n user.set_password(password)\n user.save()\n success = True\nexc... | <|body_start_0|>
success = False
try:
registration_profile = self.get(user=user)
if registration_profile.verification_code == verification_code and (not registration_profile.verification_code_expired()):
user.is_active = True
user.set_password(pass... | Custom Model Manager for the RegistrationProfile class. We use this as it is the preferred way to add "table-level" functionality to the model. The methods defined here provide shortcuts for account creation and (re)activation (including generation and SMS sending of verification code) | RegistrationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
"""Custom Model Manager for the RegistrationProfile class. We use this as it is the preferred way to add "table-level" functionality to the model. The methods defined here provide shortcuts for account creation and (re)activation (including generation and SMS sending of verif... | stack_v2_sparse_classes_75kplus_train_008530 | 19,218 | no_license | [
{
"docstring": "Validate a verification code and activate the corresponding `User` instance if valid. After successful activation set the user's password to the new value. Args: user: user who submitted a particular verification code verification_code: Verification code to check against. password: if user is ac... | 3 | stack_v2_sparse_classes_30k_train_052223 | Implement the Python class `RegistrationManager` described below.
Class description:
Custom Model Manager for the RegistrationProfile class. We use this as it is the preferred way to add "table-level" functionality to the model. The methods defined here provide shortcuts for account creation and (re)activation (includ... | Implement the Python class `RegistrationManager` described below.
Class description:
Custom Model Manager for the RegistrationProfile class. We use this as it is the preferred way to add "table-level" functionality to the model. The methods defined here provide shortcuts for account creation and (re)activation (includ... | 1f4b4cd74c9b4280437f73bdfef4491536194eeb | <|skeleton|>
class RegistrationManager:
"""Custom Model Manager for the RegistrationProfile class. We use this as it is the preferred way to add "table-level" functionality to the model. The methods defined here provide shortcuts for account creation and (re)activation (including generation and SMS sending of verif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationManager:
"""Custom Model Manager for the RegistrationProfile class. We use this as it is the preferred way to add "table-level" functionality to the model. The methods defined here provide shortcuts for account creation and (re)activation (including generation and SMS sending of verification code)... | the_stack_v2_python_sparse | gravvy/apps/account/models.py | nceruchalu/gravvy-server | train | 1 |
1756ea43dc98dc035a6c13be858c9d6390111b92 | [
"from math import sqrt\nself.min_instances = min_instances\nself.drift_level = float(drift_level)\nself.i = None\nself.pi = None\nself.si = None\nself.pi_min = None\nself.si_min = None\nself.sqrt = sqrt\nself.reset()",
"self.i = 0\nself.pi = 1.0\nself.si = 0.0\nself.pi_min = float('inf')\nself.si_min = float('inf... | <|body_start_0|>
from math import sqrt
self.min_instances = min_instances
self.drift_level = float(drift_level)
self.i = None
self.pi = None
self.si = None
self.pi_min = None
self.si_min = None
self.sqrt = sqrt
self.reset()
<|end_body_0|>
... | Implements the DDM drift detection method. This drift detector is based on the paper on the DDM Paper (João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning with Drift Detection. SBIA 2004: 286-295). We keep the highest alarm level of drift detection (out of control), leaving out warning level. Att... | DDM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DDM:
"""Implements the DDM drift detection method. This drift detector is based on the paper on the DDM Paper (João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning with Drift Detection. SBIA 2004: 286-295). We keep the highest alarm level of drift detection (out of control),... | stack_v2_sparse_classes_75kplus_train_008531 | 3,161 | no_license | [
{
"docstring": "Initialize the DDM Drift Detector Initialize the DDM Drift detector. Default parameters are provided as well. Args: min_instances: INT. Minimum number of instances for Detector to return a result. drift_level: Alarm level for drift detector. 3.0 is from the DDM paper. 2.0 would be for drift warn... | 3 | stack_v2_sparse_classes_30k_train_048429 | Implement the Python class `DDM` described below.
Class description:
Implements the DDM drift detection method. This drift detector is based on the paper on the DDM Paper (João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning with Drift Detection. SBIA 2004: 286-295). We keep the highest alarm lev... | Implement the Python class `DDM` described below.
Class description:
Implements the DDM drift detection method. This drift detector is based on the paper on the DDM Paper (João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning with Drift Detection. SBIA 2004: 286-295). We keep the highest alarm lev... | 4938936dbf08b5331275d4413dbad51acbaf7da9 | <|skeleton|>
class DDM:
"""Implements the DDM drift detection method. This drift detector is based on the paper on the DDM Paper (João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning with Drift Detection. SBIA 2004: 286-295). We keep the highest alarm level of drift detection (out of control),... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DDM:
"""Implements the DDM drift detection method. This drift detector is based on the paper on the DDM Paper (João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning with Drift Detection. SBIA 2004: 286-295). We keep the highest alarm level of drift detection (out of control), leaving out ... | the_stack_v2_python_sparse | mlep_odin_main/mlep/mlep/drift_detector/LabeledDriftDetector/DDM.py | asuprem/ODIN | train | 7 |
5613767004b318d3177e27172d8585b4c7d3a669 | [
"if fitType not in ('full', 'cope', 'pe'):\n raise ValueError('Unknown model fit type {}'.format(fitType))\nVoxelTimeSeries.__init__(self, overlay, overlayList, displayCtx, plotCanvas)\nself.parentTs = parentTs\nself.fitType = fitType\nself.idx = idx\nself.contrast = contrast",
"label = '{} ({})'.format(self.p... | <|body_start_0|>
if fitType not in ('full', 'cope', 'pe'):
raise ValueError('Unknown model fit type {}'.format(fitType))
VoxelTimeSeries.__init__(self, overlay, overlayList, displayCtx, plotCanvas)
self.parentTs = parentTs
self.fitType = fitType
self.idx = idx
... | A :class:`TimeSeries` class which represents the time course for a model fit from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class. | FEATModelFitTimeSeries | [
"Apache-2.0",
"CC-BY-3.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FEATModelFitTimeSeries:
"""A :class:`TimeSeries` class which represents the time course for a model fit from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class."""
def __init__(self, overlay, overlayList, displayCtx, plotCanvas, pare... | stack_v2_sparse_classes_75kplus_train_008532 | 29,239 | permissive | [
{
"docstring": "Create a ``FEATModelFitTimeSeries``. :arg overlay: The :class:`.FEATImage` instance to extract the data from. :arg overlayList: The :class:`.OverlayList` instance. :arg displayCtx: The :class:`.DisplayContext` instance. :arg plotCanvas: The :class:`TimeSeriesPanel` which owns this ``FEATModelFit... | 3 | null | Implement the Python class `FEATModelFitTimeSeries` described below.
Class description:
A :class:`TimeSeries` class which represents the time course for a model fit from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class.
Method signatures and docstrings:
- d... | Implement the Python class `FEATModelFitTimeSeries` described below.
Class description:
A :class:`TimeSeries` class which represents the time course for a model fit from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class.
Method signatures and docstrings:
- d... | 37b45d034d60660b6de3e4bdf5dd6349ed6d853b | <|skeleton|>
class FEATModelFitTimeSeries:
"""A :class:`TimeSeries` class which represents the time course for a model fit from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class."""
def __init__(self, overlay, overlayList, displayCtx, plotCanvas, pare... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FEATModelFitTimeSeries:
"""A :class:`TimeSeries` class which represents the time course for a model fit from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class."""
def __init__(self, overlay, overlayList, displayCtx, plotCanvas, parentTs, contras... | the_stack_v2_python_sparse | fsleyes/plotting/timeseries.py | CGSchwarzMayo/fsleyes | train | 0 |
1d8fdb21b89fb94a101a75e486c2a5a43dba9116 | [
"hash_values = []\nfor f in self.hash_fields:\n try:\n if getattr(self, f) is None:\n hash_values.append('')\n else:\n hash_values.append(getattr(self, f))\n except AttributeError:\n hash_values.append('')\nreturn hash_values",
"str_hash = '.'.join(self.get_hash_va... | <|body_start_0|>
hash_values = []
for f in self.hash_fields:
try:
if getattr(self, f) is None:
hash_values.append('')
else:
hash_values.append(getattr(self, f))
except AttributeError:
hash_val... | This mixin generate hash for every request Attributes: hash_fields Hash a string made up of the request values | HashMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashMixin:
"""This mixin generate hash for every request Attributes: hash_fields Hash a string made up of the request values"""
def get_hash_values(self):
"""This method return a list values to generate hash :return: list"""
<|body_0|>
def generate_hash(self, secret):
... | stack_v2_sparse_classes_75kplus_train_008533 | 2,121 | permissive | [
{
"docstring": "This method return a list values to generate hash :return: list",
"name": "get_hash_values",
"signature": "def get_hash_values(self)"
},
{
"docstring": "Generate the security hash from a number of fields and the shared secret. :rtype: object",
"name": "generate_hash",
"si... | 2 | stack_v2_sparse_classes_30k_test_002918 | Implement the Python class `HashMixin` described below.
Class description:
This mixin generate hash for every request Attributes: hash_fields Hash a string made up of the request values
Method signatures and docstrings:
- def get_hash_values(self): This method return a list values to generate hash :return: list
- def... | Implement the Python class `HashMixin` described below.
Class description:
This mixin generate hash for every request Attributes: hash_fields Hash a string made up of the request values
Method signatures and docstrings:
- def get_hash_values(self): This method return a list values to generate hash :return: list
- def... | 8fcf2a0e9d6d99d18e313f04b9721ccc4769a83f | <|skeleton|>
class HashMixin:
"""This mixin generate hash for every request Attributes: hash_fields Hash a string made up of the request values"""
def get_hash_values(self):
"""This method return a list values to generate hash :return: list"""
<|body_0|>
def generate_hash(self, secret):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HashMixin:
"""This mixin generate hash for every request Attributes: hash_fields Hash a string made up of the request values"""
def get_hash_values(self):
"""This method return a list values to generate hash :return: list"""
hash_values = []
for f in self.hash_fields:
... | the_stack_v2_python_sparse | addonpayments/mixins.py | ComerciaGP/addonpayments-Python-SDK | train | 3 |
58d627730547ed9dd17e0b295edb3cfba894968d | [
"self.object = form.save(commit=False)\nself.object.supplier = get_object_or_404(models.Supplier, pk=self.kwargs['supplier_pk'])\nself.object.save()\nreturn super().form_valid(form)",
"context = super().get_context_data(*args, **kwargs)\ncontext['supplier'] = get_object_or_404(models.Supplier, pk=self.kwargs['sup... | <|body_start_0|>
self.object = form.save(commit=False)
self.object.supplier = get_object_or_404(models.Supplier, pk=self.kwargs['supplier_pk'])
self.object.save()
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(*args, **kwargs)
... | View for creating supplier contacts. | CreateSupplierContact | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateSupplierContact:
"""View for creating supplier contacts."""
def form_valid(self, form):
"""Add the supplier to the contact object."""
<|body_0|>
def get_context_data(self, *args, **kwargs):
"""Add supplier to the template context."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_008534 | 3,540 | no_license | [
{
"docstring": "Add the supplier to the contact object.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Add supplier to the template context.",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036818 | Implement the Python class `CreateSupplierContact` described below.
Class description:
View for creating supplier contacts.
Method signatures and docstrings:
- def form_valid(self, form): Add the supplier to the contact object.
- def get_context_data(self, *args, **kwargs): Add supplier to the template context. | Implement the Python class `CreateSupplierContact` described below.
Class description:
View for creating supplier contacts.
Method signatures and docstrings:
- def form_valid(self, form): Add the supplier to the contact object.
- def get_context_data(self, *args, **kwargs): Add supplier to the template context.
<|sk... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class CreateSupplierContact:
"""View for creating supplier contacts."""
def form_valid(self, form):
"""Add the supplier to the contact object."""
<|body_0|>
def get_context_data(self, *args, **kwargs):
"""Add supplier to the template context."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateSupplierContact:
"""View for creating supplier contacts."""
def form_valid(self, form):
"""Add the supplier to the contact object."""
self.object = form.save(commit=False)
self.object.supplier = get_object_or_404(models.Supplier, pk=self.kwargs['supplier_pk'])
self.o... | the_stack_v2_python_sparse | inventory/views/suppliers.py | stcstores/stcadmin | train | 0 |
ad6ed68aa5be3aaeb38d04615db7c3b00f45fa75 | [
"task_id = request.args.get('task_id')\nif not task_id:\n response_data = self.wrap_json_response(errmsg='Lost query params of task_id', code=ReturnCode.WRONG_PARAMS)\n return jsonify(response_data)\ndict_result = mongo_cli[vulscan_db].find_one({'_id': ObjectId(task_id)})\ndict_result['_id'] = '%s' % dict_res... | <|body_start_0|>
task_id = request.args.get('task_id')
if not task_id:
response_data = self.wrap_json_response(errmsg='Lost query params of task_id', code=ReturnCode.WRONG_PARAMS)
return jsonify(response_data)
dict_result = mongo_cli[vulscan_db].find_one({'_id': ObjectId(... | WebVulTaskView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebVulTaskView:
def get(self):
"""获取任务详情 --- tags: - Web漏洞检测 definitions: - schema: id: dao.webvul_taskinfo properties: target_id: type: array description: 目标ID items: type: string target_list: type: array description: 目标列表 items: type: string _id: type: string description: 任务ID task_nam... | stack_v2_sparse_classes_75kplus_train_008535 | 17,764 | no_license | [
{
"docstring": "获取任务详情 --- tags: - Web漏洞检测 definitions: - schema: id: dao.webvul_taskinfo properties: target_id: type: array description: 目标ID items: type: string target_list: type: array description: 目标列表 items: type: string _id: type: string description: 任务ID task_name: type: string description: 任务名 status: t... | 3 | null | Implement the Python class `WebVulTaskView` described below.
Class description:
Implement the WebVulTaskView class.
Method signatures and docstrings:
- def get(self): 获取任务详情 --- tags: - Web漏洞检测 definitions: - schema: id: dao.webvul_taskinfo properties: target_id: type: array description: 目标ID items: type: string targ... | Implement the Python class `WebVulTaskView` described below.
Class description:
Implement the WebVulTaskView class.
Method signatures and docstrings:
- def get(self): 获取任务详情 --- tags: - Web漏洞检测 definitions: - schema: id: dao.webvul_taskinfo properties: target_id: type: array description: 目标ID items: type: string targ... | aa75f06ad25b1238176165a0dcf4685c59cd8284 | <|skeleton|>
class WebVulTaskView:
def get(self):
"""获取任务详情 --- tags: - Web漏洞检测 definitions: - schema: id: dao.webvul_taskinfo properties: target_id: type: array description: 目标ID items: type: string target_list: type: array description: 目标列表 items: type: string _id: type: string description: 任务ID task_nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebVulTaskView:
def get(self):
"""获取任务详情 --- tags: - Web漏洞检测 definitions: - schema: id: dao.webvul_taskinfo properties: target_id: type: array description: 目标ID items: type: string target_list: type: array description: 目标列表 items: type: string _id: type: string description: 任务ID task_name: type: strin... | the_stack_v2_python_sparse | aquaman/views/web_vul.py | jstang9527/aquaman | train | 15 | |
a3308edb21ae0e4abbd6b1b7265276b8c9ae6372 | [
"for port in ports:\n try:\n mode = os.stat(port).st_mode\n except OSError as e:\n raise ChargenTestError(e)\n if not stat.S_ISCHR(mode):\n raise ChargenTestError('%s is not a character device.' % port)\nif duration <= 0:\n raise ChargenTestError('Input error: duration is not positi... | <|body_start_0|>
for port in ports:
try:
mode = os.stat(port).st_mode
except OSError as e:
raise ChargenTestError(e)
if not stat.S_ISCHR(mode):
raise ChargenTestError('%s is not a character device.' % port)
if duration <... | UART stress tester Attributes: logger: logging object serials: Dictionary where key is filename of UART device, and the value is UartSerial object | ChargenTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChargenTest:
"""UART stress tester Attributes: logger: logging object serials: Dictionary where key is filename of UART device, and the value is UartSerial object"""
def __init__(self, ports, duration, cr50_workload=False, usb_output=False):
"""Initialize UART stress tester Args: por... | stack_v2_sparse_classes_75kplus_train_008536 | 18,551 | permissive | [
{
"docstring": "Initialize UART stress tester Args: ports: List of UART ports to test. duration: Time to keep testing in seconds. cr50_workload: True if a workload should be generated on cr50 usb_output: True if a workload should be generated to USB channel Raises: ChargenTestError: if any of ports is not a val... | 4 | stack_v2_sparse_classes_30k_train_052822 | Implement the Python class `ChargenTest` described below.
Class description:
UART stress tester Attributes: logger: logging object serials: Dictionary where key is filename of UART device, and the value is UartSerial object
Method signatures and docstrings:
- def __init__(self, ports, duration, cr50_workload=False, u... | Implement the Python class `ChargenTest` described below.
Class description:
UART stress tester Attributes: logger: logging object serials: Dictionary where key is filename of UART device, and the value is UartSerial object
Method signatures and docstrings:
- def __init__(self, ports, duration, cr50_workload=False, u... | f6d6b927eed71550d3475411cfc3e59abe5cef2a | <|skeleton|>
class ChargenTest:
"""UART stress tester Attributes: logger: logging object serials: Dictionary where key is filename of UART device, and the value is UartSerial object"""
def __init__(self, ports, duration, cr50_workload=False, usb_output=False):
"""Initialize UART stress tester Args: por... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChargenTest:
"""UART stress tester Attributes: logger: logging object serials: Dictionary where key is filename of UART device, and the value is UartSerial object"""
def __init__(self, ports, duration, cr50_workload=False, usb_output=False):
"""Initialize UART stress tester Args: ports: List of U... | the_stack_v2_python_sparse | util/uart_stress_tester.py | FrameworkComputer/EmbeddedController | train | 846 |
b95793d6938f209d6cbdc0a21b861d673381ce9a | [
"super().__init__(**kwargs)\nself._default_args = {}\ndict_full_update(self._default_args, self._base_args)\ndict_full_update(self._default_args, kwargs)\nself._default_args['url'] = url_assembly(**self._default_args)",
"response = False\ntry:\n result = self.__send(body, title, notify_type, *args, meta=self._... | <|body_start_0|>
super().__init__(**kwargs)
self._default_args = {}
dict_full_update(self._default_args, self._base_args)
dict_full_update(self._default_args, kwargs)
self._default_args['url'] = url_assembly(**self._default_args)
<|end_body_0|>
<|body_start_1|>
response ... | CustomNotifyPluginWrapper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomNotifyPluginWrapper:
def __init__(self, **kwargs):
"""Our initialization"""
<|body_0|>
def send(self, body, title='', notify_type=common.NotifyType.INFO, *args, **kwargs):
"""Our send() call which triggers our hook"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_008537 | 9,106 | permissive | [
{
"docstring": "Our initialization",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Our send() call which triggers our hook",
"name": "send",
"signature": "def send(self, body, title='', notify_type=common.NotifyType.INFO, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `CustomNotifyPluginWrapper` described below.
Class description:
Implement the CustomNotifyPluginWrapper class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Our initialization
- def send(self, body, title='', notify_type=common.NotifyType.INFO, *args, **kwargs): Our send... | Implement the Python class `CustomNotifyPluginWrapper` described below.
Class description:
Implement the CustomNotifyPluginWrapper class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Our initialization
- def send(self, body, title='', notify_type=common.NotifyType.INFO, *args, **kwargs): Our send... | be3baed7e3d33bae973f1714df4ebbf65aa33f85 | <|skeleton|>
class CustomNotifyPluginWrapper:
def __init__(self, **kwargs):
"""Our initialization"""
<|body_0|>
def send(self, body, title='', notify_type=common.NotifyType.INFO, *args, **kwargs):
"""Our send() call which triggers our hook"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomNotifyPluginWrapper:
def __init__(self, **kwargs):
"""Our initialization"""
super().__init__(**kwargs)
self._default_args = {}
dict_full_update(self._default_args, self._base_args)
dict_full_update(self._default_args, kwargs)
self._default_args['url'] = ur... | the_stack_v2_python_sparse | apprise/decorators/CustomNotifyPlugin.py | caronc/apprise | train | 8,426 | |
07a6929141184e5c65d6621f6e8d872ef933ce02 | [
"_input = input.clone()\nif isinstance(module, (K.GeometricAugmentationBase2D,)):\n _input = module.transform_keypoints(_input, cls.get_instance_module_param(param), module.flags, transform=module.transform_matrix, **extra_args)\nelif isinstance(module, (K.GeometricAugmentationBase3D,)):\n raise NotImplemente... | <|body_start_0|>
_input = input.clone()
if isinstance(module, (K.GeometricAugmentationBase2D,)):
_input = module.transform_keypoints(_input, cls.get_instance_module_param(param), module.flags, transform=module.transform_matrix, **extra_args)
elif isinstance(module, (K.GeometricAugmen... | Apply and inverse transformations for keypoints tensors. This is for transform keypoints in the format (B, N, 2). | KeypointSequentialOps | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeypointSequentialOps:
"""Apply and inverse transformations for keypoints tensors. This is for transform keypoints in the format (B, N, 2)."""
def transform(cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any]={}) -> Keypoints:
"""Apply a transformation... | stack_v2_sparse_classes_75kplus_train_008538 | 19,475 | permissive | [
{
"docstring": "Apply a transformation with respect to the parameters. Args: input: the input tensor, (B, N, 4, 2) or (B, 4, 2). module: any torch Module but only kornia augmentation modules will count to apply transformations. param: the corresponding parameters to the module.",
"name": "transform",
"s... | 2 | null | Implement the Python class `KeypointSequentialOps` described below.
Class description:
Apply and inverse transformations for keypoints tensors. This is for transform keypoints in the format (B, N, 2).
Method signatures and docstrings:
- def transform(cls, input: Keypoints, module: Module, param: ParamItem, extra_args... | Implement the Python class `KeypointSequentialOps` described below.
Class description:
Apply and inverse transformations for keypoints tensors. This is for transform keypoints in the format (B, N, 2).
Method signatures and docstrings:
- def transform(cls, input: Keypoints, module: Module, param: ParamItem, extra_args... | 1e0f8baa7318c05b17ea6dbb48605691bca8972f | <|skeleton|>
class KeypointSequentialOps:
"""Apply and inverse transformations for keypoints tensors. This is for transform keypoints in the format (B, N, 2)."""
def transform(cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any]={}) -> Keypoints:
"""Apply a transformation... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeypointSequentialOps:
"""Apply and inverse transformations for keypoints tensors. This is for transform keypoints in the format (B, N, 2)."""
def transform(cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any]={}) -> Keypoints:
"""Apply a transformation with respect... | the_stack_v2_python_sparse | kornia/augmentation/container/ops.py | kornia/kornia | train | 7,351 |
34515948bdfba1f78f70d16bcfd012cd0dad1678 | [
"self.stack = []\nwhile root:\n self.stack.append(root)\n root = root.left",
"if len(self.stack) > 0:\n return True\nreturn False",
"node = self.stack.pop()\nnode_right = node.right\nwhile node_right:\n self.stack.append(node_right)\n node_right = node_right.left\nreturn node.val"
] | <|body_start_0|>
self.stack = []
while root:
self.stack.append(root)
root = root.left
<|end_body_0|>
<|body_start_1|>
if len(self.stack) > 0:
return True
return False
<|end_body_1|>
<|body_start_2|>
node = self.stack.pop()
node_right ... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.stack = []
... | stack_v2_sparse_classes_75kplus_train_008539 | 1,082 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasNext(self)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_031528 | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int
<|skeleton|>
class BSTIterator:
def __init__(self, root... | f047810f01685d8bf513e8ee7dab9d15f1c04bbc | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.stack = []
while root:
self.stack.append(root)
root = root.left
def hasNext(self):
""":rtype: bool"""
if len(self.stack) > 0:
return True
return False... | the_stack_v2_python_sparse | leetcode/company specific problems/Amazon/binary_search_tree_iterator.py | Gabrielatb/Interview-Prep | train | 1 | |
b2391cedad75a08834a418f03a8b4d90fbd9891c | [
"mapping_file = open(filepath, 'r')\nmatrix = []\nfor row in mapping_file:\n matrix.append([int(n) for n in list(row)[:-1]])\nself._mapping = matrix",
"if score_from_current_incident > 1 or score_from_prev_incidents > 1:\n warnings.warn(f'Current or previous risk score > 1:\\n\\n Current:... | <|body_start_0|>
mapping_file = open(filepath, 'r')
matrix = []
for row in mapping_file:
matrix.append([int(n) for n in list(row)[:-1]])
self._mapping = matrix
<|end_body_0|>
<|body_start_1|>
if score_from_current_incident > 1 or score_from_prev_incidents > 1:
... | RiskScoreCombiner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskScoreCombiner:
def __init__(self, filepath: str='server/risk_scores/mapping.txt'):
"""Reads a text file that contains the mappings for incoming risk scores. e.g., _mapping[20, 30] corresponds to the risk score for all scores where: 0.20 <= score_from_current_incident < 0.21 0.30 <= s... | stack_v2_sparse_classes_75kplus_train_008540 | 5,842 | permissive | [
{
"docstring": "Reads a text file that contains the mappings for incoming risk scores. e.g., _mapping[20, 30] corresponds to the risk score for all scores where: 0.20 <= score_from_current_incident < 0.21 0.30 <= score_from_prev_incidents < 0.31",
"name": "__init__",
"signature": "def __init__(self, fil... | 2 | stack_v2_sparse_classes_30k_train_008268 | Implement the Python class `RiskScoreCombiner` described below.
Class description:
Implement the RiskScoreCombiner class.
Method signatures and docstrings:
- def __init__(self, filepath: str='server/risk_scores/mapping.txt'): Reads a text file that contains the mappings for incoming risk scores. e.g., _mapping[20, 30... | Implement the Python class `RiskScoreCombiner` described below.
Class description:
Implement the RiskScoreCombiner class.
Method signatures and docstrings:
- def __init__(self, filepath: str='server/risk_scores/mapping.txt'): Reads a text file that contains the mappings for incoming risk scores. e.g., _mapping[20, 30... | a2ff0c96f449e81998fca6fa083350cf22eac382 | <|skeleton|>
class RiskScoreCombiner:
def __init__(self, filepath: str='server/risk_scores/mapping.txt'):
"""Reads a text file that contains the mappings for incoming risk scores. e.g., _mapping[20, 30] corresponds to the risk score for all scores where: 0.20 <= score_from_current_incident < 0.21 0.30 <= s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RiskScoreCombiner:
def __init__(self, filepath: str='server/risk_scores/mapping.txt'):
"""Reads a text file that contains the mappings for incoming risk scores. e.g., _mapping[20, 30] corresponds to the risk score for all scores where: 0.20 <= score_from_current_incident < 0.21 0.30 <= score_from_prev... | the_stack_v2_python_sparse | server/risk_scores/risk_scores.py | Code-the-Change-YYC/YW-NLP-Report-Classifier | train | 1 | |
42c78aae211d122e6efaa4897def9d44b16f5d96 | [
"extra_context = cache_memoize('admin-widget-repos-data', lambda: self._get_repositories_data(request))\nextra_context['add_repo_docs_url'] = '%sadmin/configuration/repositories/' % get_manual_url()\nreturn extra_context",
"queryset = Repository.objects.accessible(request.user)\ntotal_repositories = queryset.coun... | <|body_start_0|>
extra_context = cache_memoize('admin-widget-repos-data', lambda: self._get_repositories_data(request))
extra_context['add_repo_docs_url'] = '%sadmin/configuration/repositories/' % get_manual_url()
return extra_context
<|end_body_0|>
<|body_start_1|>
queryset = Repositor... | A widget displaying the most recent repositories. This widget displays a grid of the most recent repositories and their services/types. | RepositoriesWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoriesWidget:
"""A widget displaying the most recent repositories. This widget displays a grid of the most recent repositories and their services/types."""
def get_extra_context(self, request):
"""Return extra context for the template. Args: request (django.http.HttpRequest): T... | stack_v2_sparse_classes_75kplus_train_008541 | 19,615 | permissive | [
{
"docstring": "Return extra context for the template. Args: request (django.http.HttpRequest): The HTTP request from the client. Returns: dict: Extra context to pass to the template.",
"name": "get_extra_context",
"signature": "def get_extra_context(self, request)"
},
{
"docstring": "Return dat... | 2 | stack_v2_sparse_classes_30k_train_002139 | Implement the Python class `RepositoriesWidget` described below.
Class description:
A widget displaying the most recent repositories. This widget displays a grid of the most recent repositories and their services/types.
Method signatures and docstrings:
- def get_extra_context(self, request): Return extra context for... | Implement the Python class `RepositoriesWidget` described below.
Class description:
A widget displaying the most recent repositories. This widget displays a grid of the most recent repositories and their services/types.
Method signatures and docstrings:
- def get_extra_context(self, request): Return extra context for... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class RepositoriesWidget:
"""A widget displaying the most recent repositories. This widget displays a grid of the most recent repositories and their services/types."""
def get_extra_context(self, request):
"""Return extra context for the template. Args: request (django.http.HttpRequest): T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepositoriesWidget:
"""A widget displaying the most recent repositories. This widget displays a grid of the most recent repositories and their services/types."""
def get_extra_context(self, request):
"""Return extra context for the template. Args: request (django.http.HttpRequest): The HTTP reque... | the_stack_v2_python_sparse | reviewboard/admin/widgets.py | reviewboard/reviewboard | train | 1,141 |
a509ef89257a2bff137624e4ec93709c45c28f79 | [
"test_name = self._testMethodName\nalways_allow(driver=self.driver)\nmylogger.debug(test_name)\nself.driver.implicitly_wait(5)\nuserAvatar_element(self.driver)\nmylogger.info('进入我的页面')\nself.driver.implicitly_wait(5)\ndL_element(self.driver)\nmylogger.info('点击注册/登录 进入登录页面')\nself.driver.implicitly_wait(10)\nwX_elem... | <|body_start_0|>
test_name = self._testMethodName
always_allow(driver=self.driver)
mylogger.debug(test_name)
self.driver.implicitly_wait(5)
userAvatar_element(self.driver)
mylogger.info('进入我的页面')
self.driver.implicitly_wait(5)
dL_element(self.driver)
... | WX | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WX:
def test_1(self):
"""微信登录"""
<|body_0|>
def test_2(self):
"""当前用户退出"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_name = self._testMethodName
always_allow(driver=self.driver)
mylogger.debug(test_name)
self.driver.i... | stack_v2_sparse_classes_75kplus_train_008542 | 1,793 | no_license | [
{
"docstring": "微信登录",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "当前用户退出",
"name": "test_2",
"signature": "def test_2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000561 | Implement the Python class `WX` described below.
Class description:
Implement the WX class.
Method signatures and docstrings:
- def test_1(self): 微信登录
- def test_2(self): 当前用户退出 | Implement the Python class `WX` described below.
Class description:
Implement the WX class.
Method signatures and docstrings:
- def test_1(self): 微信登录
- def test_2(self): 当前用户退出
<|skeleton|>
class WX:
def test_1(self):
"""微信登录"""
<|body_0|>
def test_2(self):
"""当前用户退出"""
<|b... | 5924b88c5bc2a41d62807cc665bb3a76dfe0f3d3 | <|skeleton|>
class WX:
def test_1(self):
"""微信登录"""
<|body_0|>
def test_2(self):
"""当前用户退出"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WX:
def test_1(self):
"""微信登录"""
test_name = self._testMethodName
always_allow(driver=self.driver)
mylogger.debug(test_name)
self.driver.implicitly_wait(5)
userAvatar_element(self.driver)
mylogger.info('进入我的页面')
self.driver.implicitly_wait(5)
... | the_stack_v2_python_sparse | testsuite/test1_wxdl.py | Lkamanda/LT | train | 2 | |
a8f3c7a256a5eb5b06b6988049109bae6d20b7bc | [
"self.case_input = case_input\nself.weights = weights\nself.biases = biases\nself.net0 = net0\nself.out0 = out0\nself.net1 = net1\nself.out1 = out1",
"print('Input array:')\nprint(self.case_input)\nprint('\\nWeights (first row corresponds to first output):')\nprint(self.weights)\nprint('\\nBiases:')\nprint(self.b... | <|body_start_0|>
self.case_input = case_input
self.weights = weights
self.biases = biases
self.net0 = net0
self.out0 = out0
self.net1 = net1
self.out1 = out1
<|end_body_0|>
<|body_start_1|>
print('Input array:')
print(self.case_input)
prin... | Describes a neural network of the type used in this example. | NeuralNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralNet:
"""Describes a neural network of the type used in this example."""
def __init__(self, case_input, weights, biases, net0, out0, net1, out1):
"""Create starting parts of the neural net."""
<|body_0|>
def describe(self):
"""Print information about the neu... | stack_v2_sparse_classes_75kplus_train_008543 | 11,919 | no_license | [
{
"docstring": "Create starting parts of the neural net.",
"name": "__init__",
"signature": "def __init__(self, case_input, weights, biases, net0, out0, net1, out1)"
},
{
"docstring": "Print information about the neural network.",
"name": "describe",
"signature": "def describe(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_036258 | Implement the Python class `NeuralNet` described below.
Class description:
Describes a neural network of the type used in this example.
Method signatures and docstrings:
- def __init__(self, case_input, weights, biases, net0, out0, net1, out1): Create starting parts of the neural net.
- def describe(self): Print info... | Implement the Python class `NeuralNet` described below.
Class description:
Describes a neural network of the type used in this example.
Method signatures and docstrings:
- def __init__(self, case_input, weights, biases, net0, out0, net1, out1): Create starting parts of the neural net.
- def describe(self): Print info... | bdde45fc936783fd80589c53e23aa3aabd11cc88 | <|skeleton|>
class NeuralNet:
"""Describes a neural network of the type used in this example."""
def __init__(self, case_input, weights, biases, net0, out0, net1, out1):
"""Create starting parts of the neural net."""
<|body_0|>
def describe(self):
"""Print information about the neu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralNet:
"""Describes a neural network of the type used in this example."""
def __init__(self, case_input, weights, biases, net0, out0, net1, out1):
"""Create starting parts of the neural net."""
self.case_input = case_input
self.weights = weights
self.biases = biases
... | the_stack_v2_python_sparse | Artificial Intelligence and Deep Learning/Training X-OR with Backpropagation/Codes/results_xor.py | yfeng47/Data-Science-Portfolio | train | 1 |
18d77dd3863b9e011dbbbf4f0089361ed26993ba | [
"super(Blank, self).__init__()\nself.__keywords = sorted(kw.keys())\nfor k, v in kw.iteritems():\n setattr(self, k, v)\nself.__isfrozen = True",
"if self.__isfrozen and (not hasattr(self, name)):\n raise AttributeError(\"Trying to set invalid attribute '%s'. Valid attributes are: %s.\" % (name, ', '.join(se... | <|body_start_0|>
super(Blank, self).__init__()
self.__keywords = sorted(kw.keys())
for k, v in kw.iteritems():
setattr(self, k, v)
self.__isfrozen = True
<|end_body_0|>
<|body_start_1|>
if self.__isfrozen and (not hasattr(self, name)):
raise AttributeErro... | Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dictionaries, but with simpler access... | Blank | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dict... | stack_v2_sparse_classes_75kplus_train_008544 | 4,466 | permissive | [
{
"docstring": "Initializes the attributes given in keyword arguments. No new attribute is allowed after this.",
"name": "__init__",
"signature": "def __init__(self, **kw)"
},
{
"docstring": "Sets an attribute. If the attribute name was given during initialization, it's set to value. Raises an e... | 4 | stack_v2_sparse_classes_30k_train_024421 | Implement the Python class `Blank` described below.
Class description:
Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use o... | Implement the Python class `Blank` described below.
Class description:
Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use o... | c1bcca66a5ef1ff0ebd6373e3820e72dee6b0b70 | <|skeleton|>
class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dict... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dictionaries, but... | the_stack_v2_python_sparse | mir3/data/blank.py | pymir3/pymir3 | train | 13 |
7aafae220e8992f9073ca1e4a03d26a851c53f20 | [
"if document not in models:\n abort(404, 'document does not exist')\nres = current_app.backend.documents_get(config, document)\nreturn marshal(res, models[document], skip_none=True)",
"if document not in models:\n abort(404, 'document does not exist')\ndata = marshal(request.json, models[document], skip_non... | <|body_start_0|>
if document not in models:
abort(404, 'document does not exist')
res = current_app.backend.documents_get(config, document)
return marshal(res, models[document], skip_none=True)
<|end_body_0|>
<|body_start_1|>
if document not in models:
abort(404,... | DocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentResource:
def get(self, config, document):
"""Get a complete document"""
<|body_0|>
def post(self, config, document):
"""Create a new complete document"""
<|body_1|>
def put(self, config, document):
"""Update an existing document"""
... | stack_v2_sparse_classes_75kplus_train_008545 | 23,252 | permissive | [
{
"docstring": "Get a complete document",
"name": "get",
"signature": "def get(self, config, document)"
},
{
"docstring": "Create a new complete document",
"name": "post",
"signature": "def post(self, config, document)"
},
{
"docstring": "Update an existing document",
"name":... | 4 | stack_v2_sparse_classes_30k_train_003321 | Implement the Python class `DocumentResource` described below.
Class description:
Implement the DocumentResource class.
Method signatures and docstrings:
- def get(self, config, document): Get a complete document
- def post(self, config, document): Create a new complete document
- def put(self, config, document): Upd... | Implement the Python class `DocumentResource` described below.
Class description:
Implement the DocumentResource class.
Method signatures and docstrings:
- def get(self, config, document): Get a complete document
- def post(self, config, document): Create a new complete document
- def put(self, config, document): Upd... | f40321800c04fe68a0da425b4c65602ed132657e | <|skeleton|>
class DocumentResource:
def get(self, config, document):
"""Get a complete document"""
<|body_0|>
def post(self, config, document):
"""Create a new complete document"""
<|body_1|>
def put(self, config, document):
"""Update an existing document"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentResource:
def get(self, config, document):
"""Get a complete document"""
if document not in models:
abort(404, 'document does not exist')
res = current_app.backend.documents_get(config, document)
return marshal(res, models[document], skip_none=True)
def... | the_stack_v2_python_sparse | curiefense/curieconf/server/curieconf/confserver/v1/api.py | jdorfman/curiefense | train | 0 | |
a38edfb4d11a8be7b8b782cd0d8b2d74dcbd878a | [
"try:\n book = BookInfo.objects.get(pk=pk)\nexcept:\n return Http404('数据不存在')\nbook_dict = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date}\nreturn JsonResponse(book_dict)",
"param_dict = json.loads(request.body.decode())\nbtitle = param_dict.get('btitle')\nbpub_date = param_dict.get('bpu... | <|body_start_0|>
try:
book = BookInfo.objects.get(pk=pk)
except:
return Http404('数据不存在')
book_dict = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date}
return JsonResponse(book_dict)
<|end_body_0|>
<|body_start_1|>
param_dict = json.loads... | BookView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookView:
def get(self, request, pk):
"""根据主键查询一个对象"""
<|body_0|>
def put(self, request, pk):
"""修改指定主键的对象"""
<|body_1|>
def delete(self, request, pk):
"""删除指定主键的对象"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_008546 | 3,452 | permissive | [
{
"docstring": "根据主键查询一个对象",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "修改指定主键的对象",
"name": "put",
"signature": "def put(self, request, pk)"
},
{
"docstring": "删除指定主键的对象",
"name": "delete",
"signature": "def delete(self, request, pk)"
}
... | 3 | stack_v2_sparse_classes_30k_train_025631 | Implement the Python class `BookView` described below.
Class description:
Implement the BookView class.
Method signatures and docstrings:
- def get(self, request, pk): 根据主键查询一个对象
- def put(self, request, pk): 修改指定主键的对象
- def delete(self, request, pk): 删除指定主键的对象 | Implement the Python class `BookView` described below.
Class description:
Implement the BookView class.
Method signatures and docstrings:
- def get(self, request, pk): 根据主键查询一个对象
- def put(self, request, pk): 修改指定主键的对象
- def delete(self, request, pk): 删除指定主键的对象
<|skeleton|>
class BookView:
def get(self, request... | 63ae6891d3be243c5c46329e65fcf47133c5890f | <|skeleton|>
class BookView:
def get(self, request, pk):
"""根据主键查询一个对象"""
<|body_0|>
def put(self, request, pk):
"""修改指定主键的对象"""
<|body_1|>
def delete(self, request, pk):
"""删除指定主键的对象"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookView:
def get(self, request, pk):
"""根据主键查询一个对象"""
try:
book = BookInfo.objects.get(pk=pk)
except:
return Http404('数据不存在')
book_dict = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date}
return JsonResponse(book_dict)
def... | the_stack_v2_python_sparse | pro_drf/demo1/booktest/views.py | yongfang117/pro_useful_code | train | 0 | |
6910c6d218fcb79d896fa7c111c82895a03ebd13 | [
"self.comid = comid\nself.hydroseq = hydroseq\nself.down = down\nself.up = up\nself.drain = drain\nself.area = area\nself.divarea = div\nself.reach = reachcode",
"self.maxelev = maxelev\nself.minelev = minelev\nself.length = length",
"self.flow = flow\nself.velocity = velocity\nself.gageid = gageid",
"ft_per_... | <|body_start_0|>
self.comid = comid
self.hydroseq = hydroseq
self.down = down
self.up = up
self.drain = drain
self.area = area
self.divarea = div
self.reach = reachcode
<|end_body_0|>
<|body_start_1|>
self.maxelev = maxelev
self.minelev = ... | A class to store the attributes of a flowline from the NHDPlus database. | Flowline | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flowline:
"""A class to store the attributes of a flowline from the NHDPlus database."""
def __init__(self, comid, hydroseq, down, up, drain, area, div, reachcode):
"""Attributes from NHDPlus PlusFlowVAA."""
<|body_0|>
def add_slope(self, maxelev, minelev, length):
... | stack_v2_sparse_classes_75kplus_train_008547 | 1,290 | permissive | [
{
"docstring": "Attributes from NHDPlus PlusFlowVAA.",
"name": "__init__",
"signature": "def __init__(self, comid, hydroseq, down, up, drain, area, div, reachcode)"
},
{
"docstring": "Attributes from NHDPlus ElevSlope.",
"name": "add_slope",
"signature": "def add_slope(self, maxelev, min... | 4 | stack_v2_sparse_classes_30k_train_046965 | Implement the Python class `Flowline` described below.
Class description:
A class to store the attributes of a flowline from the NHDPlus database.
Method signatures and docstrings:
- def __init__(self, comid, hydroseq, down, up, drain, area, div, reachcode): Attributes from NHDPlus PlusFlowVAA.
- def add_slope(self, ... | Implement the Python class `Flowline` described below.
Class description:
A class to store the attributes of a flowline from the NHDPlus database.
Method signatures and docstrings:
- def __init__(self, comid, hydroseq, down, up, drain, area, div, reachcode): Attributes from NHDPlus PlusFlowVAA.
- def add_slope(self, ... | 248f0193391b5019df28987ef93f35eebb575ee1 | <|skeleton|>
class Flowline:
"""A class to store the attributes of a flowline from the NHDPlus database."""
def __init__(self, comid, hydroseq, down, up, drain, area, div, reachcode):
"""Attributes from NHDPlus PlusFlowVAA."""
<|body_0|>
def add_slope(self, maxelev, minelev, length):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Flowline:
"""A class to store the attributes of a flowline from the NHDPlus database."""
def __init__(self, comid, hydroseq, down, up, drain, area, div, reachcode):
"""Attributes from NHDPlus PlusFlowVAA."""
self.comid = comid
self.hydroseq = hydroseq
self.down = down
... | the_stack_v2_python_sparse | src/pyhspf/preprocessing/flowline.py | xuexianwu/PyHSPF | train | 0 |
f6d9cf8630a7fa3df33e5ab2a585ed50947b3b96 | [
"instance.remove = validated_data.get('remove', instance.remove)\ninstance.save()\nreturn instance",
"instance = ShareTeamProject(**validated_data)\ninstance.save()\nreturn instance"
] | <|body_start_0|>
instance.remove = validated_data.get('remove', instance.remove)
instance.save()
return instance
<|end_body_0|>
<|body_start_1|>
instance = ShareTeamProject(**validated_data)
instance.save()
return instance
<|end_body_1|>
| Remove a team from a project. | RemoveTeamFromProjectSerializer | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveTeamFromProjectSerializer:
"""Remove a team from a project."""
def update(self, instance, validated_data):
"""Remove a team from a project"""
<|body_0|>
def create(self, validated_data):
"""Remove a team from a project"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_008548 | 1,900 | permissive | [
{
"docstring": "Remove a team from a project",
"name": "update",
"signature": "def update(self, instance, validated_data)"
},
{
"docstring": "Remove a team from a project",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012786 | Implement the Python class `RemoveTeamFromProjectSerializer` described below.
Class description:
Remove a team from a project.
Method signatures and docstrings:
- def update(self, instance, validated_data): Remove a team from a project
- def create(self, validated_data): Remove a team from a project | Implement the Python class `RemoveTeamFromProjectSerializer` described below.
Class description:
Remove a team from a project.
Method signatures and docstrings:
- def update(self, instance, validated_data): Remove a team from a project
- def create(self, validated_data): Remove a team from a project
<|skeleton|>
cla... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class RemoveTeamFromProjectSerializer:
"""Remove a team from a project."""
def update(self, instance, validated_data):
"""Remove a team from a project"""
<|body_0|>
def create(self, validated_data):
"""Remove a team from a project"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoveTeamFromProjectSerializer:
"""Remove a team from a project."""
def update(self, instance, validated_data):
"""Remove a team from a project"""
instance.remove = validated_data.get('remove', instance.remove)
instance.save()
return instance
def create(self, validat... | the_stack_v2_python_sparse | onadata/libs/serializers/share_team_project_serializer.py | onaio/onadata | train | 177 |
93dfb7f205faacc4290127bb99d058ee0f466153 | [
"gst_data = mongoUtils.index('gst')\nreturn_data = []\nfor gst in gst_data:\n return_data.append(dict(_id=gst['_id']))\nreturn (dumps(return_data), 200)",
"data = mongoUtils.get('gst', uuid)\nif data:\n return (dumps(data), 200)\nelse:\n return ('Not Found', 404)"
] | <|body_start_0|>
gst_data = mongoUtils.index('gst')
return_data = []
for gst in gst_data:
return_data.append(dict(_id=gst['_id']))
return (dumps(return_data), 200)
<|end_body_0|>
<|body_start_1|>
data = mongoUtils.get('gst', uuid)
if data:
return ... | GstView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GstView:
def index(self):
"""Returns a list of GST and their details, used by: `katana gst ls`"""
<|body_0|>
def get(self, uuid):
"""Returns the details of specific GST, used by: `katana gst inspect [uuid]`"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008549 | 1,388 | permissive | [
{
"docstring": "Returns a list of GST and their details, used by: `katana gst ls`",
"name": "index",
"signature": "def index(self)"
},
{
"docstring": "Returns the details of specific GST, used by: `katana gst inspect [uuid]`",
"name": "get",
"signature": "def get(self, uuid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053745 | Implement the Python class `GstView` described below.
Class description:
Implement the GstView class.
Method signatures and docstrings:
- def index(self): Returns a list of GST and their details, used by: `katana gst ls`
- def get(self, uuid): Returns the details of specific GST, used by: `katana gst inspect [uuid]` | Implement the Python class `GstView` described below.
Class description:
Implement the GstView class.
Method signatures and docstrings:
- def index(self): Returns a list of GST and their details, used by: `katana gst ls`
- def get(self, uuid): Returns the details of specific GST, used by: `katana gst inspect [uuid]`
... | 2e7a14a41fc85bd7188d71ef9beaf51acc94015c | <|skeleton|>
class GstView:
def index(self):
"""Returns a list of GST and their details, used by: `katana gst ls`"""
<|body_0|>
def get(self, uuid):
"""Returns the details of specific GST, used by: `katana gst inspect [uuid]`"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GstView:
def index(self):
"""Returns a list of GST and their details, used by: `katana gst ls`"""
gst_data = mongoUtils.index('gst')
return_data = []
for gst in gst_data:
return_data.append(dict(_id=gst['_id']))
return (dumps(return_data), 200)
def get(... | the_stack_v2_python_sparse | katana-nbi/katana/api/gst.py | tgogos/katana-slice_manager | train | 0 | |
a18b9e34b72348f510e9bac436026852b5e4459b | [
"rev_total = self.score * self.count\nrev_total += review.score\nself.count += 1\nself.score = rev_total / self.count\nself.save()",
"reviews = Review.objects.filter(item=self.item).filter(color=self.color)\ncount = len(reviews)\nagg = sum((review.score for review in reviews))\nself.count = count\nself.score = ag... | <|body_start_0|>
rev_total = self.score * self.count
rev_total += review.score
self.count += 1
self.score = rev_total / self.count
self.save()
<|end_body_0|>
<|body_start_1|>
reviews = Review.objects.filter(item=self.item).filter(color=self.color)
count = len(rev... | ReviewAvg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewAvg:
def add_review(self, review):
"""Adjust the score and the count based on a review"""
<|body_0|>
def reset_average(self):
"""Totally resets averages by looking at all reviews"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rev_total = self... | stack_v2_sparse_classes_75kplus_train_008550 | 1,555 | no_license | [
{
"docstring": "Adjust the score and the count based on a review",
"name": "add_review",
"signature": "def add_review(self, review)"
},
{
"docstring": "Totally resets averages by looking at all reviews",
"name": "reset_average",
"signature": "def reset_average(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009893 | Implement the Python class `ReviewAvg` described below.
Class description:
Implement the ReviewAvg class.
Method signatures and docstrings:
- def add_review(self, review): Adjust the score and the count based on a review
- def reset_average(self): Totally resets averages by looking at all reviews | Implement the Python class `ReviewAvg` described below.
Class description:
Implement the ReviewAvg class.
Method signatures and docstrings:
- def add_review(self, review): Adjust the score and the count based on a review
- def reset_average(self): Totally resets averages by looking at all reviews
<|skeleton|>
class ... | 36e08862d1bbcc9a4b535d948199e569ecbdd115 | <|skeleton|>
class ReviewAvg:
def add_review(self, review):
"""Adjust the score and the count based on a review"""
<|body_0|>
def reset_average(self):
"""Totally resets averages by looking at all reviews"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReviewAvg:
def add_review(self, review):
"""Adjust the score and the count based on a review"""
rev_total = self.score * self.count
rev_total += review.score
self.count += 1
self.score = rev_total / self.count
self.save()
def reset_average(self):
""... | the_stack_v2_python_sparse | Assignments/Brea/Django Labs/color_review_base/colors/models.py | PdxCodeGuild/class_mudpuppy | train | 5 | |
725638e3324986a74500d31db22aae5ed36aa4d7 | [
"self.matrix = matrix\nself.prefix_sum = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if i == 0:\n self.prefix_sum[i][j] = matrix[i][j]\n else:\n self.prefix_sum[i][j] = matrix[i][j] + self.p... | <|body_start_0|>
self.matrix = matrix
self.prefix_sum = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i == 0:
self.prefix_sum[i][j] = matrix[i][j]
el... | NumMatrix1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix1:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":ty... | stack_v2_sparse_classes_75kplus_train_008551 | 4,080 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | stack_v2_sparse_classes_30k_train_014922 | Implement the Python class `NumMatrix1` described below.
Class description:
Implement the NumMatrix1 class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, r... | Implement the Python class `NumMatrix1` described below.
Class description:
Implement the NumMatrix1 class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, r... | c7bf3eed366b91d6bdebb79d0f11680cf7c18344 | <|skeleton|>
class NumMatrix1:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix1:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.matrix = matrix
self.prefix_sum = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i == 0... | the_stack_v2_python_sparse | ch09/optional/0817-range-sum-query-2d-mutable.py | zzy1120716/my-nine-chapter | train | 0 | |
06f60112d8b0de54934ffb50a1d0743103898ab3 | [
"self.clock = False\nself.bus = bus\nself.bus.register(self)\nself._data = [0] * (16635 + 1)\nreturn",
"if self.bus.address > 16635:\n return\nif self.bus.mode == MODE.READ:\n self.bus.data = self._data[self.bus.address]\nelif self.bus.mode == MODE.WRITE:\n self._data[self.bus.address] = self.bus.data\nr... | <|body_start_0|>
self.clock = False
self.bus = bus
self.bus.register(self)
self._data = [0] * (16635 + 1)
return
<|end_body_0|>
<|body_start_1|>
if self.bus.address > 16635:
return
if self.bus.mode == MODE.READ:
self.bus.data = self._data[... | class ROM ======================== Cette classe représente la mémoire du micro-ordinateur. Elle contient une fonction qui permet d'uploader le code dans la mémoire ROM (un peu comme nous pourrions le faire avec certains micro-controlleur USB). À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effect... | ROM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROM:
"""class ROM ======================== Cette classe représente la mémoire du micro-ordinateur. Elle contient une fonction qui permet d'uploader le code dans la mémoire ROM (un peu comme nous pourrions le faire avec certains micro-controlleur USB). À chaque coup d'horloge (clock/event), la cla... | stack_v2_sparse_classes_75kplus_train_008552 | 4,546 | permissive | [
{
"docstring": "Constructeur de la classe ROM. Le constructeur s'occupe d'initialiser la mémoire et lie ce composant avec le bus. :example: >>> test = ROM(modBus.Bus()) :param bus: Composant Bus du Micro-Ordinateur. :type bus: Bus",
"name": "__init__",
"signature": "def __init__(self, bus)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_046502 | Implement the Python class `ROM` described below.
Class description:
class ROM ======================== Cette classe représente la mémoire du micro-ordinateur. Elle contient une fonction qui permet d'uploader le code dans la mémoire ROM (un peu comme nous pourrions le faire avec certains micro-controlleur USB). À chaq... | Implement the Python class `ROM` described below.
Class description:
class ROM ======================== Cette classe représente la mémoire du micro-ordinateur. Elle contient une fonction qui permet d'uploader le code dans la mémoire ROM (un peu comme nous pourrions le faire avec certains micro-controlleur USB). À chaq... | 0a3a9b0deffa16e8c851eb53e6aad1a8983936e6 | <|skeleton|>
class ROM:
"""class ROM ======================== Cette classe représente la mémoire du micro-ordinateur. Elle contient une fonction qui permet d'uploader le code dans la mémoire ROM (un peu comme nous pourrions le faire avec certains micro-controlleur USB). À chaque coup d'horloge (clock/event), la cla... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ROM:
"""class ROM ======================== Cette classe représente la mémoire du micro-ordinateur. Elle contient une fonction qui permet d'uploader le code dans la mémoire ROM (un peu comme nous pourrions le faire avec certains micro-controlleur USB). À chaque coup d'horloge (clock/event), la classe vérifie s... | the_stack_v2_python_sparse | Modules/04-04-ROM.py | MarcAndreJean/PCONC | train | 0 |
e15b465622e47a68a8695038667022d733c9c81c | [
"effectiveTime = self.get_time2()[1]\nexpirationTime = self.get_time2()[2]\nsend_url = self.get_peizhi('mensuo', yaml_ming='yilou_fangdong.yaml')\nsend_url = send_url['addDoorGuestPwd']\nlogging.info('url is %s' % send_url)\nsend_dict = {'doorId': doorId, 'effectiveTime': effectiveTime, 'expirationTime': expiration... | <|body_start_0|>
effectiveTime = self.get_time2()[1]
expirationTime = self.get_time2()[2]
send_url = self.get_peizhi('mensuo', yaml_ming='yilou_fangdong.yaml')
send_url = send_url['addDoorGuestPwd']
logging.info('url is %s' % send_url)
send_dict = {'doorId': doorId, 'effe... | 门锁 | MenSuo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenSuo:
"""门锁"""
def getNewDoorPWD(self, doorId, mobile, name):
"""创建临时密码 :param doorId: 门锁ID :return:"""
<|body_0|>
def listDoorInfo(self, houseId):
"""获取房源门锁列表 :param houseId: :return:"""
<|body_1|>
def getDoorBaseInfo(self, doorId):
"""获取门... | stack_v2_sparse_classes_75kplus_train_008553 | 3,026 | no_license | [
{
"docstring": "创建临时密码 :param doorId: 门锁ID :return:",
"name": "getNewDoorPWD",
"signature": "def getNewDoorPWD(self, doorId, mobile, name)"
},
{
"docstring": "获取房源门锁列表 :param houseId: :return:",
"name": "listDoorInfo",
"signature": "def listDoorInfo(self, houseId)"
},
{
"docstrin... | 5 | null | Implement the Python class `MenSuo` described below.
Class description:
门锁
Method signatures and docstrings:
- def getNewDoorPWD(self, doorId, mobile, name): 创建临时密码 :param doorId: 门锁ID :return:
- def listDoorInfo(self, houseId): 获取房源门锁列表 :param houseId: :return:
- def getDoorBaseInfo(self, doorId): 获取门锁基本信息 :param do... | Implement the Python class `MenSuo` described below.
Class description:
门锁
Method signatures and docstrings:
- def getNewDoorPWD(self, doorId, mobile, name): 创建临时密码 :param doorId: 门锁ID :return:
- def listDoorInfo(self, houseId): 获取房源门锁列表 :param houseId: :return:
- def getDoorBaseInfo(self, doorId): 获取门锁基本信息 :param do... | e173d4e535ac22b72b67371b8a2524ee425cdcbf | <|skeleton|>
class MenSuo:
"""门锁"""
def getNewDoorPWD(self, doorId, mobile, name):
"""创建临时密码 :param doorId: 门锁ID :return:"""
<|body_0|>
def listDoorInfo(self, houseId):
"""获取房源门锁列表 :param houseId: :return:"""
<|body_1|>
def getDoorBaseInfo(self, doorId):
"""获取门... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenSuo:
"""门锁"""
def getNewDoorPWD(self, doorId, mobile, name):
"""创建临时密码 :param doorId: 门锁ID :return:"""
effectiveTime = self.get_time2()[1]
expirationTime = self.get_time2()[2]
send_url = self.get_peizhi('mensuo', yaml_ming='yilou_fangdong.yaml')
send_url = send_... | the_stack_v2_python_sparse | public/aYiLou_fangdong/yilou_fangdong_business/yilou_fangdong_menSuo.py | GSIL-Monitor/mrbao_python | train | 0 |
09dfba5d7654b314c15dde8fb145403b4e99554f | [
"F = defaultdict(lambda: defaultdict(int))\nm = len(word1)\nn = len(word2)\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n F[i][j] = F[i - 1][j - 1] + 1\n else:\n F[i][j] = max(F[i - 1][j], F[i][j - 1])\nreturn m - F[m][n] + n - F[m]... | <|body_start_0|>
F = defaultdict(lambda: defaultdict(int))
m = len(word1)
n = len(word2)
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
F[i][j] = F[i - 1][j - 1] + 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""Longest Common Subsequence (LCS) Find the LCS, and delete the char in BOTH strings into LCS Let F[i][j] be length of LCS word1[:i] and word2[:j] F[i][j] = F[i-1][j-1] + 1 if word1[i-1] == word2[j-1] F[i][j] = max(F[i-1][j... | stack_v2_sparse_classes_75kplus_train_008554 | 2,291 | no_license | [
{
"docstring": "Longest Common Subsequence (LCS) Find the LCS, and delete the char in BOTH strings into LCS Let F[i][j] be length of LCS word1[:i] and word2[:j] F[i][j] = F[i-1][j-1] + 1 if word1[i-1] == word2[j-1] F[i][j] = max(F[i-1][j], F[i][j-1])",
"name": "minDistance",
"signature": "def minDistanc... | 2 | stack_v2_sparse_classes_30k_train_035599 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: Longest Common Subsequence (LCS) Find the LCS, and delete the char in BOTH strings into LCS Let F[i][j] be length of LCS wor... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: Longest Common Subsequence (LCS) Find the LCS, and delete the char in BOTH strings into LCS Let F[i][j] be length of LCS wor... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""Longest Common Subsequence (LCS) Find the LCS, and delete the char in BOTH strings into LCS Let F[i][j] be length of LCS word1[:i] and word2[:j] F[i][j] = F[i-1][j-1] + 1 if word1[i-1] == word2[j-1] F[i][j] = max(F[i-1][j... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""Longest Common Subsequence (LCS) Find the LCS, and delete the char in BOTH strings into LCS Let F[i][j] be length of LCS word1[:i] and word2[:j] F[i][j] = F[i-1][j-1] + 1 if word1[i-1] == word2[j-1] F[i][j] = max(F[i-1][j], F[i][j-1])"... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/583 Delete Operation for Two Strings.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
02b435b71f152337db30b6fc6253d7152eaa245e | [
"self.data = data_input\nself.lr = lambda t: lt * np.exp(-t / lr)\nself.nr = lambda t: nt * np.exp(-t / nr)\nself.iterations = iterations\nxx, yy = np.meshgrid(np.linspace(0, 0.5, 10), np.linspace(0, 0.5, 10))\nself.w = np.stack((xx, yy), 2)\nself.initial_w = np.copy(self.w)\nself.neighborhood = lambda sigma: self.... | <|body_start_0|>
self.data = data_input
self.lr = lambda t: lt * np.exp(-t / lr)
self.nr = lambda t: nt * np.exp(-t / nr)
self.iterations = iterations
xx, yy = np.meshgrid(np.linspace(0, 0.5, 10), np.linspace(0, 0.5, 10))
self.w = np.stack((xx, yy), 2)
self.initia... | A self organizing map | SOM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SOM:
"""A self organizing map"""
def __init__(self, data_input, lr=300, lt=4, nr=300, nt=4, iterations=2000):
"""Initialization"""
<|body_0|>
def train(self):
"""Train the SOM"""
<|body_1|>
def gkern(sig, n):
"""creates gaussian kernel look u... | stack_v2_sparse_classes_75kplus_train_008555 | 8,324 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, data_input, lr=300, lt=4, nr=300, nt=4, iterations=2000)"
},
{
"docstring": "Train the SOM",
"name": "train",
"signature": "def train(self)"
},
{
"docstring": "creates gaussian kernel look up ta... | 3 | stack_v2_sparse_classes_30k_train_009370 | Implement the Python class `SOM` described below.
Class description:
A self organizing map
Method signatures and docstrings:
- def __init__(self, data_input, lr=300, lt=4, nr=300, nt=4, iterations=2000): Initialization
- def train(self): Train the SOM
- def gkern(sig, n): creates gaussian kernel look up table | Implement the Python class `SOM` described below.
Class description:
A self organizing map
Method signatures and docstrings:
- def __init__(self, data_input, lr=300, lt=4, nr=300, nt=4, iterations=2000): Initialization
- def train(self): Train the SOM
- def gkern(sig, n): creates gaussian kernel look up table
<|skel... | afb0bac438cccc7e759ec9961f240745b48da664 | <|skeleton|>
class SOM:
"""A self organizing map"""
def __init__(self, data_input, lr=300, lt=4, nr=300, nt=4, iterations=2000):
"""Initialization"""
<|body_0|>
def train(self):
"""Train the SOM"""
<|body_1|>
def gkern(sig, n):
"""creates gaussian kernel look u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SOM:
"""A self organizing map"""
def __init__(self, data_input, lr=300, lt=4, nr=300, nt=4, iterations=2000):
"""Initialization"""
self.data = data_input
self.lr = lambda t: lt * np.exp(-t / lr)
self.nr = lambda t: nt * np.exp(-t / nr)
self.iterations = iterations
... | the_stack_v2_python_sparse | HW2/code/Problem3.py | vanandrew/BME572 | train | 0 |
94ee02b8bd646e085100725fb7389e78ad1fb518 | [
"headers = {}\nif status:\n headers['x-image-meta-status'] = status\nurl = '/v1/images/' + image_id\nresponse = self._put(url, headers)\nresponse.raise_for_status()",
"response = self._head('/v1/images/{}'.format(image_id))\nresponse.raise_for_status()\ndata = self._retrieve_data(response)\nreturn Resource(sel... | <|body_start_0|>
headers = {}
if status:
headers['x-image-meta-status'] = status
url = '/v1/images/' + image_id
response = self._put(url, headers)
response.raise_for_status()
<|end_body_0|>
<|body_start_1|>
response = self._head('/v1/images/{}'.format(image_i... | Glance API client v1. | ApiClientV1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiClientV1:
"""Glance API client v1."""
def images_update(self, image_id, status=None):
"""Update image via API call."""
<|body_0|>
def images_get(self, image_id):
"""Get image via API call. Args: image id (str): image ID Returns: Resource: image"""
<|bo... | stack_v2_sparse_classes_75kplus_train_008556 | 1,422 | no_license | [
{
"docstring": "Update image via API call.",
"name": "images_update",
"signature": "def images_update(self, image_id, status=None)"
},
{
"docstring": "Get image via API call. Args: image id (str): image ID Returns: Resource: image",
"name": "images_get",
"signature": "def images_get(self... | 2 | stack_v2_sparse_classes_30k_val_002237 | Implement the Python class `ApiClientV1` described below.
Class description:
Glance API client v1.
Method signatures and docstrings:
- def images_update(self, image_id, status=None): Update image via API call.
- def images_get(self, image_id): Get image via API call. Args: image id (str): image ID Returns: Resource: ... | Implement the Python class `ApiClientV1` described below.
Class description:
Glance API client v1.
Method signatures and docstrings:
- def images_update(self, image_id, status=None): Update image via API call.
- def images_get(self, image_id): Get image via API call. Args: image id (str): image ID Returns: Resource: ... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class ApiClientV1:
"""Glance API client v1."""
def images_update(self, image_id, status=None):
"""Update image via API call."""
<|body_0|>
def images_get(self, image_id):
"""Get image via API call. Args: image id (str): image ID Returns: Resource: image"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiClientV1:
"""Glance API client v1."""
def images_update(self, image_id, status=None):
"""Update image via API call."""
headers = {}
if status:
headers['x-image-meta-status'] = status
url = '/v1/images/' + image_id
response = self._put(url, headers)
... | the_stack_v2_python_sparse | stepler/glance/api_clients/v1.py | Mirantis/stepler | train | 16 |
4a0dc7be60ff96c3a52cde3d05cd70679b6f8b20 | [
"self.domain = domain\nself.ip = ip\nself.ucenter = ucenter\nself.user = user\nself.password = password\nself.server = Server(self.ip, get_info=ALL)\nself.conn = Connection(self.server, user=self.domain + '\\\\' + self.user, password=self.password, auto_bind=True, authentication=NTLM)",
"att_list = ['displayName'... | <|body_start_0|>
self.domain = domain
self.ip = ip
self.ucenter = ucenter
self.user = user
self.password = password
self.server = Server(self.ip, get_info=ALL)
self.conn = Connection(self.server, user=self.domain + '\\' + self.user, password=self.password, auto_bi... | AD域操作 | Adoper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adoper:
"""AD域操作"""
def __init__(self, domain, ip, ucenter, user, password):
""":param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:"""
<|body_0|>
def searchuser(self, orgunit):
""":param orgunit: 组织单... | stack_v2_sparse_classes_75kplus_train_008557 | 4,132 | no_license | [
{
"docstring": ":param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:",
"name": "__init__",
"signature": "def __init__(self, domain, ip, ucenter, user, password)"
},
{
"docstring": ":param orgunit: 组织单元名,格式为aaa.bbb 即bbb组织下的aaa组织,不包含域地... | 4 | stack_v2_sparse_classes_30k_train_030948 | Implement the Python class `Adoper` described below.
Class description:
AD域操作
Method signatures and docstrings:
- def __init__(self, domain, ip, ucenter, user, password): :param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:
- def searchuser(self, orgunit)... | Implement the Python class `Adoper` described below.
Class description:
AD域操作
Method signatures and docstrings:
- def __init__(self, domain, ip, ucenter, user, password): :param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:
- def searchuser(self, orgunit)... | 2a733b34f337d4497051660f473a4cfb977fc15b | <|skeleton|>
class Adoper:
"""AD域操作"""
def __init__(self, domain, ip, ucenter, user, password):
""":param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:"""
<|body_0|>
def searchuser(self, orgunit):
""":param orgunit: 组织单... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Adoper:
"""AD域操作"""
def __init__(self, domain, ip, ucenter, user, password):
""":param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:"""
self.domain = domain
self.ip = ip
self.ucenter = ucenter
self.user... | the_stack_v2_python_sparse | VMwareAutoApi/kdldapapi/ldaptool/adoper.py | vkhaibao/PyProject | train | 1 |
d83ec030afe80674ea238dddee10e37aba7083de | [
"self.__server_ip = ip\nself.__port = port\nself.__tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"endpoint = (self.__server_ip, self.__port)\ntry:\n self.__tcp.connect(endpoint)\n print('conexao realizada com sucesso!')\n self.__method()\nexcept Exception as e:\n print('Erro de conecacao c... | <|body_start_0|>
self.__server_ip = ip
self.__port = port
self.__tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
<|end_body_0|>
<|body_start_1|>
endpoint = (self.__server_ip, self.__port)
try:
self.__tcp.connect(endpoint)
print('conexao realizada ... | Classe cliente | Cliente | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cliente:
"""Classe cliente"""
def __init__(self, ip, port):
"""costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor"""
<|body_0|>
def start(self):
"""Metodo de inicializacao do cliente"""
<|body_1|>
def __method(self):
... | stack_v2_sparse_classes_75kplus_train_008558 | 1,751 | no_license | [
{
"docstring": "costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor",
"name": "__init__",
"signature": "def __init__(self, ip, port)"
},
{
"docstring": "Metodo de inicializacao do cliente",
"name": "start",
"signature": "def start(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_020126 | Implement the Python class `Cliente` described below.
Class description:
Classe cliente
Method signatures and docstrings:
- def __init__(self, ip, port): costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor
- def start(self): Metodo de inicializacao do cliente
- def __method(self): metodod ... | Implement the Python class `Cliente` described below.
Class description:
Classe cliente
Method signatures and docstrings:
- def __init__(self, ip, port): costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor
- def start(self): Metodo de inicializacao do cliente
- def __method(self): metodod ... | c7208c4075dc250e348003226c13c47142c05c71 | <|skeleton|>
class Cliente:
"""Classe cliente"""
def __init__(self, ip, port):
"""costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor"""
<|body_0|>
def start(self):
"""Metodo de inicializacao do cliente"""
<|body_1|>
def __method(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cliente:
"""Classe cliente"""
def __init__(self, ip, port):
"""costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor"""
self.__server_ip = ip
self.__port = port
self.__tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def start(self):
... | the_stack_v2_python_sparse | semana_7/cliente/cliente.py | EduardFonseca/InformaticaIndustrial | train | 0 |
91014a472b550ceb686eaaa31d5d08ec4938dce7 | [
"if start:\n s0 = 2 * start / mother2d.flambda()\nelse:\n print('No start scale given, set to 2*dx')\n s0 = 4 * res / mother2d.flambda()\na = s0 * 2.0 ** (np.arange(0, nb + 1) * dist)\nfreqs = 1.0 / (mother2d.flambda() * a)\nperiod = 1.0 / freqs\nscales = period / 2.0\nself.scale_dist = dist\nself.scale_st... | <|body_start_0|>
if start:
s0 = 2 * start / mother2d.flambda()
else:
print('No start scale given, set to 2*dx')
s0 = 4 * res / mother2d.flambda()
a = s0 * 2.0 ** (np.arange(0, nb + 1) * dist)
freqs = 1.0 / (mother2d.flambda() * a)
period = 1.0 ... | wavelet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wavelet:
def __init__(self, res, dist, nb, mother2d=w2d.Mexican_hat(), start=None):
"""2D continuous wavelet analysis initialisation. This only supports dx == dy. Initialisation sets the scales we want to decompose into. From Torrence and Compo: Mexican Hat period, in Fourier sense, is 4... | stack_v2_sparse_classes_75kplus_train_008559 | 3,390 | no_license | [
{
"docstring": "2D continuous wavelet analysis initialisation. This only supports dx == dy. Initialisation sets the scales we want to decompose into. From Torrence and Compo: Mexican Hat period, in Fourier sense, is 4 * wavelet scale :param res: pixel resolution of prospective input data (e.g. in km) :param dis... | 2 | stack_v2_sparse_classes_30k_train_019216 | Implement the Python class `wavelet` described below.
Class description:
Implement the wavelet class.
Method signatures and docstrings:
- def __init__(self, res, dist, nb, mother2d=w2d.Mexican_hat(), start=None): 2D continuous wavelet analysis initialisation. This only supports dx == dy. Initialisation sets the scale... | Implement the Python class `wavelet` described below.
Class description:
Implement the wavelet class.
Method signatures and docstrings:
- def __init__(self, res, dist, nb, mother2d=w2d.Mexican_hat(), start=None): 2D continuous wavelet analysis initialisation. This only supports dx == dy. Initialisation sets the scale... | 790ad1aa7e7a8c6593a21ee53b2c946b2f7a356b | <|skeleton|>
class wavelet:
def __init__(self, res, dist, nb, mother2d=w2d.Mexican_hat(), start=None):
"""2D continuous wavelet analysis initialisation. This only supports dx == dy. Initialisation sets the scales we want to decompose into. From Torrence and Compo: Mexican Hat period, in Fourier sense, is 4... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class wavelet:
def __init__(self, res, dist, nb, mother2d=w2d.Mexican_hat(), start=None):
"""2D continuous wavelet analysis initialisation. This only supports dx == dy. Initialisation sets the scales we want to decompose into. From Torrence and Compo: Mexican Hat period, in Fourier sense, is 4 * wavelet sca... | the_stack_v2_python_sparse | saveCore_standalone_v2/wav.py | cornkle/proj_CEH | train | 2 | |
f8b140da34b16442a8140e2f9d54191bd6efdd36 | [
"datasets = handler_get_request(request)\nfor dataset in datasets:\n if dataset.slug == dataset_name:\n return JsonResponse(serialize(dataset), safe=True)\nraise Http404()",
"request.PUT, request._files = parse_request(request)\nrequest.PUT._mutable = True\ntry:\n handle_pust_request(request, dataset... | <|body_start_0|>
datasets = handler_get_request(request)
for dataset in datasets:
if dataset.slug == dataset_name:
return JsonResponse(serialize(dataset), safe=True)
raise Http404()
<|end_body_0|>
<|body_start_1|>
request.PUT, request._files = parse_request(r... | DatasetShow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetShow:
def get(self, request, dataset_name):
"""Voir le jeu de données."""
<|body_0|>
def put(self, request, dataset_name):
"""Modifier le jeu de données."""
<|body_1|>
def delete(self, request, dataset_name):
"""Supprimer le jeu de données... | stack_v2_sparse_classes_75kplus_train_008560 | 14,797 | permissive | [
{
"docstring": "Voir le jeu de données.",
"name": "get",
"signature": "def get(self, request, dataset_name)"
},
{
"docstring": "Modifier le jeu de données.",
"name": "put",
"signature": "def put(self, request, dataset_name)"
},
{
"docstring": "Supprimer le jeu de données.",
"... | 3 | stack_v2_sparse_classes_30k_train_051847 | Implement the Python class `DatasetShow` described below.
Class description:
Implement the DatasetShow class.
Method signatures and docstrings:
- def get(self, request, dataset_name): Voir le jeu de données.
- def put(self, request, dataset_name): Modifier le jeu de données.
- def delete(self, request, dataset_name):... | Implement the Python class `DatasetShow` described below.
Class description:
Implement the DatasetShow class.
Method signatures and docstrings:
- def get(self, request, dataset_name): Voir le jeu de données.
- def put(self, request, dataset_name): Modifier le jeu de données.
- def delete(self, request, dataset_name):... | c73e67f22fa9bb38577c286271d02c2d9a708e40 | <|skeleton|>
class DatasetShow:
def get(self, request, dataset_name):
"""Voir le jeu de données."""
<|body_0|>
def put(self, request, dataset_name):
"""Modifier le jeu de données."""
<|body_1|>
def delete(self, request, dataset_name):
"""Supprimer le jeu de données... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetShow:
def get(self, request, dataset_name):
"""Voir le jeu de données."""
datasets = handler_get_request(request)
for dataset in datasets:
if dataset.slug == dataset_name:
return JsonResponse(serialize(dataset), safe=True)
raise Http404()
... | the_stack_v2_python_sparse | api/views/dataset.py | DataSud/DataSud-2017-2019 | train | 1 | |
2aa6b0330d3cc8239442815f6d2062ffebc1deaf | [
"parsed_url = URL(url)\nschema = parsed_url.drivername\nif '+' in schema:\n dialect, driver = schema.split('+')\nelse:\n dialect, driver = (schema, 'base')\ndialect = dialect.strip().lower()\ndriver = driver.strip()\narguments = {'echo': self._echo}\nif dialect == 'sqlite':\n arguments['module'] = sqlite3.... | <|body_start_0|>
parsed_url = URL(url)
schema = parsed_url.drivername
if '+' in schema:
dialect, driver = schema.split('+')
else:
dialect, driver = (schema, 'base')
dialect = dialect.strip().lower()
driver = driver.strip()
arguments = {'ech... | Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module use L{_url}.get_driver() instead. @... | BaseDAO | [
"EPL-1.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDAO:
"""Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module ... | stack_v2_sparse_classes_75kplus_train_008561 | 34,997 | permissive | [
{
"docstring": "Connect to the database using the given connection URL. The current implementation uses SQLAlchemy and so it will support whatever database said module supports. @type url: str @param url: URL that specifies the database to connect to. Some examples: - Opening an SQLite file: C{dao = CrashDAO(\"... | 2 | stack_v2_sparse_classes_30k_train_010784 | Implement the Python class `BaseDAO` described below.
Class description:
Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being... | Implement the Python class `BaseDAO` described below.
Class description:
Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being... | 05dbd4575d01a213f3f4d69aa4968473f2536142 | <|skeleton|>
class BaseDAO:
"""Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseDAO:
"""Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module use L{_url}.g... | the_stack_v2_python_sparse | python/helpers/pydev/pydevd_attach_to_process/winappdbg/sql.py | JetBrains/intellij-community | train | 16,288 |
02c7bfdc6ebb7f470269771b7ee997165d49b407 | [
"if self.tool in RelengTool.detected:\n return RelengTool.detected[self.tool]\nif not super(MesonTool, self).exists():\n debug('attempting to find {} in the running interpreter', self.tool)\n self._meson_interpreter = None\n try:\n import mesonbuild\n debug('{} tool is detected in the inte... | <|body_start_0|>
if self.tool in RelengTool.detected:
return RelengTool.detected[self.tool]
if not super(MesonTool, self).exists():
debug('attempting to find {} in the running interpreter', self.tool)
self._meson_interpreter = None
try:
imp... | meson host tool Provides addition helper methods for meson-based tool interaction. | MesonTool | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MesonTool:
"""meson host tool Provides addition helper methods for meson-based tool interaction."""
def exists(self):
"""return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` other... | stack_v2_sparse_classes_75kplus_train_008562 | 2,680 | permissive | [
{
"docstring": "return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` otherwise",
"name": "exists",
"signature": "def exists(self)"
},
{
"docstring": "returns the tool arguments to be invoked ... | 2 | stack_v2_sparse_classes_30k_test_002416 | Implement the Python class `MesonTool` described below.
Class description:
meson host tool Provides addition helper methods for meson-based tool interaction.
Method signatures and docstrings:
- def exists(self): return whether or not the host tool exists Returns whether or not the tool is available on the host for us... | Implement the Python class `MesonTool` described below.
Class description:
meson host tool Provides addition helper methods for meson-based tool interaction.
Method signatures and docstrings:
- def exists(self): return whether or not the host tool exists Returns whether or not the tool is available on the host for us... | d05eb2153c72e9bd82c5fdddd5eb41d5316592d6 | <|skeleton|>
class MesonTool:
"""meson host tool Provides addition helper methods for meson-based tool interaction."""
def exists(self):
"""return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` other... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MesonTool:
"""meson host tool Provides addition helper methods for meson-based tool interaction."""
def exists(self):
"""return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` otherwise"""
... | the_stack_v2_python_sparse | releng_tool/tool/meson.py | releng-tool/releng-tool | train | 12 |
a76c0a5311d456fe929a1f060cae6b9fe799fcba | [
"def helper(root):\n if not root:\n return None\n left_tail = helper(root.left)\n right_tail = helper(root.right)\n if not left_tail and (not right_tail):\n return root\n elif left_tail and right_tail:\n root.right, left_tail.right = (root.left, root.right)\n root.left = N... | <|body_start_0|>
def helper(root):
if not root:
return None
left_tail = helper(root.left)
right_tail = helper(root.right)
if not left_tail and (not right_tail):
return root
elif left_tail and right_tail:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_75kplus_train_008563 | 2,316 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.",
"name": "flatten",
... | 3 | stack_v2_sparse_classes_30k_train_054096 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: None Do n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: None Do n... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
def helper(root):
if not root:
return None
left_tail = helper(root.left)
right_tail = helper(root.right)
... | the_stack_v2_python_sparse | problems/flatten.py | joddiy/leetcode | train | 1 | |
a4d8b4f7d435e33388666d172d0a9367a0187ad6 | [
"SegmentSimMeasurement.__init__(self, source_segment, target_segment)\nself.lower_case = lower_case\nself.stopword_removal = stopword_removal\nself.stemming = stemming\nself.stemmer = stemmer\nself.lemmatization = lemmatization",
"s1_tokens = [token for token in self.source_segment.get_instances('part_of_speech',... | <|body_start_0|>
SegmentSimMeasurement.__init__(self, source_segment, target_segment)
self.lower_case = lower_case
self.stopword_removal = stopword_removal
self.stemming = stemming
self.stemmer = stemmer
self.lemmatization = lemmatization
<|end_body_0|>
<|body_start_1|>
... | TokenOverlap | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenOverlap:
def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=False, stemming=False, stemmer='porter', lemmatization=False):
""":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Fl... | stack_v2_sparse_classes_75kplus_train_008564 | 2,838 | permissive | [
{
"docstring": ":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Flag, whether all tokens should be lower case :param stopword_removal: Flag, whether stop words should be removed before the computation :param stemming: Flag, whether word st... | 2 | stack_v2_sparse_classes_30k_train_046313 | Implement the Python class `TokenOverlap` described below.
Class description:
Implement the TokenOverlap class.
Method signatures and docstrings:
- def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=False, stemming=False, stemmer='porter', lemmatization=False): :param source_segment:... | Implement the Python class `TokenOverlap` described below.
Class description:
Implement the TokenOverlap class.
Method signatures and docstrings:
- def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=False, stemming=False, stemmer='porter', lemmatization=False): :param source_segment:... | 2e6a85dc9e95ef94bec2339987950f4e88f5d909 | <|skeleton|>
class TokenOverlap:
def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=False, stemming=False, stemmer='porter', lemmatization=False):
""":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Fl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokenOverlap:
def __init__(self, source_segment, target_segment, lower_case=True, stopword_removal=False, stemming=False, stemmer='porter', lemmatization=False):
""":param source_segment: Segment from source article :param target_segment: Segment from target article :param lower_case: Flag, whether al... | the_stack_v2_python_sparse | newssimilarity/segment_sim/token_overlap.py | imackerracher/NewsSimilarity | train | 0 | |
ca5b175e946c6dfe48420cd65539e82ff6fc54ad | [
"tree = [1]\nreverse = True\nnum = 2\nlength = 2\nres = [label]\nwhile True:\n temp = [n for n in range(num, num + length)]\n if reverse:\n temp.reverse()\n tree.extend(temp)\n reverse = not reverse\n num += length\n length <<= 1\n if num > label:\n break\nidx = tree.index(label)\... | <|body_start_0|>
tree = [1]
reverse = True
num = 2
length = 2
res = [label]
while True:
temp = [n for n in range(num, num + length)]
if reverse:
temp.reverse()
tree.extend(temp)
reverse = not reverse
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathInZigZagTree(self, label):
""":type label: int :rtype: List[int]"""
<|body_0|>
def pathInZigZagTree2(self, label):
""":type label: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tree = [1]
reverse = T... | stack_v2_sparse_classes_75kplus_train_008565 | 2,836 | no_license | [
{
"docstring": ":type label: int :rtype: List[int]",
"name": "pathInZigZagTree",
"signature": "def pathInZigZagTree(self, label)"
},
{
"docstring": ":type label: int :rtype: List[int]",
"name": "pathInZigZagTree2",
"signature": "def pathInZigZagTree2(self, label)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008795 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathInZigZagTree(self, label): :type label: int :rtype: List[int]
- def pathInZigZagTree2(self, label): :type label: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathInZigZagTree(self, label): :type label: int :rtype: List[int]
- def pathInZigZagTree2(self, label): :type label: int :rtype: List[int]
<|skeleton|>
class Solution:
... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def pathInZigZagTree(self, label):
""":type label: int :rtype: List[int]"""
<|body_0|>
def pathInZigZagTree2(self, label):
""":type label: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pathInZigZagTree(self, label):
""":type label: int :rtype: List[int]"""
tree = [1]
reverse = True
num = 2
length = 2
res = [label]
while True:
temp = [n for n in range(num, num + length)]
if reverse:
... | the_stack_v2_python_sparse | LC1104.py | Qiao-Liang/LeetCode | train | 0 | |
cae652a69b8bb25c7e0638774fcb3499349c5e76 | [
"task_loader = task_utils.TaskLoader()\nself.assertTrue(task_loader.check_task_name('PlasoTask'))\nself.assertFalse(task_loader.check_task_name('NoSuchTask'))",
"task_loader = task_utils.TaskLoader()\ntask_names = task_loader.get_task_names()\nself.assertIn('PlasoTask', task_names)",
"task_loader = task_utils.T... | <|body_start_0|>
task_loader = task_utils.TaskLoader()
self.assertTrue(task_loader.check_task_name('PlasoTask'))
self.assertFalse(task_loader.check_task_name('NoSuchTask'))
<|end_body_0|>
<|body_start_1|>
task_loader = task_utils.TaskLoader()
task_names = task_loader.get_task_na... | Test Turbinia task_utils module. | TestTurbiniaTaskLoader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTurbiniaTaskLoader:
"""Test Turbinia task_utils module."""
def testCheckTaskNames(self):
"""Basic test for Turbinia get_task_names."""
<|body_0|>
def testGetTaskNames(self):
"""Basic test for get_task_names."""
<|body_1|>
def testGetTask(self):
... | stack_v2_sparse_classes_75kplus_train_008566 | 2,555 | permissive | [
{
"docstring": "Basic test for Turbinia get_task_names.",
"name": "testCheckTaskNames",
"signature": "def testCheckTaskNames(self)"
},
{
"docstring": "Basic test for get_task_names.",
"name": "testGetTaskNames",
"signature": "def testGetTaskNames(self)"
},
{
"docstring": "Basic t... | 5 | null | Implement the Python class `TestTurbiniaTaskLoader` described below.
Class description:
Test Turbinia task_utils module.
Method signatures and docstrings:
- def testCheckTaskNames(self): Basic test for Turbinia get_task_names.
- def testGetTaskNames(self): Basic test for get_task_names.
- def testGetTask(self): Basic... | Implement the Python class `TestTurbiniaTaskLoader` described below.
Class description:
Test Turbinia task_utils module.
Method signatures and docstrings:
- def testCheckTaskNames(self): Basic test for Turbinia get_task_names.
- def testGetTaskNames(self): Basic test for get_task_names.
- def testGetTask(self): Basic... | a756f4c625cf3796fc82d160f3c794c7e2039437 | <|skeleton|>
class TestTurbiniaTaskLoader:
"""Test Turbinia task_utils module."""
def testCheckTaskNames(self):
"""Basic test for Turbinia get_task_names."""
<|body_0|>
def testGetTaskNames(self):
"""Basic test for get_task_names."""
<|body_1|>
def testGetTask(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTurbiniaTaskLoader:
"""Test Turbinia task_utils module."""
def testCheckTaskNames(self):
"""Basic test for Turbinia get_task_names."""
task_loader = task_utils.TaskLoader()
self.assertTrue(task_loader.check_task_name('PlasoTask'))
self.assertFalse(task_loader.check_tas... | the_stack_v2_python_sparse | turbinia/task_utils_test.py | joachimmetz/turbinia | train | 1 |
96a055279e043c2c22f6d9762cd74471e4bfa8c4 | [
"self.L = L\nself.W = W\nself.Q = np.zeros((L, W, 4))\nself.model = {}\nself.tau = np.zeros((L, W, 4))",
"self.Q[x, y, action] += alpha * (reward + gamma * max(self.Q[new_x][new_y]) - self.Q[x, y, action])\nself.tau[x, y, action] = t\nself.model[x, y, action] = (new_x, new_y, reward)\nfor action in range(4):\n ... | <|body_start_0|>
self.L = L
self.W = W
self.Q = np.zeros((L, W, 4))
self.model = {}
self.tau = np.zeros((L, W, 4))
<|end_body_0|>
<|body_start_1|>
self.Q[x, y, action] += alpha * (reward + gamma * max(self.Q[new_x][new_y]) - self.Q[x, y, action])
self.tau[x, y, a... | Dyna-Q agent that attempts to learn the optimal policy. | Agent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agent:
"""Dyna-Q agent that attempts to learn the optimal policy."""
def __init__(self, L, W):
"""Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid."""
<|body_0|>
def updateQ(self, x, y, action, reward, new_x, new_y, alpha, ga... | stack_v2_sparse_classes_75kplus_train_008567 | 9,439 | permissive | [
{
"docstring": "Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid.",
"name": "__init__",
"signature": "def __init__(self, L, W)"
},
{
"docstring": "Performs the direct RL update in the Dyna-Q algorithm and updates the learned model based on a real int... | 4 | stack_v2_sparse_classes_30k_train_006369 | Implement the Python class `Agent` described below.
Class description:
Dyna-Q agent that attempts to learn the optimal policy.
Method signatures and docstrings:
- def __init__(self, L, W): Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid.
- def updateQ(self, x, y, action,... | Implement the Python class `Agent` described below.
Class description:
Dyna-Q agent that attempts to learn the optimal policy.
Method signatures and docstrings:
- def __init__(self, L, W): Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid.
- def updateQ(self, x, y, action,... | 127d3fe10fe5774be7f8db3b00f6737f3eed363d | <|skeleton|>
class Agent:
"""Dyna-Q agent that attempts to learn the optimal policy."""
def __init__(self, L, W):
"""Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid."""
<|body_0|>
def updateQ(self, x, y, action, reward, new_x, new_y, alpha, ga... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Agent:
"""Dyna-Q agent that attempts to learn the optimal policy."""
def __init__(self, L, W):
"""Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid."""
self.L = L
self.W = W
self.Q = np.zeros((L, W, 4))
self.model = {}
... | the_stack_v2_python_sparse | Ch8/dynaQ.py | lolcharles2/Reinforcement_learning_book_implementations | train | 0 |
f2fd4144eaaf00d459e1a1979885f5374226819b | [
"freq = {}\nfor x in nums:\n freq[x] = freq.get(x, 0) + 1\nnum, counts = ([], [])\nfor x, count in freq.items():\n num.append(x)\n counts.append(count)\nnum_heap, count_heap = self.build_heap(num[:k], counts[:k], k)\nfor i in range(len(num) - k):\n if count_heap[0] >= counts[i + k]:\n continue\n ... | <|body_start_0|>
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1
num, counts = ([], [])
for x, count in freq.items():
num.append(x)
counts.append(count)
num_heap, count_heap = self.build_heap(num[:k], counts[:k], k)
for i in range... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def top_k_frequent(self, nums, k):
"""使用堆的方法 :param nums: (list) :param k: (int) :return:"""
<|body_0|>
def build_heap(self, num, counts, n):
"""构建最小堆 :param num: (list) :param counts: (list) :param n: (int) :return: (list, list)"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008568 | 4,818 | no_license | [
{
"docstring": "使用堆的方法 :param nums: (list) :param k: (int) :return:",
"name": "top_k_frequent",
"signature": "def top_k_frequent(self, nums, k)"
},
{
"docstring": "构建最小堆 :param num: (list) :param counts: (list) :param n: (int) :return: (list, list)",
"name": "build_heap",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_047079 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def top_k_frequent(self, nums, k): 使用堆的方法 :param nums: (list) :param k: (int) :return:
- def build_heap(self, num, counts, n): 构建最小堆 :param num: (list) :param counts: (list) :p... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def top_k_frequent(self, nums, k): 使用堆的方法 :param nums: (list) :param k: (int) :return:
- def build_heap(self, num, counts, n): 构建最小堆 :param num: (list) :param counts: (list) :p... | 497c9717d783bb9f2d2675a3b254ec406582d849 | <|skeleton|>
class Solution1:
def top_k_frequent(self, nums, k):
"""使用堆的方法 :param nums: (list) :param k: (int) :return:"""
<|body_0|>
def build_heap(self, num, counts, n):
"""构建最小堆 :param num: (list) :param counts: (list) :param n: (int) :return: (list, list)"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
def top_k_frequent(self, nums, k):
"""使用堆的方法 :param nums: (list) :param k: (int) :return:"""
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1
num, counts = ([], [])
for x, count in freq.items():
num.append(x)
counts.ap... | the_stack_v2_python_sparse | 347.前K个高频元素/topKFrequent.py | boyshen/leetcode_Algorithm_problem | train | 0 | |
85de44272a770f037d86db5dde74edb60e7236e1 | [
"if path:\n return os.path.split(path)[0]\nelse:\n return os.getcwd()",
"try:\n if path and name:\n file_list = [os.path.join(path, file) for file in os.listdir(path)]\n search_result = [i for i in file_list if i.find(name) != -1]\n return search_result\n elif path is None and nam... | <|body_start_0|>
if path:
return os.path.split(path)[0]
else:
return os.getcwd()
<|end_body_0|>
<|body_start_1|>
try:
if path and name:
file_list = [os.path.join(path, file) for file in os.listdir(path)]
search_result = [i for ... | PubFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PubFunctions:
def getFolderPath(self, path=None):
"""获取文件夹路径 :param path: 文件夹路径,为None时,返回当前文件夹路径 :return: str类型,文件夹路径"""
<|body_0|>
def getFilePath(self, path=None, name=None):
"""获取文件绝对路径,通过name进行模糊查询,返回结果list :param path:文件夹路径,eg: D:\\CX\\test11,当path为None时,默认为当前路径... | stack_v2_sparse_classes_75kplus_train_008569 | 1,750 | no_license | [
{
"docstring": "获取文件夹路径 :param path: 文件夹路径,为None时,返回当前文件夹路径 :return: str类型,文件夹路径",
"name": "getFolderPath",
"signature": "def getFolderPath(self, path=None)"
},
{
"docstring": "获取文件绝对路径,通过name进行模糊查询,返回结果list :param path:文件夹路径,eg: D:\\\\CX\\\\test11,当path为None时,默认为当前路径 :param name:模糊查找文件或者文件夹名字中包... | 2 | stack_v2_sparse_classes_30k_test_002428 | Implement the Python class `PubFunctions` described below.
Class description:
Implement the PubFunctions class.
Method signatures and docstrings:
- def getFolderPath(self, path=None): 获取文件夹路径 :param path: 文件夹路径,为None时,返回当前文件夹路径 :return: str类型,文件夹路径
- def getFilePath(self, path=None, name=None): 获取文件绝对路径,通过name进行模糊查询,... | Implement the Python class `PubFunctions` described below.
Class description:
Implement the PubFunctions class.
Method signatures and docstrings:
- def getFolderPath(self, path=None): 获取文件夹路径 :param path: 文件夹路径,为None时,返回当前文件夹路径 :return: str类型,文件夹路径
- def getFilePath(self, path=None, name=None): 获取文件绝对路径,通过name进行模糊查询,... | a2688155bacde0f69be56161643da2140a0e8e46 | <|skeleton|>
class PubFunctions:
def getFolderPath(self, path=None):
"""获取文件夹路径 :param path: 文件夹路径,为None时,返回当前文件夹路径 :return: str类型,文件夹路径"""
<|body_0|>
def getFilePath(self, path=None, name=None):
"""获取文件绝对路径,通过name进行模糊查询,返回结果list :param path:文件夹路径,eg: D:\\CX\\test11,当path为None时,默认为当前路径... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PubFunctions:
def getFolderPath(self, path=None):
"""获取文件夹路径 :param path: 文件夹路径,为None时,返回当前文件夹路径 :return: str类型,文件夹路径"""
if path:
return os.path.split(path)[0]
else:
return os.getcwd()
def getFilePath(self, path=None, name=None):
"""获取文件绝对路径,通过name进... | the_stack_v2_python_sparse | comm/PubFunctions.py | chxu1989/autotest | train | 0 | |
8c12a9ff57fc9587185456f7bb4e9d1b03e004e6 | [
"tmp_nums = nums[:]\nn = len(nums)\nfor idx in range(n):\n new_idx = (idx + k) % n\n nums[new_idx] = tmp_nums[idx]",
"def reverse(i, j):\n while i < j:\n nums[i], nums[j] = (nums[j], nums[i])\n i += 1\n j -= 1\nn = len(nums)\nk %= n\nreverse(0, n - 1)\nreverse(0, k - 1)\nreverse(k, n... | <|body_start_0|>
tmp_nums = nums[:]
n = len(nums)
for idx in range(n):
new_idx = (idx + k) % n
nums[new_idx] = tmp_nums[idx]
<|end_body_0|>
<|body_start_1|>
def reverse(i, j):
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""使用额外的数组"""
<|body_0|>
def rotate_reverse(self, nums: List[int], k: int) -> None:
"""数组反转"""
<|body_1|>
def rotate_ring(self, nums: List[int], k: int) -> None:
"""环状替换"""
<|bo... | stack_v2_sparse_classes_75kplus_train_008570 | 1,634 | no_license | [
{
"docstring": "使用额外的数组",
"name": "rotate",
"signature": "def rotate(self, nums: List[int], k: int) -> None"
},
{
"docstring": "数组反转",
"name": "rotate_reverse",
"signature": "def rotate_reverse(self, nums: List[int], k: int) -> None"
},
{
"docstring": "环状替换",
"name": "rotate_... | 3 | stack_v2_sparse_classes_30k_train_021428 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: 使用额外的数组
- def rotate_reverse(self, nums: List[int], k: int) -> None: 数组反转
- def rotate_ring(self, nums: List[int], k: int) -> N... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: 使用额外的数组
- def rotate_reverse(self, nums: List[int], k: int) -> None: 数组反转
- def rotate_ring(self, nums: List[int], k: int) -> N... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""使用额外的数组"""
<|body_0|>
def rotate_reverse(self, nums: List[int], k: int) -> None:
"""数组反转"""
<|body_1|>
def rotate_ring(self, nums: List[int], k: int) -> None:
"""环状替换"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""使用额外的数组"""
tmp_nums = nums[:]
n = len(nums)
for idx in range(n):
new_idx = (idx + k) % n
nums[new_idx] = tmp_nums[idx]
def rotate_reverse(self, nums: List[int], k: int) -> None:
... | the_stack_v2_python_sparse | 189.旋转数组/solution.py | QtTao/daily_leetcode | train | 0 | |
9d234b5b7344118b6e7e0df451e54a327ccd50cf | [
"if not matrix:\n return []\nres = []\nSHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0))\nm, n = (len(matrix), len(matrix[0]))\nx = y = direction = 0\nfor i in range(m * n):\n res.append(matrix[x][y])\n matrix[x][y] = 0\n next_x, next_y = (x + SHIFT[direction][0], y + SHIFT[direction][1])\n if not 0 <= next... | <|body_start_0|>
if not matrix:
return []
res = []
SHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0))
m, n = (len(matrix), len(matrix[0]))
x = y = direction = 0
for i in range(m * n):
res.append(matrix[x][y])
matrix[x][y] = 0
next_x... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed"""
<|body_0|>
def spiralOrder2(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] mod ele not allowed"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_008571 | 1,920 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed",
"name": "spiralOrder",
"signature": "def spiralOrder(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int] mod ele not allowed",
"name": "spiralOrder2",
"signature": "def s... | 2 | stack_v2_sparse_classes_30k_train_047715 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed
- def spiralOrder2(self, matrix): :type matrix: List[List[int]] :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed
- def spiralOrder2(self, matrix): :type matrix: List[List[int]] :rtype: List[... | 4d2b4e322f92de71c7d13c9a2289a422242da38f | <|skeleton|>
class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed"""
<|body_0|>
def spiralOrder2(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] mod ele not allowed"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed"""
if not matrix:
return []
res = []
SHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0))
m, n = (len(matrix), len(matrix[0]))
x = y = direction =... | the_stack_v2_python_sparse | leetcode/arrays/54_spiral_matrix.py | Lance117/Etudes | train | 0 | |
ac9ababe475f5df2a0ad7f9961ac0e9991245aa8 | [
"self.cassandra_auth_required = cassandra_auth_required\nself.cassandra_auth_type = cassandra_auth_type\nself.cassandra_authorizer = cassandra_authorizer\nself.client_encryption = client_encryption\nself.dse_authorization = dse_authorization\nself.server_encryption_req_client_auth = server_encryption_req_client_aut... | <|body_start_0|>
self.cassandra_auth_required = cassandra_auth_required
self.cassandra_auth_type = cassandra_auth_type
self.cassandra_authorizer = cassandra_authorizer
self.client_encryption = client_encryption
self.dse_authorization = dse_authorization
self.server_encryp... | Implementation of the 'CassandraSecurityInfo' model. Specifies an Object containing information on Cassandra security. Attributes: cassandra_auth_required (bool): Is Cassandra authentication required ? cassandra_auth_type (CassandraAuthTypeEnum): Cassandra Authentication type. Enum: [PASSWORD KERBEROS LDAP] Specifies t... | CassandraSecurityInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CassandraSecurityInfo:
"""Implementation of the 'CassandraSecurityInfo' model. Specifies an Object containing information on Cassandra security. Attributes: cassandra_auth_required (bool): Is Cassandra authentication required ? cassandra_auth_type (CassandraAuthTypeEnum): Cassandra Authentication... | stack_v2_sparse_classes_75kplus_train_008572 | 3,898 | permissive | [
{
"docstring": "Constructor for the CassandraSecurityInfo class",
"name": "__init__",
"signature": "def __init__(self, cassandra_auth_required=None, cassandra_auth_type=None, cassandra_authorizer=None, client_encryption=None, dse_authorization=None, server_encryption_req_client_auth=None, server_interno... | 2 | stack_v2_sparse_classes_30k_train_009449 | Implement the Python class `CassandraSecurityInfo` described below.
Class description:
Implementation of the 'CassandraSecurityInfo' model. Specifies an Object containing information on Cassandra security. Attributes: cassandra_auth_required (bool): Is Cassandra authentication required ? cassandra_auth_type (Cassandra... | Implement the Python class `CassandraSecurityInfo` described below.
Class description:
Implementation of the 'CassandraSecurityInfo' model. Specifies an Object containing information on Cassandra security. Attributes: cassandra_auth_required (bool): Is Cassandra authentication required ? cassandra_auth_type (Cassandra... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CassandraSecurityInfo:
"""Implementation of the 'CassandraSecurityInfo' model. Specifies an Object containing information on Cassandra security. Attributes: cassandra_auth_required (bool): Is Cassandra authentication required ? cassandra_auth_type (CassandraAuthTypeEnum): Cassandra Authentication... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CassandraSecurityInfo:
"""Implementation of the 'CassandraSecurityInfo' model. Specifies an Object containing information on Cassandra security. Attributes: cassandra_auth_required (bool): Is Cassandra authentication required ? cassandra_auth_type (CassandraAuthTypeEnum): Cassandra Authentication type. Enum: ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cassandra_security_info.py | cohesity/management-sdk-python | train | 24 |
b3c269119b5e63386f9eee39795d21bcb80d157c | [
"chunk_id = kwargs.get('chunk_id', '[UNKNOWN]')\nmsg = 'Chunk {} (Celery task_id {}) failed: {}.\\nTraceback: {}'.format(chunk_id, task_id, exc, einfo)\ntry:\n exp = spawn_exporter(*args[1:])\nexcept Exception:\n exp_logger.error(msg)\nelse:\n exp.log('Error', msg)",
"chunk_id = kwargs.get('chunk_id', '[... | <|body_start_0|>
chunk_id = kwargs.get('chunk_id', '[UNKNOWN]')
msg = 'Chunk {} (Celery task_id {}) failed: {}.\nTraceback: {}'.format(chunk_id, task_id, exc, einfo)
try:
exp = spawn_exporter(*args[1:])
except Exception:
exp_logger.error(msg)
else:
... | Subclasses celery.Task to provide custom on_failure and on_success behavior. | ExportTask | [
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportTask:
"""Subclasses celery.Task to provide custom on_failure and on_success behavior."""
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""Handle a task that raises an uncaught exception."""
<|body_0|>
def on_success(self, vals, task_id, args, kwargs):
... | stack_v2_sparse_classes_75kplus_train_008573 | 25,127 | permissive | [
{
"docstring": "Handle a task that raises an uncaught exception.",
"name": "on_failure",
"signature": "def on_failure(self, exc, task_id, args, kwargs, einfo)"
},
{
"docstring": "When a task succeeds, the registry for that chunk should be cleared from Redis.",
"name": "on_success",
"sign... | 2 | null | Implement the Python class `ExportTask` described below.
Class description:
Subclasses celery.Task to provide custom on_failure and on_success behavior.
Method signatures and docstrings:
- def on_failure(self, exc, task_id, args, kwargs, einfo): Handle a task that raises an uncaught exception.
- def on_success(self, ... | Implement the Python class `ExportTask` described below.
Class description:
Subclasses celery.Task to provide custom on_failure and on_success behavior.
Method signatures and docstrings:
- def on_failure(self, exc, task_id, args, kwargs, einfo): Handle a task that raises an uncaught exception.
- def on_success(self, ... | 9189a6cc64305a6ead4b95ca0b56d7b7ae6c87d5 | <|skeleton|>
class ExportTask:
"""Subclasses celery.Task to provide custom on_failure and on_success behavior."""
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""Handle a task that raises an uncaught exception."""
<|body_0|>
def on_success(self, vals, task_id, args, kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExportTask:
"""Subclasses celery.Task to provide custom on_failure and on_success behavior."""
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""Handle a task that raises an uncaught exception."""
chunk_id = kwargs.get('chunk_id', '[UNKNOWN]')
msg = 'Chunk {} (Celery tas... | the_stack_v2_python_sparse | django/sierra/export/tasks.py | unt-libraries/catalog-api | train | 20 |
423e1e7b1f1bdd41d62a2b8910ce4ee556b0f984 | [
"if data:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n elif not isinstance(data, list):\n raise TypeError('data must be a list')\n elif len(data) < 2:\n raise ValueError('data must contain multiple values')\n else:\n self.lambtha = float(sum(dat... | <|body_start_0|>
if data:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
elif not isinstance(data, list):
raise TypeError('data must be a list')
elif len(data) < 2:
raise ValueError('data must contain mult... | Poisson distribution stats class | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Poisson distribution stats class"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize poisson distribution stats"""
<|body_0|>
def pmf(self, k):
"""PMF at k number of events"""
<|body_1|>
def cdf(self, k):
"""CDF at k numb... | stack_v2_sparse_classes_75kplus_train_008574 | 1,223 | no_license | [
{
"docstring": "Initialize poisson distribution stats",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "PMF at k number of events",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "CDF at k number of events",
"... | 3 | null | Implement the Python class `Poisson` described below.
Class description:
Poisson distribution stats class
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Initialize poisson distribution stats
- def pmf(self, k): PMF at k number of events
- def cdf(self, k): CDF at k number of events | Implement the Python class `Poisson` described below.
Class description:
Poisson distribution stats class
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Initialize poisson distribution stats
- def pmf(self, k): PMF at k number of events
- def cdf(self, k): CDF at k number of events
<... | a51fbcb76dae9281ff34ace0fb762ef899b4c380 | <|skeleton|>
class Poisson:
"""Poisson distribution stats class"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize poisson distribution stats"""
<|body_0|>
def pmf(self, k):
"""PMF at k number of events"""
<|body_1|>
def cdf(self, k):
"""CDF at k numb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Poisson:
"""Poisson distribution stats class"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize poisson distribution stats"""
if data:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
elif not isinstance(data, list):
... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | Diegokernel/holbertonschool-machine_learning | train | 0 |
cc15e2111cd96a422debe0d6bf491ae7cdd6723a | [
"self.bot_id = kwargs.get('bot_id')\nself.bot_type = kwargs.get('bot_type')\nself.position = kwargs.get('position')\nself.rotation = kwargs.get('rotation')",
"self.bot_id = kwargs['bot_id']\nself.bot_type = kwargs['bot_type']\nself.position = kwargs['position']\nself.rotation = kwargs['rotation']",
"ret = {}\nr... | <|body_start_0|>
self.bot_id = kwargs.get('bot_id')
self.bot_type = kwargs.get('bot_type')
self.position = kwargs.get('position')
self.rotation = kwargs.get('rotation')
<|end_body_0|>
<|body_start_1|>
self.bot_id = kwargs['bot_id']
self.bot_type = kwargs['bot_type']
... | SpawnBotRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpawnBotRequest:
def __init__(self, **kwargs):
"""Params: bot_id: int bot_type: str position: Vector3 rotation: float"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
"""dump -> dict"""
... | stack_v2_sparse_classes_75kplus_train_008575 | 26,590 | no_license | [
{
"docstring": "Params: bot_id: int bot_type: str position: Vector3 rotation: float",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "load from dict Exception: KeyError",
"name": "load",
"signature": "def load(self, **kwargs)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_015215 | Implement the Python class `SpawnBotRequest` described below.
Class description:
Implement the SpawnBotRequest class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: bot_id: int bot_type: str position: Vector3 rotation: float
- def load(self, **kwargs): load from dict Exception: KeyError
- d... | Implement the Python class `SpawnBotRequest` described below.
Class description:
Implement the SpawnBotRequest class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: bot_id: int bot_type: str position: Vector3 rotation: float
- def load(self, **kwargs): load from dict Exception: KeyError
- d... | aa0b2697e295889e8c23a7104889ea95f2a4b6b1 | <|skeleton|>
class SpawnBotRequest:
def __init__(self, **kwargs):
"""Params: bot_id: int bot_type: str position: Vector3 rotation: float"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
"""dump -> dict"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpawnBotRequest:
def __init__(self, **kwargs):
"""Params: bot_id: int bot_type: str position: Vector3 rotation: float"""
self.bot_id = kwargs.get('bot_id')
self.bot_type = kwargs.get('bot_type')
self.position = kwargs.get('position')
self.rotation = kwargs.get('rotation... | the_stack_v2_python_sparse | message.py | songhui17/Server | train | 0 | |
17d96e22c570c5ef6df00175b4e8f0a03f0b89ba | [
"try:\n return json.loads(data)\nexcept Exception as e:\n raise CorruptConfigurationFormatException(f'Incorrect JSON format: {e}')",
"for key in response.keys():\n if key == 'checks':\n if not response[key].keys():\n for check in response['checks'].keys():\n if check not ... | <|body_start_0|>
try:
return json.loads(data)
except Exception as e:
raise CorruptConfigurationFormatException(f'Incorrect JSON format: {e}')
<|end_body_0|>
<|body_start_1|>
for key in response.keys():
if key == 'checks':
if not response[key].... | Object in charge of reading and validating a configuration file | ConfigurationReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationReader:
"""Object in charge of reading and validating a configuration file"""
def _is_valid_json(self, data):
"""Checks if a string is a correct JSON Args: data (string). Checks if the data provided is a valid json. Return: dict/bool."""
<|body_0|>
def _is_c... | stack_v2_sparse_classes_75kplus_train_008576 | 5,018 | no_license | [
{
"docstring": "Checks if a string is a correct JSON Args: data (string). Checks if the data provided is a valid json. Return: dict/bool.",
"name": "_is_valid_json",
"signature": "def _is_valid_json(self, data)"
},
{
"docstring": "Checks if a response object has a correct format It checks whethe... | 4 | stack_v2_sparse_classes_30k_train_030545 | Implement the Python class `ConfigurationReader` described below.
Class description:
Object in charge of reading and validating a configuration file
Method signatures and docstrings:
- def _is_valid_json(self, data): Checks if a string is a correct JSON Args: data (string). Checks if the data provided is a valid json... | Implement the Python class `ConfigurationReader` described below.
Class description:
Object in charge of reading and validating a configuration file
Method signatures and docstrings:
- def _is_valid_json(self, data): Checks if a string is a correct JSON Args: data (string). Checks if the data provided is a valid json... | f30cf7d7b19bb04566c274440a9e046004ba569b | <|skeleton|>
class ConfigurationReader:
"""Object in charge of reading and validating a configuration file"""
def _is_valid_json(self, data):
"""Checks if a string is a correct JSON Args: data (string). Checks if the data provided is a valid json. Return: dict/bool."""
<|body_0|>
def _is_c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigurationReader:
"""Object in charge of reading and validating a configuration file"""
def _is_valid_json(self, data):
"""Checks if a string is a correct JSON Args: data (string). Checks if the data provided is a valid json. Return: dict/bool."""
try:
return json.loads(dat... | the_stack_v2_python_sparse | quickmock/validation.py | febrezo/quickmock | train | 1 |
74d8c37775bcba9cac2315c1d7f9a27e52f89daf | [
"super().__init__(n_head=n_head, n_feat=n_feat, dropout_rate=dropout_rate, max_cache_len=max_cache_len)\nself.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\nif pos_bias_u is None or pos_bias_v is None:\n self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d_k))\n self.pos_bias_v = nn.Parameter(... | <|body_start_0|>
super().__init__(n_head=n_head, n_feat=n_feat, dropout_rate=dropout_rate, max_cache_len=max_cache_len)
self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
if pos_bias_u is None or pos_bias_v is None:
self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d... | Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate | RelPositionMultiHeadAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionMultiHeadAttention:
"""Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate"""
def __init__(self,... | stack_v2_sparse_classes_75kplus_train_008577 | 45,820 | permissive | [
{
"docstring": "Construct an RelPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate, pos_bias_u, pos_bias_v, max_cache_len=0)"
},
{
"docstring": "Compute relative positional encoding. Args: x (torch.Tensor): (batch, nheads, tim... | 3 | stack_v2_sparse_classes_30k_train_021649 | Implement the Python class `RelPositionMultiHeadAttention` described below.
Class description:
Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): ... | Implement the Python class `RelPositionMultiHeadAttention` described below.
Class description:
Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): ... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class RelPositionMultiHeadAttention:
"""Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate"""
def __init__(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelPositionMultiHeadAttention:
"""Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate"""
def __init__(self, n_head, n_fe... | the_stack_v2_python_sparse | nemo/collections/asr/parts/submodules/multi_head_attention.py | NVIDIA/NeMo | train | 7,957 |
395560f1a00fd5f45d473268ee78825a58e37d5e | [
"user = User.find_by_email_or_username(params['email_or_username'])\nif not user:\n abort(404, 'Could not find a user with that email address')\ntoken = password_reset_jwt_manager.encode_reset_token(user)\nreset_url = set_query_parameter(params['base_url'], 'reset_token', token)\nsend_reset_password_email(reset_... | <|body_start_0|>
user = User.find_by_email_or_username(params['email_or_username'])
if not user:
abort(404, 'Could not find a user with that email address')
token = password_reset_jwt_manager.encode_reset_token(user)
reset_url = set_query_parameter(params['base_url'], 'reset_... | Routes for resetting a password with a reset link. | PasswordResets | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResets:
"""Routes for resetting a password with a reset link."""
def post(self, **params):
"""Logic for sending a password reset link"""
<|body_0|>
def put(self, **params):
"""Logic for changing the users password with a reset link"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008578 | 2,734 | permissive | [
{
"docstring": "Logic for sending a password reset link",
"name": "post",
"signature": "def post(self, **params)"
},
{
"docstring": "Logic for changing the users password with a reset link",
"name": "put",
"signature": "def put(self, **params)"
}
] | 2 | null | Implement the Python class `PasswordResets` described below.
Class description:
Routes for resetting a password with a reset link.
Method signatures and docstrings:
- def post(self, **params): Logic for sending a password reset link
- def put(self, **params): Logic for changing the users password with a reset link | Implement the Python class `PasswordResets` described below.
Class description:
Routes for resetting a password with a reset link.
Method signatures and docstrings:
- def post(self, **params): Logic for sending a password reset link
- def put(self, **params): Logic for changing the users password with a reset link
<... | 98173eb380bd6add52b21dc9045893949a8a2d30 | <|skeleton|>
class PasswordResets:
"""Routes for resetting a password with a reset link."""
def post(self, **params):
"""Logic for sending a password reset link"""
<|body_0|>
def put(self, **params):
"""Logic for changing the users password with a reset link"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordResets:
"""Routes for resetting a password with a reset link."""
def post(self, **params):
"""Logic for sending a password reset link"""
user = User.find_by_email_or_username(params['email_or_username'])
if not user:
abort(404, 'Could not find a user with that ... | the_stack_v2_python_sparse | application/password_resets/password_resets_view.py | hpi-sam/ask-your-repository-api | train | 4 |
f0ab0569da86f0794dc9af9bcf3226a44e534656 | [
"res = super(ResConfigSettings, self).get_values()\nparams = self.env['ir.config_parameter'].sudo().get_param\npos_all_order = params('pos_all_orders.pos_all_order')\nn_days = params('pos_all_orders.n_days')\nres.update(pos_all_order=pos_all_order, n_days=n_days)\nreturn res",
"super(ResConfigSettings, self).set_... | <|body_start_0|>
res = super(ResConfigSettings, self).get_values()
params = self.env['ir.config_parameter'].sudo().get_param
pos_all_order = params('pos_all_orders.pos_all_order')
n_days = params('pos_all_orders.n_days')
res.update(pos_all_order=pos_all_order, n_days=n_days)
... | ResConfigSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResConfigSettings:
def get_values(self):
"""get values from the fields"""
<|body_0|>
def set_values(self):
"""Set values in the fields"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = super(ResConfigSettings, self).get_values()
params =... | stack_v2_sparse_classes_75kplus_train_008579 | 4,742 | no_license | [
{
"docstring": "get values from the fields",
"name": "get_values",
"signature": "def get_values(self)"
},
{
"docstring": "Set values in the fields",
"name": "set_values",
"signature": "def set_values(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011272 | Implement the Python class `ResConfigSettings` described below.
Class description:
Implement the ResConfigSettings class.
Method signatures and docstrings:
- def get_values(self): get values from the fields
- def set_values(self): Set values in the fields | Implement the Python class `ResConfigSettings` described below.
Class description:
Implement the ResConfigSettings class.
Method signatures and docstrings:
- def get_values(self): get values from the fields
- def set_values(self): Set values in the fields
<|skeleton|>
class ResConfigSettings:
def get_values(sel... | 4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14 | <|skeleton|>
class ResConfigSettings:
def get_values(self):
"""get values from the fields"""
<|body_0|>
def set_values(self):
"""Set values in the fields"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResConfigSettings:
def get_values(self):
"""get values from the fields"""
res = super(ResConfigSettings, self).get_values()
params = self.env['ir.config_parameter'].sudo().get_param
pos_all_order = params('pos_all_orders.pos_all_order')
n_days = params('pos_all_orders.n... | the_stack_v2_python_sparse | pos_all_orders/models/pos_session.py | CybroOdoo/CybroAddons | train | 209 | |
fc24e691f38cb2fb80b27e180517a1fad9a75fb4 | [
"logging.info('===test_CommonPageTest1===')\nc = CommonPage(self.driver)\nc.check_index(test_data['phone2'], test_data_pwd['phone2'])",
"logging.info('===test_CommonPageTest2===')\nc = CommonPage(self.driver)\nc.check_quotation()",
"logging.info('===test_CommonPageTest3===')\nc = CommonPage(self.driver)\nc.chec... | <|body_start_0|>
logging.info('===test_CommonPageTest1===')
c = CommonPage(self.driver)
c.check_index(test_data['phone2'], test_data_pwd['phone2'])
<|end_body_0|>
<|body_start_1|>
logging.info('===test_CommonPageTest2===')
c = CommonPage(self.driver)
c.check_quotation()
... | CommonPageTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonPageTest:
def test_CommonPageTest1(self):
"""1.入口测试"""
<|body_0|>
def test_CommonPageTest2(self):
"""2.市场行情"""
<|body_1|>
def test_CommonPageTest3(self):
"""3.昨日排行榜"""
<|body_2|>
def test_CommonPageTest4(self):
"""4.优惠活... | stack_v2_sparse_classes_75kplus_train_008580 | 1,213 | no_license | [
{
"docstring": "1.入口测试",
"name": "test_CommonPageTest1",
"signature": "def test_CommonPageTest1(self)"
},
{
"docstring": "2.市场行情",
"name": "test_CommonPageTest2",
"signature": "def test_CommonPageTest2(self)"
},
{
"docstring": "3.昨日排行榜",
"name": "test_CommonPageTest3",
"s... | 4 | stack_v2_sparse_classes_30k_train_008743 | Implement the Python class `CommonPageTest` described below.
Class description:
Implement the CommonPageTest class.
Method signatures and docstrings:
- def test_CommonPageTest1(self): 1.入口测试
- def test_CommonPageTest2(self): 2.市场行情
- def test_CommonPageTest3(self): 3.昨日排行榜
- def test_CommonPageTest4(self): 4.优惠活动 | Implement the Python class `CommonPageTest` described below.
Class description:
Implement the CommonPageTest class.
Method signatures and docstrings:
- def test_CommonPageTest1(self): 1.入口测试
- def test_CommonPageTest2(self): 2.市场行情
- def test_CommonPageTest3(self): 3.昨日排行榜
- def test_CommonPageTest4(self): 4.优惠活动
<|... | 80539f8d3fc5ccb5c07aab2ad37a9c071bb4944d | <|skeleton|>
class CommonPageTest:
def test_CommonPageTest1(self):
"""1.入口测试"""
<|body_0|>
def test_CommonPageTest2(self):
"""2.市场行情"""
<|body_1|>
def test_CommonPageTest3(self):
"""3.昨日排行榜"""
<|body_2|>
def test_CommonPageTest4(self):
"""4.优惠活... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonPageTest:
def test_CommonPageTest1(self):
"""1.入口测试"""
logging.info('===test_CommonPageTest1===')
c = CommonPage(self.driver)
c.check_index(test_data['phone2'], test_data_pwd['phone2'])
def test_CommonPageTest2(self):
"""2.市场行情"""
logging.info('===tes... | the_stack_v2_python_sparse | WFX_App_Test/test_case/test_03_commonPage.py | yangyuexiong/WFX_Test | train | 0 | |
e126afdd797eed0fb5020aa344aff6cb38d65d00 | [
"if len(values) == 0:\n self._times = []\n self._values = []\n self.timeseries = []\nelse:\n assert isNumericList(values), 'Values sequence must be only contain numerical entries'\n self._values = [v for v in values]\n if times is not None:\n assert isNumericList(times), 'Time sequence must... | <|body_start_0|>
if len(values) == 0:
self._times = []
self._values = []
self.timeseries = []
else:
assert isNumericList(values), 'Values sequence must be only contain numerical entries'
self._values = [v for v in values]
if times i... | This TimeSeries class stores a single, ordered set of numerical data as a Python list. It inherites from the SizedContainerTimeSeriesInterface and hence from the TimeSeriesInterface. | TimeSeries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSeries:
"""This TimeSeries class stores a single, ordered set of numerical data as a Python list. It inherites from the SizedContainerTimeSeriesInterface and hence from the TimeSeriesInterface."""
def __init__(self, values, times=None):
"""The constructor of the class takes for a... | stack_v2_sparse_classes_75kplus_train_008581 | 24,433 | no_license | [
{
"docstring": "The constructor of the class takes for argumnent an ordered set of numerical data. Parameters ---------- values: Numerical Sequence, compulsory times: Ordered Numerical Sequence, optional Attributes ---------- self._times: list self._values: list self.timeseries: list of tuples (time, value) Not... | 6 | stack_v2_sparse_classes_30k_train_008336 | Implement the Python class `TimeSeries` described below.
Class description:
This TimeSeries class stores a single, ordered set of numerical data as a Python list. It inherites from the SizedContainerTimeSeriesInterface and hence from the TimeSeriesInterface.
Method signatures and docstrings:
- def __init__(self, valu... | Implement the Python class `TimeSeries` described below.
Class description:
This TimeSeries class stores a single, ordered set of numerical data as a Python list. It inherites from the SizedContainerTimeSeriesInterface and hence from the TimeSeriesInterface.
Method signatures and docstrings:
- def __init__(self, valu... | d882d2f365addcc949754895a43ba946326a7716 | <|skeleton|>
class TimeSeries:
"""This TimeSeries class stores a single, ordered set of numerical data as a Python list. It inherites from the SizedContainerTimeSeriesInterface and hence from the TimeSeriesInterface."""
def __init__(self, values, times=None):
"""The constructor of the class takes for a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeSeries:
"""This TimeSeries class stores a single, ordered set of numerical data as a Python list. It inherites from the SizedContainerTimeSeriesInterface and hence from the TimeSeriesInterface."""
def __init__(self, values, times=None):
"""The constructor of the class takes for argumnent an o... | the_stack_v2_python_sparse | timeseries/series.py | jovhscript/cs207project | train | 1 |
976590ab7b3f8eaf116d9c524ed5ed8448826247 | [
"super(JabsorbRpcServiceExporter, self).__init__()\nself._kinds = None\nself._http = None\nself._path = None\nself._servlet = None",
"jabsorb_name = svc_ref.get_property(PROP_JABSORB_ENDPOINT_NAME)\nif jabsorb_name:\n name = jabsorb_name\nreturn {pelix.remote.PROP_ENDPOINT_NAME: name, PROP_JABSORB_ENDPOINT_NAM... | <|body_start_0|>
super(JabsorbRpcServiceExporter, self).__init__()
self._kinds = None
self._http = None
self._path = None
self._servlet = None
<|end_body_0|>
<|body_start_1|>
jabsorb_name = svc_ref.get_property(PROP_JABSORB_ENDPOINT_NAME)
if jabsorb_name:
... | JABSORB-RPC Remote Services exporter | JabsorbRpcServiceExporter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JabsorbRpcServiceExporter:
"""JABSORB-RPC Remote Services exporter"""
def __init__(self):
"""Sets up the exporter"""
<|body_0|>
def make_endpoint_properties(self, svc_ref, name, fw_uid):
"""Prepare properties for the ExportEndpoint to be created :param svc_ref: S... | stack_v2_sparse_classes_75kplus_train_008582 | 10,902 | permissive | [
{
"docstring": "Sets up the exporter",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Prepare properties for the ExportEndpoint to be created :param svc_ref: Service reference :param name: Endpoint name :param fw_uid: Framework UID :return: A dictionary of extra endpoin... | 5 | null | Implement the Python class `JabsorbRpcServiceExporter` described below.
Class description:
JABSORB-RPC Remote Services exporter
Method signatures and docstrings:
- def __init__(self): Sets up the exporter
- def make_endpoint_properties(self, svc_ref, name, fw_uid): Prepare properties for the ExportEndpoint to be crea... | Implement the Python class `JabsorbRpcServiceExporter` described below.
Class description:
JABSORB-RPC Remote Services exporter
Method signatures and docstrings:
- def __init__(self): Sets up the exporter
- def make_endpoint_properties(self, svc_ref, name, fw_uid): Prepare properties for the ExportEndpoint to be crea... | 1d0add361ca219da8fdf72bb9ba8cb0ade01ad2f | <|skeleton|>
class JabsorbRpcServiceExporter:
"""JABSORB-RPC Remote Services exporter"""
def __init__(self):
"""Sets up the exporter"""
<|body_0|>
def make_endpoint_properties(self, svc_ref, name, fw_uid):
"""Prepare properties for the ExportEndpoint to be created :param svc_ref: S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JabsorbRpcServiceExporter:
"""JABSORB-RPC Remote Services exporter"""
def __init__(self):
"""Sets up the exporter"""
super(JabsorbRpcServiceExporter, self).__init__()
self._kinds = None
self._http = None
self._path = None
self._servlet = None
def make_... | the_stack_v2_python_sparse | pelix/remote/transport/jabsorb_rpc.py | tcalmant/ipopo | train | 67 |
d23a5e3c4a06a8ec33aac1bf4a4b276f896c5460 | [
"def sortedArrayToBST(arr):\n if not arr:\n return None\n mid = len(arr) // 2\n root = TreeNode(arr[mid])\n root.left = sortedArrayToBST(arr[:mid])\n root.right = sortedArrayToBST(arr[mid + 1:])\n return root\narr = []\nwhile head:\n arr.append(head.val)\n head = head.next\nreturn sor... | <|body_start_0|>
def sortedArrayToBST(arr):
if not arr:
return None
mid = len(arr) // 2
root = TreeNode(arr[mid])
root.left = sortedArrayToBST(arr[:mid])
root.right = sortedArrayToBST(arr[mid + 1:])
return root
arr =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
"""May 06, 2018 19:50"""
<|body_0|>
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
"""Apr 13, 2023 00:08"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def sortedArrayToBST(arr)... | stack_v2_sparse_classes_75kplus_train_008583 | 2,676 | no_license | [
{
"docstring": "May 06, 2018 19:50",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head)"
},
{
"docstring": "Apr 13, 2023 00:08",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]"
}
] | 2 | stack_v2_sparse_classes_30k_val_001075 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): May 06, 2018 19:50
- def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: Apr 13, 2023 00:08 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): May 06, 2018 19:50
- def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: Apr 13, 2023 00:08
<|skeleton|>
class Solution:
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
"""May 06, 2018 19:50"""
<|body_0|>
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
"""Apr 13, 2023 00:08"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortedListToBST(self, head):
"""May 06, 2018 19:50"""
def sortedArrayToBST(arr):
if not arr:
return None
mid = len(arr) // 2
root = TreeNode(arr[mid])
root.left = sortedArrayToBST(arr[:mid])
root.right = ... | the_stack_v2_python_sparse | leetcode/solved/109_Convert_Sorted_List_to_Binary_Search_Tree/solution.py | sungminoh/algorithms | train | 0 | |
81849e3d65ced44702ce74452740d6a4d2d74ca6 | [
"data = copy(data)\nif data is not None:\n data['step'] = step\n data = self.preprocess(data)\nif initial is not None:\n initial['step'] = step\nsuper().__init__(request, data=data, initial=initial, **kwargs)\nself._checkout_errors = errors\nsettings.clear_cache()\nif not (settings.SHOP_DISCOUNT_FIELD_IN_C... | <|body_start_0|>
data = copy(data)
if data is not None:
data['step'] = step
data = self.preprocess(data)
if initial is not None:
initial['step'] = step
super().__init__(request, data=data, initial=initial, **kwargs)
self._checkout_errors = erro... | Main Form for the checkout process - ModelForm for the Order Model with extra fields for credit card. Used across each step of the checkout process with fields being hidden where applicable. | OrderForm | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderForm:
"""Main Form for the checkout process - ModelForm for the Order Model with extra fields for credit card. Used across each step of the checkout process with fields being hidden where applicable."""
def __init__(self, request, step, data=None, initial=None, errors=None, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_008584 | 21,988 | permissive | [
{
"docstring": "Setup for each order form step which does a few things: - Calls OrderForm.preprocess on posted data - Sets up any custom checkout errors - Hides the discount code field if applicable - Hides sets of fields based on the checkout step - Sets year choices for cc expiry field based on current date",... | 4 | stack_v2_sparse_classes_30k_train_022887 | Implement the Python class `OrderForm` described below.
Class description:
Main Form for the checkout process - ModelForm for the Order Model with extra fields for credit card. Used across each step of the checkout process with fields being hidden where applicable.
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `OrderForm` described below.
Class description:
Main Form for the checkout process - ModelForm for the Order Model with extra fields for credit card. Used across each step of the checkout process with fields being hidden where applicable.
Method signatures and docstrings:
- def __init__(sel... | 065c9b71ec67141040c424ab3c26a17410581a43 | <|skeleton|>
class OrderForm:
"""Main Form for the checkout process - ModelForm for the Order Model with extra fields for credit card. Used across each step of the checkout process with fields being hidden where applicable."""
def __init__(self, request, step, data=None, initial=None, errors=None, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderForm:
"""Main Form for the checkout process - ModelForm for the Order Model with extra fields for credit card. Used across each step of the checkout process with fields being hidden where applicable."""
def __init__(self, request, step, data=None, initial=None, errors=None, **kwargs):
"""Set... | the_stack_v2_python_sparse | cartridge/shop/forms.py | stephenmcd/cartridge | train | 477 |
6f0cd797ff5ba99eee120876480f2411a22de064 | [
"self.site = pywikibot.Site(u'commons', u'commons')\nself.site.login()\nself.site.get_tokens('csrf')\nself.repo = self.site.data_repository()\nself.fullrun = fullrun\nself.generator = self.getGenerator(fullrun)",
"if fullrun:\n category = pywikibot.Category(self.site, title='Category:Featured_pictures_on_Wikim... | <|body_start_0|>
self.site = pywikibot.Site(u'commons', u'commons')
self.site.login()
self.site.get_tokens('csrf')
self.repo = self.site.data_repository()
self.fullrun = fullrun
self.generator = self.getGenerator(fullrun)
<|end_body_0|>
<|body_start_1|>
if fullru... | Bot to add structured data statements on Commons | FeaturedPictureBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeaturedPictureBot:
"""Bot to add structured data statements on Commons"""
def __init__(self, fullrun=False):
"""Grab generator based on search to work on."""
<|body_0|>
def getGenerator(self, fullrun):
"""Get the generator to work on."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008585 | 5,250 | no_license | [
{
"docstring": "Grab generator based on search to work on.",
"name": "__init__",
"signature": "def __init__(self, fullrun=False)"
},
{
"docstring": "Get the generator to work on.",
"name": "getGenerator",
"signature": "def getGenerator(self, fullrun)"
},
{
"docstring": "Run on th... | 5 | stack_v2_sparse_classes_30k_test_001926 | Implement the Python class `FeaturedPictureBot` described below.
Class description:
Bot to add structured data statements on Commons
Method signatures and docstrings:
- def __init__(self, fullrun=False): Grab generator based on search to work on.
- def getGenerator(self, fullrun): Get the generator to work on.
- def ... | Implement the Python class `FeaturedPictureBot` described below.
Class description:
Bot to add structured data statements on Commons
Method signatures and docstrings:
- def __init__(self, fullrun=False): Grab generator based on search to work on.
- def getGenerator(self, fullrun): Get the generator to work on.
- def ... | 99a96e49cfe6b2d3151da7ad5469792d80171be3 | <|skeleton|>
class FeaturedPictureBot:
"""Bot to add structured data statements on Commons"""
def __init__(self, fullrun=False):
"""Grab generator based on search to work on."""
<|body_0|>
def getGenerator(self, fullrun):
"""Get the generator to work on."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeaturedPictureBot:
"""Bot to add structured data statements on Commons"""
def __init__(self, fullrun=False):
"""Grab generator based on search to work on."""
self.site = pywikibot.Site(u'commons', u'commons')
self.site.login()
self.site.get_tokens('csrf')
self.rep... | the_stack_v2_python_sparse | bot/commons/featured_picture_add.py | multichill/toollabs | train | 18 |
81f3bfc03d0609d6f20c9ac1e8bd4e537c3f9c6e | [
"new_data = []\nfor data in data_list:\n repo_data = repo[data]\n for row in repo_data.find():\n element = {}\n element['facility_type'] = data[17:]\n element['coordinates'] = row['geometry']['coordinates'][::-1]\n new_data.append(element)\nreturn new_data",
"startTime = datetime... | <|body_start_0|>
new_data = []
for data in data_list:
repo_data = repo[data]
for row in repo_data.find():
element = {}
element['facility_type'] = data[17:]
element['coordinates'] = row['geometry']['coordinates'][::-1]
... | boston_fire_facility_transformation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class boston_fire_facility_transformation:
def merge_data(data_list, repo):
""":param data_list: The data list of mongodb as input :param repo: Mongodb repo :return: merged data which includes Boston Fire Hydrants, Fire Department, Fire Alarm Boxes with their coordinates and zipcode"""
... | stack_v2_sparse_classes_75kplus_train_008586 | 5,696 | no_license | [
{
"docstring": ":param data_list: The data list of mongodb as input :param repo: Mongodb repo :return: merged data which includes Boston Fire Hydrants, Fire Department, Fire Alarm Boxes with their coordinates and zipcode",
"name": "merge_data",
"signature": "def merge_data(data_list, repo)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004656 | Implement the Python class `boston_fire_facility_transformation` described below.
Class description:
Implement the boston_fire_facility_transformation class.
Method signatures and docstrings:
- def merge_data(data_list, repo): :param data_list: The data list of mongodb as input :param repo: Mongodb repo :return: merg... | Implement the Python class `boston_fire_facility_transformation` described below.
Class description:
Implement the boston_fire_facility_transformation class.
Method signatures and docstrings:
- def merge_data(data_list, repo): :param data_list: The data list of mongodb as input :param repo: Mongodb repo :return: merg... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class boston_fire_facility_transformation:
def merge_data(data_list, repo):
""":param data_list: The data list of mongodb as input :param repo: Mongodb repo :return: merged data which includes Boston Fire Hydrants, Fire Department, Fire Alarm Boxes with their coordinates and zipcode"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class boston_fire_facility_transformation:
def merge_data(data_list, repo):
""":param data_list: The data list of mongodb as input :param repo: Mongodb repo :return: merged data which includes Boston Fire Hydrants, Fire Department, Fire Alarm Boxes with their coordinates and zipcode"""
new_data = []... | the_stack_v2_python_sparse | liweixi_mogujzhu/boston_fire_facility_transformation.py | maximega/course-2019-spr-proj | train | 2 | |
f6f97f811c651443e4d5947d9682359ed0694e6e | [
"try:\n review = Review.objects.get(id=review_id)\n r_serializer = ReviewSerializer(review)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept:\n return Http404",
"try:\n transaction = Transaction.objects.get(post__id=post_id)\nexcept Post.DoesNotExist:\n return Http404\nr_ser... | <|body_start_0|>
try:
review = Review.objects.get(id=review_id)
r_serializer = ReviewSerializer(review)
return Response(serializer.data, status=status.HTTP_200_OK)
except:
return Http404
<|end_body_0|>
<|body_start_1|>
try:
transaction... | ReviewHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewHandler:
def get(self, request, post_id=None, format=None):
"""Get Review of Transaction if the review exists."""
<|body_0|>
def post(self, request, format=None):
"""Create Reivew of Transaction if the tranaction is finished and no review is written."""
... | stack_v2_sparse_classes_75kplus_train_008587 | 10,133 | no_license | [
{
"docstring": "Get Review of Transaction if the review exists.",
"name": "get",
"signature": "def get(self, request, post_id=None, format=None)"
},
{
"docstring": "Create Reivew of Transaction if the tranaction is finished and no review is written.",
"name": "post",
"signature": "def po... | 2 | stack_v2_sparse_classes_30k_train_052084 | Implement the Python class `ReviewHandler` described below.
Class description:
Implement the ReviewHandler class.
Method signatures and docstrings:
- def get(self, request, post_id=None, format=None): Get Review of Transaction if the review exists.
- def post(self, request, format=None): Create Reivew of Transaction ... | Implement the Python class `ReviewHandler` described below.
Class description:
Implement the ReviewHandler class.
Method signatures and docstrings:
- def get(self, request, post_id=None, format=None): Get Review of Transaction if the review exists.
- def post(self, request, format=None): Create Reivew of Transaction ... | 148e6594fab9809f4e9b045ebb61e2dc6b66741c | <|skeleton|>
class ReviewHandler:
def get(self, request, post_id=None, format=None):
"""Get Review of Transaction if the review exists."""
<|body_0|>
def post(self, request, format=None):
"""Create Reivew of Transaction if the tranaction is finished and no review is written."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReviewHandler:
def get(self, request, post_id=None, format=None):
"""Get Review of Transaction if the review exists."""
try:
review = Review.objects.get(id=review_id)
r_serializer = ReviewSerializer(review)
return Response(serializer.data, status=status.HTTP... | the_stack_v2_python_sparse | buysell/api/post/views.py | bigeye/buysell | train | 0 | |
0bee5206f4a01e85d9b0e90bf375d09171a2eb24 | [
"driver = self.driver\nassert_list = []\ndriver.find_element_by_css_selector('#main-navigation > ul > li:nth-child(3) > a').click()\ndriver.find_element_by_link_text('口岸数据').click()\njs = 'document.getElementById(\"from\").value = \"2018-09-08\"'\ndriver.execute_script(js)\ndriver.find_element_by_xpath('//*[@id=\"B... | <|body_start_0|>
driver = self.driver
assert_list = []
driver.find_element_by_css_selector('#main-navigation > ul > li:nth-child(3) > a').click()
driver.find_element_by_link_text('口岸数据').click()
js = 'document.getElementById("from").value = "2018-09-08"'
driver.execute_sc... | 物流节点跟踪 | TestTrack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTrack:
"""物流节点跟踪"""
def query_track(self):
"""口岸数据 : 查询 > 添加订阅 > 批量订阅 > 重置 > 舱单运抵对比"""
<|body_0|>
def down_db(self):
"""新舱单节点查询导入模板下载"""
<|body_1|>
def check(self):
"""查验数据: 查询 > 添加订阅 > 批量订阅 > 重置"""
<|body_2|>
def down_cd(sel... | stack_v2_sparse_classes_75kplus_train_008588 | 4,730 | no_license | [
{
"docstring": "口岸数据 : 查询 > 添加订阅 > 批量订阅 > 重置 > 舱单运抵对比",
"name": "query_track",
"signature": "def query_track(self)"
},
{
"docstring": "新舱单节点查询导入模板下载",
"name": "down_db",
"signature": "def down_db(self)"
},
{
"docstring": "查验数据: 查询 > 添加订阅 > 批量订阅 > 重置",
"name": "check",
"si... | 4 | stack_v2_sparse_classes_30k_val_002749 | Implement the Python class `TestTrack` described below.
Class description:
物流节点跟踪
Method signatures and docstrings:
- def query_track(self): 口岸数据 : 查询 > 添加订阅 > 批量订阅 > 重置 > 舱单运抵对比
- def down_db(self): 新舱单节点查询导入模板下载
- def check(self): 查验数据: 查询 > 添加订阅 > 批量订阅 > 重置
- def down_cd(self): 查验数据查询导入模板下载 | Implement the Python class `TestTrack` described below.
Class description:
物流节点跟踪
Method signatures and docstrings:
- def query_track(self): 口岸数据 : 查询 > 添加订阅 > 批量订阅 > 重置 > 舱单运抵对比
- def down_db(self): 新舱单节点查询导入模板下载
- def check(self): 查验数据: 查询 > 添加订阅 > 批量订阅 > 重置
- def down_cd(self): 查验数据查询导入模板下载
<|skeleton|>
class Tes... | 28ccb35c0de98aa3753c7f3809979d0b00bddfe0 | <|skeleton|>
class TestTrack:
"""物流节点跟踪"""
def query_track(self):
"""口岸数据 : 查询 > 添加订阅 > 批量订阅 > 重置 > 舱单运抵对比"""
<|body_0|>
def down_db(self):
"""新舱单节点查询导入模板下载"""
<|body_1|>
def check(self):
"""查验数据: 查询 > 添加订阅 > 批量订阅 > 重置"""
<|body_2|>
def down_cd(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTrack:
"""物流节点跟踪"""
def query_track(self):
"""口岸数据 : 查询 > 添加订阅 > 批量订阅 > 重置 > 舱单运抵对比"""
driver = self.driver
assert_list = []
driver.find_element_by_css_selector('#main-navigation > ul > li:nth-child(3) > a').click()
driver.find_element_by_link_text('口岸数据').clic... | the_stack_v2_python_sparse | cangdan-test/user_script/test_track.py | butaihuiwan/cangdan | train | 0 |
00fa062314283f0ec79082ce615e928df8af2eaf | [
"atomtypes = list(set([Zi for Zi, posi in atomlist]))\natomtypes.sort()\nC6 = np.array([AtomicData.Grimme_C6[AtomicData.atom_names[Zi - 1]] for Zi in atomtypes])\nC6 *= 17.34525539265301\nR0 = np.array([AtomicData.Grimme_R0[AtomicData.atom_names[Zi - 1]] for Zi in atomtypes])\nR0 /= AtomicData.bohr_to_angs\nself.C6... | <|body_start_0|>
atomtypes = list(set([Zi for Zi, posi in atomlist]))
atomtypes.sort()
C6 = np.array([AtomicData.Grimme_C6[AtomicData.atom_names[Zi - 1]] for Zi in atomtypes])
C6 *= 17.34525539265301
R0 = np.array([AtomicData.Grimme_R0[AtomicData.atom_names[Zi - 1]] for Zi in ato... | DispersionCorrection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DispersionCorrection:
def __init__(self, atomlist):
"""This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and ca... | stack_v2_sparse_classes_75kplus_train_008589 | 4,341 | no_license | [
{
"docstring": "This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and cartesian coordinates in bohr for each atom",
"name": "__init... | 3 | stack_v2_sparse_classes_30k_train_025996 | Implement the Python class `DispersionCorrection` described below.
Class description:
Implement the DispersionCorrection class.
Method signatures and docstrings:
- def __init__(self, atomlist): This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in th... | Implement the Python class `DispersionCorrection` described below.
Class description:
Implement the DispersionCorrection class.
Method signatures and docstrings:
- def __init__(self, atomlist): This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in th... | 92cb73f1a6472f88588986561349d7f2ad1b1c15 | <|skeleton|>
class DispersionCorrection:
def __init__(self, atomlist):
"""This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DispersionCorrection:
def __init__(self, atomlist):
"""This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and cartesian coordi... | the_stack_v2_python_sparse | DFTB/Dispersion.py | by-student-2017/DFTBaby-0.1.0-31Jul2019 | train | 1 | |
9ee58d9c3d533edbfef1cc1c36903fb204a22742 | [
"self.id = id\nself.date = APIHelper.RFC3339DateTime(date) if date else None\nself.product_id = product_id\nself.description = description\nself.count = count\nself.customer_number = customer_number\nself.external_reference = external_reference\nself.department_id = department_id\nself.additional_properties = addit... | <|body_start_0|>
self.id = id
self.date = APIHelper.RFC3339DateTime(date) if date else None
self.product_id = product_id
self.description = description
self.count = count
self.customer_number = customer_number
self.external_reference = external_reference
s... | Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string): Transaction description count (int): Number of transactions for the selecte... | Transaction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transaction:
"""Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string): Transaction description count (int):... | stack_v2_sparse_classes_75kplus_train_008590 | 3,800 | permissive | [
{
"docstring": "Constructor for the Transaction class",
"name": "__init__",
"signature": "def __init__(self, id=None, date=None, product_id=None, description=None, count=None, customer_number=None, external_reference=None, department_id=None, additional_properties={})"
},
{
"docstring": "Creates... | 2 | stack_v2_sparse_classes_30k_val_002343 | Implement the Python class `Transaction` described below.
Class description:
Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string... | Implement the Python class `Transaction` described below.
Class description:
Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Transaction:
"""Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string): Transaction description count (int):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transaction:
"""Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string): Transaction description count (int): Number of tr... | the_stack_v2_python_sparse | idfy_rest_client/models/transaction.py | dealflowteam/Idfy | train | 0 |
519127431cccfbb2ff502a3520b9ee554721da20 | [
"super(HiveFilteredPartitionSensor, self).__init__(host, port, **kwargs)\nself._table_name = table_name\nself._partition_filter = partition_filter",
"with self._hive_metastore_client as client:\n partitions = client.get_partitions_by_filter(db_name=self._schema, tbl_name=self._table_name, filter=self._partitio... | <|body_start_0|>
super(HiveFilteredPartitionSensor, self).__init__(host, port, **kwargs)
self._table_name = table_name
self._partition_filter = partition_filter
<|end_body_0|>
<|body_start_1|>
with self._hive_metastore_client as client:
partitions = client.get_partitions_by_... | HiveFilteredPartitionSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiveFilteredPartitionSensor:
def __init__(self, table_name, partition_filter, host, port, **kwargs):
"""This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it ... | stack_v2_sparse_classes_75kplus_train_008591 | 4,900 | permissive | [
{
"docstring": "This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it is a more efficient API. :param Text table_name: The name of the table :param Text partition_filter: A filter ex... | 2 | stack_v2_sparse_classes_30k_train_054585 | Implement the Python class `HiveFilteredPartitionSensor` described below.
Class description:
Implement the HiveFilteredPartitionSensor class.
Method signatures and docstrings:
- def __init__(self, table_name, partition_filter, host, port, **kwargs): This class allows sensing for any Hive partition that matches a filt... | Implement the Python class `HiveFilteredPartitionSensor` described below.
Class description:
Implement the HiveFilteredPartitionSensor class.
Method signatures and docstrings:
- def __init__(self, table_name, partition_filter, host, port, **kwargs): This class allows sensing for any Hive partition that matches a filt... | 2eb9ce7aacaab6e49c1fc901c14c7b0d6b479523 | <|skeleton|>
class HiveFilteredPartitionSensor:
def __init__(self, table_name, partition_filter, host, port, **kwargs):
"""This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HiveFilteredPartitionSensor:
def __init__(self, table_name, partition_filter, host, port, **kwargs):
"""This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it is a more effi... | the_stack_v2_python_sparse | flytekit/contrib/sensors/impl.py | jbrambleDC/flytekit | train | 1 | |
6702ed69e8b8b657f69824e879d632a9ef624975 | [
"super(RandomWander, self).__init__()\nself.iteration = 0\nself.rate = rate\nself.speed = 0\nself.heading = 0",
"if self.iteration > self.rate:\n self.iteration = 0\n heading = random.random() * 180 - 90\n self.speed = 0.1\n if heading >= 0:\n self.heading = heading\n else:\n self.hea... | <|body_start_0|>
super(RandomWander, self).__init__()
self.iteration = 0
self.rate = rate
self.speed = 0
self.heading = 0
<|end_body_0|>
<|body_start_1|>
if self.iteration > self.rate:
self.iteration = 0
heading = random.random() * 180 - 90
... | Simple behavior tht wanders, turning with some randomness each time. | RandomWander | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWander:
"""Simple behavior tht wanders, turning with some randomness each time."""
def __init__(self, rate):
"""Sets up the behavior with all rates set to zero."""
<|body_0|>
def update(self):
"""wanders with a random heading."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_008592 | 8,374 | no_license | [
{
"docstring": "Sets up the behavior with all rates set to zero.",
"name": "__init__",
"signature": "def __init__(self, rate)"
},
{
"docstring": "wanders with a random heading.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053764 | Implement the Python class `RandomWander` described below.
Class description:
Simple behavior tht wanders, turning with some randomness each time.
Method signatures and docstrings:
- def __init__(self, rate): Sets up the behavior with all rates set to zero.
- def update(self): wanders with a random heading. | Implement the Python class `RandomWander` described below.
Class description:
Simple behavior tht wanders, turning with some randomness each time.
Method signatures and docstrings:
- def __init__(self, rate): Sets up the behavior with all rates set to zero.
- def update(self): wanders with a random heading.
<|skelet... | 97bb378a325b1639110de06b88d6e237dffc7330 | <|skeleton|>
class RandomWander:
"""Simple behavior tht wanders, turning with some randomness each time."""
def __init__(self, rate):
"""Sets up the behavior with all rates set to zero."""
<|body_0|>
def update(self):
"""wanders with a random heading."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWander:
"""Simple behavior tht wanders, turning with some randomness each time."""
def __init__(self, rate):
"""Sets up the behavior with all rates set to zero."""
super(RandomWander, self).__init__()
self.iteration = 0
self.rate = rate
self.speed = 0
... | the_stack_v2_python_sparse | src/match_seeker/scripts/FieldBehaviors.py | FoxRobotLab/catkin_ws | train | 6 |
d3465b903788536c612f5ae4df0d43f34d1078a9 | [
"super(baseline_network_conv, self).__init__()\nself.linear1st = nn.Linear(input_size, hidden_size)\nself.FC_layers = nn.ModuleList([MLP(hidden_size) for i in range(n_linear_layers)])\nself.myreshape = View(output_size)\nself.conv_layer1 = nn.Sequential(nn.Conv2d(1, 1, kernel_size=5, padding=2))",
"x = self.linea... | <|body_start_0|>
super(baseline_network_conv, self).__init__()
self.linear1st = nn.Linear(input_size, hidden_size)
self.FC_layers = nn.ModuleList([MLP(hidden_size) for i in range(n_linear_layers)])
self.myreshape = View(output_size)
self.conv_layer1 = nn.Sequential(nn.Conv2d(1, 1... | a simple feedforward network from mean word vector representation to 2D brain activation NOTE: we do note employ deconvolutions, just reshape the output and (possibly) apply some convolutions. This network implements a function from extbf{R}^d -> extbf{R}^k imes extbf{R}^k where d is the dimension of word embeddings an... | baseline_network_conv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class baseline_network_conv:
"""a simple feedforward network from mean word vector representation to 2D brain activation NOTE: we do note employ deconvolutions, just reshape the output and (possibly) apply some convolutions. This network implements a function from extbf{R}^d -> extbf{R}^k imes extbf{R}... | stack_v2_sparse_classes_75kplus_train_008593 | 2,538 | no_license | [
{
"docstring": "INPUT: - input_size : dimension of word vector embeddings - hidden_size : dimension of linear hidden layers (try to match with dimension of output images) - output_size : size output image (e.g., if 20, then image will be 20 by 20) - n_linear_layers : number of fully connected layers - n_conv_la... | 2 | stack_v2_sparse_classes_30k_train_002648 | Implement the Python class `baseline_network_conv` described below.
Class description:
a simple feedforward network from mean word vector representation to 2D brain activation NOTE: we do note employ deconvolutions, just reshape the output and (possibly) apply some convolutions. This network implements a function from... | Implement the Python class `baseline_network_conv` described below.
Class description:
a simple feedforward network from mean word vector representation to 2D brain activation NOTE: we do note employ deconvolutions, just reshape the output and (possibly) apply some convolutions. This network implements a function from... | 97ad23f27877ba143311ab79afb81f60b8c2c01f | <|skeleton|>
class baseline_network_conv:
"""a simple feedforward network from mean word vector representation to 2D brain activation NOTE: we do note employ deconvolutions, just reshape the output and (possibly) apply some convolutions. This network implements a function from extbf{R}^d -> extbf{R}^k imes extbf{R}... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class baseline_network_conv:
"""a simple feedforward network from mean word vector representation to 2D brain activation NOTE: we do note employ deconvolutions, just reshape the output and (possibly) apply some convolutions. This network implements a function from extbf{R}^d -> extbf{R}^k imes extbf{R}^k where d is... | the_stack_v2_python_sparse | Code/networks/baseline_network_conv.py | piomonti/abstract2brain | train | 0 |
4d2b97b3d5493bf74f2437bd64365f203305a16f | [
"data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)\nthresholds = np.array([273.0, 275.0, 277.0], dtype=np.float32)\nself.cube = set_up_probability_cube(data.copy(), thresholds)\nself.cell_method1 = iris.coords.CellMethod('mean', 'realization')\nself.cell_method... | <|body_start_0|>
data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)
thresholds = np.array([273.0, 275.0, 277.0], dtype=np.float32)
self.cube = set_up_probability_cube(data.copy(), thresholds)
self.cell_method1 = iris.coords.CellMethod... | Test the _equalise_cell_methods method | Test__equalise_cell_methods | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__equalise_cell_methods:
"""Test the _equalise_cell_methods method"""
def setUp(self):
"""Use temperature probability cube to test with."""
<|body_0|>
def test_basic(self):
"""Test returns an iris.cube.CubeList."""
<|body_1|>
def test_different_c... | stack_v2_sparse_classes_75kplus_train_008594 | 13,177 | permissive | [
{
"docstring": "Use temperature probability cube to test with.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test returns an iris.cube.CubeList.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test returns an iris.cube.CubeLis... | 3 | stack_v2_sparse_classes_30k_train_033614 | Implement the Python class `Test__equalise_cell_methods` described below.
Class description:
Test the _equalise_cell_methods method
Method signatures and docstrings:
- def setUp(self): Use temperature probability cube to test with.
- def test_basic(self): Test returns an iris.cube.CubeList.
- def test_different_cell_... | Implement the Python class `Test__equalise_cell_methods` described below.
Class description:
Test the _equalise_cell_methods method
Method signatures and docstrings:
- def setUp(self): Use temperature probability cube to test with.
- def test_basic(self): Test returns an iris.cube.CubeList.
- def test_different_cell_... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__equalise_cell_methods:
"""Test the _equalise_cell_methods method"""
def setUp(self):
"""Use temperature probability cube to test with."""
<|body_0|>
def test_basic(self):
"""Test returns an iris.cube.CubeList."""
<|body_1|>
def test_different_c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__equalise_cell_methods:
"""Test the _equalise_cell_methods method"""
def setUp(self):
"""Use temperature probability cube to test with."""
data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)
thresholds = np.array([273.0, 27... | the_stack_v2_python_sparse | improver_tests/utilities/cube_manipulation/test_MergeCubes.py | metoppv/improver | train | 101 |
a69a7b8edc84aa7be3ca26c91d5dac759153177e | [
"super().__init__()\nself.topk = topk\nself.weight = weight\nself.norm = normalize\nself.binary = binary\nself.word2vec_path = word2vec_path\nif word2vec_path is None:\n self._wv = api.load('word2vec-google-news-300')\nelse:\n self._wv = KeyedVectors.load_word2vec_format(word2vec_path, binary=self.binary)",
... | <|body_start_0|>
super().__init__()
self.topk = topk
self.weight = weight
self.norm = normalize
self.binary = binary
self.word2vec_path = word2vec_path
if word2vec_path is None:
self._wv = api.load('word2vec-google-news-300')
else:
... | WordEmbeddingsInvertedRBO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordEmbeddingsInvertedRBO:
def __init__(self, topk=10, weight=0.9, normalize=True, word2vec_path=None, binary=True):
"""Initialize metric WE-IRBO-Match Parameters ---------- :param topk: top k words on which the topic diversity will be computed :param word2vec_path: word embedding space ... | stack_v2_sparse_classes_75kplus_train_008595 | 8,087 | permissive | [
{
"docstring": "Initialize metric WE-IRBO-Match Parameters ---------- :param topk: top k words on which the topic diversity will be computed :param word2vec_path: word embedding space in gensim word2vec format :param weight: Weight of each agreement at depth d. When set to 1.0, there is no weight, the rbo retur... | 2 | stack_v2_sparse_classes_30k_train_046643 | Implement the Python class `WordEmbeddingsInvertedRBO` described below.
Class description:
Implement the WordEmbeddingsInvertedRBO class.
Method signatures and docstrings:
- def __init__(self, topk=10, weight=0.9, normalize=True, word2vec_path=None, binary=True): Initialize metric WE-IRBO-Match Parameters ---------- ... | Implement the Python class `WordEmbeddingsInvertedRBO` described below.
Class description:
Implement the WordEmbeddingsInvertedRBO class.
Method signatures and docstrings:
- def __init__(self, topk=10, weight=0.9, normalize=True, word2vec_path=None, binary=True): Initialize metric WE-IRBO-Match Parameters ---------- ... | 71d65fc74d7290fd8aee37e4d828792f344b7695 | <|skeleton|>
class WordEmbeddingsInvertedRBO:
def __init__(self, topk=10, weight=0.9, normalize=True, word2vec_path=None, binary=True):
"""Initialize metric WE-IRBO-Match Parameters ---------- :param topk: top k words on which the topic diversity will be computed :param word2vec_path: word embedding space ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordEmbeddingsInvertedRBO:
def __init__(self, topk=10, weight=0.9, normalize=True, word2vec_path=None, binary=True):
"""Initialize metric WE-IRBO-Match Parameters ---------- :param topk: top k words on which the topic diversity will be computed :param word2vec_path: word embedding space in gensim word... | the_stack_v2_python_sparse | octis/evaluation_metrics/diversity_metrics.py | EamonJarrett-Mann/OCTIS | train | 0 | |
231fac2daf4fd5966c62f1388e378d5fc54835ba | [
"super(ResidualAttention, self).__init__()\nself.e = nn.Linear(n_hidden, n_embedding)\nself.v = nn.Linear(n_embedding, n_hidden)\nself.scale = scale",
"emb_c = self.e(c.permute(0, 2, 1))\ncombined = (emb_c + emb) * self.scale\nenergy = torch.matmul(combined, enc_c.permute(0, 2, 1))\nattention = nn.functional.soft... | <|body_start_0|>
super(ResidualAttention, self).__init__()
self.e = nn.Linear(n_hidden, n_embedding)
self.v = nn.Linear(n_embedding, n_hidden)
self.scale = scale
<|end_body_0|>
<|body_start_1|>
emb_c = self.e(c.permute(0, 2, 1))
combined = (emb_c + emb) * self.scale
... | A ResidualAttention class is used to provide attention-based mechanisms in a neural network layer among residual connections. References: F. Wang, et al. Residual attention network for image classification. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (2017). | ResidualAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualAttention:
"""A ResidualAttention class is used to provide attention-based mechanisms in a neural network layer among residual connections. References: F. Wang, et al. Residual attention network for image classification. Proceedings of the IEEE Conference on Computer Vision and Pattern Re... | stack_v2_sparse_classes_75kplus_train_008596 | 2,423 | permissive | [
{
"docstring": "Initialization method. Args: n_hidden (int): Number of hidden units. n_embedding (int): Number of embedding units. scale (float): Value for the residual learning.",
"name": "__init__",
"signature": "def __init__(self, n_hidden, n_embedding, scale)"
},
{
"docstring": "Performs a f... | 2 | stack_v2_sparse_classes_30k_test_002088 | Implement the Python class `ResidualAttention` described below.
Class description:
A ResidualAttention class is used to provide attention-based mechanisms in a neural network layer among residual connections. References: F. Wang, et al. Residual attention network for image classification. Proceedings of the IEEE Confe... | Implement the Python class `ResidualAttention` described below.
Class description:
A ResidualAttention class is used to provide attention-based mechanisms in a neural network layer among residual connections. References: F. Wang, et al. Residual attention network for image classification. Proceedings of the IEEE Confe... | cccc670d48995fa0bfbdf9fc8013d13a90ea5e84 | <|skeleton|>
class ResidualAttention:
"""A ResidualAttention class is used to provide attention-based mechanisms in a neural network layer among residual connections. References: F. Wang, et al. Residual attention network for image classification. Proceedings of the IEEE Conference on Computer Vision and Pattern Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResidualAttention:
"""A ResidualAttention class is used to provide attention-based mechanisms in a neural network layer among residual connections. References: F. Wang, et al. Residual attention network for image classification. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (20... | the_stack_v2_python_sparse | textformer/models/layers/residual_attention.py | gugarosa/textformer | train | 3 |
10cde9cf7e35d3bef870e3600d6ab79aaed72481 | [
"self.name = name\nself.type = type\nself.days_till_expiration = days_till_expiration",
"if self.days_till_expiration == 0:\n return f'name = {self.name}, type = {self.type}, expires today.'\nelif self.days_till_expiration < -1:\n return f'name = {self.name}, type = {self.type}, expired {self.days_till_expi... | <|body_start_0|>
self.name = name
self.type = type
self.days_till_expiration = days_till_expiration
<|end_body_0|>
<|body_start_1|>
if self.days_till_expiration == 0:
return f'name = {self.name}, type = {self.type}, expires today.'
elif self.days_till_expiration < -1... | Fridge item class. | FridgeItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FridgeItem:
"""Fridge item class."""
def __init__(self, name: str, type: str, days_till_expiration: int):
"""Constructor."""
<|body_0|>
def __repr__(self):
"""Return FridgeItem in nice string form. For example: name = "apple", type = "fruit", days_till_expiration... | stack_v2_sparse_classes_75kplus_train_008597 | 9,004 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, name: str, type: str, days_till_expiration: int)"
},
{
"docstring": "Return FridgeItem in nice string form. For example: name = \"apple\", type = \"fruit\", days_till_expiration = 4 \"Name: apple, type: fruit, ex... | 2 | stack_v2_sparse_classes_30k_train_002255 | Implement the Python class `FridgeItem` described below.
Class description:
Fridge item class.
Method signatures and docstrings:
- def __init__(self, name: str, type: str, days_till_expiration: int): Constructor.
- def __repr__(self): Return FridgeItem in nice string form. For example: name = "apple", type = "fruit",... | Implement the Python class `FridgeItem` described below.
Class description:
Fridge item class.
Method signatures and docstrings:
- def __init__(self, name: str, type: str, days_till_expiration: int): Constructor.
- def __repr__(self): Return FridgeItem in nice string form. For example: name = "apple", type = "fruit",... | af01b1bb49f28a24730d5c3b5b6613fd2d81c839 | <|skeleton|>
class FridgeItem:
"""Fridge item class."""
def __init__(self, name: str, type: str, days_till_expiration: int):
"""Constructor."""
<|body_0|>
def __repr__(self):
"""Return FridgeItem in nice string form. For example: name = "apple", type = "fruit", days_till_expiration... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FridgeItem:
"""Fridge item class."""
def __init__(self, name: str, type: str, days_till_expiration: int):
"""Constructor."""
self.name = name
self.type = type
self.days_till_expiration = days_till_expiration
def __repr__(self):
"""Return FridgeItem in nice str... | the_stack_v2_python_sparse | iti0102-2020-master/KT/kt1/exam.py | mazariks/ITI0102 | train | 0 |
54fef5127108a4c4826401ffd9651f7bd8e85679 | [
"self.root = None\nself.words_in_tree = 0\nself.fileName = 'dataStructures/words.txt'\nfor word in open(self.fileName):\n self.add(word[:-1])\n self.words_in_tree += 1\n if self.words_in_tree > 1000:\n break",
"if node == -1:\n node = self.root\nif node is None:\n return []\npossible_matches... | <|body_start_0|>
self.root = None
self.words_in_tree = 0
self.fileName = 'dataStructures/words.txt'
for word in open(self.fileName):
self.add(word[:-1])
self.words_in_tree += 1
if self.words_in_tree > 1000:
break
<|end_body_0|>
<|body_... | Tree data structure that allows for fast querying of matches given a dictionary of words to iterate over using Levenshtein distance. Each node in the tree is the value (a word) and a dictionary of children for each of the nodes. When reading the code, remember the definition of a bk tree: Each node has one unique dista... | bk_tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class bk_tree:
"""Tree data structure that allows for fast querying of matches given a dictionary of words to iterate over using Levenshtein distance. Each node in the tree is the value (a word) and a dictionary of children for each of the nodes. When reading the code, remember the definition of a bk t... | stack_v2_sparse_classes_75kplus_train_008598 | 4,313 | no_license | [
{
"docstring": "Initialize a bk tree for spellchecking with a wordlist. This bk tree uses Levenshtein distance. Each node is a list containing the node value and its children. The idea is summarized below: Each node has one unique distance; if not, walk down the tree and add it to the only place that doesn't ha... | 3 | stack_v2_sparse_classes_30k_train_033529 | Implement the Python class `bk_tree` described below.
Class description:
Tree data structure that allows for fast querying of matches given a dictionary of words to iterate over using Levenshtein distance. Each node in the tree is the value (a word) and a dictionary of children for each of the nodes. When reading the ... | Implement the Python class `bk_tree` described below.
Class description:
Tree data structure that allows for fast querying of matches given a dictionary of words to iterate over using Levenshtein distance. Each node in the tree is the value (a word) and a dictionary of children for each of the nodes. When reading the ... | 918ca0714ee54e9aeb0d3bc7f167720dd8230dc3 | <|skeleton|>
class bk_tree:
"""Tree data structure that allows for fast querying of matches given a dictionary of words to iterate over using Levenshtein distance. Each node in the tree is the value (a word) and a dictionary of children for each of the nodes. When reading the code, remember the definition of a bk t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class bk_tree:
"""Tree data structure that allows for fast querying of matches given a dictionary of words to iterate over using Levenshtein distance. Each node in the tree is the value (a word) and a dictionary of children for each of the nodes. When reading the code, remember the definition of a bk tree: Each nod... | the_stack_v2_python_sparse | src/dataStructures/bkTree.py | alexsieusahai/dim | train | 2 |
0113e85782f9de8d443fbe0b86c9937f6b41ad7b | [
"assert size in ['small', 'medium', 'large'], \"model size must be one of ['small', 'medium', 'large']\"\nsuper().__init__(f'microsoft/DialoGPT-{size}', env)\nself.device = device.lower()\nself.model = GPT2LMHeadModel.from_pretrained(self.name).to(device)\nself.tokenizer = GPT2Tokenizer.from_pretrained(self.name)\n... | <|body_start_0|>
assert size in ['small', 'medium', 'large'], "model size must be one of ['small', 'medium', 'large']"
super().__init__(f'microsoft/DialoGPT-{size}', env)
self.device = device.lower()
self.model = GPT2LMHeadModel.from_pretrained(self.name).to(device)
self.tokenize... | DialoGPT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialoGPT:
def __init__(self, size, env, device, max_context_length):
"""DialoGPT was proposed in DialoGPT: Large-Scale Generative Pre- training for Conversational Response Generation by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing... | stack_v2_sparse_classes_75kplus_train_008599 | 3,641 | permissive | [
{
"docstring": "DialoGPT was proposed in DialoGPT: Large-Scale Generative Pre- training for Conversational Response Generation by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan. It’s a GPT2 Model trained on 147M conversation-like exchanges ... | 2 | stack_v2_sparse_classes_30k_train_016667 | Implement the Python class `DialoGPT` described below.
Class description:
Implement the DialoGPT class.
Method signatures and docstrings:
- def __init__(self, size, env, device, max_context_length): DialoGPT was proposed in DialoGPT: Large-Scale Generative Pre- training for Conversational Response Generation by Yizhe... | Implement the Python class `DialoGPT` described below.
Class description:
Implement the DialoGPT class.
Method signatures and docstrings:
- def __init__(self, size, env, device, max_context_length): DialoGPT was proposed in DialoGPT: Large-Scale Generative Pre- training for Conversational Response Generation by Yizhe... | af87a17275f02c94932bb2e29f132a84db812002 | <|skeleton|>
class DialoGPT:
def __init__(self, size, env, device, max_context_length):
"""DialoGPT was proposed in DialoGPT: Large-Scale Generative Pre- training for Conversational Response Generation by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DialoGPT:
def __init__(self, size, env, device, max_context_length):
"""DialoGPT was proposed in DialoGPT: Large-Scale Generative Pre- training for Conversational Response Generation by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dol... | the_stack_v2_python_sparse | openchat/openchat/models/dialogpt.py | linxi1158/iMIX | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.