blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
dd5e067bdd138e92ad3cb25a5410c843c1b94202
[ "self.scanner_name = 'container-capabilities-scanner'\nself.full_scanner_name = 'registry.centos.org/pipeline-images/container-capabilities-scanner'\nself.scan_types = ['check-capabilities']", "logs = []\nsuper(ContainerCapabilities, self).__init__(image_under_test=image_under_test, scanner_name=self.scanner_name...
<|body_start_0|> self.scanner_name = 'container-capabilities-scanner' self.full_scanner_name = 'registry.centos.org/pipeline-images/container-capabilities-scanner' self.scan_types = ['check-capabilities'] <|end_body_0|> <|body_start_1|> logs = [] super(ContainerCapabilities, sel...
Container Capabilities scan.
ContainerCapabilities
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContainerCapabilities: """Container Capabilities scan.""" def __init__(self): """Scanner name and types.""" <|body_0|> def scan(self, image_under_test): """Run the scanner on image under test.""" <|body_1|> def process_output(self, logs): """...
stack_v2_sparse_classes_36k_train_033400
2,140
no_license
[ { "docstring": "Scanner name and types.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Run the scanner on image under test.", "name": "scan", "signature": "def scan(self, image_under_test)" }, { "docstring": "Process the output logs to send to other wo...
3
stack_v2_sparse_classes_30k_train_021663
Implement the Python class `ContainerCapabilities` described below. Class description: Container Capabilities scan. Method signatures and docstrings: - def __init__(self): Scanner name and types. - def scan(self, image_under_test): Run the scanner on image under test. - def process_output(self, logs): Process the out...
Implement the Python class `ContainerCapabilities` described below. Class description: Container Capabilities scan. Method signatures and docstrings: - def __init__(self): Scanner name and types. - def scan(self, image_under_test): Run the scanner on image under test. - def process_output(self, logs): Process the out...
4b59184c3453ae706d5e352306fe9e551c90dc41
<|skeleton|> class ContainerCapabilities: """Container Capabilities scan.""" def __init__(self): """Scanner name and types.""" <|body_0|> def scan(self, image_under_test): """Run the scanner on image under test.""" <|body_1|> def process_output(self, logs): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ContainerCapabilities: """Container Capabilities scan.""" def __init__(self): """Scanner name and types.""" self.scanner_name = 'container-capabilities-scanner' self.full_scanner_name = 'registry.centos.org/pipeline-images/container-capabilities-scanner' self.scan_types = ...
the_stack_v2_python_sparse
container_pipeline/scanners/container_capabilities.py
eupraxialabs/container-pipeline-service
train
0
6f1bcea99af09f0bd30fab0cc486c8e6fe043792
[ "self.center = center\nself.indices = indices\nself.score = score\nself.left = None\nself.right = None", "self.left = _BisectingTree(indices=self.indices[labels == 0], center=centers[0], score=scores[0])\nself.right = _BisectingTree(indices=self.indices[labels == 1], center=centers[1], score=scores[1])\nself.indi...
<|body_start_0|> self.center = center self.indices = indices self.score = score self.left = None self.right = None <|end_body_0|> <|body_start_1|> self.left = _BisectingTree(indices=self.indices[labels == 0], center=centers[0], score=scores[0]) self.right = _Bise...
Tree structure representing the hierarchical clusters of BisectingKMeans.
_BisectingTree
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _BisectingTree: """Tree structure representing the hierarchical clusters of BisectingKMeans.""" def __init__(self, center, indices, score): """Create a new cluster node in the tree. The node holds the center of this cluster and the indices of the data points that belong to it.""" ...
stack_v2_sparse_classes_36k_train_033401
18,882
permissive
[ { "docstring": "Create a new cluster node in the tree. The node holds the center of this cluster and the indices of the data points that belong to it.", "name": "__init__", "signature": "def __init__(self, center, indices, score)" }, { "docstring": "Split the cluster node into two subclusters.",...
4
stack_v2_sparse_classes_30k_train_000369
Implement the Python class `_BisectingTree` described below. Class description: Tree structure representing the hierarchical clusters of BisectingKMeans. Method signatures and docstrings: - def __init__(self, center, indices, score): Create a new cluster node in the tree. The node holds the center of this cluster and...
Implement the Python class `_BisectingTree` described below. Class description: Tree structure representing the hierarchical clusters of BisectingKMeans. Method signatures and docstrings: - def __init__(self, center, indices, score): Create a new cluster node in the tree. The node holds the center of this cluster and...
061f8777b48e5491b0c57bb8e0bc7067c103079d
<|skeleton|> class _BisectingTree: """Tree structure representing the hierarchical clusters of BisectingKMeans.""" def __init__(self, center, indices, score): """Create a new cluster node in the tree. The node holds the center of this cluster and the indices of the data points that belong to it.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _BisectingTree: """Tree structure representing the hierarchical clusters of BisectingKMeans.""" def __init__(self, center, indices, score): """Create a new cluster node in the tree. The node holds the center of this cluster and the indices of the data points that belong to it.""" self.cen...
the_stack_v2_python_sparse
sklearn/cluster/_bisect_k_means.py
scikit-learn/scikit-learn
train
58,456
f2089bd9188880443dd919bfc65fef2ac84b5987
[ "if area_m2 is None:\n area = 1000000.0 * self.sample.farea[i]\nelse:\n area = area_m2\nhflux_kW = 1000.0 * rad2conv * self.sample.pow[i] / area\nptop = 1.0\nu = self.sample.u[i]\nv = self.sample.v[i]\nT = self.sample.t[i]\nq = self.sample.qv[i]\ndelp = self.sample.delp[i]\nif delp.min() <= 0 or T.min() <= 0:...
<|body_start_0|> if area_m2 is None: area = 1000000.0 * self.sample.farea[i] else: area = area_m2 hflux_kW = 1000.0 * rad2conv * self.sample.pow[i] / area ptop = 1.0 u = self.sample.u[i] v = self.sample.v[i] T = self.sample.t[i] q =...
Extension of the MxD14,IGBP and DOZIER classes, adding the Plume Rise functionality. This class handles non-gridded, observation location fires.
PLUME_L2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PLUME_L2: """Extension of the MxD14,IGBP and DOZIER classes, adding the Plume Rise functionality. This class handles non-gridded, observation location fires.""" def getPlume1(self, i, Verbose=False, rad2conv=5, area_m2=None): """Compute plume height for the ith fire.""" <|bod...
stack_v2_sparse_classes_36k_train_033402
46,607
permissive
[ { "docstring": "Compute plume height for the ith fire.", "name": "getPlume1", "signature": "def getPlume1(self, i, Verbose=False, rad2conv=5, area_m2=None)" }, { "docstring": "Runs the Plume Rise extension to compute the extent of the plume for each fire. It is assumed that the necessary met fie...
3
stack_v2_sparse_classes_30k_train_016712
Implement the Python class `PLUME_L2` described below. Class description: Extension of the MxD14,IGBP and DOZIER classes, adding the Plume Rise functionality. This class handles non-gridded, observation location fires. Method signatures and docstrings: - def getPlume1(self, i, Verbose=False, rad2conv=5, area_m2=None)...
Implement the Python class `PLUME_L2` described below. Class description: Extension of the MxD14,IGBP and DOZIER classes, adding the Plume Rise functionality. This class handles non-gridded, observation location fires. Method signatures and docstrings: - def getPlume1(self, i, Verbose=False, rad2conv=5, area_m2=None)...
dff1f2ed36189f6879409375d241be40f18c5666
<|skeleton|> class PLUME_L2: """Extension of the MxD14,IGBP and DOZIER classes, adding the Plume Rise functionality. This class handles non-gridded, observation location fires.""" def getPlume1(self, i, Verbose=False, rad2conv=5, area_m2=None): """Compute plume height for the ith fire.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PLUME_L2: """Extension of the MxD14,IGBP and DOZIER classes, adding the Plume Rise functionality. This class handles non-gridded, observation location fires.""" def getPlume1(self, i, Verbose=False, rad2conv=5, area_m2=None): """Compute plume height for the ith fire.""" if area_m2 is None...
the_stack_v2_python_sparse
src/Components/qfed/qfed/PlumeRise.py
GEOS-ESM/AeroApps
train
4
95381f61022132a181a0b5399a1854c8f40fbb40
[ "AssessmentResults.__init__(self, controller, **kwargs)\nself._lst_labels.append(u'π<sub>C</sub>:')\nself._lblModel.set_tooltip_markup(_(u\"The assessment model used to calculate the inductive device's failure rate.\"))\nself.txtPiC = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'The construc...
<|body_start_0|> AssessmentResults.__init__(self, controller, **kwargs) self._lst_labels.append(u'π<sub>C</sub>:') self._lblModel.set_tooltip_markup(_(u"The assessment model used to calculate the inductive device's failure rate.")) self.txtPiC = ramstk.RAMSTKEntry(width=125, editable=Fal...
Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. The attributes of an Inductor assessment result view a...
InductorAssessmentResults
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InductorAssessmentResults: """Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. T...
stack_v2_sparse_classes_36k_train_033403
20,499
permissive
[ { "docstring": "Initialize an instance of the Inductor assessment result view. :param controller: the hardware data controller instance. :type controller: :class:`ramstk.hardware.Controller.HardwareBoMDataController` :param int hardware_id: the hardware ID of the currently selected inductor. :param int subcateg...
5
stack_v2_sparse_classes_30k_train_010546
Implement the Python class `InductorAssessmentResults` described below. Class description: Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2...
Implement the Python class `InductorAssessmentResults` described below. Class description: Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2...
488ffed8b842399ddcae93007de6c6f1dda23d05
<|skeleton|> class InductorAssessmentResults: """Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InductorAssessmentResults: """Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. The attributes...
the_stack_v2_python_sparse
src/ramstk/gui/gtk/workviews/components/Inductor.py
JmiXIII/ramstk
train
0
866459d62327a5df7621afee0713a5cee04b036e
[ "self.lowest_list_price = lowest_list_price\nself.highest_list_price = highest_list_price\nself.lowest_sale_price = lowest_sale_price\nself.highest_sale_price = highest_sale_price", "if dictionary is None:\n return None\nlowest_list_price = awsecommerceservice.models.price.Price.from_dictionary(dictionary.get(...
<|body_start_0|> self.lowest_list_price = lowest_list_price self.highest_list_price = highest_list_price self.lowest_sale_price = lowest_sale_price self.highest_sale_price = highest_sale_price <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'CollectionSummary' model. TODO: type model description here. Attributes: lowest_list_price (Price): TODO: type description here. highest_list_price (Price): TODO: type description here. lowest_sale_price (Price): TODO: type description here. highest_sale_price (Price): TODO: type description here...
CollectionSummary
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CollectionSummary: """Implementation of the 'CollectionSummary' model. TODO: type model description here. Attributes: lowest_list_price (Price): TODO: type description here. highest_list_price (Price): TODO: type description here. lowest_sale_price (Price): TODO: type description here. highest_sa...
stack_v2_sparse_classes_36k_train_033404
2,826
permissive
[ { "docstring": "Constructor for the CollectionSummary class", "name": "__init__", "signature": "def __init__(self, lowest_list_price=None, highest_list_price=None, lowest_sale_price=None, highest_sale_price=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dicti...
2
stack_v2_sparse_classes_30k_train_008524
Implement the Python class `CollectionSummary` described below. Class description: Implementation of the 'CollectionSummary' model. TODO: type model description here. Attributes: lowest_list_price (Price): TODO: type description here. highest_list_price (Price): TODO: type description here. lowest_sale_price (Price): ...
Implement the Python class `CollectionSummary` described below. Class description: Implementation of the 'CollectionSummary' model. TODO: type model description here. Attributes: lowest_list_price (Price): TODO: type description here. highest_list_price (Price): TODO: type description here. lowest_sale_price (Price): ...
26ea1019115a1de3b1b37a4b830525e164ac55ce
<|skeleton|> class CollectionSummary: """Implementation of the 'CollectionSummary' model. TODO: type model description here. Attributes: lowest_list_price (Price): TODO: type description here. highest_list_price (Price): TODO: type description here. lowest_sale_price (Price): TODO: type description here. highest_sa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CollectionSummary: """Implementation of the 'CollectionSummary' model. TODO: type model description here. Attributes: lowest_list_price (Price): TODO: type description here. highest_list_price (Price): TODO: type description here. lowest_sale_price (Price): TODO: type description here. highest_sale_price (Pri...
the_stack_v2_python_sparse
awsecommerceservice/models/collection_summary.py
nidaizamir/Test-PY
train
0
c929e66ccb7582ca2e8427ddf32fee9206e4664c
[ "self.F = F\nself.F0 = B\nself.Q = chol_ext(len(B))", "def getA(i, j):\n n = len(x)\n return self.F0[i, j] - sum((self.F[k][i, j] * x[k] for k in range(n)))\nif self.Q.factor(getA):\n return None\nep = self.Q.witness()\ng = np.array([self.Q.sym_quad(Fk) for Fk in self.F])\nreturn (g, ep)" ]
<|body_start_0|> self.F = F self.F0 = B self.Q = chol_ext(len(B)) <|end_body_0|> <|body_start_1|> def getA(i, j): n = len(x) return self.F0[i, j] - sum((self.F[k][i, j] * x[k] for k in range(n))) if self.Q.factor(getA): return None ep ...
Oracle for Linear Matrix Inequality constraint. This oracle solves the following feasibility problem: find x s.t. (B − F * x) ⪰ 0
lmi_oracle
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class lmi_oracle: """Oracle for Linear Matrix Inequality constraint. This oracle solves the following feasibility problem: find x s.t. (B − F * x) ⪰ 0""" def __init__(self, F, B): """Construct a new lmi oracle object Arguments: F (List[Arr]): [description] B (Arr): [description]""" ...
stack_v2_sparse_classes_36k_train_033405
1,216
permissive
[ { "docstring": "Construct a new lmi oracle object Arguments: F (List[Arr]): [description] B (Arr): [description]", "name": "__init__", "signature": "def __init__(self, F, B)" }, { "docstring": "[summary] Arguments: x (Arr): [description] Returns: Optional[Cut]: [description]", "name": "__cal...
2
stack_v2_sparse_classes_30k_train_017317
Implement the Python class `lmi_oracle` described below. Class description: Oracle for Linear Matrix Inequality constraint. This oracle solves the following feasibility problem: find x s.t. (B − F * x) ⪰ 0 Method signatures and docstrings: - def __init__(self, F, B): Construct a new lmi oracle object Arguments: F (Li...
Implement the Python class `lmi_oracle` described below. Class description: Oracle for Linear Matrix Inequality constraint. This oracle solves the following feasibility problem: find x s.t. (B − F * x) ⪰ 0 Method signatures and docstrings: - def __init__(self, F, B): Construct a new lmi oracle object Arguments: F (Li...
4cf885a8656b6aac1bb08040e3e1bf00c74ac6a8
<|skeleton|> class lmi_oracle: """Oracle for Linear Matrix Inequality constraint. This oracle solves the following feasibility problem: find x s.t. (B − F * x) ⪰ 0""" def __init__(self, F, B): """Construct a new lmi oracle object Arguments: F (List[Arr]): [description] B (Arr): [description]""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class lmi_oracle: """Oracle for Linear Matrix Inequality constraint. This oracle solves the following feasibility problem: find x s.t. (B − F * x) ⪰ 0""" def __init__(self, F, B): """Construct a new lmi oracle object Arguments: F (List[Arr]): [description] B (Arr): [description]""" self.F = F ...
the_stack_v2_python_sparse
src/ellpy/oracles/lmi_oracle.py
luk036/ellpy
train
10
f1ba499debd71c1f75cc9519fad89284ae9dea20
[ "def predict_fn(model_config: ml_collections.FrozenConfigDict, model_params: Dict[str, Any], model_vars: Dict[str, Any], batch: Dict[str, Any]) -> Dict[str, Array]:\n \"\"\"Model-specific prediction function.\n\n Args:\n model_config: contains model config hyperparameters.\n model_params: cont...
<|body_start_0|> def predict_fn(model_config: ml_collections.FrozenConfigDict, model_params: Dict[str, Any], model_vars: Dict[str, Any], batch: Dict[str, Any]) -> Dict[str, Array]: """Model-specific prediction function. Args: model_config: contains model config hyperpa...
Task that generates memory from the corpus using an encoder.
MemoryGenerationTask
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MemoryGenerationTask: """Task that generates memory from the corpus using an encoder.""" def make_prediction_fn(cls, config: ml_collections.ConfigDict) -> Callable[..., Dict[str, Array]]: """Creates task prediction function for inference.""" <|body_0|> def make_preproces...
stack_v2_sparse_classes_36k_train_033406
14,047
permissive
[ { "docstring": "Creates task prediction function for inference.", "name": "make_prediction_fn", "signature": "def make_prediction_fn(cls, config: ml_collections.ConfigDict) -> Callable[..., Dict[str, Array]]" }, { "docstring": "Produces function to preprocess samples. See BaseTask. Here we add a...
5
stack_v2_sparse_classes_30k_train_018291
Implement the Python class `MemoryGenerationTask` described below. Class description: Task that generates memory from the corpus using an encoder. Method signatures and docstrings: - def make_prediction_fn(cls, config: ml_collections.ConfigDict) -> Callable[..., Dict[str, Array]]: Creates task prediction function for...
Implement the Python class `MemoryGenerationTask` described below. Class description: Task that generates memory from the corpus using an encoder. Method signatures and docstrings: - def make_prediction_fn(cls, config: ml_collections.ConfigDict) -> Callable[..., Dict[str, Array]]: Creates task prediction function for...
ac9447064195e06de48cc91ff642f7fffa28ffe8
<|skeleton|> class MemoryGenerationTask: """Task that generates memory from the corpus using an encoder.""" def make_prediction_fn(cls, config: ml_collections.ConfigDict) -> Callable[..., Dict[str, Array]]: """Creates task prediction function for inference.""" <|body_0|> def make_preproces...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MemoryGenerationTask: """Task that generates memory from the corpus using an encoder.""" def make_prediction_fn(cls, config: ml_collections.ConfigDict) -> Callable[..., Dict[str, Array]]: """Creates task prediction function for inference.""" def predict_fn(model_config: ml_collections.Fro...
the_stack_v2_python_sparse
language/mentionmemory/tasks/memory_generation_task.py
google-research/language
train
1,567
549a2ef77f7024d0387f8b9c57ac04f637af5f8f
[ "for asset_name in AVAILABLE_STAGES:\n if asset_name != BASE_CLASS_NAME:\n AVAILABLE_STAGES[asset_name] = {}\nself.pipeline_name = ''\nif isinstance(pipeline_input, list):\n self.stages = pipeline_input\nif isinstance(pipeline_input, str):\n self.pipeline_name = \" '\" + pipeline_input + \"'\"\n ...
<|body_start_0|> for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str): ...
PipelineManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PipelineManager: def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): """:param pipeline_input: the pipeline name string or list of strings :param _input: IOmanager instance with input to the pipeline :param _output: IOmanager instan...
stack_v2_sparse_classes_36k_train_033407
7,804
permissive
[ { "docstring": ":param pipeline_input: the pipeline name string or list of strings :param _input: IOmanager instance with input to the pipeline :param _output: IOmanager instance to store the outputs of the pipelines to be saved externally :param config: config string of the pipeline :param args: :param kwargs:...
5
null
Implement the Python class `PipelineManager` described below. Class description: Implement the PipelineManager class. Method signatures and docstrings: - def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): :param pipeline_input: the pipeline name string or list ...
Implement the Python class `PipelineManager` described below. Class description: Implement the PipelineManager class. Method signatures and docstrings: - def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): :param pipeline_input: the pipeline name string or list ...
db34927e4c45df93438e2b7129f01388f1a34753
<|skeleton|> class PipelineManager: def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): """:param pipeline_input: the pipeline name string or list of strings :param _input: IOmanager instance with input to the pipeline :param _output: IOmanager instan...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PipelineManager: def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): """:param pipeline_input: the pipeline name string or list of strings :param _input: IOmanager instance with input to the pipeline :param _output: IOmanager instance to store th...
the_stack_v2_python_sparse
mlapp/managers/pipeline_manager.py
ghas-results/mlapp
train
0
18374e3a0394f568e6ee8f47cc759e82eb8b5893
[ "self.input = input.clone()\noutput = input.tanh()\nreturn output", "grad_input = 1 - self.input.tanh() ** 2\ngrad_input = grad_output * grad_input\nreturn grad_input" ]
<|body_start_0|> self.input = input.clone() output = input.tanh() return output <|end_body_0|> <|body_start_1|> grad_input = 1 - self.input.tanh() ** 2 grad_input = grad_output * grad_input return grad_input <|end_body_1|>
Class representing the hyperbolic tangent activation function.
Tanh
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tanh: """Class representing the hyperbolic tangent activation function.""" def forward(self, input): """Applies the hyperbolic tangent to the input. Args: input -- tensor of size (N, *) Returns: output -- tensor of same size as input""" <|body_0|> def backward(self, grad...
stack_v2_sparse_classes_36k_train_033408
2,186
permissive
[ { "docstring": "Applies the hyperbolic tangent to the input. Args: input -- tensor of size (N, *) Returns: output -- tensor of same size as input", "name": "forward", "signature": "def forward(self, input)" }, { "docstring": "Given the gradient w.r.t. to the output of the activation, computes th...
2
stack_v2_sparse_classes_30k_train_002663
Implement the Python class `Tanh` described below. Class description: Class representing the hyperbolic tangent activation function. Method signatures and docstrings: - def forward(self, input): Applies the hyperbolic tangent to the input. Args: input -- tensor of size (N, *) Returns: output -- tensor of same size as...
Implement the Python class `Tanh` described below. Class description: Class representing the hyperbolic tangent activation function. Method signatures and docstrings: - def forward(self, input): Applies the hyperbolic tangent to the input. Args: input -- tensor of size (N, *) Returns: output -- tensor of same size as...
056b1be878b77c5a7dd5cff8d29ecb390be8b5de
<|skeleton|> class Tanh: """Class representing the hyperbolic tangent activation function.""" def forward(self, input): """Applies the hyperbolic tangent to the input. Args: input -- tensor of size (N, *) Returns: output -- tensor of same size as input""" <|body_0|> def backward(self, grad...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tanh: """Class representing the hyperbolic tangent activation function.""" def forward(self, input): """Applies the hyperbolic tangent to the input. Args: input -- tensor of size (N, *) Returns: output -- tensor of same size as input""" self.input = input.clone() output = input.ta...
the_stack_v2_python_sparse
Proj2/modules/Activations.py
jouvemax/DeepLearning
train
0
b346fc6cb43b2bfc84761f27bbec5042c8222a53
[ "super().__init__()\nconfig = AutoConfig.from_pretrained(pretrained_model_name, num_labels=num_classes)\nself.distilbert = AutoModel.from_pretrained(pretrained_model_name, config=config)\nself.pre_classifier = nn.Linear(config.dim, config.dim)\nself.classifier = nn.Sequential(nn.ReLU(), nn.Dropout(config.seq_classi...
<|body_start_0|> super().__init__() config = AutoConfig.from_pretrained(pretrained_model_name, num_labels=num_classes) self.distilbert = AutoModel.from_pretrained(pretrained_model_name, config=config) self.pre_classifier = nn.Linear(config.dim, config.dim) self.classifier = nn.Se...
Simplified version of the same class by HuggingFace. See ``transformers/modeling_distilbert.py`` in the transformers repository.
BertClassifier
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BertClassifier: """Simplified version of the same class by HuggingFace. See ``transformers/modeling_distilbert.py`` in the transformers repository.""" def __init__(self, pretrained_model_name: str, num_classes: Optional[int]=None): """Args: pretrained_model_name (str): HuggingFace mo...
stack_v2_sparse_classes_36k_train_033409
2,717
permissive
[ { "docstring": "Args: pretrained_model_name (str): HuggingFace model name. See transformers/modeling_auto.py num_classes (int, optional): the number of class labels in the classification task", "name": "__init__", "signature": "def __init__(self, pretrained_model_name: str, num_classes: Optional[int]=No...
2
null
Implement the Python class `BertClassifier` described below. Class description: Simplified version of the same class by HuggingFace. See ``transformers/modeling_distilbert.py`` in the transformers repository. Method signatures and docstrings: - def __init__(self, pretrained_model_name: str, num_classes: Optional[int]...
Implement the Python class `BertClassifier` described below. Class description: Simplified version of the same class by HuggingFace. See ``transformers/modeling_distilbert.py`` in the transformers repository. Method signatures and docstrings: - def __init__(self, pretrained_model_name: str, num_classes: Optional[int]...
a35297ecab8d1a6c2f00b6435ea1d6d37ec9f441
<|skeleton|> class BertClassifier: """Simplified version of the same class by HuggingFace. See ``transformers/modeling_distilbert.py`` in the transformers repository.""" def __init__(self, pretrained_model_name: str, num_classes: Optional[int]=None): """Args: pretrained_model_name (str): HuggingFace mo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BertClassifier: """Simplified version of the same class by HuggingFace. See ``transformers/modeling_distilbert.py`` in the transformers repository.""" def __init__(self, pretrained_model_name: str, num_classes: Optional[int]=None): """Args: pretrained_model_name (str): HuggingFace model name. See...
the_stack_v2_python_sparse
catalyst/contrib/models/nlp/classification/bert.py
saswat0/catalyst
train
2
e0880581d64c978acf267852b35dd723a4c6b0f3
[ "super().__init__()\nself.session = requests.Session()\nlogin_page = self.session.get('https://ers.cr.usgs.gov/login/')\nhtml_root = html.fromstring(login_page.content)\ncsrf, = html_root.xpath('//*[@id=\"csrf_token\"]')\nncforminfo, = html_root.xpath('//*[@id=\"loginForm\"]/input[2]')\ncsrf_token = csrf.get('value...
<|body_start_0|> super().__init__() self.session = requests.Session() login_page = self.session.get('https://ers.cr.usgs.gov/login/') html_root = html.fromstring(login_page.content) csrf, = html_root.xpath('//*[@id="csrf_token"]') ncforminfo, = html_root.xpath('//*[@id="l...
USGSCrawler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class USGSCrawler: def __init__(self): """login is required to download files from USGS. we are simulating a login with session here""" <|body_0|> def crawl(self, target_date: date) -> Optional[str]: """this func will download a single file :param target_date: date :return...
stack_v2_sparse_classes_36k_train_033410
3,922
no_license
[ { "docstring": "login is required to download files from USGS. we are simulating a login with session here", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "this func will download a single file :param target_date: date :return: full-path of downloaded file. None if not ...
2
stack_v2_sparse_classes_30k_train_007821
Implement the Python class `USGSCrawler` described below. Class description: Implement the USGSCrawler class. Method signatures and docstrings: - def __init__(self): login is required to download files from USGS. we are simulating a login with session here - def crawl(self, target_date: date) -> Optional[str]: this f...
Implement the Python class `USGSCrawler` described below. Class description: Implement the USGSCrawler class. Method signatures and docstrings: - def __init__(self): login is required to download files from USGS. we are simulating a login with session here - def crawl(self, target_date: date) -> Optional[str]: this f...
9d0dc17e0e5a60fc0507475cd5ef0975beb8b397
<|skeleton|> class USGSCrawler: def __init__(self): """login is required to download files from USGS. we are simulating a login with session here""" <|body_0|> def crawl(self, target_date: date) -> Optional[str]: """this func will download a single file :param target_date: date :return...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class USGSCrawler: def __init__(self): """login is required to download files from USGS. we are simulating a login with session here""" super().__init__() self.session = requests.Session() login_page = self.session.get('https://ers.cr.usgs.gov/login/') html_root = html.fromst...
the_stack_v2_python_sparse
backend/data_preparation/crawler/usgs_crawler.py
totemprotocol/Wildfires
train
0
e6883236df27c4ad73472e5c6f6567a84768d900
[ "server = 'guess-api/guessActivity/betting'\nplatformPassword = '111111'\nheader = [{'access-auth-token': 'd809615e96176085a1152f74c8a47b78800141539678969628'}, {'access-auth-token': 'f2794f54e17720d34aa505e3556724f3'}, {'access-auth-token': '492675514ec5f4d8ee249f26b15a4746'}]\nfor i in range(0, 20):\n for hd i...
<|body_start_0|> server = 'guess-api/guessActivity/betting' platformPassword = '111111' header = [{'access-auth-token': 'd809615e96176085a1152f74c8a47b78800141539678969628'}, {'access-auth-token': 'f2794f54e17720d34aa505e3556724f3'}, {'access-auth-token': '492675514ec5f4d8ee249f26b15a4746'}] ...
疯狂的BTMC游戏
reqApi_crazy_BTGame_1_3
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class reqApi_crazy_BTGame_1_3: """疯狂的BTMC游戏""" def guess_api_guessActivity_betting(self): """投票活动 :return:""" <|body_0|> def guess_api_guessActivity_receiveAward(self): """中奖,领取奖励 :return:""" <|body_1|> def guess_api_guessActivity_openRedPacket(self): ...
stack_v2_sparse_classes_36k_train_033411
1,952
no_license
[ { "docstring": "投票活动 :return:", "name": "guess_api_guessActivity_betting", "signature": "def guess_api_guessActivity_betting(self)" }, { "docstring": "中奖,领取奖励 :return:", "name": "guess_api_guessActivity_receiveAward", "signature": "def guess_api_guessActivity_receiveAward(self)" }, {...
3
stack_v2_sparse_classes_30k_train_011389
Implement the Python class `reqApi_crazy_BTGame_1_3` described below. Class description: 疯狂的BTMC游戏 Method signatures and docstrings: - def guess_api_guessActivity_betting(self): 投票活动 :return: - def guess_api_guessActivity_receiveAward(self): 中奖,领取奖励 :return: - def guess_api_guessActivity_openRedPacket(self): 开启红包 :re...
Implement the Python class `reqApi_crazy_BTGame_1_3` described below. Class description: 疯狂的BTMC游戏 Method signatures and docstrings: - def guess_api_guessActivity_betting(self): 投票活动 :return: - def guess_api_guessActivity_receiveAward(self): 中奖,领取奖励 :return: - def guess_api_guessActivity_openRedPacket(self): 开启红包 :re...
260bddce56a72a780dc305ca4805cfd176756e7d
<|skeleton|> class reqApi_crazy_BTGame_1_3: """疯狂的BTMC游戏""" def guess_api_guessActivity_betting(self): """投票活动 :return:""" <|body_0|> def guess_api_guessActivity_receiveAward(self): """中奖,领取奖励 :return:""" <|body_1|> def guess_api_guessActivity_openRedPacket(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class reqApi_crazy_BTGame_1_3: """疯狂的BTMC游戏""" def guess_api_guessActivity_betting(self): """投票活动 :return:""" server = 'guess-api/guessActivity/betting' platformPassword = '111111' header = [{'access-auth-token': 'd809615e96176085a1152f74c8a47b78800141539678969628'}, {'access-au...
the_stack_v2_python_sparse
requestApi/reqApi_crazy_BTGame_1_3.py
chenshl/DKTest
train
0
9e4b268afffe19e25278214c982f35b872917655
[ "self.m = m\nself.k = k\nself.hashers = [HashFunction(seed=i, length=m) for i in range(len(hist_cols)) for j in range(self.k)]", "output = []\nfor idx, vc in enumerate(value_counts):\n hashers = self.hashers[idx * self.k:(idx + 1) * self.k]\n for h in hashers:\n hist = [0 for i in range(2 ** self.m)]...
<|body_start_0|> self.m = m self.k = k self.hashers = [HashFunction(seed=i, length=m) for i in range(len(hist_cols)) for j in range(self.k)] <|end_body_0|> <|body_start_1|> output = [] for idx, vc in enumerate(value_counts): hashers = self.hashers[idx * self.k:(idx +...
HistogramClones
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HistogramClones: def __init__(self, m, k): """Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones""" <|body_0|> def value_counts_to_hists(self, value_counts): """convert value counts of columns to histogram clones Arguments: value_counts {...
stack_v2_sparse_classes_36k_train_033412
4,897
no_license
[ { "docstring": "Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones", "name": "__init__", "signature": "def __init__(self, m, k)" }, { "docstring": "convert value counts of columns to histogram clones Arguments: value_counts {list of Counters} Returns: [type] -- [desc...
3
stack_v2_sparse_classes_30k_train_012253
Implement the Python class `HistogramClones` described below. Class description: Implement the HistogramClones class. Method signatures and docstrings: - def __init__(self, m, k): Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones - def value_counts_to_hists(self, value_counts): convert v...
Implement the Python class `HistogramClones` described below. Class description: Implement the HistogramClones class. Method signatures and docstrings: - def __init__(self, m, k): Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones - def value_counts_to_hists(self, value_counts): convert v...
aa46c84169b8c6c4fb0deefb453e5d4d9e80dc0f
<|skeleton|> class HistogramClones: def __init__(self, m, k): """Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones""" <|body_0|> def value_counts_to_hists(self, value_counts): """convert value counts of columns to histogram clones Arguments: value_counts {...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HistogramClones: def __init__(self, m, k): """Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones""" self.m = m self.k = k self.hashers = [HashFunction(seed=i, length=m) for i in range(len(hist_cols)) for j in range(self.k)] def value_counts_to_...
the_stack_v2_python_sparse
histogram/compute_kl.py
Narkle/UGR_Experiments
train
0
860c6fa3102d6a5afca1f901ee9ed69c36cad7a7
[ "if method == 'deeplearning':\n nltkInitialize(dataSettings['datasets']['nltk_sources'])\n ' \\n\\t\\t\\tLoads model runners according to the selected DL model (defined in settings.ini)\\n\\t\\t\\t'\n if dataSettings['DLmodel']['model'] == 'biowordvec_bilstm':\n from models.Embedding_BiLstmCRF.model...
<|body_start_0|> if method == 'deeplearning': nltkInitialize(dataSettings['datasets']['nltk_sources']) ' \n\t\t\tLoads model runners according to the selected DL model (defined in settings.ini)\n\t\t\t' if dataSettings['DLmodel']['model'] == 'biowordvec_bilstm': ...
Orchestrator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Orchestrator: def processTask1(files, XMLAnnotations, dictionaries, dataSettings, method=None, show=False): """Method to handle with task 1 . :param files: dictionary containing the clinical reports (key: filename) :.... returns tuple(dictionary containing family members (key: filename, ...
stack_v2_sparse_classes_36k_train_033413
4,860
permissive
[ { "docstring": "Method to handle with task 1 . :param files: dictionary containing the clinical reports (key: filename) :.... returns tuple(dictionary containing family members (key: filename, value: list of tuples ((fm, fs), sentence), dictionary containing observations (key: filename, value: list of tuples (o...
3
stack_v2_sparse_classes_30k_train_004880
Implement the Python class `Orchestrator` described below. Class description: Implement the Orchestrator class. Method signatures and docstrings: - def processTask1(files, XMLAnnotations, dictionaries, dataSettings, method=None, show=False): Method to handle with task 1 . :param files: dictionary containing the clini...
Implement the Python class `Orchestrator` described below. Class description: Implement the Orchestrator class. Method signatures and docstrings: - def processTask1(files, XMLAnnotations, dictionaries, dataSettings, method=None, show=False): Method to handle with task 1 . :param files: dictionary containing the clini...
0c03d587eb2cf2d26e7834ff879f9c0131f2d5ac
<|skeleton|> class Orchestrator: def processTask1(files, XMLAnnotations, dictionaries, dataSettings, method=None, show=False): """Method to handle with task 1 . :param files: dictionary containing the clinical reports (key: filename) :.... returns tuple(dictionary containing family members (key: filename, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Orchestrator: def processTask1(files, XMLAnnotations, dictionaries, dataSettings, method=None, show=False): """Method to handle with task 1 . :param files: dictionary containing the clinical reports (key: filename) :.... returns tuple(dictionary containing family members (key: filename, value: list of...
the_stack_v2_python_sparse
src/Orchestrator.py
odnodn/PatientFM
train
0
0390e3c8a3692ad1811c00b225c0c24536fc1574
[ "from torchvision import datasets\ndset = datasets.MNIST('/tmp', download=True)\nrows = [{'mnist_id': i, 'image': np.array(im), 'split': 'train', 'label': label} for i, (im, label) in enumerate(dset, start=1)]\nDigits.insert(rows)\ndset = datasets.MNIST('/tmp', train=False, download=True)\nrows = [{'mnist_id': i, '...
<|body_start_0|> from torchvision import datasets dset = datasets.MNIST('/tmp', download=True) rows = [{'mnist_id': i, 'image': np.array(im), 'split': 'train', 'label': label} for i, (im, label) in enumerate(dset, start=1)] Digits.insert(rows) dset = datasets.MNIST('/tmp', train=...
Digits
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Digits: def fill(): """Download MNIST dataset and fill this table.""" <|body_0|> def fill_stimulus(self): """Inserts some digits as stimulus. It rotates the image 90 degrees counter-clockwise, enlarges it to 144 x 144 and pads 56 pixels to the left and right to make ...
stack_v2_sparse_classes_36k_train_033414
14,690
no_license
[ { "docstring": "Download MNIST dataset and fill this table.", "name": "fill", "signature": "def fill()" }, { "docstring": "Inserts some digits as stimulus. It rotates the image 90 degrees counter-clockwise, enlarges it to 144 x 144 and pads 56 pixels to the left and right to make a 144 x 256 (16...
2
stack_v2_sparse_classes_30k_train_011627
Implement the Python class `Digits` described below. Class description: Implement the Digits class. Method signatures and docstrings: - def fill(): Download MNIST dataset and fill this table. - def fill_stimulus(self): Inserts some digits as stimulus. It rotates the image 90 degrees counter-clockwise, enlarges it to ...
Implement the Python class `Digits` described below. Class description: Implement the Digits class. Method signatures and docstrings: - def fill(): Download MNIST dataset and fill this table. - def fill_stimulus(self): Inserts some digits as stimulus. It rotates the image 90 degrees counter-clockwise, enlarges it to ...
e3086381e8da3c0698f3beefe4c067c4716cb654
<|skeleton|> class Digits: def fill(): """Download MNIST dataset and fill this table.""" <|body_0|> def fill_stimulus(self): """Inserts some digits as stimulus. It rotates the image 90 degrees counter-clockwise, enlarges it to 144 x 144 and pads 56 pixels to the left and right to make ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Digits: def fill(): """Download MNIST dataset and fill this table.""" from torchvision import datasets dset = datasets.MNIST('/tmp', download=True) rows = [{'mnist_id': i, 'image': np.array(im), 'split': 'train', 'label': label} for i, (im, label) in enumerate(dset, start=1)] ...
the_stack_v2_python_sparse
brainreader/mnist.py
ecobost/brainreader
train
0
2874baaa24f1c2cdafe8577cd7b68d50be0329b1
[ "nums = [1, 2, 3]\nlets = ['a', 'b', 'c']\nn, m = zip(*[random_product(nums, lets) for _ in range(100)])\nn, m = (set(n), set(m))\neq_(n, set(nums))\neq_(m, set(lets))\neq_(len(n), len(nums))\neq_(len(m), len(lets))", "nums = [1, 2, 3]\nlets = ['a', 'b', 'c']\nr = list(random_product(nums, lets, repeat=100))\neq_...
<|body_start_0|> nums = [1, 2, 3] lets = ['a', 'b', 'c'] n, m = zip(*[random_product(nums, lets) for _ in range(100)]) n, m = (set(n), set(m)) eq_(n, set(nums)) eq_(m, set(lets)) eq_(len(n), len(nums)) eq_(len(m), len(lets)) <|end_body_0|> <|body_start_1|...
Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms.
RandomProductTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomProductTests: """Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms.""" def test_simple_lists(self): """Ensure t...
stack_v2_sparse_classes_36k_train_033415
47,145
no_license
[ { "docstring": "Ensure that one item is chosen from each list in each pair. Also ensure that each item from each list eventually appears in the chosen combinations. Odds are roughly 1 in 7.1 * 10e16 that one item from either list will not be chosen after 100 samplings of one item from each list. Just to be safe...
2
null
Implement the Python class `RandomProductTests` described below. Class description: Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms. Method signature...
Implement the Python class `RandomProductTests` described below. Class description: Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms. Method signature...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class RandomProductTests: """Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms.""" def test_simple_lists(self): """Ensure t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomProductTests: """Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms.""" def test_simple_lists(self): """Ensure that one item ...
the_stack_v2_python_sparse
repoData/erikrose-more-itertools/allPythonContent.py
aCoffeeYin/pyreco
train
0
d6afcc23d03e1975bdc65ebe37b80153f54ddd14
[ "if picking.purchase_id:\n return picking.purchase_id.company_id.currency_id.id\nreturn super(stock_picking, self).get_currency_id(cursor, user, picking)", "if move_line.purchase_line_id:\n return [x.id for x in move_line.purchase_line_id.order_id.taxes_id]\nreturn super(stock_picking, self)._get_taxes_invo...
<|body_start_0|> if picking.purchase_id: return picking.purchase_id.company_id.currency_id.id return super(stock_picking, self).get_currency_id(cursor, user, picking) <|end_body_0|> <|body_start_1|> if move_line.purchase_line_id: return [x.id for x in move_line.purchase_...
To let functions read data from company and purchase order and remove price list
stock_picking
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class stock_picking: """To let functions read data from company and purchase order and remove price list""" def get_currency_id(self, cursor, user, picking): """Get currency from company instaed of pricelist. @param picking: The picking id @return: returns currency id""" <|body_0|>...
stack_v2_sparse_classes_36k_train_033416
5,611
no_license
[ { "docstring": "Get currency from company instaed of pricelist. @param picking: The picking id @return: returns currency id", "name": "get_currency_id", "signature": "def get_currency_id(self, cursor, user, picking)" }, { "docstring": "To get taxes from purchase_order instead of getting them fro...
3
stack_v2_sparse_classes_30k_train_019279
Implement the Python class `stock_picking` described below. Class description: To let functions read data from company and purchase order and remove price list Method signatures and docstrings: - def get_currency_id(self, cursor, user, picking): Get currency from company instaed of pricelist. @param picking: The pick...
Implement the Python class `stock_picking` described below. Class description: To let functions read data from company and purchase order and remove price list Method signatures and docstrings: - def get_currency_id(self, cursor, user, picking): Get currency from company instaed of pricelist. @param picking: The pick...
0b997095c260d58b026440967fea3a202bef7efb
<|skeleton|> class stock_picking: """To let functions read data from company and purchase order and remove price list""" def get_currency_id(self, cursor, user, picking): """Get currency from company instaed of pricelist. @param picking: The picking id @return: returns currency id""" <|body_0|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class stock_picking: """To let functions read data from company and purchase order and remove price list""" def get_currency_id(self, cursor, user, picking): """Get currency from company instaed of pricelist. @param picking: The picking id @return: returns currency id""" if picking.purchase_id:...
the_stack_v2_python_sparse
v_7/GDS/shamil_v3/purchase_no_pricelist/stock.py
musabahmed/baba
train
0
1cef4cc27c1e96a21a1162e8c7e9b363f8d390f6
[ "candidates.sort()\nres = []\nself.DFS(candidates, target, 0, res, [])\nreturn res", "if target == 0:\n res.append(intermedia)\n return\nfor i in range(start, len(candidates)):\n if target < candidates[i]:\n return\n self.DFS(candidates, target - candidates[i], i, res, intermedia + [candidates[...
<|body_start_0|> candidates.sort() res = [] self.DFS(candidates, target, 0, res, []) return res <|end_body_0|> <|body_start_1|> if target == 0: res.append(intermedia) return for i in range(start, len(candidates)): if target < candidate...
@param candidates, a list of integers @param target, integer @return a list of lists of integers
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """@param candidates, a list of integers @param target, integer @return a list of lists of integers""" def func(self, candidates, target): """solution func""" <|body_0|> def DFS(self, candidates, target, start, res, intermedia): """solution dfs""" ...
stack_v2_sparse_classes_36k_train_033417
984
permissive
[ { "docstring": "solution func", "name": "func", "signature": "def func(self, candidates, target)" }, { "docstring": "solution dfs", "name": "DFS", "signature": "def DFS(self, candidates, target, start, res, intermedia)" } ]
2
stack_v2_sparse_classes_30k_train_012681
Implement the Python class `Solution` described below. Class description: @param candidates, a list of integers @param target, integer @return a list of lists of integers Method signatures and docstrings: - def func(self, candidates, target): solution func - def DFS(self, candidates, target, start, res, intermedia): ...
Implement the Python class `Solution` described below. Class description: @param candidates, a list of integers @param target, integer @return a list of lists of integers Method signatures and docstrings: - def func(self, candidates, target): solution func - def DFS(self, candidates, target, start, res, intermedia): ...
869ee24c50c08403b170e8f7868699185e9dfdd1
<|skeleton|> class Solution: """@param candidates, a list of integers @param target, integer @return a list of lists of integers""" def func(self, candidates, target): """solution func""" <|body_0|> def DFS(self, candidates, target, start, res, intermedia): """solution dfs""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """@param candidates, a list of integers @param target, integer @return a list of lists of integers""" def func(self, candidates, target): """solution func""" candidates.sort() res = [] self.DFS(candidates, target, 0, res, []) return res def DFS(self...
the_stack_v2_python_sparse
39.Combination.Sum/2.py
cerebrumaize/leetcode
train
0
b0ee622d09dd2b8053933fb34f60185cb025608a
[ "self.callbacks = callbacks\nself.model = model\nself.loss = loss\nself.optimizer = optimizer", "if self.model is None:\n raise RuntimeError('You must compile the trainer first!')\nself.loss.reset_avg()\nfor callback in self.callbacks:\n callback.on_epoch_begin(dataloader, phase, epoch)\nvariables = self.mo...
<|body_start_0|> self.callbacks = callbacks self.model = model self.loss = loss self.optimizer = optimizer <|end_body_0|> <|body_start_1|> if self.model is None: raise RuntimeError('You must compile the trainer first!') self.loss.reset_avg() for callb...
SupervisedTrainer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SupervisedTrainer: def __init__(self, model: Module, loss: Loss, optimizer: Optimizer, callbacks: Iterable[BaseCallback]=DEFAULT_CALLBACKS): """Create a trainer for supervised training scenarios. The fit function is very basic and can be vastly extended by using callbacks. The default be...
stack_v2_sparse_classes_36k_train_033418
5,957
permissive
[ { "docstring": "Create a trainer for supervised training scenarios. The fit function is very basic and can be vastly extended by using callbacks. The default behaviour can be changed by changing not passing the DEFAULT_CALLBACKS but a modified set of callbacks (only do this if you know what you are doing). A no...
3
stack_v2_sparse_classes_30k_train_012875
Implement the Python class `SupervisedTrainer` described below. Class description: Implement the SupervisedTrainer class. Method signatures and docstrings: - def __init__(self, model: Module, loss: Loss, optimizer: Optimizer, callbacks: Iterable[BaseCallback]=DEFAULT_CALLBACKS): Create a trainer for supervised traini...
Implement the Python class `SupervisedTrainer` described below. Class description: Implement the SupervisedTrainer class. Method signatures and docstrings: - def __init__(self, model: Module, loss: Loss, optimizer: Optimizer, callbacks: Iterable[BaseCallback]=DEFAULT_CALLBACKS): Create a trainer for supervised traini...
d3b1dd7c38a9de8f1e553cc5c0b2dfa62fe25c27
<|skeleton|> class SupervisedTrainer: def __init__(self, model: Module, loss: Loss, optimizer: Optimizer, callbacks: Iterable[BaseCallback]=DEFAULT_CALLBACKS): """Create a trainer for supervised training scenarios. The fit function is very basic and can be vastly extended by using callbacks. The default be...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SupervisedTrainer: def __init__(self, model: Module, loss: Loss, optimizer: Optimizer, callbacks: Iterable[BaseCallback]=DEFAULT_CALLBACKS): """Create a trainer for supervised training scenarios. The fit function is very basic and can be vastly extended by using callbacks. The default behaviour can be...
the_stack_v2_python_sparse
babilim/training/supervised.py
penguinmenac3/babilim
train
1
e5644e3db89bc29be04231d23f5a64f329b91bec
[ "pygame.init()\npygame.joystick.init()\nself.controller = pygame.joystick.Joystick(0)\nself.controller.init()", "if not self.axis_data:\n self.axis_data = {}\nif not self.button_data:\n self.button_data = {}\n for i in range(self.controller.get_numbuttons()):\n self.button_data[i] = False\nif not ...
<|body_start_0|> pygame.init() pygame.joystick.init() self.controller = pygame.joystick.Joystick(0) self.controller.init() <|end_body_0|> <|body_start_1|> if not self.axis_data: self.axis_data = {} if not self.button_data: self.button_data = {} ...
Class representing the PS4 controller. Pretty straightforward functionality.
PS4Controller
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PS4Controller: """Class representing the PS4 controller. Pretty straightforward functionality.""" def init(self): """Initialize the joystick components""" <|body_0|> def listen(self): """Listen for events to happen""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_033419
2,441
permissive
[ { "docstring": "Initialize the joystick components", "name": "init", "signature": "def init(self)" }, { "docstring": "Listen for events to happen", "name": "listen", "signature": "def listen(self)" } ]
2
null
Implement the Python class `PS4Controller` described below. Class description: Class representing the PS4 controller. Pretty straightforward functionality. Method signatures and docstrings: - def init(self): Initialize the joystick components - def listen(self): Listen for events to happen
Implement the Python class `PS4Controller` described below. Class description: Class representing the PS4 controller. Pretty straightforward functionality. Method signatures and docstrings: - def init(self): Initialize the joystick components - def listen(self): Listen for events to happen <|skeleton|> class PS4Cont...
665d39a2bd82543d5196555f0801ef8fd4a3ee48
<|skeleton|> class PS4Controller: """Class representing the PS4 controller. Pretty straightforward functionality.""" def init(self): """Initialize the joystick components""" <|body_0|> def listen(self): """Listen for events to happen""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PS4Controller: """Class representing the PS4 controller. Pretty straightforward functionality.""" def init(self): """Initialize the joystick components""" pygame.init() pygame.joystick.init() self.controller = pygame.joystick.Joystick(0) self.controller.init() ...
the_stack_v2_python_sparse
all-gists/028386b860b75e4f5472/snippet.py
gistable/gistable
train
76
1451ccf5ff0951b9c8a222db4384a22ec0166fec
[ "super(ConvolutionModule, self).__init__()\nassert (depthwise_kernel_size - 1) % 2 == 0, \"kernel_size should be a odd number for 'SAME' padding\"\nself.layer_norm = LayerNorm(embed_dim, export=export)\nself.pointwise_conv1 = torch.nn.Conv1d(embed_dim, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias)\ns...
<|body_start_0|> super(ConvolutionModule, self).__init__() assert (depthwise_kernel_size - 1) % 2 == 0, "kernel_size should be a odd number for 'SAME' padding" self.layer_norm = LayerNorm(embed_dim, export=export) self.pointwise_conv1 = torch.nn.Conv1d(embed_dim, 2 * channels, kernel_siz...
Convolution block used in the conformer block
ConvolutionModule
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LGPL-2.1-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvolutionModule: """Convolution block used in the conformer block""" def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): """Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv laye...
stack_v2_sparse_classes_36k_train_033420
9,087
permissive
[ { "docstring": "Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv layers depthwise_kernel_size: Depthwise conv layer kernel size dropout: dropout value activation_fn: Activation function to use after depthwise convolution kernel bias: If bias should be added to conv layers expo...
2
stack_v2_sparse_classes_30k_train_014781
Implement the Python class `ConvolutionModule` described below. Class description: Convolution block used in the conformer block Method signatures and docstrings: - def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): Args: embed_dim: Embedding dime...
Implement the Python class `ConvolutionModule` described below. Class description: Convolution block used in the conformer block Method signatures and docstrings: - def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): Args: embed_dim: Embedding dime...
b60c741f746877293bb85eed6806736fc8fa0ffd
<|skeleton|> class ConvolutionModule: """Convolution block used in the conformer block""" def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): """Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv laye...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConvolutionModule: """Convolution block used in the conformer block""" def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): """Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv layers depthwise_...
the_stack_v2_python_sparse
kosmos-2/fairseq/fairseq/modules/conformer_layer.py
microsoft/unilm
train
15,313
beb38cc997755610caf12d1abca076ead5e0cf6b
[ "super().__init__()\nself.blocks = ModuleList()\nfor in_feat_os in in_feature_output_strides:\n num_upsample = int(math.log2(int(in_feat_os))) - int(math.log2(int(out_feature_output_stride)))\n num_layers = num_upsample if num_upsample != 0 else 1\n self.blocks.append(Sequential(*[Sequential(Conv2d(in_chan...
<|body_start_0|> super().__init__() self.blocks = ModuleList() for in_feat_os in in_feature_output_strides: num_upsample = int(math.log2(int(in_feat_os))) - int(math.log2(int(out_feature_output_stride))) num_layers = num_upsample if num_upsample != 0 else 1 se...
Light Weight Decoder.
_LightWeightDecoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _LightWeightDecoder: """Light Weight Decoder.""" def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: """Initialize the _LightWeightDecoder module. Args: in_channels: ...
stack_v2_sparse_classes_36k_train_033421
8,033
permissive
[ { "docstring": "Initialize the _LightWeightDecoder module. Args: in_channels: number of channels of input feature maps out_channels: number of channels of output feature maps num_classes: number of output segmentation classes in_feature_output_strides: output stride of input feature maps at different levels out...
2
null
Implement the Python class `_LightWeightDecoder` described below. Class description: Light Weight Decoder. Method signatures and docstrings: - def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: Initi...
Implement the Python class `_LightWeightDecoder` described below. Class description: Light Weight Decoder. Method signatures and docstrings: - def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: Initi...
29985861614b3b93f9ef5389469ebb98570de7dd
<|skeleton|> class _LightWeightDecoder: """Light Weight Decoder.""" def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: """Initialize the _LightWeightDecoder module. Args: in_channels: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _LightWeightDecoder: """Light Weight Decoder.""" def __init__(self, in_channels: int, out_channels: int, num_classes: int, in_feature_output_strides: list[int]=[4, 8, 16, 32], out_feature_output_stride: int=4) -> None: """Initialize the _LightWeightDecoder module. Args: in_channels: number of cha...
the_stack_v2_python_sparse
torchgeo/models/farseg.py
microsoft/torchgeo
train
1,724
bf2d31d8dd13d7c1bc6c3cbef8dd6300cb327961
[ "if data_type == 'mel' or data_type == 'scatter':\n self.data_type = data_type\nelse:\n raise ValueError(\"data_type must be 'mel' or 'scatter'.\")", "if self.data_type == 'mel':\n mean = 2.3779549598693848\nelif self.data_type == 'scatter':\n mean = 0.21285544335842133\nif 'data' in sample:\n key ...
<|body_start_0|> if data_type == 'mel' or data_type == 'scatter': self.data_type = data_type else: raise ValueError("data_type must be 'mel' or 'scatter'.") <|end_body_0|> <|body_start_1|> if self.data_type == 'mel': mean = 2.3779549598693848 elif sel...
Subtract mean from audio input.
SubtractMean
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubtractMean: """Subtract mean from audio input.""" def __init__(self, data_type): """Initialize SubtractMean.""" <|body_0|> def __call__(self, sample): """Subtract the appropriate mean from the sample data.""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_033422
1,433
no_license
[ { "docstring": "Initialize SubtractMean.", "name": "__init__", "signature": "def __init__(self, data_type)" }, { "docstring": "Subtract the appropriate mean from the sample data.", "name": "__call__", "signature": "def __call__(self, sample)" } ]
2
stack_v2_sparse_classes_30k_train_013309
Implement the Python class `SubtractMean` described below. Class description: Subtract mean from audio input. Method signatures and docstrings: - def __init__(self, data_type): Initialize SubtractMean. - def __call__(self, sample): Subtract the appropriate mean from the sample data.
Implement the Python class `SubtractMean` described below. Class description: Subtract mean from audio input. Method signatures and docstrings: - def __init__(self, data_type): Initialize SubtractMean. - def __call__(self, sample): Subtract the appropriate mean from the sample data. <|skeleton|> class SubtractMean: ...
55a62c62d26534f3f1a0d7d529cc79d4796680a1
<|skeleton|> class SubtractMean: """Subtract mean from audio input.""" def __init__(self, data_type): """Initialize SubtractMean.""" <|body_0|> def __call__(self, sample): """Subtract the appropriate mean from the sample data.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubtractMean: """Subtract mean from audio input.""" def __init__(self, data_type): """Initialize SubtractMean.""" if data_type == 'mel' or data_type == 'scatter': self.data_type = data_type else: raise ValueError("data_type must be 'mel' or 'scatter'.") ...
the_stack_v2_python_sparse
dc/datasets/transforms.py
yamato2199/DeepContentRecommenders
train
1
5fa62ecdfde88d6ec041563490ced6f5da083bf1
[ "l1, l2 = (len(word1) + 1, len(word2) + 1)\ndp = [[0 for _ in range(l2)] for _ in range(l1)]\nfor i in range(l1):\n dp[i][0] = i\nfor j in range(l2):\n dp[0][j] = j\nfor i in range(1, l1):\n for j in range(1, l2):\n dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1[i - 1] ...
<|body_start_0|> l1, l2 = (len(word1) + 1, len(word2) + 1) dp = [[0 for _ in range(l2)] for _ in range(l1)] for i in range(l1): dp[i][0] = i for j in range(l2): dp[0][j] = j for i in range(1, l1): for j in range(1, l2): dp[i][j]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minDistance(self, word1, word2): """:type word1: str :type word2: str :rtype: int O(m*n) space beats 54.30%""" <|body_0|> def minDistance1(self, word1, word2): """:param word1: :param word2: :return: O(n) space with rolling array beats 87.02%""" ...
stack_v2_sparse_classes_36k_train_033423
1,190
no_license
[ { "docstring": ":type word1: str :type word2: str :rtype: int O(m*n) space beats 54.30%", "name": "minDistance", "signature": "def minDistance(self, word1, word2)" }, { "docstring": ":param word1: :param word2: :return: O(n) space with rolling array beats 87.02%", "name": "minDistance1", ...
2
stack_v2_sparse_classes_30k_train_016471
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int O(m*n) space beats 54.30% - def minDistance1(self, word1, word2): :param word1: :param word2: :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int O(m*n) space beats 54.30% - def minDistance1(self, word1, word2): :param word1: :param word2: :...
7e0e917c15d3e35f49da3a00ef395bd5ff180d79
<|skeleton|> class Solution: def minDistance(self, word1, word2): """:type word1: str :type word2: str :rtype: int O(m*n) space beats 54.30%""" <|body_0|> def minDistance1(self, word1, word2): """:param word1: :param word2: :return: O(n) space with rolling array beats 87.02%""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minDistance(self, word1, word2): """:type word1: str :type word2: str :rtype: int O(m*n) space beats 54.30%""" l1, l2 = (len(word1) + 1, len(word2) + 1) dp = [[0 for _ in range(l2)] for _ in range(l1)] for i in range(l1): dp[i][0] = i for j in ...
the_stack_v2_python_sparse
LeetCode/072_edit_distance.py
yao23/Machine_Learning_Playground
train
12
0bb1206ec28a05d04314cd05801171a84bf787c0
[ "if jwthandler.authorize_action(self, 1) == False:\n return None\nbody_categories = {'node_id': 0, 'link_id': 0}\nmetadata_dict = errorutil.check_fields(self.request.arguments, body_categories, self)\nif metadata_dict == False:\n self.set_status(400)\n self.write({'message': 'Empty get request'})\n retu...
<|body_start_0|> if jwthandler.authorize_action(self, 1) == False: return None body_categories = {'node_id': 0, 'link_id': 0} metadata_dict = errorutil.check_fields(self.request.arguments, body_categories, self) if metadata_dict == False: self.set_status(400) ...
Class to handle metadata API requests Functions: get, post, put, delete
Metadata
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Metadata: """Class to handle metadata API requests Functions: get, post, put, delete""" def get(self): """Function to get metadata or a single metadata record Inputs: Tornado web request Output: Metadata data Caveats: Authentication needs to be passed""" <|body_0|> def p...
stack_v2_sparse_classes_36k_train_033424
5,025
no_license
[ { "docstring": "Function to get metadata or a single metadata record Inputs: Tornado web request Output: Metadata data Caveats: Authentication needs to be passed", "name": "get", "signature": "def get(self)" }, { "docstring": "Function to create a metadata record Inputs: Tornado web request Outp...
4
stack_v2_sparse_classes_30k_train_000849
Implement the Python class `Metadata` described below. Class description: Class to handle metadata API requests Functions: get, post, put, delete Method signatures and docstrings: - def get(self): Function to get metadata or a single metadata record Inputs: Tornado web request Output: Metadata data Caveats: Authentic...
Implement the Python class `Metadata` described below. Class description: Class to handle metadata API requests Functions: get, post, put, delete Method signatures and docstrings: - def get(self): Function to get metadata or a single metadata record Inputs: Tornado web request Output: Metadata data Caveats: Authentic...
ee812db479ccd65bb319c1d5e268cd119952e2f0
<|skeleton|> class Metadata: """Class to handle metadata API requests Functions: get, post, put, delete""" def get(self): """Function to get metadata or a single metadata record Inputs: Tornado web request Output: Metadata data Caveats: Authentication needs to be passed""" <|body_0|> def p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Metadata: """Class to handle metadata API requests Functions: get, post, put, delete""" def get(self): """Function to get metadata or a single metadata record Inputs: Tornado web request Output: Metadata data Caveats: Authentication needs to be passed""" if jwthandler.authorize_action(sel...
the_stack_v2_python_sparse
src/handlers/api/metadata.py
FedoraTipper/AMS-Project
train
0
7610424e221559b22fed52aaaee6fb8c679f4f3e
[ "self._model = model\nself._model.build_graph()\nself._batch_reader = batch_reader\nself._hps = hps\nself._vocab = vocab\nself._saver = tf.train.Saver()\nself._decode_io = DecodeIO(FLAGS.decode_dir)", "sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\nstep = 0\nwhile step < FLAGS.max_decode_ste...
<|body_start_0|> self._model = model self._model.build_graph() self._batch_reader = batch_reader self._hps = hps self._vocab = vocab self._saver = tf.train.Saver() self._decode_io = DecodeIO(FLAGS.decode_dir) <|end_body_0|> <|body_start_1|> sess = tf.Sess...
Beam search decoder.
BSDecoder
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSDecoder: """Beam search decoder.""" def __init__(self, model, batch_reader, hps, vocab): """Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary""" <|body_0|> def DecodeLoop(self):...
stack_v2_sparse_classes_36k_train_033425
5,579
permissive
[ { "docstring": "Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary", "name": "__init__", "signature": "def __init__(self, model, batch_reader, hps, vocab)" }, { "docstring": "Decoding loop for long running...
4
stack_v2_sparse_classes_30k_train_003525
Implement the Python class `BSDecoder` described below. Class description: Beam search decoder. Method signatures and docstrings: - def __init__(self, model, batch_reader, hps, vocab): Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vo...
Implement the Python class `BSDecoder` described below. Class description: Beam search decoder. Method signatures and docstrings: - def __init__(self, model, batch_reader, hps, vocab): Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vo...
92ec5ec3efeee852aec5c057798298cd3a8e58ae
<|skeleton|> class BSDecoder: """Beam search decoder.""" def __init__(self, model, batch_reader, hps, vocab): """Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary""" <|body_0|> def DecodeLoop(self):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BSDecoder: """Beam search decoder.""" def __init__(self, model, batch_reader, hps, vocab): """Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary""" self._model = model self._model.build_grap...
the_stack_v2_python_sparse
model_zoo/models/textsum/seq2seq_attention_decode.py
coderSkyChen/Action_Recognition_Zoo
train
246
377c54471b3906b2b620013d5b17d09e7549a10b
[ "gazettes_data = requests.get(self.BASE_URL).json()\nnumber_of_documents = gazettes_data['response']['numFound']\nurl = f'{self.BASE_URL}?start=0&rows={number_of_documents}'\nyield scrapy.Request(url=url, callback=self.parse)", "data = json.loads(response.body)['response']\nfor gazette_data in data['docs']:\n ...
<|body_start_0|> gazettes_data = requests.get(self.BASE_URL).json() number_of_documents = gazettes_data['response']['numFound'] url = f'{self.BASE_URL}?start=0&rows={number_of_documents}' yield scrapy.Request(url=url, callback=self.parse) <|end_body_0|> <|body_start_1|> data = j...
PaBelemSpider
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PaBelemSpider: def start_requests(self): """Requests the gazette to get the total of documents and use it as a query param @url https://sistemas.belem.pa.gov.br/diario-consulta-api/diarios @returns requests 1""" <|body_0|> def parse(self, response): """@url https://s...
stack_v2_sparse_classes_36k_train_033426
1,742
permissive
[ { "docstring": "Requests the gazette to get the total of documents and use it as a query param @url https://sistemas.belem.pa.gov.br/diario-consulta-api/diarios @returns requests 1", "name": "start_requests", "signature": "def start_requests(self)" }, { "docstring": "@url https://sistemas.belem....
2
stack_v2_sparse_classes_30k_train_020490
Implement the Python class `PaBelemSpider` described below. Class description: Implement the PaBelemSpider class. Method signatures and docstrings: - def start_requests(self): Requests the gazette to get the total of documents and use it as a query param @url https://sistemas.belem.pa.gov.br/diario-consulta-api/diari...
Implement the Python class `PaBelemSpider` described below. Class description: Implement the PaBelemSpider class. Method signatures and docstrings: - def start_requests(self): Requests the gazette to get the total of documents and use it as a query param @url https://sistemas.belem.pa.gov.br/diario-consulta-api/diari...
feef1d36d540b052ec0b178015872a215352ba80
<|skeleton|> class PaBelemSpider: def start_requests(self): """Requests the gazette to get the total of documents and use it as a query param @url https://sistemas.belem.pa.gov.br/diario-consulta-api/diarios @returns requests 1""" <|body_0|> def parse(self, response): """@url https://s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PaBelemSpider: def start_requests(self): """Requests the gazette to get the total of documents and use it as a query param @url https://sistemas.belem.pa.gov.br/diario-consulta-api/diarios @returns requests 1""" gazettes_data = requests.get(self.BASE_URL).json() number_of_documents = g...
the_stack_v2_python_sparse
data_collection/gazette/spiders/pa_belem.py
tiagofer/querido-diario
train
1
f98f2bd04367b414fb00d1f1b863858066055ce0
[ "self.df = df\nself.col_name = col_name\nself.threshold = threshold\nself.relative_error = relative_error\nself.upper_bound, self.lower_bound = dict_filter(self.whiskers(), ['upper_bound', 'lower_bound'])\nsuper().__init__(df, col_name)", "mad_value = self.df.cols.mad(self.col_name, self.relative_error, more=True...
<|body_start_0|> self.df = df self.col_name = col_name self.threshold = threshold self.relative_error = relative_error self.upper_bound, self.lower_bound = dict_filter(self.whiskers(), ['upper_bound', 'lower_bound']) super().__init__(df, col_name) <|end_body_0|> <|body_s...
Handle outliers using mad
MAD
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MAD: """Handle outliers using mad""" def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): """:param df: :param col_name: :type threshold: object :type relative_error: object""" <|body_0|> def whiskers(self): """Get the wisker used...
stack_v2_sparse_classes_36k_train_033427
1,930
permissive
[ { "docstring": ":param df: :param col_name: :type threshold: object :type relative_error: object", "name": "__init__", "signature": "def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR)" }, { "docstring": "Get the wisker used to defined outliers :return:", "na...
3
null
Implement the Python class `MAD` described below. Class description: Handle outliers using mad Method signatures and docstrings: - def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): :param df: :param col_name: :type threshold: object :type relative_error: object - def whiskers(self)...
Implement the Python class `MAD` described below. Class description: Handle outliers using mad Method signatures and docstrings: - def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): :param df: :param col_name: :type threshold: object :type relative_error: object - def whiskers(self)...
13e7b180f0970addae77cafe128bd2a93be138a2
<|skeleton|> class MAD: """Handle outliers using mad""" def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): """:param df: :param col_name: :type threshold: object :type relative_error: object""" <|body_0|> def whiskers(self): """Get the wisker used...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MAD: """Handle outliers using mad""" def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): """:param df: :param col_name: :type threshold: object :type relative_error: object""" self.df = df self.col_name = col_name self.threshold = threshol...
the_stack_v2_python_sparse
optimus/outliers/mad.py
XD-DENG/Optimus
train
1
cacb6ec8145bcd9298c91b9adfea0e97439b6fc1
[ "config_properties = config_domain.Registry.get_config_property_schemas()\nconfig_prop_for_blog_admin = {'max_number_of_tags_assigned_to_blog_post': config_properties['max_number_of_tags_assigned_to_blog_post']}\nrole_to_action = role_services.get_role_actions()\nself.render_json({'config_properties': config_prop_f...
<|body_start_0|> config_properties = config_domain.Registry.get_config_property_schemas() config_prop_for_blog_admin = {'max_number_of_tags_assigned_to_blog_post': config_properties['max_number_of_tags_assigned_to_blog_post']} role_to_action = role_services.get_role_actions() self.render...
Handler for the blog admin page.
BlogAdminHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BlogAdminHandler: """Handler for the blog admin page.""" def get(self) -> None: """Handles GET requests.""" <|body_0|> def post(self) -> None: """Handles POST requests.""" <|body_1|> <|end_skeleton|> <|body_start_0|> config_properties = config_d...
stack_v2_sparse_classes_36k_train_033428
8,179
permissive
[ { "docstring": "Handles GET requests.", "name": "get", "signature": "def get(self) -> None" }, { "docstring": "Handles POST requests.", "name": "post", "signature": "def post(self) -> None" } ]
2
null
Implement the Python class `BlogAdminHandler` described below. Class description: Handler for the blog admin page. Method signatures and docstrings: - def get(self) -> None: Handles GET requests. - def post(self) -> None: Handles POST requests.
Implement the Python class `BlogAdminHandler` described below. Class description: Handler for the blog admin page. Method signatures and docstrings: - def get(self) -> None: Handles GET requests. - def post(self) -> None: Handles POST requests. <|skeleton|> class BlogAdminHandler: """Handler for the blog admin p...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class BlogAdminHandler: """Handler for the blog admin page.""" def get(self) -> None: """Handles GET requests.""" <|body_0|> def post(self) -> None: """Handles POST requests.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BlogAdminHandler: """Handler for the blog admin page.""" def get(self) -> None: """Handles GET requests.""" config_properties = config_domain.Registry.get_config_property_schemas() config_prop_for_blog_admin = {'max_number_of_tags_assigned_to_blog_post': config_properties['max_num...
the_stack_v2_python_sparse
core/controllers/blog_admin.py
oppia/oppia
train
6,172
39700ebad682933b18916046daa1d43242ff6df5
[ "return_type = AppPrincipalCredential(context)\npayload = {'symmetricKey': symmetric_key, 'notBefore': not_before.isoformat(), 'notAfter': not_after.isoformat()}\nqry = ServiceOperationQuery(return_type, 'CreateFromSymmetricKey', None, payload, None, return_type)\nqry.static = True\ncontext.add_query(qry)\nreturn r...
<|body_start_0|> return_type = AppPrincipalCredential(context) payload = {'symmetricKey': symmetric_key, 'notBefore': not_before.isoformat(), 'notAfter': not_after.isoformat()} qry = ServiceOperationQuery(return_type, 'CreateFromSymmetricKey', None, payload, None, return_type) qry.static...
Represents a credential belonging to an app principal.
AppPrincipalCredential
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppPrincipalCredential: """Represents a credential belonging to an app principal.""" def create_from_symmetric_key(context, symmetric_key, not_before, not_after=None): """Create an instance of SP.AppPrincipalCredential that wraps a symmetric key. :type context: office365.sharepoint.c...
stack_v2_sparse_classes_36k_train_033429
1,836
permissive
[ { "docstring": "Create an instance of SP.AppPrincipalCredential that wraps a symmetric key. :type context: office365.sharepoint.client_context.ClientContext :param str symmetric_key: The symmetric key of the app principal credential. :param datetime.datetime not_before: The earliest time when the key is valid. ...
2
null
Implement the Python class `AppPrincipalCredential` described below. Class description: Represents a credential belonging to an app principal. Method signatures and docstrings: - def create_from_symmetric_key(context, symmetric_key, not_before, not_after=None): Create an instance of SP.AppPrincipalCredential that wra...
Implement the Python class `AppPrincipalCredential` described below. Class description: Represents a credential belonging to an app principal. Method signatures and docstrings: - def create_from_symmetric_key(context, symmetric_key, not_before, not_after=None): Create an instance of SP.AppPrincipalCredential that wra...
cbd245d1af8d69e013c469cfc2a9851f51c91417
<|skeleton|> class AppPrincipalCredential: """Represents a credential belonging to an app principal.""" def create_from_symmetric_key(context, symmetric_key, not_before, not_after=None): """Create an instance of SP.AppPrincipalCredential that wraps a symmetric key. :type context: office365.sharepoint.c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AppPrincipalCredential: """Represents a credential belonging to an app principal.""" def create_from_symmetric_key(context, symmetric_key, not_before, not_after=None): """Create an instance of SP.AppPrincipalCredential that wraps a symmetric key. :type context: office365.sharepoint.client_context...
the_stack_v2_python_sparse
office365/sharepoint/appprincipal/credential.py
vgrem/Office365-REST-Python-Client
train
1,006
fc6f3d3e273a3a8e83b797f47ce4f6f7a506c5af
[ "data = self.request.get('data', {})\nuser = self.request.app['models']['user']\ncompany = self.request.app['models']['company']\nself_id = data['self_id']\nu = await user.get_user(self_id)\ncontacts = await user.get_users(u['contacts'])\ncompanys = await company.get_companys_by_user(self_id)\ndata.update({'contact...
<|body_start_0|> data = self.request.get('data', {}) user = self.request.app['models']['user'] company = self.request.app['models']['company'] self_id = data['self_id'] u = await user.get_user(self_id) contacts = await user.get_users(u['contacts']) companys = awai...
Contacts
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Contacts: async def get(self): """Контакты, с которыми есть чат или добавлены в контакты""" <|body_0|> async def put(self): """Добавить пользователя в контакты""" <|body_1|> async def delete(self): """Удалить пользователя из списка контактов""" ...
stack_v2_sparse_classes_36k_train_033430
19,248
no_license
[ { "docstring": "Контакты, с которыми есть чат или добавлены в контакты", "name": "get", "signature": "async def get(self)" }, { "docstring": "Добавить пользователя в контакты", "name": "put", "signature": "async def put(self)" }, { "docstring": "Удалить пользователя из списка кон...
3
stack_v2_sparse_classes_30k_train_003078
Implement the Python class `Contacts` described below. Class description: Implement the Contacts class. Method signatures and docstrings: - async def get(self): Контакты, с которыми есть чат или добавлены в контакты - async def put(self): Добавить пользователя в контакты - async def delete(self): Удалить пользователя...
Implement the Python class `Contacts` described below. Class description: Implement the Contacts class. Method signatures and docstrings: - async def get(self): Контакты, с которыми есть чат или добавлены в контакты - async def put(self): Добавить пользователя в контакты - async def delete(self): Удалить пользователя...
c8726ad77079b981453c11d5c7fc39bc838eec67
<|skeleton|> class Contacts: async def get(self): """Контакты, с которыми есть чат или добавлены в контакты""" <|body_0|> async def put(self): """Добавить пользователя в контакты""" <|body_1|> async def delete(self): """Удалить пользователя из списка контактов""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Contacts: async def get(self): """Контакты, с которыми есть чат или добавлены в контакты""" data = self.request.get('data', {}) user = self.request.app['models']['user'] company = self.request.app['models']['company'] self_id = data['self_id'] u = await user.get...
the_stack_v2_python_sparse
chat/views.py
ArtemZaitsev1994/chat
train
0
c8b00059b1df5aeb6eee78c16eaf76442ecb53c8
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
TodoServiceServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TodoServiceServicer: """Missing associated documentation comment in .proto file.""" def CreateTodo(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def GetTodos(self, request, context): """Missing associated docum...
stack_v2_sparse_classes_36k_train_033431
6,980
no_license
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "CreateTodo", "signature": "def CreateTodo(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "GetTodos", "signature": "def GetTodos(self, reques...
4
null
Implement the Python class `TodoServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def CreateTodo(self, request, context): Missing associated documentation comment in .proto file. - def GetTodos(self, request, context): Mis...
Implement the Python class `TodoServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def CreateTodo(self, request, context): Missing associated documentation comment in .proto file. - def GetTodos(self, request, context): Mis...
f2f5418d8a7674e8f91de443b3bf72a419589f9f
<|skeleton|> class TodoServiceServicer: """Missing associated documentation comment in .proto file.""" def CreateTodo(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def GetTodos(self, request, context): """Missing associated docum...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TodoServiceServicer: """Missing associated documentation comment in .proto file.""" def CreateTodo(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!')...
the_stack_v2_python_sparse
grpc-main-service/todo/todo_pb2_grpc.py
Jprichard314/python-workbook
train
0
bcff8fe1b938a68a11a8edc2a4ecc82e6f2f2256
[ "self.fields = list()\nfor k in argsdict.keys():\n setattr(self, k, argsdict[k])\n self.fields.append(k)", "exp = dict()\nfor key in self.fields:\n exp[key] = self.__dict__.get(key)\nreturn exp" ]
<|body_start_0|> self.fields = list() for k in argsdict.keys(): setattr(self, k, argsdict[k]) self.fields.append(k) <|end_body_0|> <|body_start_1|> exp = dict() for key in self.fields: exp[key] = self.__dict__.get(key) return exp <|end_body_1|...
fields = collections.OrderedDict([ ('id', int), ('complete', bool), ('result', bool), ('size', int), ('hashes', [str]), ('time', int) ])
CheckResult
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckResult: """fields = collections.OrderedDict([ ('id', int), ('complete', bool), ('result', bool), ('size', int), ('hashes', [str]), ('time', int) ])""" def __init__(self, argsdict): """self.id = argsdict.get('id') self.complete = argsdict.get('id') self.result = argsdict.get('res...
stack_v2_sparse_classes_36k_train_033432
5,265
permissive
[ { "docstring": "self.id = argsdict.get('id') self.complete = argsdict.get('id') self.result = argsdict.get('result') self.size = argsdict.get('size') self.hashes = argsdict.get('hashes') self.time = argsdict.get('time')", "name": "__init__", "signature": "def __init__(self, argsdict)" }, { "docs...
2
stack_v2_sparse_classes_30k_train_015571
Implement the Python class `CheckResult` described below. Class description: fields = collections.OrderedDict([ ('id', int), ('complete', bool), ('result', bool), ('size', int), ('hashes', [str]), ('time', int) ]) Method signatures and docstrings: - def __init__(self, argsdict): self.id = argsdict.get('id') self.comp...
Implement the Python class `CheckResult` described below. Class description: fields = collections.OrderedDict([ ('id', int), ('complete', bool), ('result', bool), ('size', int), ('hashes', [str]), ('time', int) ]) Method signatures and docstrings: - def __init__(self, argsdict): self.id = argsdict.get('id') self.comp...
b363a298e8a7d2918eb57a686f5db153099cb6fc
<|skeleton|> class CheckResult: """fields = collections.OrderedDict([ ('id', int), ('complete', bool), ('result', bool), ('size', int), ('hashes', [str]), ('time', int) ])""" def __init__(self, argsdict): """self.id = argsdict.get('id') self.complete = argsdict.get('id') self.result = argsdict.get('res...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckResult: """fields = collections.OrderedDict([ ('id', int), ('complete', bool), ('result', bool), ('size', int), ('hashes', [str]), ('time', int) ])""" def __init__(self, argsdict): """self.id = argsdict.get('id') self.complete = argsdict.get('id') self.result = argsdict.get('result') self.si...
the_stack_v2_python_sparse
epastack/shared/check.py
PPerfLab/EPARIMM-Release
train
8
911e0dbed9ecdcf7e1976979180f42495b73d0e7
[ "all_databases = database_services.get_all_database_names()\ndefault_database = database_services.get_default_database_name()\nall_succeeded = True\ndata = {}\nfor item in all_databases:\n name = item\n if item == default_database:\n name = None\n inspection_data, succeeded = self._test_database(nam...
<|body_start_0|> all_databases = database_services.get_all_database_names() default_database = database_services.get_default_database_name() all_succeeded = True data = {} for item in all_databases: name = item if item == default_database: ...
database audit manager class.
DatabaseAuditManager
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatabaseAuditManager: """database audit manager class.""" def inspect(self, **options): """inspects the status of available databases. it returns a tuple of two values. first value is a dict containing the inspection data. and the second value is a bool value indicating that inspecti...
stack_v2_sparse_classes_36k_train_033433
3,572
permissive
[ { "docstring": "inspects the status of available databases. it returns a tuple of two values. first value is a dict containing the inspection data. and the second value is a bool value indicating that inspection has been succeeded or failed. :keyword bool traceback: specifies that on failure report, it must inc...
2
null
Implement the Python class `DatabaseAuditManager` described below. Class description: database audit manager class. Method signatures and docstrings: - def inspect(self, **options): inspects the status of available databases. it returns a tuple of two values. first value is a dict containing the inspection data. and ...
Implement the Python class `DatabaseAuditManager` described below. Class description: database audit manager class. Method signatures and docstrings: - def inspect(self, **options): inspects the status of available databases. it returns a tuple of two values. first value is a dict containing the inspection data. and ...
9d4776498225de4f3d16a4600b5b19212abe8562
<|skeleton|> class DatabaseAuditManager: """database audit manager class.""" def inspect(self, **options): """inspects the status of available databases. it returns a tuple of two values. first value is a dict containing the inspection data. and the second value is a bool value indicating that inspecti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatabaseAuditManager: """database audit manager class.""" def inspect(self, **options): """inspects the status of available databases. it returns a tuple of two values. first value is a dict containing the inspection data. and the second value is a bool value indicating that inspection has been s...
the_stack_v2_python_sparse
src/pyrin/database/audit/manager.py
mononobi/pyrin
train
20
9796a40d6b3946ffeeb4989b72535ce12509c877
[ "super(AlexNet, self).__init__()\nself.n_bins = n_bins\nself.dropout_rate = dropout_rate\nself.conv1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2)\nself.relu = nn.ReLU(inplace=True)\nself.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)\nself.conv2 = nn.Conv2d(64, 192, kernel_size=5, stride=2)\nself.pool2 = ...
<|body_start_0|> super(AlexNet, self).__init__() self.n_bins = n_bins self.dropout_rate = dropout_rate self.conv1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2) self.relu = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2) self.conv...
Implements AlexNet, laid out as a HopeNet which classifies Euler angles in bins. Regression is then used on the output to output the expected value.
AlexNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlexNet: """Implements AlexNet, laid out as a HopeNet which classifies Euler angles in bins. Regression is then used on the output to output the expected value.""" def __init__(self, n_bins, dropout_rate=0.5): """Instantiates an AlexNet object. Parameters ---------- n_bins : int The ...
stack_v2_sparse_classes_36k_train_033434
9,784
no_license
[ { "docstring": "Instantiates an AlexNet object. Parameters ---------- n_bins : int The number of bins, which are output by the network. dropout_rate : float, optional The dropout rate passed on to ``nn.Dropout()``, by default 0.5. Returns ------- None", "name": "__init__", "signature": "def __init__(sel...
2
stack_v2_sparse_classes_30k_train_014700
Implement the Python class `AlexNet` described below. Class description: Implements AlexNet, laid out as a HopeNet which classifies Euler angles in bins. Regression is then used on the output to output the expected value. Method signatures and docstrings: - def __init__(self, n_bins, dropout_rate=0.5): Instantiates a...
Implement the Python class `AlexNet` described below. Class description: Implements AlexNet, laid out as a HopeNet which classifies Euler angles in bins. Regression is then used on the output to output the expected value. Method signatures and docstrings: - def __init__(self, n_bins, dropout_rate=0.5): Instantiates a...
a7c30481822ecb945e3ff6ad184d104361a40ed1
<|skeleton|> class AlexNet: """Implements AlexNet, laid out as a HopeNet which classifies Euler angles in bins. Regression is then used on the output to output the expected value.""" def __init__(self, n_bins, dropout_rate=0.5): """Instantiates an AlexNet object. Parameters ---------- n_bins : int The ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AlexNet: """Implements AlexNet, laid out as a HopeNet which classifies Euler angles in bins. Regression is then used on the output to output the expected value.""" def __init__(self, n_bins, dropout_rate=0.5): """Instantiates an AlexNet object. Parameters ---------- n_bins : int The number of bin...
the_stack_v2_python_sparse
cheapfake/hopenet/models.py
hu-simon/cheapfake
train
0
4a11ad8a0bf8b8772aa39bfa39c7ba5a9acccff5
[ "mats = cmds.ls(materials=1)\nmats.remove('lambert1')\nmats.remove('particleCloud1')\nreturn mats", "rv = []\nSS = cmds.shadingNode('surfaceShader', asShader=1, n=name)\nSLCode = cmds.shadingNode('SLCodeNode', asUtility=1, n=name)\nmel.eval('source \"//file-cluster/GDC/Resource/Support/AnimalLogic/mayaman2.0.7/me...
<|body_start_0|> mats = cmds.ls(materials=1) mats.remove('lambert1') mats.remove('particleCloud1') return mats <|end_body_0|> <|body_start_1|> rv = [] SS = cmds.shadingNode('surfaceShader', asShader=1, n=name) SLCode = cmds.shadingNode('SLCodeNode', asUtility=1, ...
Materials
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Materials: def ListMats(self): """list all materials except lamber1 and particleCloud1""" <|body_0|> def CreateZdpShader(self, name): """return value===>[surfaceShader,SLCode,]""" <|body_1|> <|end_skeleton|> <|body_start_0|> mats = cmds.ls(materials...
stack_v2_sparse_classes_36k_train_033435
14,297
no_license
[ { "docstring": "list all materials except lamber1 and particleCloud1", "name": "ListMats", "signature": "def ListMats(self)" }, { "docstring": "return value===>[surfaceShader,SLCode,]", "name": "CreateZdpShader", "signature": "def CreateZdpShader(self, name)" } ]
2
stack_v2_sparse_classes_30k_train_006716
Implement the Python class `Materials` described below. Class description: Implement the Materials class. Method signatures and docstrings: - def ListMats(self): list all materials except lamber1 and particleCloud1 - def CreateZdpShader(self, name): return value===>[surfaceShader,SLCode,]
Implement the Python class `Materials` described below. Class description: Implement the Materials class. Method signatures and docstrings: - def ListMats(self): list all materials except lamber1 and particleCloud1 - def CreateZdpShader(self, name): return value===>[surfaceShader,SLCode,] <|skeleton|> class Material...
c11f715996a435396c28ffb4c20f11f8e3c1a681
<|skeleton|> class Materials: def ListMats(self): """list all materials except lamber1 and particleCloud1""" <|body_0|> def CreateZdpShader(self, name): """return value===>[surfaceShader,SLCode,]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Materials: def ListMats(self): """list all materials except lamber1 and particleCloud1""" mats = cmds.ls(materials=1) mats.remove('lambert1') mats.remove('particleCloud1') return mats def CreateZdpShader(self, name): """return value===>[surfaceShader,SLCode...
the_stack_v2_python_sparse
OLD/idmt/maya/ROMA/wxII_RenderTools.py
Bn-com/myProj_octv
train
1
e872d5529ef84268616f7ebc4fb78c9c704916c7
[ "regular_attrs = kwargs.pop('regular_attrs', None)\nextra_attrs = kwargs.pop('extra_attrs', None)\npreserve_order = kwargs.pop('preserve_order', False)\nspecific_order = kwargs.pop('specific_order', None)\nsuper(DictFormatter, self).__init__(*args, **kwargs)\nif regular_attrs is None:\n self.regular_attrs = copy...
<|body_start_0|> regular_attrs = kwargs.pop('regular_attrs', None) extra_attrs = kwargs.pop('extra_attrs', None) preserve_order = kwargs.pop('preserve_order', False) specific_order = kwargs.pop('specific_order', None) super(DictFormatter, self).__init__(*args, **kwargs) i...
Used for formatting log records into a dict.
DictFormatter
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DictFormatter: """Used for formatting log records into a dict.""" def __init__(self, *args, **kwargs): """:param list regular_attrs: A list of strings specifying built-in python logging args that should be included in each output dict. If not specified, all args will be used. Setting...
stack_v2_sparse_classes_36k_train_033436
4,802
permissive
[ { "docstring": ":param list regular_attrs: A list of strings specifying built-in python logging args that should be included in each output dict. If not specified, all args will be used. Setting to an empty list will disable regular args. :param list extra_attrs: A list of strings specifying additional argument...
2
null
Implement the Python class `DictFormatter` described below. Class description: Used for formatting log records into a dict. Method signatures and docstrings: - def __init__(self, *args, **kwargs): :param list regular_attrs: A list of strings specifying built-in python logging args that should be included in each outp...
Implement the Python class `DictFormatter` described below. Class description: Used for formatting log records into a dict. Method signatures and docstrings: - def __init__(self, *args, **kwargs): :param list regular_attrs: A list of strings specifying built-in python logging args that should be included in each outp...
2b5f3562584137c8c9f5392265db1ab8ee8acf75
<|skeleton|> class DictFormatter: """Used for formatting log records into a dict.""" def __init__(self, *args, **kwargs): """:param list regular_attrs: A list of strings specifying built-in python logging args that should be included in each output dict. If not specified, all args will be used. Setting...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DictFormatter: """Used for formatting log records into a dict.""" def __init__(self, *args, **kwargs): """:param list regular_attrs: A list of strings specifying built-in python logging args that should be included in each output dict. If not specified, all args will be used. Setting to an empty ...
the_stack_v2_python_sparse
bluebottle/utils/formatters.py
onepercentclub/bluebottle
train
15
93e833a7df5203491a5dc5f8b6315c63468f5fcf
[ "devices = i2c.scan()\nassert slave_addr in devices, 'Did not find slave %d in scan: %s' % (slave_addr, devices)\nself.i2c = i2c\nself.addr = slave_addr\nself.fmt = '>2B'\nsleep(0.015)\nsetup_data = 1 << 4\ndata = bytearray(3)\ndata[0] = CONF_REG\ndata[1] = setup_data\ni2c.writeto(self.addr, data)", "data = bytea...
<|body_start_0|> devices = i2c.scan() assert slave_addr in devices, 'Did not find slave %d in scan: %s' % (slave_addr, devices) self.i2c = i2c self.addr = slave_addr self.fmt = '>2B' sleep(0.015) setup_data = 1 << 4 data = bytearray(3) data[0] = CO...
HDC1080
[ "LicenseRef-scancode-free-unknown", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HDC1080: def __init__(self, i2c, slave_addr=64): """Initialize a HDC1080 temperature and humidity sensor. Keyword arguments: i2c -- The i2c object (driver) used to interact through device addresses. slave_addr -- The slave address of the sensor (default 64 or 0x40).""" <|body_0|>...
stack_v2_sparse_classes_36k_train_033437
3,281
permissive
[ { "docstring": "Initialize a HDC1080 temperature and humidity sensor. Keyword arguments: i2c -- The i2c object (driver) used to interact through device addresses. slave_addr -- The slave address of the sensor (default 64 or 0x40).", "name": "__init__", "signature": "def __init__(self, i2c, slave_addr=64...
3
null
Implement the Python class `HDC1080` described below. Class description: Implement the HDC1080 class. Method signatures and docstrings: - def __init__(self, i2c, slave_addr=64): Initialize a HDC1080 temperature and humidity sensor. Keyword arguments: i2c -- The i2c object (driver) used to interact through device addr...
Implement the Python class `HDC1080` described below. Class description: Implement the HDC1080 class. Method signatures and docstrings: - def __init__(self, i2c, slave_addr=64): Initialize a HDC1080 temperature and humidity sensor. Keyword arguments: i2c -- The i2c object (driver) used to interact through device addr...
5366302af8073fd3d122865272f92215b363f3a6
<|skeleton|> class HDC1080: def __init__(self, i2c, slave_addr=64): """Initialize a HDC1080 temperature and humidity sensor. Keyword arguments: i2c -- The i2c object (driver) used to interact through device addresses. slave_addr -- The slave address of the sensor (default 64 or 0x40).""" <|body_0|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HDC1080: def __init__(self, i2c, slave_addr=64): """Initialize a HDC1080 temperature and humidity sensor. Keyword arguments: i2c -- The i2c object (driver) used to interact through device addresses. slave_addr -- The slave address of the sensor (default 64 or 0x40).""" devices = i2c.scan() ...
the_stack_v2_python_sparse
lib/sensor/hdc1080/hdc1080.py
digidotcom/xbee-micropython
train
72
78eafb97ba6c2ea8c173a9cea7f4d2afaabe6633
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PlannerBucket()", "from .entity import Entity\nfrom .planner_task import PlannerTask\nfrom .entity import Entity\nfrom .planner_task import PlannerTask\nfields: Dict[str, Callable[[Any], None]] = {'name': lambda n: setattr(self, 'name'...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return PlannerBucket() <|end_body_0|> <|body_start_1|> from .entity import Entity from .planner_task import PlannerTask from .entity import Entity from .planner_task import Plan...
PlannerBucket
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlannerBucket: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PlannerBucket: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns...
stack_v2_sparse_classes_36k_train_033438
2,863
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: PlannerBucket", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value...
3
stack_v2_sparse_classes_30k_train_002117
Implement the Python class `PlannerBucket` described below. Class description: Implement the PlannerBucket class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PlannerBucket: Creates a new instance of the appropriate class based on discriminator value...
Implement the Python class `PlannerBucket` described below. Class description: Implement the PlannerBucket class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PlannerBucket: Creates a new instance of the appropriate class based on discriminator value...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class PlannerBucket: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PlannerBucket: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlannerBucket: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PlannerBucket: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: PlannerBucke...
the_stack_v2_python_sparse
msgraph/generated/models/planner_bucket.py
microsoftgraph/msgraph-sdk-python
train
135
e33aa5bf9d7ade33b15f8024897bc2855f694c11
[ "descriptions = descriptions or list(utils.generate_ids(count=count))\nchassis_list = []\n_chassis_descriptions = {}\nfor description in descriptions:\n chassis = self._client.create(description=description)\n _chassis_descriptions[chassis.uuid] = description\n chassis_list.append(chassis)\nif check:\n ...
<|body_start_0|> descriptions = descriptions or list(utils.generate_ids(count=count)) chassis_list = [] _chassis_descriptions = {} for description in descriptions: chassis = self._client.create(description=description) _chassis_descriptions[chassis.uuid] = descrip...
Chassis steps.
IronicChassisSteps
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IronicChassisSteps: """Chassis steps.""" def create_ironic_chassis(self, descriptions=None, count=1, check=True): """Step to create a ironic chassis. Args: descriptions (list): descriptions of created chassis, if not specified one chassis description will be generate count (int): cou...
stack_v2_sparse_classes_36k_train_033439
4,645
no_license
[ { "docstring": "Step to create a ironic chassis. Args: descriptions (list): descriptions of created chassis, if not specified one chassis description will be generate count (int): count of created chassis, it's ignored if chassis_descriptions are specified; one chassis is created if both args are missing check ...
4
stack_v2_sparse_classes_30k_train_013369
Implement the Python class `IronicChassisSteps` described below. Class description: Chassis steps. Method signatures and docstrings: - def create_ironic_chassis(self, descriptions=None, count=1, check=True): Step to create a ironic chassis. Args: descriptions (list): descriptions of created chassis, if not specified ...
Implement the Python class `IronicChassisSteps` described below. Class description: Chassis steps. Method signatures and docstrings: - def create_ironic_chassis(self, descriptions=None, count=1, check=True): Step to create a ironic chassis. Args: descriptions (list): descriptions of created chassis, if not specified ...
e7583444cd24893ec6ae237b47db7c605b99b0c5
<|skeleton|> class IronicChassisSteps: """Chassis steps.""" def create_ironic_chassis(self, descriptions=None, count=1, check=True): """Step to create a ironic chassis. Args: descriptions (list): descriptions of created chassis, if not specified one chassis description will be generate count (int): cou...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IronicChassisSteps: """Chassis steps.""" def create_ironic_chassis(self, descriptions=None, count=1, check=True): """Step to create a ironic chassis. Args: descriptions (list): descriptions of created chassis, if not specified one chassis description will be generate count (int): count of created...
the_stack_v2_python_sparse
stepler/baremetal/steps/chassis.py
Mirantis/stepler
train
16
8c120896a5a268336a4ad3e61acf430a521d019e
[ "_data = {BGPStream_Website_Event_Types.HIJACK.value: Hijack(self.csv_dir), BGPStream_Website_Event_Types.LEAK.value: Leak(self.csv_dir), BGPStream_Website_Event_Types.OUTAGE.value: Outage(self.csv_dir)}\nself._data = {k: v for k, v in _data.items() if k in data_types}\nknown_events = self._generate_known_events()\...
<|body_start_0|> _data = {BGPStream_Website_Event_Types.HIJACK.value: Hijack(self.csv_dir), BGPStream_Website_Event_Types.LEAK.value: Leak(self.csv_dir), BGPStream_Website_Event_Types.OUTAGE.value: Outage(self.csv_dir)} self._data = {k: v for k, v in _data.items() if k in data_types} known_event...
This class parses bgpstream.com information into a database. For a more in depth explanation, read the top of the file.
BGPStream_Website_Parser
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BGPStream_Website_Parser: """This class parses bgpstream.com information into a database. For a more in depth explanation, read the top of the file.""" def _run(self, row_limit: int=None, IPV4=True, IPV6=True, data_types: list=BGPStream_Website_Event_Types.list_values(), refresh=False): ...
stack_v2_sparse_classes_36k_train_033440
5,973
permissive
[ { "docstring": "Parses rows in the bgpstream website. row_limit is for testing purposes only, to run a small subset. IPV4 and IPV6 are the prefixes that should be included if true. The possible values for data_types are anything in BGPStream_Website_Event_Types, these are the values that will be parsed, everyth...
5
null
Implement the Python class `BGPStream_Website_Parser` described below. Class description: This class parses bgpstream.com information into a database. For a more in depth explanation, read the top of the file. Method signatures and docstrings: - def _run(self, row_limit: int=None, IPV4=True, IPV6=True, data_types: li...
Implement the Python class `BGPStream_Website_Parser` described below. Class description: This class parses bgpstream.com information into a database. For a more in depth explanation, read the top of the file. Method signatures and docstrings: - def _run(self, row_limit: int=None, IPV4=True, IPV6=True, data_types: li...
91c92584b31bd128d818c7fee86c738367c0712e
<|skeleton|> class BGPStream_Website_Parser: """This class parses bgpstream.com information into a database. For a more in depth explanation, read the top of the file.""" def _run(self, row_limit: int=None, IPV4=True, IPV6=True, data_types: list=BGPStream_Website_Event_Types.list_values(), refresh=False): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BGPStream_Website_Parser: """This class parses bgpstream.com information into a database. For a more in depth explanation, read the top of the file.""" def _run(self, row_limit: int=None, IPV4=True, IPV6=True, data_types: list=BGPStream_Website_Event_Types.list_values(), refresh=False): """Parses...
the_stack_v2_python_sparse
lib_bgp_data/collectors/bgpstream_website/bgpstream_website_parser.py
jfuruness/lib_bgp_data
train
16
874cc24f7a574cfd5868862487d3c795e46a64a0
[ "logic = AppraisingScoreLogic(self.auth, sid, aid)\nparams = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\nscore = AppraisingScore.objects.values('id', 'update_time').filter(association=logic.assoc...
<|body_start_0|> logic = AppraisingScoreLogic(self.auth, sid, aid) params = ParamsParser(request.GET) limit = params.int('limit', desc='每页最大渲染数', require=False, default=10) page = params.int('page', desc='当前页数', require=False, default=1) score = AppraisingScore.objects.values('id...
AppraisingScoreInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppraisingScoreInfo: def get(self, request, sid, aid): """获取评分列表 :param request: :param sid: :param aid: :return:""" <|body_0|> def post(self, request, sid, aid): """批量获取评分信息 :param request: :param sid: :param aid: :return:""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_36k_train_033441
6,147
no_license
[ { "docstring": "获取评分列表 :param request: :param sid: :param aid: :return:", "name": "get", "signature": "def get(self, request, sid, aid)" }, { "docstring": "批量获取评分信息 :param request: :param sid: :param aid: :return:", "name": "post", "signature": "def post(self, request, sid, aid)" } ]
2
stack_v2_sparse_classes_30k_train_004065
Implement the Python class `AppraisingScoreInfo` described below. Class description: Implement the AppraisingScoreInfo class. Method signatures and docstrings: - def get(self, request, sid, aid): 获取评分列表 :param request: :param sid: :param aid: :return: - def post(self, request, sid, aid): 批量获取评分信息 :param request: :par...
Implement the Python class `AppraisingScoreInfo` described below. Class description: Implement the AppraisingScoreInfo class. Method signatures and docstrings: - def get(self, request, sid, aid): 获取评分列表 :param request: :param sid: :param aid: :return: - def post(self, request, sid, aid): 批量获取评分信息 :param request: :par...
a0553be3c259712de1fe5517b06317ad5756f79d
<|skeleton|> class AppraisingScoreInfo: def get(self, request, sid, aid): """获取评分列表 :param request: :param sid: :param aid: :return:""" <|body_0|> def post(self, request, sid, aid): """批量获取评分信息 :param request: :param sid: :param aid: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AppraisingScoreInfo: def get(self, request, sid, aid): """获取评分列表 :param request: :param sid: :param aid: :return:""" logic = AppraisingScoreLogic(self.auth, sid, aid) params = ParamsParser(request.GET) limit = params.int('limit', desc='每页最大渲染数', require=False, default=10) ...
the_stack_v2_python_sparse
LittlePigHoHo/server/appraising/views/score.py
shoogoome/hoho
train
1
4bd4ec6862a16cd5348d284673bbe52e44be01ba
[ "s = session()\ngoals = Goal.query.all()\nfor goal in goals:\n print(goal.old_numbered, type(goal.old_numbered))\n for each in goal.old_numbered:\n gs = GoalStep(each, goal.id)\n s.add(gs)\n s.commit()", "rv = []\ntokens = nltk.word_tokenize(data)\nfor token in tokens:\n if token.low...
<|body_start_0|> s = session() goals = Goal.query.all() for goal in goals: print(goal.old_numbered, type(goal.old_numbered)) for each in goal.old_numbered: gs = GoalStep(each, goal.id) s.add(gs) s.commit() <|end_body_0|> <|...
Represent patient/caregiver goal.
Goal
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Goal: """Represent patient/caregiver goal.""" def goal_step_extractor(): """Decompose goal instances into goal-steps.""" <|body_0|> def handle_proper_nouns(data): """Parameters ---------- data""" <|body_1|> def __init__(self, data, source): "...
stack_v2_sparse_classes_36k_train_033442
5,825
permissive
[ { "docstring": "Decompose goal instances into goal-steps.", "name": "goal_step_extractor", "signature": "def goal_step_extractor()" }, { "docstring": "Parameters ---------- data", "name": "handle_proper_nouns", "signature": "def handle_proper_nouns(data)" }, { "docstring": "Goal ...
3
stack_v2_sparse_classes_30k_train_009596
Implement the Python class `Goal` described below. Class description: Represent patient/caregiver goal. Method signatures and docstrings: - def goal_step_extractor(): Decompose goal instances into goal-steps. - def handle_proper_nouns(data): Parameters ---------- data - def __init__(self, data, source): Goal construc...
Implement the Python class `Goal` described below. Class description: Represent patient/caregiver goal. Method signatures and docstrings: - def goal_step_extractor(): Decompose goal instances into goal-steps. - def handle_proper_nouns(data): Parameters ---------- data - def __init__(self, data, source): Goal construc...
96935bb06f71b509f97ca426afe14713d5830e46
<|skeleton|> class Goal: """Represent patient/caregiver goal.""" def goal_step_extractor(): """Decompose goal instances into goal-steps.""" <|body_0|> def handle_proper_nouns(data): """Parameters ---------- data""" <|body_1|> def __init__(self, data, source): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Goal: """Represent patient/caregiver goal.""" def goal_step_extractor(): """Decompose goal instances into goal-steps.""" s = session() goals = Goal.query.all() for goal in goals: print(goal.old_numbered, type(goal.old_numbered)) for each in goal.old...
the_stack_v2_python_sparse
tcas/abstract/model/goal.py
mishrasushruti99/TransitionalCareAnalyticsServer
train
0
0a7bb81c88338d5bcebdb82e6c6931febb20808c
[ "super().__init__()\nself._use_condition = use_condition\nself._model = tf.keras.Sequential([tf.keras.layers.Conv2D(64, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormalization(), tf.keras.layers.LeakyReLU(), tf.keras.layers.Conv2D(128, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormaliz...
<|body_start_0|> super().__init__() self._use_condition = use_condition self._model = tf.keras.Sequential([tf.keras.layers.Conv2D(64, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormalization(), tf.keras.layers.LeakyReLU(), tf.keras.layers.Conv2D(128, [5, 5], strides=2, padding='sam...
Class conditioned encoder. This encoder is used by MNIST and FMNIST dataset. Attributes: _use_condition: _model: _mu_layer: _logvar_layer:
ClassConditionedEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassConditionedEncoder: """Class conditioned encoder. This encoder is used by MNIST and FMNIST dataset. Attributes: _use_condition: _model: _mu_layer: _logvar_layer:""" def __init__(self, use_condition, noise_size): """Initializes the object. Args: use_condition: noise_size:""" ...
stack_v2_sparse_classes_36k_train_033443
10,560
no_license
[ { "docstring": "Initializes the object. Args: use_condition: noise_size:", "name": "__init__", "signature": "def __init__(self, use_condition, noise_size)" }, { "docstring": "Apples the model to the inputs. Args: image: embedding: Returns:", "name": "call", "signature": "def call(self, i...
2
stack_v2_sparse_classes_30k_train_016420
Implement the Python class `ClassConditionedEncoder` described below. Class description: Class conditioned encoder. This encoder is used by MNIST and FMNIST dataset. Attributes: _use_condition: _model: _mu_layer: _logvar_layer: Method signatures and docstrings: - def __init__(self, use_condition, noise_size): Initial...
Implement the Python class `ClassConditionedEncoder` described below. Class description: Class conditioned encoder. This encoder is used by MNIST and FMNIST dataset. Attributes: _use_condition: _model: _mu_layer: _logvar_layer: Method signatures and docstrings: - def __init__(self, use_condition, noise_size): Initial...
6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa
<|skeleton|> class ClassConditionedEncoder: """Class conditioned encoder. This encoder is used by MNIST and FMNIST dataset. Attributes: _use_condition: _model: _mu_layer: _logvar_layer:""" def __init__(self, use_condition, noise_size): """Initializes the object. Args: use_condition: noise_size:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassConditionedEncoder: """Class conditioned encoder. This encoder is used by MNIST and FMNIST dataset. Attributes: _use_condition: _model: _mu_layer: _logvar_layer:""" def __init__(self, use_condition, noise_size): """Initializes the object. Args: use_condition: noise_size:""" super()._...
the_stack_v2_python_sparse
vae.py
gaotianxiang/text-to-image-synthesis
train
0
fffed213ed11b43a5328b06caca1320208cf87be
[ "queryset = self.get_queryset()\nslug = self.kwargs.get(self.slug_url_kwarg)\nif slug is not None:\n slug_field = self.get_slug_field()\n queryset = queryset.filter(**{slug_field: slug})\n try:\n part = queryset.get()\n return part\n except queryset.model.MultipleObjectsReturned:\n ...
<|body_start_0|> queryset = self.get_queryset() slug = self.kwargs.get(self.slug_url_kwarg) if slug is not None: slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) try: part = queryset.get() retu...
Part detail view using the IPN (internal part number) of the Part as the lookup field
PartDetailFromIPN
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PartDetailFromIPN: """Part detail view using the IPN (internal part number) of the Part as the lookup field""" def get_object(self): """Return Part object which IPN field matches the slug value.""" <|body_0|> def get(self, request, *args, **kwargs): """Attempt to...
stack_v2_sparse_classes_36k_train_033444
28,283
permissive
[ { "docstring": "Return Part object which IPN field matches the slug value.", "name": "get_object", "signature": "def get_object(self)" }, { "docstring": "Attempt to match slug to a Part, else redirect to PartIndex view.", "name": "get", "signature": "def get(self, request, *args, **kwarg...
2
stack_v2_sparse_classes_30k_train_018783
Implement the Python class `PartDetailFromIPN` described below. Class description: Part detail view using the IPN (internal part number) of the Part as the lookup field Method signatures and docstrings: - def get_object(self): Return Part object which IPN field matches the slug value. - def get(self, request, *args, ...
Implement the Python class `PartDetailFromIPN` described below. Class description: Part detail view using the IPN (internal part number) of the Part as the lookup field Method signatures and docstrings: - def get_object(self): Return Part object which IPN field matches the slug value. - def get(self, request, *args, ...
5a08ef908dd5344b4433436a4679d122f7f99e41
<|skeleton|> class PartDetailFromIPN: """Part detail view using the IPN (internal part number) of the Part as the lookup field""" def get_object(self): """Return Part object which IPN field matches the slug value.""" <|body_0|> def get(self, request, *args, **kwargs): """Attempt to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PartDetailFromIPN: """Part detail view using the IPN (internal part number) of the Part as the lookup field""" def get_object(self): """Return Part object which IPN field matches the slug value.""" queryset = self.get_queryset() slug = self.kwargs.get(self.slug_url_kwarg) ...
the_stack_v2_python_sparse
InvenTree/part/views.py
onurtatli/InvenTree
train
0
61e555092a5fbd7720819b61a81a895a1a4dbe7f
[ "super().pre_craft(**kwargs)\ncrafter = self.crafter\nfor skill_name, min_value in self.skill_requirements:\n skill_value = crafter.attributes.get(skill_name)\n if skill_value is None or skill_value < min_value:\n self.msg(self.error_too_low_skill_level.format(skill_name=skill_name, spell=self.name))\n...
<|body_start_0|> super().pre_craft(**kwargs) crafter = self.crafter for skill_name, min_value in self.skill_requirements: skill_value = crafter.attributes.get(skill_name) if skill_value is None or skill_value < min_value: self.msg(self.error_too_low_skill_...
A base 'recipe' to represent magical spells. We *could* treat this just like the sword above - by combining the wand and spellbook to make a fireball object that the user can then throw with another command. For this example we instead generate 'magical effects' as strings+values that we would then supposedly inject in...
_MagicRecipe
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _MagicRecipe: """A base 'recipe' to represent magical spells. We *could* treat this just like the sword above - by combining the wand and spellbook to make a fireball object that the user can then throw with another command. For this example we instead generate 'magical effects' as strings+values...
stack_v2_sparse_classes_36k_train_033445
17,892
permissive
[ { "docstring": "This is where we do input validation. We want to do the normal validation of the tools, but also check for a skill on the crafter. This must set the result on `self.validated_inputs`. We also set the crafter's relevant skill value on `self.skill_roll_value`. Args: **kwargs: Any optional extra kw...
3
stack_v2_sparse_classes_30k_train_010547
Implement the Python class `_MagicRecipe` described below. Class description: A base 'recipe' to represent magical spells. We *could* treat this just like the sword above - by combining the wand and spellbook to make a fireball object that the user can then throw with another command. For this example we instead gener...
Implement the Python class `_MagicRecipe` described below. Class description: A base 'recipe' to represent magical spells. We *could* treat this just like the sword above - by combining the wand and spellbook to make a fireball object that the user can then throw with another command. For this example we instead gener...
b3ca58b5c1325a3bf57051dfe23560a08d2947b7
<|skeleton|> class _MagicRecipe: """A base 'recipe' to represent magical spells. We *could* treat this just like the sword above - by combining the wand and spellbook to make a fireball object that the user can then throw with another command. For this example we instead generate 'magical effects' as strings+values...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _MagicRecipe: """A base 'recipe' to represent magical spells. We *could* treat this just like the sword above - by combining the wand and spellbook to make a fireball object that the user can then throw with another command. For this example we instead generate 'magical effects' as strings+values that we woul...
the_stack_v2_python_sparse
evennia/contrib/game_systems/crafting/example_recipes.py
evennia/evennia
train
1,781
c24df6a4b42c4c985c974f2f04df2f2ef7ce7de7
[ "super().__init__(gbd_round_id=gbd_round_id)\nself.process_version_id = process_version_id\nself.cause_id = cause_id\nself.demographics = demographics\nself.decomp_step = decomp_step\nself.gbd_round_id = gbd_round_id\nself.raw = None", "if self.cause_id:\n LOG.info(f'Getting CSMR from process version ID {self....
<|body_start_0|> super().__init__(gbd_round_id=gbd_round_id) self.process_version_id = process_version_id self.cause_id = cause_id self.demographics = demographics self.decomp_step = decomp_step self.gbd_round_id = gbd_round_id self.raw = None <|end_body_0|> <|bo...
CSMR
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CSMR: def __init__(self, process_version_id, cause_id, demographics, decomp_step, gbd_round_id): """Get cause-specific mortality rate for demographic groups from a specific CodCorrect output version. :param process_version_id: (int) :param cause_id: (int) :param demographics (cascade_at....
stack_v2_sparse_classes_36k_train_033446
3,808
permissive
[ { "docstring": "Get cause-specific mortality rate for demographic groups from a specific CodCorrect output version. :param process_version_id: (int) :param cause_id: (int) :param demographics (cascade_at.inputs.demographics.Demographics) :param decomp_step: (str) :param gbd_round_id: (int)", "name": "__init...
4
null
Implement the Python class `CSMR` described below. Class description: Implement the CSMR class. Method signatures and docstrings: - def __init__(self, process_version_id, cause_id, demographics, decomp_step, gbd_round_id): Get cause-specific mortality rate for demographic groups from a specific CodCorrect output vers...
Implement the Python class `CSMR` described below. Class description: Implement the CSMR class. Method signatures and docstrings: - def __init__(self, process_version_id, cause_id, demographics, decomp_step, gbd_round_id): Get cause-specific mortality rate for demographic groups from a specific CodCorrect output vers...
b495ee82db416c9edabe992822763a9a71f60808
<|skeleton|> class CSMR: def __init__(self, process_version_id, cause_id, demographics, decomp_step, gbd_round_id): """Get cause-specific mortality rate for demographic groups from a specific CodCorrect output version. :param process_version_id: (int) :param cause_id: (int) :param demographics (cascade_at....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CSMR: def __init__(self, process_version_id, cause_id, demographics, decomp_step, gbd_round_id): """Get cause-specific mortality rate for demographic groups from a specific CodCorrect output version. :param process_version_id: (int) :param cause_id: (int) :param demographics (cascade_at.inputs.demogra...
the_stack_v2_python_sparse
src/cascade_at/inputs/csmr.py
bmiltz/cascade-at
train
0
1b2213f9a2d8af807a4f1fa066d4e902809b182e
[ "self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = P('127.0.0.1', 8000)\nself.pump.set_state = MagicMock(return_value=True)", "controller = Controller(self.sensor, self.pump, Decider(200, 0.1))\nself.sensor.measure = MagicMock(return_value=250)\nself.pump.get_state = MagicMock(return_value=P.PUMP_OFF)\ncontrol...
<|body_start_0|> self.sensor = Sensor('127.0.0.1', 8000) self.pump = P('127.0.0.1', 8000) self.pump.set_state = MagicMock(return_value=True) <|end_body_0|> <|body_start_1|> controller = Controller(self.sensor, self.pump, Decider(200, 0.1)) self.sensor.measure = MagicMock(return_...
Module tests for the water-regulation module
ModuleTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModuleTests: """Module tests for the water-regulation module""" def setUp(self): """Declare the sensor and pump objects for each test, and declare the mock for the pump's state setter method.""" <|body_0|> def test_run_water_regulator1(self): """Run the sensor, p...
stack_v2_sparse_classes_36k_train_033447
3,148
no_license
[ { "docstring": "Declare the sensor and pump objects for each test, and declare the mock for the pump's state setter method.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Run the sensor, pump, and controller against random real-life situations.", "name": "test_run_water...
3
stack_v2_sparse_classes_30k_train_013100
Implement the Python class `ModuleTests` described below. Class description: Module tests for the water-regulation module Method signatures and docstrings: - def setUp(self): Declare the sensor and pump objects for each test, and declare the mock for the pump's state setter method. - def test_run_water_regulator1(sel...
Implement the Python class `ModuleTests` described below. Class description: Module tests for the water-regulation module Method signatures and docstrings: - def setUp(self): Declare the sensor and pump objects for each test, and declare the mock for the pump's state setter method. - def test_run_water_regulator1(sel...
b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1
<|skeleton|> class ModuleTests: """Module tests for the water-regulation module""" def setUp(self): """Declare the sensor and pump objects for each test, and declare the mock for the pump's state setter method.""" <|body_0|> def test_run_water_regulator1(self): """Run the sensor, p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModuleTests: """Module tests for the water-regulation module""" def setUp(self): """Declare the sensor and pump objects for each test, and declare the mock for the pump's state setter method.""" self.sensor = Sensor('127.0.0.1', 8000) self.pump = P('127.0.0.1', 8000) self....
the_stack_v2_python_sparse
students/Craig_Morton/Lesson06/water-regulation/waterregulation/integrationtest.py
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
train
4
95fc9d1d592eafa4ad8ba4b6448c65e6c605343a
[ "if not root:\n return []\nstack = [root]\ndata = []\nwhile stack:\n levelstack = []\n for node in stack:\n if node:\n data.append(node.val)\n levelstack.append(node.left)\n levelstack.append(node.right)\n else:\n data.append('#')\n stack = level...
<|body_start_0|> if not root: return [] stack = [root] data = [] while stack: levelstack = [] for node in stack: if node: data.append(node.val) levelstack.append(node.left) lev...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_033448
1,844
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_003709
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
6fd7b1bea597867889b7a4ababfb54fa649a717c
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return [] stack = [root] data = [] while stack: levelstack = [] for node in stack: if node: ...
the_stack_v2_python_sparse
python/251-300/297. Serialize and Deserialize Binary Tree.py
CrazyCoder4Carrot/leetcode
train
3
4ffec53d436820497022e21fa24af0fe4eebe568
[ "conv1 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2)\nconv2 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2, padding=0)\nconv3 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2, padding=0)\nreturn nn.Sequential(conv1, activation_constructor(Cin, False), conv2, activation_constructor(Cin, False), conv3)", "conv1 = nn.C...
<|body_start_0|> conv1 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2) conv2 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2, padding=0) conv3 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2, padding=0) return nn.Sequential(conv1, activation_constructor(Cin, False), conv2, activation_construc...
DownUp1D
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DownUp1D: def downsample1(activation_constructor, Cin, channel_small): """First RAB downsample""" <|body_0|> def upsample1(activation_constructor, Cin, channel_small): """First RAB upsample""" <|body_1|> def downsample2(activation_constructor, Cin, chann...
stack_v2_sparse_classes_36k_train_033449
17,767
permissive
[ { "docstring": "First RAB downsample", "name": "downsample1", "signature": "def downsample1(activation_constructor, Cin, channel_small)" }, { "docstring": "First RAB upsample", "name": "upsample1", "signature": "def upsample1(activation_constructor, Cin, channel_small)" }, { "doc...
4
stack_v2_sparse_classes_30k_train_003477
Implement the Python class `DownUp1D` described below. Class description: Implement the DownUp1D class. Method signatures and docstrings: - def downsample1(activation_constructor, Cin, channel_small): First RAB downsample - def upsample1(activation_constructor, Cin, channel_small): First RAB upsample - def downsample...
Implement the Python class `DownUp1D` described below. Class description: Implement the DownUp1D class. Method signatures and docstrings: - def downsample1(activation_constructor, Cin, channel_small): First RAB downsample - def upsample1(activation_constructor, Cin, channel_small): First RAB upsample - def downsample...
b54bd53540c11aa1b70e5160751905141f463217
<|skeleton|> class DownUp1D: def downsample1(activation_constructor, Cin, channel_small): """First RAB downsample""" <|body_0|> def upsample1(activation_constructor, Cin, channel_small): """First RAB upsample""" <|body_1|> def downsample2(activation_constructor, Cin, chann...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DownUp1D: def downsample1(activation_constructor, Cin, channel_small): """First RAB downsample""" conv1 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2) conv2 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2, padding=0) conv3 = nn.Conv1d(Cin, Cin, kernel_size=3, stride=2, padding=0)...
the_stack_v2_python_sparse
UnstructuredMesh/Tucodec1D.py
MaximeRedstone/UnstructuredCAE-DA
train
0
59127335de0806c64425342931cbfd5edf9890b0
[ "self.bc_file = bc_file\nself.beta = []\nself.code = []\nself.load_bc()", "array = np.loadtxt(self.bc_file)\nself.beta = array[:, 0]\nself.code = array[:, 1].astype(int)" ]
<|body_start_0|> self.bc_file = bc_file self.beta = [] self.code = [] self.load_bc() <|end_body_0|> <|body_start_1|> array = np.loadtxt(self.bc_file) self.beta = array[:, 0] self.code = array[:, 1].astype(int) <|end_body_1|>
Class for object that represents a beta code. beta, code (corresponding to OPER Case Matrix)
BETA_CODE
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BETA_CODE: """Class for object that represents a beta code. beta, code (corresponding to OPER Case Matrix)""" def __init__(self, bc_file): """Method to initialize BETA_CODE class.""" <|body_0|> def load_bc(self): """Method to load the beta code file.""" <...
stack_v2_sparse_classes_36k_train_033450
3,260
no_license
[ { "docstring": "Method to initialize BETA_CODE class.", "name": "__init__", "signature": "def __init__(self, bc_file)" }, { "docstring": "Method to load the beta code file.", "name": "load_bc", "signature": "def load_bc(self)" } ]
2
stack_v2_sparse_classes_30k_train_009524
Implement the Python class `BETA_CODE` described below. Class description: Class for object that represents a beta code. beta, code (corresponding to OPER Case Matrix) Method signatures and docstrings: - def __init__(self, bc_file): Method to initialize BETA_CODE class. - def load_bc(self): Method to load the beta co...
Implement the Python class `BETA_CODE` described below. Class description: Class for object that represents a beta code. beta, code (corresponding to OPER Case Matrix) Method signatures and docstrings: - def __init__(self, bc_file): Method to initialize BETA_CODE class. - def load_bc(self): Method to load the beta co...
6b37842203ff4318a48dbf0258cbe2b253436e7d
<|skeleton|> class BETA_CODE: """Class for object that represents a beta code. beta, code (corresponding to OPER Case Matrix)""" def __init__(self, bc_file): """Method to initialize BETA_CODE class.""" <|body_0|> def load_bc(self): """Method to load the beta code file.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BETA_CODE: """Class for object that represents a beta code. beta, code (corresponding to OPER Case Matrix)""" def __init__(self, bc_file): """Method to initialize BETA_CODE class.""" self.bc_file = bc_file self.beta = [] self.code = [] self.load_bc() def load_...
the_stack_v2_python_sparse
thermal/beta_code.py
tslowery78/PyLnD
train
0
d3fceccb65a52320447e9be139261e875a1506a7
[ "global tree_level, current_module, module_type, return_report, last_text\ntext = bpy.context.space_data.text\nif text:\n if text.name != 'api_doc_':\n last_text = bpy.context.space_data.text.name\n elif bpy.data.texts.__len__() < 2:\n last_text = None\nelse:\n last_text = None\nbpy.context.w...
<|body_start_0|> global tree_level, current_module, module_type, return_report, last_text text = bpy.context.space_data.text if text: if text.name != 'api_doc_': last_text = bpy.context.space_data.text.name elif bpy.data.texts.__len__() < 2: ...
Parent class for API Navigator
ApiNavigator
[ "GPL-3.0-only", "Font-exception-2.0", "GPL-3.0-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain-disclaimer", "Bitstream-Vera", "LicenseRef-scancode-blender-2010", "LGPL-2.1-or-later", "GPL-2.0-or-lat...
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApiNavigator: """Parent class for API Navigator""" def generate_global_values(): """Populate the level attributes to display the panel buttons and the documentation""" <|body_0|> def generate_api_doc(): """Format the doc string for API Navigator""" <|body...
stack_v2_sparse_classes_36k_train_033451
23,528
permissive
[ { "docstring": "Populate the level attributes to display the panel buttons and the documentation", "name": "generate_global_values", "signature": "def generate_global_values()" }, { "docstring": "Format the doc string for API Navigator", "name": "generate_api_doc", "signature": "def gene...
3
null
Implement the Python class `ApiNavigator` described below. Class description: Parent class for API Navigator Method signatures and docstrings: - def generate_global_values(): Populate the level attributes to display the panel buttons and the documentation - def generate_api_doc(): Format the doc string for API Naviga...
Implement the Python class `ApiNavigator` described below. Class description: Parent class for API Navigator Method signatures and docstrings: - def generate_global_values(): Populate the level attributes to display the panel buttons and the documentation - def generate_api_doc(): Format the doc string for API Naviga...
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
<|skeleton|> class ApiNavigator: """Parent class for API Navigator""" def generate_global_values(): """Populate the level attributes to display the panel buttons and the documentation""" <|body_0|> def generate_api_doc(): """Format the doc string for API Navigator""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApiNavigator: """Parent class for API Navigator""" def generate_global_values(): """Populate the level attributes to display the panel buttons and the documentation""" global tree_level, current_module, module_type, return_report, last_text text = bpy.context.space_data.text ...
the_stack_v2_python_sparse
engine/2.80/scripts/addons/development_api_navigator.py
byteinc/Phasor
train
3
a661bd2bb893b8243363024ff444a2e2514b8755
[ "validator = UserCreateSchema()\ntry:\n loaded_data = validator.load(data)\nexcept ValidationError as error:\n raise UserControllerException(error.messages)\nloaded_data['password'] = hashpw(loaded_data['password'].encode('utf8'), gensalt())\nloaded_data.pop('confirm_password')\nuser = User(public_id=str(uuid...
<|body_start_0|> validator = UserCreateSchema() try: loaded_data = validator.load(data) except ValidationError as error: raise UserControllerException(error.messages) loaded_data['password'] = hashpw(loaded_data['password'].encode('utf8'), gensalt()) loade...
Controller class for user related data manipulations.
UserController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserController: """Controller class for user related data manipulations.""" def create_user(self, data): """Creates a new user record in the database. Raises: - UserControllerError: if validation fails; if is unable to save the new record into the database due to an integrity error. ...
stack_v2_sparse_classes_36k_train_033452
3,200
no_license
[ { "docstring": "Creates a new user record in the database. Raises: - UserControllerError: if validation fails; if is unable to save the new record into the database due to an integrity error. Args: - data (dict): Map of user data to be validated and further processed as a User instance. Returns: - user (app.mod...
3
stack_v2_sparse_classes_30k_train_001656
Implement the Python class `UserController` described below. Class description: Controller class for user related data manipulations. Method signatures and docstrings: - def create_user(self, data): Creates a new user record in the database. Raises: - UserControllerError: if validation fails; if is unable to save the...
Implement the Python class `UserController` described below. Class description: Controller class for user related data manipulations. Method signatures and docstrings: - def create_user(self, data): Creates a new user record in the database. Raises: - UserControllerError: if validation fails; if is unable to save the...
fc16ecc301c38271767f5a581d917ec6196ff14a
<|skeleton|> class UserController: """Controller class for user related data manipulations.""" def create_user(self, data): """Creates a new user record in the database. Raises: - UserControllerError: if validation fails; if is unable to save the new record into the database due to an integrity error. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserController: """Controller class for user related data manipulations.""" def create_user(self, data): """Creates a new user record in the database. Raises: - UserControllerError: if validation fails; if is unable to save the new record into the database due to an integrity error. Args: - data ...
the_stack_v2_python_sparse
app/controllers/user.py
rqroz/obd-dashboard
train
3
797fcfcc5fe254c36afd45793fa578c0bca407a6
[ "import heapq\nself.k = k\nself.h = nums\nheapq.heapify(self.h)\nwhile len(self.h) > k:\n heapq.heappop(self.h)\nprint(self.h)", "import heapq\nif len(self.h) < self.k:\n heapq.heappush(self.h, val)\nelse:\n heapq.heappushpop(self.h, val)\nreturn self.h[0]" ]
<|body_start_0|> import heapq self.k = k self.h = nums heapq.heapify(self.h) while len(self.h) > k: heapq.heappop(self.h) print(self.h) <|end_body_0|> <|body_start_1|> import heapq if len(self.h) < self.k: heapq.heappush(self.h, va...
KthLargest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KthLargest: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> import heapq self.k = k self.h = nums ...
stack_v2_sparse_classes_36k_train_033453
778
no_license
[ { "docstring": ":type k: int :type nums: List[int]", "name": "__init__", "signature": "def __init__(self, k, nums)" }, { "docstring": ":type val: int :rtype: int", "name": "add", "signature": "def add(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_006977
Implement the Python class `KthLargest` described below. Class description: Implement the KthLargest class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int
Implement the Python class `KthLargest` described below. Class description: Implement the KthLargest class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int <|skeleton|> class KthLargest: def __init__(self, k, nu...
2e1751263f484709102f7f2caf18776a004c8230
<|skeleton|> class KthLargest: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KthLargest: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" import heapq self.k = k self.h = nums heapq.heapify(self.h) while len(self.h) > k: heapq.heappop(self.h) print(self.h) def add(self, val): """:type...
the_stack_v2_python_sparse
Python/Leetcode Daily Practice/Heap/703. Kth Largest Element in a Stream.py
YaqianQi/Algorithm-and-Data-Structure
train
1
752b94e67fa092bee6c61f74d3ff74d27bf6eb16
[ "point_cloud_1 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]\npoint_cloud_2 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]\ntf_point_cloud_1 = tf.constant(point_cloud_1)\ntf_point_cloud_2 = tf.constant(point_cloud_2)\nmatch = tf_approxmatch.approx_match(tf_point_cloud_1, tf_point_cloud_2)\ndistan...
<|body_start_0|> point_cloud_1 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]] point_cloud_2 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]] tf_point_cloud_1 = tf.constant(point_cloud_1) tf_point_cloud_2 = tf.constant(point_cloud_2) match = tf_approxmatch.approx_m...
ApproxMatchTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApproxMatchTest: def test_emd(self): """Test for the approximate algorithm for computing the distance where loss should be zero.""" <|body_0|> def test_emd_2(self): """Test for the approximate algorithm for computing the Earth Mover's Distance to see if match selects...
stack_v2_sparse_classes_36k_train_033454
3,587
permissive
[ { "docstring": "Test for the approximate algorithm for computing the distance where loss should be zero.", "name": "test_emd", "signature": "def test_emd(self)" }, { "docstring": "Test for the approximate algorithm for computing the Earth Mover's Distance to see if match selects closest point, a...
4
stack_v2_sparse_classes_30k_train_000836
Implement the Python class `ApproxMatchTest` described below. Class description: Implement the ApproxMatchTest class. Method signatures and docstrings: - def test_emd(self): Test for the approximate algorithm for computing the distance where loss should be zero. - def test_emd_2(self): Test for the approximate algori...
Implement the Python class `ApproxMatchTest` described below. Class description: Implement the ApproxMatchTest class. Method signatures and docstrings: - def test_emd(self): Test for the approximate algorithm for computing the distance where loss should be zero. - def test_emd_2(self): Test for the approximate algori...
f3cb31909666012dfcf38e5fe0b0f6feb3801560
<|skeleton|> class ApproxMatchTest: def test_emd(self): """Test for the approximate algorithm for computing the distance where loss should be zero.""" <|body_0|> def test_emd_2(self): """Test for the approximate algorithm for computing the Earth Mover's Distance to see if match selects...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApproxMatchTest: def test_emd(self): """Test for the approximate algorithm for computing the distance where loss should be zero.""" point_cloud_1 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]] point_cloud_2 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]] tf_poi...
the_stack_v2_python_sparse
src/tf_ops/approxmatch/tf_approxmatch_test.py
minghanz/monopsr
train
0
9efb07e8c6460fa338f4b4901896d80f3adf9afa
[ "if isinstance(size, (str, unicode)):\n size = int(size)\nreturn numpy.ones((size, 1)) * numpy.array([1.0, 0.0])", "if isinstance(start_idx, (str, unicode)):\n start_idx = int(start_idx)\nif isinstance(end_idx, (str, unicode)):\n end_idx = int(end_idx)\nsize = end_idx - start_idx\nresult = numpy.transpos...
<|body_start_0|> if isinstance(size, (str, unicode)): size = int(size) return numpy.ones((size, 1)) * numpy.array([1.0, 0.0]) <|end_body_0|> <|body_start_1|> if isinstance(start_idx, (str, unicode)): start_idx = int(start_idx) if isinstance(end_idx, (str, unicode...
Framework methods regarding RegionMapping DataType.
RegionMappingFramework
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegionMappingFramework: """Framework methods regarding RegionMapping DataType.""" def get_alpha_array(size): """Compute alpha weights. When displaying region-based results, we need to compute color for each surface vertex based on a gradient of the neighbor region(s). Currently only ...
stack_v2_sparse_classes_36k_train_033455
25,280
no_license
[ { "docstring": "Compute alpha weights. When displaying region-based results, we need to compute color for each surface vertex based on a gradient of the neighbor region(s). Currently only one vertex is used for determining color (the one indicated by the RegionMapping). :return: NumPy array with [[1, 0], [1, 0]...
3
null
Implement the Python class `RegionMappingFramework` described below. Class description: Framework methods regarding RegionMapping DataType. Method signatures and docstrings: - def get_alpha_array(size): Compute alpha weights. When displaying region-based results, we need to compute color for each surface vertex based...
Implement the Python class `RegionMappingFramework` described below. Class description: Framework methods regarding RegionMapping DataType. Method signatures and docstrings: - def get_alpha_array(size): Compute alpha weights. When displaying region-based results, we need to compute color for each surface vertex based...
dd4beb028719abaa70c639f64c97ba23bd4a1f3a
<|skeleton|> class RegionMappingFramework: """Framework methods regarding RegionMapping DataType.""" def get_alpha_array(size): """Compute alpha weights. When displaying region-based results, we need to compute color for each surface vertex based on a gradient of the neighbor region(s). Currently only ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegionMappingFramework: """Framework methods regarding RegionMapping DataType.""" def get_alpha_array(size): """Compute alpha weights. When displaying region-based results, we need to compute color for each surface vertex based on a gradient of the neighbor region(s). Currently only one vertex is...
the_stack_v2_python_sparse
tvb/datatypes/surfaces_framework.py
HuifangWang/the-virtual-brain-website
train
0
fce9fc5746de5011cdde9b9413abc67f84a3dceb
[ "super(self.__class__, self).__init__(graph, seed)\nself.available_statuses = {'Susceptible': 0, 'Infected': 1}\nself.name = 'Voter'", "self.clean_initial_status(self.available_statuses.values())\nif self.actual_iteration == 0:\n self.actual_iteration += 1\n delta, node_count, status_delta = self.status_del...
<|body_start_0|> super(self.__class__, self).__init__(graph, seed) self.available_statuses = {'Susceptible': 0, 'Infected': 1} self.name = 'Voter' <|end_body_0|> <|body_start_1|> self.clean_initial_status(self.available_statuses.values()) if self.actual_iteration == 0: ...
VoterModel
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VoterModel: def __init__(self, graph, seed=None): """Model Constructor :param graph: A networkx graph object""" <|body_0|> def iteration(self, node_status=True): """Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->stat...
stack_v2_sparse_classes_36k_train_033456
3,326
permissive
[ { "docstring": "Model Constructor :param graph: A networkx graph object", "name": "__init__", "signature": "def __init__(self, graph, seed=None)" }, { "docstring": "Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)", "name": "iteration"...
2
stack_v2_sparse_classes_30k_train_018738
Implement the Python class `VoterModel` described below. Class description: Implement the VoterModel class. Method signatures and docstrings: - def __init__(self, graph, seed=None): Model Constructor :param graph: A networkx graph object - def iteration(self, node_status=True): Execute a single model iteration :retur...
Implement the Python class `VoterModel` described below. Class description: Implement the VoterModel class. Method signatures and docstrings: - def __init__(self, graph, seed=None): Model Constructor :param graph: A networkx graph object - def iteration(self, node_status=True): Execute a single model iteration :retur...
900cb3727795c97a73e59fdb736aa736c4d17157
<|skeleton|> class VoterModel: def __init__(self, graph, seed=None): """Model Constructor :param graph: A networkx graph object""" <|body_0|> def iteration(self, node_status=True): """Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->stat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VoterModel: def __init__(self, graph, seed=None): """Model Constructor :param graph: A networkx graph object""" super(self.__class__, self).__init__(graph, seed) self.available_statuses = {'Susceptible': 0, 'Infected': 1} self.name = 'Voter' def iteration(self, node_status...
the_stack_v2_python_sparse
ndlib/models/opinions/VoterModel.py
GiulioRossetti/ndlib
train
265
a06de08ba3b067d7648888faf37ce00055fccd46
[ "if self.kwargs.get(self.lookup_field, None) is None:\n raise ParseError('Expected URL keyword argument `%s`.' % self.lookup_field)\nqueryset = self.filter_queryset(self.get_queryset())\nfilter_kwargs = {}\nserializer = self.get_serializer()\nlookup_field = self.lookup_field\nif self.lookup_field in serializer.g...
<|body_start_0|> if self.kwargs.get(self.lookup_field, None) is None: raise ParseError('Expected URL keyword argument `%s`.' % self.lookup_field) queryset = self.filter_queryset(self.get_queryset()) filter_kwargs = {} serializer = self.get_serializer() lookup_field = ...
ObjectLookupMixin
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectLookupMixin: def get_object(self): """Incase the lookup is on an object that has been hyperlinked then update the queryset filter appropriately""" <|body_0|> def pre_save(self, obj): """Set any attributes on the object that are implicit in the request.""" ...
stack_v2_sparse_classes_36k_train_033457
2,712
permissive
[ { "docstring": "Incase the lookup is on an object that has been hyperlinked then update the queryset filter appropriately", "name": "get_object", "signature": "def get_object(self)" }, { "docstring": "Set any attributes on the object that are implicit in the request.", "name": "pre_save", ...
2
null
Implement the Python class `ObjectLookupMixin` described below. Class description: Implement the ObjectLookupMixin class. Method signatures and docstrings: - def get_object(self): Incase the lookup is on an object that has been hyperlinked then update the queryset filter appropriately - def pre_save(self, obj): Set a...
Implement the Python class `ObjectLookupMixin` described below. Class description: Implement the ObjectLookupMixin class. Method signatures and docstrings: - def get_object(self): Incase the lookup is on an object that has been hyperlinked then update the queryset filter appropriately - def pre_save(self, obj): Set a...
b8d93d4da649f323af111cf7247206554be7c8b1
<|skeleton|> class ObjectLookupMixin: def get_object(self): """Incase the lookup is on an object that has been hyperlinked then update the queryset filter appropriately""" <|body_0|> def pre_save(self, obj): """Set any attributes on the object that are implicit in the request.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObjectLookupMixin: def get_object(self): """Incase the lookup is on an object that has been hyperlinked then update the queryset filter appropriately""" if self.kwargs.get(self.lookup_field, None) is None: raise ParseError('Expected URL keyword argument `%s`.' % self.lookup_field) ...
the_stack_v2_python_sparse
onadata/libs/mixins/object_lookup_mixin.py
kobotoolbox/kobocat
train
101
da1c16b31a3b1e82d070848835f4754146eec7ff
[ "nodes = [('const_node', {'type': 'Const', 'kind': 'op'}), ('const_data', {'kind': 'data', 'value': np.array(5)}), ('result_node', {'type': 'Result', 'kind': 'op'}), ('placeholder_1', {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'}), ('placeholder_1_data', {'kind': 'data'}), ('relu_1', {'type': 'ReLU', 'kind...
<|body_start_0|> nodes = [('const_node', {'type': 'Const', 'kind': 'op'}), ('const_data', {'kind': 'data', 'value': np.array(5)}), ('result_node', {'type': 'Result', 'kind': 'op'}), ('placeholder_1', {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'}), ('placeholder_1_data', {'kind': 'data'}), ('relu_1', {'...
RemoveConstToResultReplacementTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoveConstToResultReplacementTest: def test_only_consumer(self): """Result node is only consumer of Const data node""" <|body_0|> def test_two_consumers(self): """Const data node has two consumers: Result and ReLu""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_36k_train_033458
8,443
permissive
[ { "docstring": "Result node is only consumer of Const data node", "name": "test_only_consumer", "signature": "def test_only_consumer(self)" }, { "docstring": "Const data node has two consumers: Result and ReLu", "name": "test_two_consumers", "signature": "def test_two_consumers(self)" ...
2
null
Implement the Python class `RemoveConstToResultReplacementTest` described below. Class description: Implement the RemoveConstToResultReplacementTest class. Method signatures and docstrings: - def test_only_consumer(self): Result node is only consumer of Const data node - def test_two_consumers(self): Const data node ...
Implement the Python class `RemoveConstToResultReplacementTest` described below. Class description: Implement the RemoveConstToResultReplacementTest class. Method signatures and docstrings: - def test_only_consumer(self): Result node is only consumer of Const data node - def test_two_consumers(self): Const data node ...
2e6c95f389b195f6d3ff8597147d1f817433cfb3
<|skeleton|> class RemoveConstToResultReplacementTest: def test_only_consumer(self): """Result node is only consumer of Const data node""" <|body_0|> def test_two_consumers(self): """Const data node has two consumers: Result and ReLu""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RemoveConstToResultReplacementTest: def test_only_consumer(self): """Result node is only consumer of Const data node""" nodes = [('const_node', {'type': 'Const', 'kind': 'op'}), ('const_data', {'kind': 'data', 'value': np.array(5)}), ('result_node', {'type': 'Result', 'kind': 'op'}), ('placeho...
the_stack_v2_python_sparse
model-optimizer/extensions/back/SpecialNodesFinalization_test.py
0xF6/openvino
train
2
5bb530eae97a1c0fb0e554ddc5ded860c896aa8a
[ "self.local_view_box_id = local_view_box_id\nself.local_view_box_name = local_view_box_name\nself.remote_view_box_id = remote_view_box_id\nself.remote_view_box_name = remote_view_box_name", "if dictionary is None:\n return None\nlocal_view_box_id = dictionary.get('localViewBoxId')\nlocal_view_box_name = dictio...
<|body_start_0|> self.local_view_box_id = local_view_box_id self.local_view_box_name = local_view_box_name self.remote_view_box_id = remote_view_box_id self.remote_view_box_name = remote_view_box_name <|end_body_0|> <|body_start_1|> if dictionary is None: return None...
Implementation of the 'ViewBoxPairInfo' model. Specifies a pairing between a Storage Domain (View Box) on local Cluster with a Storage Domain (View Box) on a remote Cluster. When replication is configured between a local Cluster and a remote Cluster, the Snapshots are replicated from the specified Storage Domain (View ...
ViewBoxPairInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViewBoxPairInfo: """Implementation of the 'ViewBoxPairInfo' model. Specifies a pairing between a Storage Domain (View Box) on local Cluster with a Storage Domain (View Box) on a remote Cluster. When replication is configured between a local Cluster and a remote Cluster, the Snapshots are replicat...
stack_v2_sparse_classes_36k_train_033459
2,996
permissive
[ { "docstring": "Constructor for the ViewBoxPairInfo class", "name": "__init__", "signature": "def __init__(self, local_view_box_id=None, local_view_box_name=None, remote_view_box_id=None, remote_view_box_name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dic...
2
stack_v2_sparse_classes_30k_test_000190
Implement the Python class `ViewBoxPairInfo` described below. Class description: Implementation of the 'ViewBoxPairInfo' model. Specifies a pairing between a Storage Domain (View Box) on local Cluster with a Storage Domain (View Box) on a remote Cluster. When replication is configured between a local Cluster and a rem...
Implement the Python class `ViewBoxPairInfo` described below. Class description: Implementation of the 'ViewBoxPairInfo' model. Specifies a pairing between a Storage Domain (View Box) on local Cluster with a Storage Domain (View Box) on a remote Cluster. When replication is configured between a local Cluster and a rem...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ViewBoxPairInfo: """Implementation of the 'ViewBoxPairInfo' model. Specifies a pairing between a Storage Domain (View Box) on local Cluster with a Storage Domain (View Box) on a remote Cluster. When replication is configured between a local Cluster and a remote Cluster, the Snapshots are replicat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViewBoxPairInfo: """Implementation of the 'ViewBoxPairInfo' model. Specifies a pairing between a Storage Domain (View Box) on local Cluster with a Storage Domain (View Box) on a remote Cluster. When replication is configured between a local Cluster and a remote Cluster, the Snapshots are replicated from the s...
the_stack_v2_python_sparse
cohesity_management_sdk/models/view_box_pair_info.py
cohesity/management-sdk-python
train
24
6b16751ca552c52d250410ac9fdb84c5d266b58d
[ "qs, target_qs = self._get_q_values(s_batch, a_batch, r_batch, sp_batch, done_mask)\nloss = nn.functional.smooth_l1_loss(qs, target_qs, reduction='none')\nreturn loss", "s_batch, a_batch, r_batch, sp_batch, done_mask_batch, weights = sampled_batch\nself.optimizer.zero_grad()\nelement_wise_loss = self._calc_loss(s...
<|body_start_0|> qs, target_qs = self._get_q_values(s_batch, a_batch, r_batch, sp_batch, done_mask) loss = nn.functional.smooth_l1_loss(qs, target_qs, reduction='none') return loss <|end_body_0|> <|body_start_1|> s_batch, a_batch, r_batch, sp_batch, done_mask_batch, weights = sampled_ba...
PerDblDqn
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PerDblDqn: def _calc_loss(self, s_batch: Tensor, a_batch: Tensor, r_batch: Tensor, sp_batch: Tensor, done_mask: Tensor) -> Tensor: """Calculate the Huber loss (SmoothL1Loss) of this step. loss = SmoothL1Loss(Q_sample(s) - Q(s, a)) :param s_batch: state batch (batch_size, n_channel, image...
stack_v2_sparse_classes_36k_train_033460
2,456
no_license
[ { "docstring": "Calculate the Huber loss (SmoothL1Loss) of this step. loss = SmoothL1Loss(Q_sample(s) - Q(s, a)) :param s_batch: state batch (batch_size, n_channel, image_height, image_width) :param sp_batch: next state batch (batch_size, n_channel, image_height, image_width) :param a_batch: The action the agen...
2
stack_v2_sparse_classes_30k_train_007563
Implement the Python class `PerDblDqn` described below. Class description: Implement the PerDblDqn class. Method signatures and docstrings: - def _calc_loss(self, s_batch: Tensor, a_batch: Tensor, r_batch: Tensor, sp_batch: Tensor, done_mask: Tensor) -> Tensor: Calculate the Huber loss (SmoothL1Loss) of this step. lo...
Implement the Python class `PerDblDqn` described below. Class description: Implement the PerDblDqn class. Method signatures and docstrings: - def _calc_loss(self, s_batch: Tensor, a_batch: Tensor, r_batch: Tensor, sp_batch: Tensor, done_mask: Tensor) -> Tensor: Calculate the Huber loss (SmoothL1Loss) of this step. lo...
c9421d5058d5144aec855f4be66673830652845b
<|skeleton|> class PerDblDqn: def _calc_loss(self, s_batch: Tensor, a_batch: Tensor, r_batch: Tensor, sp_batch: Tensor, done_mask: Tensor) -> Tensor: """Calculate the Huber loss (SmoothL1Loss) of this step. loss = SmoothL1Loss(Q_sample(s) - Q(s, a)) :param s_batch: state batch (batch_size, n_channel, image...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PerDblDqn: def _calc_loss(self, s_batch: Tensor, a_batch: Tensor, r_batch: Tensor, sp_batch: Tensor, done_mask: Tensor) -> Tensor: """Calculate the Huber loss (SmoothL1Loss) of this step. loss = SmoothL1Loss(Q_sample(s) - Q(s, a)) :param s_batch: state batch (batch_size, n_channel, image_height, image...
the_stack_v2_python_sparse
core/ml/dqn/model/per_dbl_dqn.py
XiaoMutt/qingting
train
1
6e985ea5213d2d82bbf233f1ed04fd79f2dec8f5
[ "from lib.httplib2 import Http\nself.login = login\nself.access_token = access_token\nself.api_key = api_key\nself.connector = Http()", "from urllib import urlencode\ndata = {'format': 'json', 'longUrl': url, 'login': self.login, 'apiKey': self.api_key}\nresp, content = self.connector.request(self.shorten_url + '...
<|body_start_0|> from lib.httplib2 import Http self.login = login self.access_token = access_token self.api_key = api_key self.connector = Http() <|end_body_0|> <|body_start_1|> from urllib import urlencode data = {'format': 'json', 'longUrl': url, 'login': self....
Interface to the bit.ly API; incomplete, containing only what is needed by the socialfeeder application.
api
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class api: """Interface to the bit.ly API; incomplete, containing only what is needed by the socialfeeder application.""" def __init__(self, login, access_token, api_key): """@param login: bit.ly username @param access_token: bit.ly user access token @param api_key: bit.ly user API key""" ...
stack_v2_sparse_classes_36k_train_033461
3,225
no_license
[ { "docstring": "@param login: bit.ly username @param access_token: bit.ly user access token @param api_key: bit.ly user API key", "name": "__init__", "signature": "def __init__(self, login, access_token, api_key)" }, { "docstring": "Shortens an URL with the given bit.ly account @param url: URL t...
2
stack_v2_sparse_classes_30k_train_021127
Implement the Python class `api` described below. Class description: Interface to the bit.ly API; incomplete, containing only what is needed by the socialfeeder application. Method signatures and docstrings: - def __init__(self, login, access_token, api_key): @param login: bit.ly username @param access_token: bit.ly ...
Implement the Python class `api` described below. Class description: Interface to the bit.ly API; incomplete, containing only what is needed by the socialfeeder application. Method signatures and docstrings: - def __init__(self, login, access_token, api_key): @param login: bit.ly username @param access_token: bit.ly ...
31d9a1892c23ae99b1b5259332fbfc93156c07ed
<|skeleton|> class api: """Interface to the bit.ly API; incomplete, containing only what is needed by the socialfeeder application.""" def __init__(self, login, access_token, api_key): """@param login: bit.ly username @param access_token: bit.ly user access token @param api_key: bit.ly user API key""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class api: """Interface to the bit.ly API; incomplete, containing only what is needed by the socialfeeder application.""" def __init__(self, login, access_token, api_key): """@param login: bit.ly username @param access_token: bit.ly user access token @param api_key: bit.ly user API key""" from ...
the_stack_v2_python_sparse
src/sfdr/modules/bitly.py
CVi/socialfeeder-2
train
0
0b4356b0175a7e926165e032baa3cdb4df7a8d7c
[ "ret = 0\nbuy = sys.maxint\nfor i, e in enumerate(prices):\n if e > buy:\n if e - buy > 0:\n ret += e - buy\n buy = e\n else:\n buy = e\nreturn ret", "if not prices:\n return 0\nres = 0\nfor i in range(1, len(prices)):\n if prices[i] > prices[i - 1]:\n res +=...
<|body_start_0|> ret = 0 buy = sys.maxint for i, e in enumerate(prices): if e > buy: if e - buy > 0: ret += e - buy buy = e else: buy = e return ret <|end_body_0|> <|body_start_1|> if...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit1(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, prices): """贪婪法 :type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ret = 0 buy = sys.maxint ...
stack_v2_sparse_classes_36k_train_033462
1,130
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit1", "signature": "def maxProfit1(self, prices)" }, { "docstring": "贪婪法 :type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): 贪婪法 :type prices: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): 贪婪法 :type prices: List[int] :rtype: int <|skeleton|> class Solution: def ma...
fabe435f366477ec3526add84accec0b4ac38919
<|skeleton|> class Solution: def maxProfit1(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, prices): """贪婪法 :type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit1(self, prices): """:type prices: List[int] :rtype: int""" ret = 0 buy = sys.maxint for i, e in enumerate(prices): if e > buy: if e - buy > 0: ret += e - buy buy = e else: ...
the_stack_v2_python_sparse
algorithm/leetcode/122_best-time-to-buy-and-sell-stock-ii.py
icejoywoo/toys
train
1
9ce241e2decc994a049d65e5351e4f982f3d37fb
[ "j = 0\nn = len(nums)\nfor i in range(n):\n if nums[i]:\n nums[j] = nums[i]\n j += 1\nfor i in range(j, n):\n nums[i] = 0", "j = 0\nfor i in range(len(nums)):\n if not nums[i]:\n continue\n if i > j:\n nums[j] = nums[i]\n nums[i] = 0\n j += 1" ]
<|body_start_0|> j = 0 n = len(nums) for i in range(n): if nums[i]: nums[j] = nums[i] j += 1 for i in range(j, n): nums[i] = 0 <|end_body_0|> <|body_start_1|> j = 0 for i in range(len(nums)): if not nums...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def moveZeroes1(self, nums: List[int]) -> None: """直接填充""" <|body_0|> def moveZeros2(self, nums: List[int]) -> None: """双指针 一个指针用于遍历数组 另一个指针用于指向数组中的 0""" <|body_1|> <|end_skeleton|> <|body_start_0|> j = 0 n = len(nums) for ...
stack_v2_sparse_classes_36k_train_033463
1,121
no_license
[ { "docstring": "直接填充", "name": "moveZeroes1", "signature": "def moveZeroes1(self, nums: List[int]) -> None" }, { "docstring": "双指针 一个指针用于遍历数组 另一个指针用于指向数组中的 0", "name": "moveZeros2", "signature": "def moveZeros2(self, nums: List[int]) -> None" } ]
2
stack_v2_sparse_classes_30k_train_011653
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes1(self, nums: List[int]) -> None: 直接填充 - def moveZeros2(self, nums: List[int]) -> None: 双指针 一个指针用于遍历数组 另一个指针用于指向数组中的 0
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes1(self, nums: List[int]) -> None: 直接填充 - def moveZeros2(self, nums: List[int]) -> None: 双指针 一个指针用于遍历数组 另一个指针用于指向数组中的 0 <|skeleton|> class Solution: def moveZe...
52756b30e9d51794591aca030bc918e707f473f1
<|skeleton|> class Solution: def moveZeroes1(self, nums: List[int]) -> None: """直接填充""" <|body_0|> def moveZeros2(self, nums: List[int]) -> None: """双指针 一个指针用于遍历数组 另一个指针用于指向数组中的 0""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def moveZeroes1(self, nums: List[int]) -> None: """直接填充""" j = 0 n = len(nums) for i in range(n): if nums[i]: nums[j] = nums[i] j += 1 for i in range(j, n): nums[i] = 0 def moveZeros2(self, nums: Lis...
the_stack_v2_python_sparse
283.移动零/solution.py
QtTao/daily_leetcode
train
0
7003e587afb757d626b1d9a2a00c2c0af4c083ad
[ "_query_builder = Configuration.base_uri\n_query_builder += '/task/cancel'\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json', 'content-type': 'application/json; charset=utf-8'}\n_request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_seriali...
<|body_start_0|> _query_builder = Configuration.base_uri _query_builder += '/task/cancel' _query_url = APIHelper.clean_url(_query_builder) _headers = {'accept': 'application/json', 'content-type': 'application/json; charset=utf-8'} _request = self.http_client.post(_query_url, hea...
A Controller to access Endpoints in the ontraportlib API.
TasksController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TasksController: """A Controller to access Endpoints in the ontraportlib API.""" def create_task_cancel(self, criteria): """Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> para...
stack_v2_sparse_classes_36k_train_033464
3,861
permissive
[ { "docstring": "Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> parameter. Otherwise, you should use <strong>performAll</strong> and other criteria to select a Group of Tasks to cancel. Args: criteria (Cr...
2
stack_v2_sparse_classes_30k_train_008694
Implement the Python class `TasksController` described below. Class description: A Controller to access Endpoints in the ontraportlib API. Method signatures and docstrings: - def create_task_cancel(self, criteria): Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong...
Implement the Python class `TasksController` described below. Class description: A Controller to access Endpoints in the ontraportlib API. Method signatures and docstrings: - def create_task_cancel(self, criteria): Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong...
fb4834e89b897dce3475c89c7e6c34bf8756880e
<|skeleton|> class TasksController: """A Controller to access Endpoints in the ontraportlib API.""" def create_task_cancel(self, criteria): """Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> para...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TasksController: """A Controller to access Endpoints in the ontraportlib API.""" def create_task_cancel(self, criteria): """Does a POST request to /task/cancel. To affect a single Task or list of specific Tasks, use the <strong>ids</strong> array in the <strong>criteria</strong> parameter. Otherw...
the_stack_v2_python_sparse
ontraportlib/controllers/tasks_controller.py
LifePosts/ontraportlib
train
0
9bd2da744ef351f2627f43339abd16cfebaae8b9
[ "self.rare_depths = range(min, max + 1, step)\nself.num_reps = num_reps\nself.otu_table = self.getBiomData(otu_path)\nself.max_num_taxa = -1\ntmp = -1\nfor val in self.otu_table.iterObservationData():\n if val.sum() > tmp:\n tmp = val.sum()\nself.max_num_taxa = tmp", "if not include_lineages:\n for v...
<|body_start_0|> self.rare_depths = range(min, max + 1, step) self.num_reps = num_reps self.otu_table = self.getBiomData(otu_path) self.max_num_taxa = -1 tmp = -1 for val in self.otu_table.iterObservationData(): if val.sum() > tmp: tmp = val.su...
RarefactionMaker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RarefactionMaker: def __init__(self, otu_path, min, max, step, num_reps): """init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond any sample in the data""" <|body_0|> def rarefy_to_files(self, output_dir, small_included=Fal...
stack_v2_sparse_classes_36k_train_033465
7,880
no_license
[ { "docstring": "init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond any sample in the data", "name": "__init__", "signature": "def __init__(self, otu_path, min, max, step, num_reps)" }, { "docstring": "computes rarefied otu tables and writes t...
4
stack_v2_sparse_classes_30k_val_000940
Implement the Python class `RarefactionMaker` described below. Class description: Implement the RarefactionMaker class. Method signatures and docstrings: - def __init__(self, otu_path, min, max, step, num_reps): init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond a...
Implement the Python class `RarefactionMaker` described below. Class description: Implement the RarefactionMaker class. Method signatures and docstrings: - def __init__(self, otu_path, min, max, step, num_reps): init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond a...
afb3eb6531badeb74fc69ae4c9e698d3e9cbe70e
<|skeleton|> class RarefactionMaker: def __init__(self, otu_path, min, max, step, num_reps): """init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond any sample in the data""" <|body_0|> def rarefy_to_files(self, output_dir, small_included=Fal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RarefactionMaker: def __init__(self, otu_path, min, max, step, num_reps): """init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond any sample in the data""" self.rare_depths = range(min, max + 1, step) self.num_reps = num_reps ...
the_stack_v2_python_sparse
qiime/rarefaction.py
rob-knight/qiime
train
2
66ef5932c9f2120ba3baf0d040c9361e9ca09163
[ "self.params = {}\nself._space = {}\nself._rank = defaultdict(lambda: [])", "self.params[name] = np.random.choice([True, False]) if default is None else default\nif name not in self._space:\n self._space[name] = {'mode': 'Boolean', 'default': default, 'values': [True, False]}\n self._rank[rank].append(name)...
<|body_start_0|> self.params = {} self._space = {} self._rank = defaultdict(lambda: []) <|end_body_0|> <|body_start_1|> self.params[name] = np.random.choice([True, False]) if default is None else default if name not in self._space: self._space[name] = {'mode': 'Boole...
HyperParametersGrid
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HyperParametersGrid: def __init__(self): """Container for both a hyperparameter space, and current values.""" <|body_0|> def Boolean(self, name, default=None, rank=0): """Choice between True and False. Arguments: name: Str. Name of parameter. Must be unique. default:...
stack_v2_sparse_classes_36k_train_033466
7,676
permissive
[ { "docstring": "Container for both a hyperparameter space, and current values.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Choice between True and False. Arguments: name: Str. Name of parameter. Must be unique. default: Default value to return for the parameter. If...
6
stack_v2_sparse_classes_30k_train_019043
Implement the Python class `HyperParametersGrid` described below. Class description: Implement the HyperParametersGrid class. Method signatures and docstrings: - def __init__(self): Container for both a hyperparameter space, and current values. - def Boolean(self, name, default=None, rank=0): Choice between True and ...
Implement the Python class `HyperParametersGrid` described below. Class description: Implement the HyperParametersGrid class. Method signatures and docstrings: - def __init__(self): Container for both a hyperparameter space, and current values. - def Boolean(self, name, default=None, rank=0): Choice between True and ...
ae965a487b4f94f05aa794000401ccc5e3be7446
<|skeleton|> class HyperParametersGrid: def __init__(self): """Container for both a hyperparameter space, and current values.""" <|body_0|> def Boolean(self, name, default=None, rank=0): """Choice between True and False. Arguments: name: Str. Name of parameter. Must be unique. default:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HyperParametersGrid: def __init__(self): """Container for both a hyperparameter space, and current values.""" self.params = {} self._space = {} self._rank = defaultdict(lambda: []) def Boolean(self, name, default=None, rank=0): """Choice between True and False. Arg...
the_stack_v2_python_sparse
linora/param_search/_HyperParameters.py
NoraXie/linora
train
1
76f40273c454274ed9aeb54653585056a9a46025
[ "self.fig = plt.figure('Trajectories')\nself.ax_arr = [None] * (num_traj * 2)\nfor k in range(num_traj * 2):\n num = 2 * 100 + num_traj * 10 + (k + 1)\n self.ax_arr[k] = self.fig.add_subplot(num, projection='3d')\nself.trajectories_in = np.zeros((0, 0, num_traj))\nself.trajectories_out = np.zeros((0, 0, num_t...
<|body_start_0|> self.fig = plt.figure('Trajectories') self.ax_arr = [None] * (num_traj * 2) for k in range(num_traj * 2): num = 2 * 100 + num_traj * 10 + (k + 1) self.ax_arr[k] = self.fig.add_subplot(num, projection='3d') self.trajectories_in = np.zeros((0, 0, nu...
TrajectoryPlot
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrajectoryPlot: def __init__(self, num_traj): """:param num_traj: The amount of training and validation trajectories that are plotted""" <|body_0|> def update_trajectories(self, trajectories_in: np.ndarray, trajectories_out: np.ndarray, prediction_out: np.ndarray) -> None: ...
stack_v2_sparse_classes_36k_train_033467
2,678
permissive
[ { "docstring": ":param num_traj: The amount of training and validation trajectories that are plotted", "name": "__init__", "signature": "def __init__(self, num_traj)" }, { "docstring": "Updates the trajectories that are plotted in the next call to plot. :param trajectories_in: The trajectories p...
3
stack_v2_sparse_classes_30k_train_013743
Implement the Python class `TrajectoryPlot` described below. Class description: Implement the TrajectoryPlot class. Method signatures and docstrings: - def __init__(self, num_traj): :param num_traj: The amount of training and validation trajectories that are plotted - def update_trajectories(self, trajectories_in: np...
Implement the Python class `TrajectoryPlot` described below. Class description: Implement the TrajectoryPlot class. Method signatures and docstrings: - def __init__(self, num_traj): :param num_traj: The amount of training and validation trajectories that are plotted - def update_trajectories(self, trajectories_in: np...
d07d1b0b54222f1b01624444591f2884b49462b0
<|skeleton|> class TrajectoryPlot: def __init__(self, num_traj): """:param num_traj: The amount of training and validation trajectories that are plotted""" <|body_0|> def update_trajectories(self, trajectories_in: np.ndarray, trajectories_out: np.ndarray, prediction_out: np.ndarray) -> None: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrajectoryPlot: def __init__(self, num_traj): """:param num_traj: The amount of training and validation trajectories that are plotted""" self.fig = plt.figure('Trajectories') self.ax_arr = [None] * (num_traj * 2) for k in range(num_traj * 2): num = 2 * 100 + num_tra...
the_stack_v2_python_sparse
src/plots/TrajectoryPlot.py
kosmitive/rnn-tetherball-dynamics
train
0
d0119e71b71fcb02867ef7f5013710853c1b6f41
[ "serialized_function = cloudpickle.dumps(function)\nself.mode = mode\nif mode == 'file':\n with tempfile.NamedTemporaryFile(delete=False) as f:\n f.write(serialized_function)\n self._cache_key = f.name\nelif mode == 'memory':\n self._cache_key = serialized_function\nelif mode == 'random_id':\n ...
<|body_start_0|> serialized_function = cloudpickle.dumps(function) self.mode = mode if mode == 'file': with tempfile.NamedTemporaryFile(delete=False) as f: f.write(serialized_function) self._cache_key = f.name elif mode == 'memory': ...
A wrapper to allow `cloudpickle.load`ed functions with `ProcessPoolExecutor`. A wrapper around a serialized function that handles deserialization and caches the deserialized function in the worker process. Parameters ---------- function The function to be serialized and wrapped. mode All of the options avoids sending t...
WrappedFunction
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WrappedFunction: """A wrapper to allow `cloudpickle.load`ed functions with `ProcessPoolExecutor`. A wrapper around a serialized function that handles deserialization and caches the deserialized function in the worker process. Parameters ---------- function The function to be serialized and wrappe...
stack_v2_sparse_classes_36k_train_033468
36,470
permissive
[ { "docstring": "Initialize WrappedFunction.", "name": "__init__", "signature": "def __init__(self, function: Callable[..., Any], *, mode: Literal['memory', 'random_id', 'file']='random_id') -> None" }, { "docstring": "Call the wrapped function. Retrieves the deserialized function from the global...
2
stack_v2_sparse_classes_30k_train_013165
Implement the Python class `WrappedFunction` described below. Class description: A wrapper to allow `cloudpickle.load`ed functions with `ProcessPoolExecutor`. A wrapper around a serialized function that handles deserialization and caches the deserialized function in the worker process. Parameters ---------- function T...
Implement the Python class `WrappedFunction` described below. Class description: A wrapper to allow `cloudpickle.load`ed functions with `ProcessPoolExecutor`. A wrapper around a serialized function that handles deserialization and caches the deserialized function in the worker process. Parameters ---------- function T...
75e83b9d645b03fe6c345e0cbedafb0b86a3568d
<|skeleton|> class WrappedFunction: """A wrapper to allow `cloudpickle.load`ed functions with `ProcessPoolExecutor`. A wrapper around a serialized function that handles deserialization and caches the deserialized function in the worker process. Parameters ---------- function The function to be serialized and wrappe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WrappedFunction: """A wrapper to allow `cloudpickle.load`ed functions with `ProcessPoolExecutor`. A wrapper around a serialized function that handles deserialization and caches the deserialized function in the worker process. Parameters ---------- function The function to be serialized and wrapped. mode All o...
the_stack_v2_python_sparse
adaptive_scheduler/utils.py
basnijholt/adaptive-scheduler
train
24
4d4e5337c55330fd7332f95f996fd795cdb63d52
[ "if not prices:\n return 0\nn = len(prices)\ndp = [[0] * 2 for _ in range(n)]\ndp[0][0] = 0\ndp[0][1] = -prices[0]\nfor i in range(1, n):\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])\n dp[i][1] = max(dp[i - 1][1], -prices[i])\nreturn dp[n - 1][0]", "if not prices:\n return 0\nn = len(price...
<|body_start_0|> if not prices: return 0 n = len(prices) dp = [[0] * 2 for _ in range(n)] dp[0][0] = 0 dp[0][1] = -prices[0] for i in range(1, n): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) dp[i][1] = max(dp[i - 1][1], -pric...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k_train_033469
1,963
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" }, { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" }, { "docstring": ":type prices: List[int...
4
stack_v2_sparse_classes_30k_train_014243
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: L...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: L...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" if not prices: return 0 n = len(prices) dp = [[0] * 2 for _ in range(n)] dp[0][0] = 0 dp[0][1] = -prices[0] for i in range(1, n): dp[i][0] = max(dp[i...
the_stack_v2_python_sparse
0121_Best_Time_to_Buy_and_Sell_Stock.py
bingli8802/leetcode
train
0
0d5ec1c2973d425d971a4623ee667629dfa88f0e
[ "assert loss_choice in ['joint', 'ctc']\nself.loss_choice = loss_choice\nif loss_choice == 'joint':\n self.xe_loss_fn = nn.CrossEntropyLoss(weights=ce_weights)\n self.ctc_loss_fn = CTCLoss()\nif loss_choice == 'ctc':\n self.ctc_loss_fn = CTCLoss()\nself.averaged = averaged", "if self.loss_choice == 'join...
<|body_start_0|> assert loss_choice in ['joint', 'ctc'] self.loss_choice = loss_choice if loss_choice == 'joint': self.xe_loss_fn = nn.CrossEntropyLoss(weights=ce_weights) self.ctc_loss_fn = CTCLoss() if loss_choice == 'ctc': self.ctc_loss_fn = CTCLoss...
Wrapper class for loss functions.
Loss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Loss: """Wrapper class for loss functions.""" def __init__(self, loss_choice, ce_weights=None, joint_balance=None, averaged=True): """Construct a loss function wrapper.""" <|body_0|> def calculate(self, signal, signal_pred, transcription_seq, target_seq, target_lengths):...
stack_v2_sparse_classes_36k_train_033470
2,637
no_license
[ { "docstring": "Construct a loss function wrapper.", "name": "__init__", "signature": "def __init__(self, loss_choice, ce_weights=None, joint_balance=None, averaged=True)" }, { "docstring": "Returns loss values after computing. If loss choice is 'joint', return a tuple `(xe_loss, ctc_loss)`. If ...
2
null
Implement the Python class `Loss` described below. Class description: Wrapper class for loss functions. Method signatures and docstrings: - def __init__(self, loss_choice, ce_weights=None, joint_balance=None, averaged=True): Construct a loss function wrapper. - def calculate(self, signal, signal_pred, transcription_s...
Implement the Python class `Loss` described below. Class description: Wrapper class for loss functions. Method signatures and docstrings: - def __init__(self, loss_choice, ce_weights=None, joint_balance=None, averaged=True): Construct a loss function wrapper. - def calculate(self, signal, signal_pred, transcription_s...
7ad943d9cc7a6872a14bba5239a99755f70db4cd
<|skeleton|> class Loss: """Wrapper class for loss functions.""" def __init__(self, loss_choice, ce_weights=None, joint_balance=None, averaged=True): """Construct a loss function wrapper.""" <|body_0|> def calculate(self, signal, signal_pred, transcription_seq, target_seq, target_lengths):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Loss: """Wrapper class for loss functions.""" def __init__(self, loss_choice, ce_weights=None, joint_balance=None, averaged=True): """Construct a loss function wrapper.""" assert loss_choice in ['joint', 'ctc'] self.loss_choice = loss_choice if loss_choice == 'joint': ...
the_stack_v2_python_sparse
Loss.py
paultsw/wavenet-speech
train
0
6b4e90c1c0ab2cabdea74d5c6b7f1d52a126cfcb
[ "if not self.burst_count:\n self.burst_count = dos.current_rate(self.principal.email, self.MAX_BURST_LIMIT, 60)\nif not self.daily_count:\n self.daily_count = dos.current_rate(self.principal.email, self.MAX_DAILY_LIMIT, 3600 * 24)\nreturn super(RateLimitMixin, self)._pre_put_hook()", "if super(RateLimitMixi...
<|body_start_0|> if not self.burst_count: self.burst_count = dos.current_rate(self.principal.email, self.MAX_BURST_LIMIT, 60) if not self.daily_count: self.daily_count = dos.current_rate(self.principal.email, self.MAX_DAILY_LIMIT, 3600 * 24) return super(RateLimitMixin, s...
A RateLimitMixin ensures that the given model will only be created a fixed number of times per minute. If the rate limit is violated, the entity is treated as though the principal creating it is unviolated. >>> from caravel.model.moderation import ModeratedMixin >>> from caravel.model.principal import PrincipalMixin >>...
RateLimitMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RateLimitMixin: """A RateLimitMixin ensures that the given model will only be created a fixed number of times per minute. If the rate limit is violated, the entity is treated as though the principal creating it is unviolated. >>> from caravel.model.moderation import ModeratedMixin >>> from carave...
stack_v2_sparse_classes_36k_train_033471
2,339
permissive
[ { "docstring": "Compute the current rate and store it in the burst/daily limits.", "name": "_pre_put_hook", "signature": "def _pre_put_hook(self)" }, { "docstring": "Ensure that listings must be manually approved.", "name": "approved", "signature": "def approved(self)" } ]
2
stack_v2_sparse_classes_30k_train_019589
Implement the Python class `RateLimitMixin` described below. Class description: A RateLimitMixin ensures that the given model will only be created a fixed number of times per minute. If the rate limit is violated, the entity is treated as though the principal creating it is unviolated. >>> from caravel.model.moderatio...
Implement the Python class `RateLimitMixin` described below. Class description: A RateLimitMixin ensures that the given model will only be created a fixed number of times per minute. If the rate limit is violated, the entity is treated as though the principal creating it is unviolated. >>> from caravel.model.moderatio...
375840db7fc1d2f00e986d305283dcc542592311
<|skeleton|> class RateLimitMixin: """A RateLimitMixin ensures that the given model will only be created a fixed number of times per minute. If the rate limit is violated, the entity is treated as though the principal creating it is unviolated. >>> from caravel.model.moderation import ModeratedMixin >>> from carave...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RateLimitMixin: """A RateLimitMixin ensures that the given model will only be created a fixed number of times per minute. If the rate limit is violated, the entity is treated as though the principal creating it is unviolated. >>> from caravel.model.moderation import ModeratedMixin >>> from caravel.model.princ...
the_stack_v2_python_sparse
caravel/model/rate_limits.py
uchicago-sg/caravel
train
17
4a0aa13bd980dbcbcb25f9e0977ba83b5eba7382
[ "res = [-1] * len(nums1)\nfor i, item in enumerate(nums1):\n if item in nums2:\n idx = nums2.index(item)\n next = idx + 1\n while next <= len(nums2) - 1:\n if item < nums2[next]:\n res[i] = nums2[next]\n break\n else:\n next ...
<|body_start_0|> res = [-1] * len(nums1) for i, item in enumerate(nums1): if item in nums2: idx = nums2.index(item) next = idx + 1 while next <= len(nums2) - 1: if item < nums2[next]: res[i] = nums2[n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def nextGreaterElement(self, nums1, nums2): """TC - O(m*n) Space Complexity - O(m)""" <|body_0|> def next_greater_elem_hash(self, nums1, nums2): """Time Complexity - O(m*n) Space Complexity - O(m+n)""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_033472
4,264
no_license
[ { "docstring": "TC - O(m*n) Space Complexity - O(m)", "name": "nextGreaterElement", "signature": "def nextGreaterElement(self, nums1, nums2)" }, { "docstring": "Time Complexity - O(m*n) Space Complexity - O(m+n)", "name": "next_greater_elem_hash", "signature": "def next_greater_elem_hash...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextGreaterElement(self, nums1, nums2): TC - O(m*n) Space Complexity - O(m) - def next_greater_elem_hash(self, nums1, nums2): Time Complexity - O(m*n) Space Complexity - O(m+...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextGreaterElement(self, nums1, nums2): TC - O(m*n) Space Complexity - O(m) - def next_greater_elem_hash(self, nums1, nums2): Time Complexity - O(m*n) Space Complexity - O(m+...
f51caae9b764837ff9107d8b3d116637cdc102b0
<|skeleton|> class Solution: def nextGreaterElement(self, nums1, nums2): """TC - O(m*n) Space Complexity - O(m)""" <|body_0|> def next_greater_elem_hash(self, nums1, nums2): """Time Complexity - O(m*n) Space Complexity - O(m+n)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def nextGreaterElement(self, nums1, nums2): """TC - O(m*n) Space Complexity - O(m)""" res = [-1] * len(nums1) for i, item in enumerate(nums1): if item in nums2: idx = nums2.index(item) next = idx + 1 while next <= le...
the_stack_v2_python_sparse
Leetcode/next_greater_element.py
madhuri-majety/IK
train
0
4f7fd58a1115af7eef8c88d59605bbdca1177874
[ "super(FeedForwardSiamese, self).__init__()\nself.linear1 = torch.nn.Linear(INPUT_DIM, args.ff_hidden_dim)\nself.linear2 = torch.nn.Linear(args.ff_hidden_dim, 1)\nself.relu = ReLU()\nself.sigmoid = Sigmoid()\nself.ff2 = torch.nn.Sequential(torch.nn.Linear(INPUT_DIM, args.ff_hidden_dim), ReLU(), torch.nn.Linear(args...
<|body_start_0|> super(FeedForwardSiamese, self).__init__() self.linear1 = torch.nn.Linear(INPUT_DIM, args.ff_hidden_dim) self.linear2 = torch.nn.Linear(args.ff_hidden_dim, 1) self.relu = ReLU() self.sigmoid = Sigmoid() self.ff2 = torch.nn.Sequential(torch.nn.Linear(INPUT...
FeedForwardSiamese
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeedForwardSiamese: def __init__(self, args): """In the constructor we instantiate two nn.Linear modules and assign them as member variables.""" <|body_0|> def forward(self, x1, x2): """In the forward function we accept a Tensor of input data and we must return a Ten...
stack_v2_sparse_classes_36k_train_033473
2,388
no_license
[ { "docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.", "name": "__init__", "signature": "def __init__(self, args)" }, { "docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We ca...
2
stack_v2_sparse_classes_30k_train_009055
Implement the Python class `FeedForwardSiamese` described below. Class description: Implement the FeedForwardSiamese class. Method signatures and docstrings: - def __init__(self, args): In the constructor we instantiate two nn.Linear modules and assign them as member variables. - def forward(self, x1, x2): In the for...
Implement the Python class `FeedForwardSiamese` described below. Class description: Implement the FeedForwardSiamese class. Method signatures and docstrings: - def __init__(self, args): In the constructor we instantiate two nn.Linear modules and assign them as member variables. - def forward(self, x1, x2): In the for...
c39a4145fa2f45d824f437193a59b1aa60c31f38
<|skeleton|> class FeedForwardSiamese: def __init__(self, args): """In the constructor we instantiate two nn.Linear modules and assign them as member variables.""" <|body_0|> def forward(self, x1, x2): """In the forward function we accept a Tensor of input data and we must return a Ten...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeedForwardSiamese: def __init__(self, args): """In the constructor we instantiate two nn.Linear modules and assign them as member variables.""" super(FeedForwardSiamese, self).__init__() self.linear1 = torch.nn.Linear(INPUT_DIM, args.ff_hidden_dim) self.linear2 = torch.nn.Line...
the_stack_v2_python_sparse
ML_Project_Template/ranking_model.py
saiful1105020/park_motor
train
1
1d8efd8103ca82623309c647404db76c406b5436
[ "q = [root]\nwhile q:\n pp = []\n node = q.pop(0)\n while node:\n if not node.left and node.right:\n return False\n Nochild = False\n if not node.right:\n if node.left:\n pp.append(node.left)\n Nochild = True\n else:\n i...
<|body_start_0|> q = [root] while q: pp = [] node = q.pop(0) while node: if not node.left and node.right: return False Nochild = False if not node.right: if node.left: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isCompleteTree(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isCompleteTree2(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> q = [root] while q: ...
stack_v2_sparse_classes_36k_train_033474
1,903
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isCompleteTree", "signature": "def isCompleteTree(self, root)" }, { "docstring": ":type root: TreeNode :rtype: bool", "name": "isCompleteTree2", "signature": "def isCompleteTree2(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_008740
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isCompleteTree(self, root): :type root: TreeNode :rtype: bool - def isCompleteTree2(self, root): :type root: TreeNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isCompleteTree(self, root): :type root: TreeNode :rtype: bool - def isCompleteTree2(self, root): :type root: TreeNode :rtype: bool <|skeleton|> class Solution: def isCo...
61966ef769b079024a6f72bcf608486343e033e6
<|skeleton|> class Solution: def isCompleteTree(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isCompleteTree2(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isCompleteTree(self, root): """:type root: TreeNode :rtype: bool""" q = [root] while q: pp = [] node = q.pop(0) while node: if not node.left and node.right: return False Nochild = Fals...
the_stack_v2_python_sparse
lintcode/P11.py
hanrick2000/coderunpython
train
0
b346509a2819d4df2dfcc90e6cf3a75349e614a8
[ "if type(tor_entries) is not list:\n raise ValueError('tor_entries has to be an array')\nfor tor_entry in tor_entries:\n if 'node_id' not in tor_entry:\n raise ValueError('tor_entries instances must have node_id')\n id = str(tor_entry['node_id'])\n vtep_cmd = cls.OVS_VTEP_BIN\n vtep_cmd = vtep...
<|body_start_0|> if type(tor_entries) is not list: raise ValueError('tor_entries has to be an array') for tor_entry in tor_entries: if 'node_id' not in tor_entry: raise ValueError('tor_entries instances must have node_id') id = str(tor_entry['node_id']...
Ubuntu1204ServiceImpl
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ubuntu1204ServiceImpl: def start_service(cls, client_object, service_name=None, tor_entries=None): """Starts ovs vtep service on torgateway. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type service_name: string @param service_name: name of se...
stack_v2_sparse_classes_36k_train_033475
2,432
no_license
[ { "docstring": "Starts ovs vtep service on torgateway. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type service_name: string @param service_name: name of service to be started @type tor_entries: list @param tor_entries: List of torswitch ids @rtype: NonType @return:...
2
null
Implement the Python class `Ubuntu1204ServiceImpl` described below. Class description: Implement the Ubuntu1204ServiceImpl class. Method signatures and docstrings: - def start_service(cls, client_object, service_name=None, tor_entries=None): Starts ovs vtep service on torgateway. @type client_object: BaseClient @para...
Implement the Python class `Ubuntu1204ServiceImpl` described below. Class description: Implement the Ubuntu1204ServiceImpl class. Method signatures and docstrings: - def start_service(cls, client_object, service_name=None, tor_entries=None): Starts ovs vtep service on torgateway. @type client_object: BaseClient @para...
5b55817c050b637e2747084290f6206d2e622938
<|skeleton|> class Ubuntu1204ServiceImpl: def start_service(cls, client_object, service_name=None, tor_entries=None): """Starts ovs vtep service on torgateway. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type service_name: string @param service_name: name of se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Ubuntu1204ServiceImpl: def start_service(cls, client_object, service_name=None, tor_entries=None): """Starts ovs vtep service on torgateway. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type service_name: string @param service_name: name of service to be st...
the_stack_v2_python_sparse
SystemTesting/pylib/vmware/torgateway/cmd/ubuntu1204_service_impl.py
Cloudxtreme/MyProject
train
0
a77178b6300f4d67a242e57599942c56d2c6956d
[ "self.num_features = num_features\nself.filter_func_list = filter_func_list\nself.word_pattern = re.compile('[a-z]{3,}')", "tf = self._countTermFrequency(raw_instance)\nfeatures = []\nfor word in self.order:\n if word in tf:\n features += [tf[word] * self.idf[word]]\n else:\n features += [0]\n...
<|body_start_0|> self.num_features = num_features self.filter_func_list = filter_func_list self.word_pattern = re.compile('[a-z]{3,}') <|end_body_0|> <|body_start_1|> tf = self._countTermFrequency(raw_instance) features = [] for word in self.order: if word in...
Extracts a bag of words representation with TFIDF scores from raw text.
BagOfWordsFiltered
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BagOfWordsFiltered: """Extracts a bag of words representation with TFIDF scores from raw text.""" def __init__(self, num_features, filter_func_list): """Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]""" ...
stack_v2_sparse_classes_36k_train_033476
4,111
no_license
[ { "docstring": "Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]", "name": "__init__", "signature": "def __init__(self, num_features, filter_func_list)" }, { "docstring": "Creates a new instance in the feature-space fr...
6
stack_v2_sparse_classes_30k_train_019278
Implement the Python class `BagOfWordsFiltered` described below. Class description: Extracts a bag of words representation with TFIDF scores from raw text. Method signatures and docstrings: - def __init__(self, num_features, filter_func_list): Constructor. @param num_features: The number of features to extract. @para...
Implement the Python class `BagOfWordsFiltered` described below. Class description: Extracts a bag of words representation with TFIDF scores from raw text. Method signatures and docstrings: - def __init__(self, num_features, filter_func_list): Constructor. @param num_features: The number of features to extract. @para...
fe417881ea523a64e9ab05b975b86cc3357835db
<|skeleton|> class BagOfWordsFiltered: """Extracts a bag of words representation with TFIDF scores from raw text.""" def __init__(self, num_features, filter_func_list): """Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BagOfWordsFiltered: """Extracts a bag of words representation with TFIDF scores from raw text.""" def __init__(self, num_features, filter_func_list): """Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]""" self.n...
the_stack_v2_python_sparse
src/s_bag_of_words.py
gzvulon/IAI3-LM
train
0
3a921b99d94ae16bcc8d48ef8b0666efe431a36d
[ "left = 1\nright = len(nums)\nwhile left < right:\n cnt = 0\n mid = (left + right) / 2\n for i in nums:\n if i <= mid:\n cnt += 1\n if cnt <= mid:\n left = mid + 1\n else:\n right = mid\nreturn right", "dic = dict(collections.Counter(nums))\nfor i, v in dic.items():\...
<|body_start_0|> left = 1 right = len(nums) while left < right: cnt = 0 mid = (left + right) / 2 for i in nums: if i <= mid: cnt += 1 if cnt <= mid: left = mid + 1 else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> left = 1 right = len(nums) ...
stack_v2_sparse_classes_36k_train_033477
1,037
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findDuplicate", "signature": "def findDuplicate(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "findDuplicate", "signature": "def findDuplicate(self, nums)" } ]
2
stack_v2_sparse_classes_30k_val_000780
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def findDuplicate(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def findDuplicate(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def findDup...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" left = 1 right = len(nums) while left < right: cnt = 0 mid = (left + right) / 2 for i in nums: if i <= mid: cnt += 1 ...
the_stack_v2_python_sparse
0287_Find_the_Duplicate_Number.py
bingli8802/leetcode
train
0
e37c7a2b403a5ea08a4c4dca7671bbb891921288
[ "super(EnhancedEmbedding, self).__init__()\nself.word_embedding = nn.Embedding(vocab_size, hidden_size)\nself.position_embedding = nn.Embedding(max_position_size, hidden_size)\nself.LayerNorm = LayerNorm(hidden_size)\nself.dropout = nn.Dropout(dropout_ratio)", "seq_len = input_id.size(1)\nposition_id = paddle.ara...
<|body_start_0|> super(EnhancedEmbedding, self).__init__() self.word_embedding = nn.Embedding(vocab_size, hidden_size) self.position_embedding = nn.Embedding(max_position_size, hidden_size) self.LayerNorm = LayerNorm(hidden_size) self.dropout = nn.Dropout(dropout_ratio) <|end_bod...
Enhanced Embeddings of drug, target
EnhancedEmbedding
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnhancedEmbedding: """Enhanced Embeddings of drug, target""" def __init__(self, vocab_size, hidden_size, max_position_size, dropout_ratio): """Initialization""" <|body_0|> def forward(self, input_id): """Embeddings""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_033478
12,741
permissive
[ { "docstring": "Initialization", "name": "__init__", "signature": "def __init__(self, vocab_size, hidden_size, max_position_size, dropout_ratio)" }, { "docstring": "Embeddings", "name": "forward", "signature": "def forward(self, input_id)" } ]
2
null
Implement the Python class `EnhancedEmbedding` described below. Class description: Enhanced Embeddings of drug, target Method signatures and docstrings: - def __init__(self, vocab_size, hidden_size, max_position_size, dropout_ratio): Initialization - def forward(self, input_id): Embeddings
Implement the Python class `EnhancedEmbedding` described below. Class description: Enhanced Embeddings of drug, target Method signatures and docstrings: - def __init__(self, vocab_size, hidden_size, max_position_size, dropout_ratio): Initialization - def forward(self, input_id): Embeddings <|skeleton|> class Enhance...
e6ab0261eb719c21806bbadfd94001ecfe27de45
<|skeleton|> class EnhancedEmbedding: """Enhanced Embeddings of drug, target""" def __init__(self, vocab_size, hidden_size, max_position_size, dropout_ratio): """Initialization""" <|body_0|> def forward(self, input_id): """Embeddings""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnhancedEmbedding: """Enhanced Embeddings of drug, target""" def __init__(self, vocab_size, hidden_size, max_position_size, dropout_ratio): """Initialization""" super(EnhancedEmbedding, self).__init__() self.word_embedding = nn.Embedding(vocab_size, hidden_size) self.posit...
the_stack_v2_python_sparse
apps/drug_target_interaction/moltrans_dti/double_towers.py
PaddlePaddle/PaddleHelix
train
771
8a15c5893c654c2b36786bb85c4c96552f3dd296
[ "actor = eventContext.event.actor\nif actor.HasField(type_id_field):\n if not (actor.HasField(identifier_field) and actor.HasField(uuid_field)):\n if actor.HasField(uuid_field):\n uuid = getattr(actor, uuid_field, None)\n element = evtProcessorManager.getElementByUuid(uuid)\n ...
<|body_start_0|> actor = eventContext.event.actor if actor.HasField(type_id_field): if not (actor.HasField(identifier_field) and actor.HasField(uuid_field)): if actor.HasField(uuid_field): uuid = getattr(actor, uuid_field, None) element...
BaseEventIdentifierPlugin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseEventIdentifierPlugin: def _resolveElement(self, evtProcessorManager, catalog, eventContext, type_id_field, identifier_field, uuid_field): """Lookup an element by identifier or uuid and make sure both identifier and uuid are set.""" <|body_0|> def resolveIdentifiers(self...
stack_v2_sparse_classes_36k_train_033479
35,633
no_license
[ { "docstring": "Lookup an element by identifier or uuid and make sure both identifier and uuid are set.", "name": "_resolveElement", "signature": "def _resolveElement(self, evtProcessorManager, catalog, eventContext, type_id_field, identifier_field, uuid_field)" }, { "docstring": "Update eventCo...
2
stack_v2_sparse_classes_30k_train_017930
Implement the Python class `BaseEventIdentifierPlugin` described below. Class description: Implement the BaseEventIdentifierPlugin class. Method signatures and docstrings: - def _resolveElement(self, evtProcessorManager, catalog, eventContext, type_id_field, identifier_field, uuid_field): Lookup an element by identif...
Implement the Python class `BaseEventIdentifierPlugin` described below. Class description: Implement the BaseEventIdentifierPlugin class. Method signatures and docstrings: - def _resolveElement(self, evtProcessorManager, catalog, eventContext, type_id_field, identifier_field, uuid_field): Lookup an element by identif...
1ea508c3d2b51742bc3b448c445cd0a3dba9e798
<|skeleton|> class BaseEventIdentifierPlugin: def _resolveElement(self, evtProcessorManager, catalog, eventContext, type_id_field, identifier_field, uuid_field): """Lookup an element by identifier or uuid and make sure both identifier and uuid are set.""" <|body_0|> def resolveIdentifiers(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseEventIdentifierPlugin: def _resolveElement(self, evtProcessorManager, catalog, eventContext, type_id_field, identifier_field, uuid_field): """Lookup an element by identifier or uuid and make sure both identifier and uuid are set.""" actor = eventContext.event.actor if actor.HasFiel...
the_stack_v2_python_sparse
Products/ZenEvents/events2/processing.py
zenoss/zenoss-prodbin
train
27
7da86e4b476d500aede58fa2e682b7fea9a8fd15
[ "super().setupUI(Form)\nself.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)\nself.label_4.setToolTip('')\nself.label_4.setAlignment(QtCore.Qt.AlignCenter)\nself.label_4.setObjectName('label_4')\nself.verticalLayout_2.addWidget(self.label_4)\nself.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)\nself.la...
<|body_start_0|> super().setupUI(Form) self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget) self.label_4.setToolTip('') self.label_4.setAlignment(QtCore.Qt.AlignCenter) self.label_4.setObjectName('label_4') self.verticalLayout_2.addWidget(self.label_4) self....
MVCWindowWidget
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MVCWindowWidget: def setupUi(self, Form): """Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)""" <|body_0|> def retranslateUi(sel...
stack_v2_sparse_classes_36k_train_033480
2,746
no_license
[ { "docstring": "Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)", "name": "setupUi", "signature": "def setupUi(self, Form)" }, { "docstring": "Método...
2
null
Implement the Python class `MVCWindowWidget` described below. Class description: Implement the MVCWindowWidget class. Method signatures and docstrings: - def setupUi(self, Form): Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la...
Implement the Python class `MVCWindowWidget` described below. Class description: Implement the MVCWindowWidget class. Method signatures and docstrings: - def setupUi(self, Form): Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la...
5d1d68fc4476ed866ecfc305112854d9a49c3876
<|skeleton|> class MVCWindowWidget: def setupUi(self, Form): """Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)""" <|body_0|> def retranslateUi(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MVCWindowWidget: def setupUi(self, Form): """Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)""" super().setupUI(Form) self.label_4 = QtWidg...
the_stack_v2_python_sparse
src/main/python/vistas/MVCWindowWidget.py
ProyectoIntegrador2018/reportes-neurociencias
train
1
20fa88941344e2835fa8e175a61cf16ba8c14d00
[ "self.flow = flow\nself.porosity = 0.92\nself.k_matrix = 0.0058\nself.PPI = 10.0\nself.k = self.k_matrix\nself.Nu_D = 4.93", "self.G = self.flow.rho * self.flow.velocity\nself.D_pore = 0.0122 * self.PPI ** (-0.849)\nself.Re_D = self.D_pore * self.G / (self.flow.mu * self.porosity)\nself.F = 1.765 * self.Re_D ** (...
<|body_start_0|> self.flow = flow self.porosity = 0.92 self.k_matrix = 0.0058 self.PPI = 10.0 self.k = self.k_matrix self.Nu_D = 4.93 <|end_body_0|> <|body_start_1|> self.G = self.flow.rho * self.flow.velocity self.D_pore = 0.0122 * self.PPI ** (-0.849) ...
Class for modeling porous media according to Mancin. Mancin, S., C. Zilio, A. Cavallini, and L. Rossetto. “Pressure Drop During Air Flow in Aluminum Foams.” International Journal of Heat and Mass Transfer 53, no. 15–16 (2010): 3121–3130. Methods: __init__ solve_enh
MancinPorous
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MancinPorous: """Class for modeling porous media according to Mancin. Mancin, S., C. Zilio, A. Cavallini, and L. Rossetto. “Pressure Drop During Air Flow in Aluminum Foams.” International Journal of Heat and Mass Transfer 53, no. 15–16 (2010): 3121–3130. Methods: __init__ solve_enh""" def __...
stack_v2_sparse_classes_36k_train_033481
15,856
no_license
[ { "docstring": "Sets constants.", "name": "__init__", "signature": "def __init__(self, flow)" }, { "docstring": "Solves for convection parameters with enhancement.", "name": "solve_enh", "signature": "def solve_enh(self)" } ]
2
null
Implement the Python class `MancinPorous` described below. Class description: Class for modeling porous media according to Mancin. Mancin, S., C. Zilio, A. Cavallini, and L. Rossetto. “Pressure Drop During Air Flow in Aluminum Foams.” International Journal of Heat and Mass Transfer 53, no. 15–16 (2010): 3121–3130. Met...
Implement the Python class `MancinPorous` described below. Class description: Class for modeling porous media according to Mancin. Mancin, S., C. Zilio, A. Cavallini, and L. Rossetto. “Pressure Drop During Air Flow in Aluminum Foams.” International Journal of Heat and Mass Transfer 53, no. 15–16 (2010): 3121–3130. Met...
d619b66b1f16557e06c94eee1c16d4ee2a9e896a
<|skeleton|> class MancinPorous: """Class for modeling porous media according to Mancin. Mancin, S., C. Zilio, A. Cavallini, and L. Rossetto. “Pressure Drop During Air Flow in Aluminum Foams.” International Journal of Heat and Mass Transfer 53, no. 15–16 (2010): 3121–3130. Methods: __init__ solve_enh""" def __...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MancinPorous: """Class for modeling porous media according to Mancin. Mancin, S., C. Zilio, A. Cavallini, and L. Rossetto. “Pressure Drop During Air Flow in Aluminum Foams.” International Journal of Heat and Mass Transfer 53, no. 15–16 (2010): 3121–3130. Methods: __init__ solve_enh""" def __init__(self, ...
the_stack_v2_python_sparse
Modules/enhancement.py
hfateh/TE_Model-1
train
0
18471895f6d7dd36b558eed15daf9a356edcb36c
[ "if is_datetime_type(obj):\n return convert_datetime_type(obj)\nif is_timedelta_type(obj):\n return convert_timedelta_type(obj)\nelif isinstance(obj, slice):\n return dict(start=obj.start, stop=obj.stop, step=obj.step)\nelif np.issubdtype(type(obj), np.floating):\n return float(obj)\nelif np.issubdtype(...
<|body_start_0|> if is_datetime_type(obj): return convert_datetime_type(obj) if is_timedelta_type(obj): return convert_timedelta_type(obj) elif isinstance(obj, slice): return dict(start=obj.start, stop=obj.stop, step=obj.step) elif np.issubdtype(type(o...
A custom ``json.JSONEncoder`` subclass for encoding objects in accordance with the BokehJS protocol.
BokehJSONEncoder
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BokehJSONEncoder: """A custom ``json.JSONEncoder`` subclass for encoding objects in accordance with the BokehJS protocol.""" def transform_python_types(self, obj): """Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object ...
stack_v2_sparse_classes_36k_train_033482
9,015
permissive
[ { "docstring": "Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.", "name": "transform_python_types", "signature": "def transfor...
2
null
Implement the Python class `BokehJSONEncoder` described below. Class description: A custom ``json.JSONEncoder`` subclass for encoding objects in accordance with the BokehJS protocol. Method signatures and docstrings: - def transform_python_types(self, obj): Handle special scalars such as (Python, NumPy, or Pandas) da...
Implement the Python class `BokehJSONEncoder` described below. Class description: A custom ``json.JSONEncoder`` subclass for encoding objects in accordance with the BokehJS protocol. Method signatures and docstrings: - def transform_python_types(self, obj): Handle special scalars such as (Python, NumPy, or Pandas) da...
1ad7ec05fb1e3676ac879585296c513c3ee50ef9
<|skeleton|> class BokehJSONEncoder: """A custom ``json.JSONEncoder`` subclass for encoding objects in accordance with the BokehJS protocol.""" def transform_python_types(self, obj): """Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BokehJSONEncoder: """A custom ``json.JSONEncoder`` subclass for encoding objects in accordance with the BokehJS protocol.""" def transform_python_types(self, obj): """Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object to encode. An...
the_stack_v2_python_sparse
Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/core/json_encoder.py
holzschu/Carnets
train
541
20ec1b0df243c6691540e6039a2c9ab99025b643
[ "t_argsTuples = []\nfor t_tuple in _cls_functorClass.getFunctorArgs():\n t_widgetArgs = copy.copy(t_tuple[_cls_functorClass.U_FUNC_ARG_KWARGS_INDEX])\n s_key = t_tuple[_cls_functorClass.U_FUNC_ARG_KEY_INDEX]\n s_label = t_widgetArgs.pop('_s_label')\n x_defaultValue = t_tuple[_cls_functorClass.U_FUNC_ARG...
<|body_start_0|> t_argsTuples = [] for t_tuple in _cls_functorClass.getFunctorArgs(): t_widgetArgs = copy.copy(t_tuple[_cls_functorClass.U_FUNC_ARG_KWARGS_INDEX]) s_key = t_tuple[_cls_functorClass.U_FUNC_ARG_KEY_INDEX] s_label = t_widgetArgs.pop('_s_label') ...
QArkFunctorFactory
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QArkFunctorFactory: def functorToWidget(cls, parent, _cls_functorClass, _o_vectorDataSet): """Construct a generic widget to enter the functor arguments @param _cls_functorClass : the functor class for which we want to generate a widget @param _x_data : the data on which we want the funct...
stack_v2_sparse_classes_36k_train_033483
6,171
permissive
[ { "docstring": "Construct a generic widget to enter the functor arguments @param _cls_functorClass : the functor class for which we want to generate a widget @param _x_data : the data on which we want the functor to be applied", "name": "functorToWidget", "signature": "def functorToWidget(cls, parent, _...
2
null
Implement the Python class `QArkFunctorFactory` described below. Class description: Implement the QArkFunctorFactory class. Method signatures and docstrings: - def functorToWidget(cls, parent, _cls_functorClass, _o_vectorDataSet): Construct a generic widget to enter the functor arguments @param _cls_functorClass : th...
Implement the Python class `QArkFunctorFactory` described below. Class description: Implement the QArkFunctorFactory class. Method signatures and docstrings: - def functorToWidget(cls, parent, _cls_functorClass, _o_vectorDataSet): Construct a generic widget to enter the functor arguments @param _cls_functorClass : th...
46e03095028d2a2f153959d910ceab06a633223d
<|skeleton|> class QArkFunctorFactory: def functorToWidget(cls, parent, _cls_functorClass, _o_vectorDataSet): """Construct a generic widget to enter the functor arguments @param _cls_functorClass : the functor class for which we want to generate a widget @param _x_data : the data on which we want the funct...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QArkFunctorFactory: def functorToWidget(cls, parent, _cls_functorClass, _o_vectorDataSet): """Construct a generic widget to enter the functor arguments @param _cls_functorClass : the functor class for which we want to generate a widget @param _x_data : the data on which we want the functor to be appli...
the_stack_v2_python_sparse
src/pyQArk/Core/QArkFunctorFactory.py
arnaudkelbert/pyQArk
train
1
bc07131ea149006a74120c4bfb2dedbaef8abd60
[ "try:\n for field in dataclasses.fields(self):\n setattr(self, field.name, field.type(env_file))\nexcept ValidationError as err:\n config_field = None\n first_error = err.errors()[0]\n loc: str = first_error['loc'][0]\n if loc != '__root__':\n settings_model = cast(BaseSettings, err.mod...
<|body_start_0|> try: for field in dataclasses.fields(self): setattr(self, field.name, field.type(env_file)) except ValidationError as err: config_field = None first_error = err.errors()[0] loc: str = first_error['loc'][0] if lo...
Globally manage environment variables configuration options.
Settings
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Settings: """Globally manage environment variables configuration options.""" def __init__(self, env_file: Optional[Path]=None) -> None: """Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configura...
stack_v2_sparse_classes_36k_train_033484
6,638
permissive
[ { "docstring": "Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configuration option is not valid.", "name": "__init__", "signature": "def __init__(self, env_file: Optional[Path]=None) -> None" }, { "docstrin...
2
stack_v2_sparse_classes_30k_train_021092
Implement the Python class `Settings` described below. Class description: Globally manage environment variables configuration options. Method signatures and docstrings: - def __init__(self, env_file: Optional[Path]=None) -> None: Checks the validity of each configuration option. Args: env_file: Path to a file definin...
Implement the Python class `Settings` described below. Class description: Globally manage environment variables configuration options. Method signatures and docstrings: - def __init__(self, env_file: Optional[Path]=None) -> None: Checks the validity of each configuration option. Args: env_file: Path to a file definin...
9e3370a7656b415058acf2d39a690a72f6eb343f
<|skeleton|> class Settings: """Globally manage environment variables configuration options.""" def __init__(self, env_file: Optional[Path]=None) -> None: """Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configura...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Settings: """Globally manage environment variables configuration options.""" def __init__(self, env_file: Optional[Path]=None) -> None: """Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configuration option i...
the_stack_v2_python_sparse
src/opcua_webhmi_bridge/config.py
renovate-tests/opcua-webhmi-bridge
train
0
19f1fd2f3ffb66de5e6afa4b04cfb09280008422
[ "ngram2count = dict()\ntokens = re.split('\\\\s', text)\nfor order in range(startOrder, maxOrder + 1):\n for token in tokens:\n token = '_' + token + '_'\n for i in range(len(token) - order + 1):\n ngram = token[i:i + order]\n if not cls.NGRAM_PATTERN.match(ngram):\n ...
<|body_start_0|> ngram2count = dict() tokens = re.split('\\s', text) for order in range(startOrder, maxOrder + 1): for token in tokens: token = '_' + token + '_' for i in range(len(token) - order + 1): ngram = token[i:i + order] ...
Some convenient string utilities.
SimilarityUtils
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimilarityUtils: """Some convenient string utilities.""" def computeNGrams(cls, startOrder, maxOrder, text): """Compute N Grams. @param startOrder @param maxOrder @param text @return a n gram to frequency map.""" <|body_0|> def computeWord2count(text): """Calcula...
stack_v2_sparse_classes_36k_train_033485
4,522
no_license
[ { "docstring": "Compute N Grams. @param startOrder @param maxOrder @param text @return a n gram to frequency map.", "name": "computeNGrams", "signature": "def computeNGrams(cls, startOrder, maxOrder, text)" }, { "docstring": "Calculate word frequency. @param text a text to process @return a map ...
6
null
Implement the Python class `SimilarityUtils` described below. Class description: Some convenient string utilities. Method signatures and docstrings: - def computeNGrams(cls, startOrder, maxOrder, text): Compute N Grams. @param startOrder @param maxOrder @param text @return a n gram to frequency map. - def computeWord...
Implement the Python class `SimilarityUtils` described below. Class description: Some convenient string utilities. Method signatures and docstrings: - def computeNGrams(cls, startOrder, maxOrder, text): Compute N Grams. @param startOrder @param maxOrder @param text @return a n gram to frequency map. - def computeWord...
58e12957dee8b4b18127df9daeb8825d8ada7923
<|skeleton|> class SimilarityUtils: """Some convenient string utilities.""" def computeNGrams(cls, startOrder, maxOrder, text): """Compute N Grams. @param startOrder @param maxOrder @param text @return a n gram to frequency map.""" <|body_0|> def computeWord2count(text): """Calcula...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimilarityUtils: """Some convenient string utilities.""" def computeNGrams(cls, startOrder, maxOrder, text): """Compute N Grams. @param startOrder @param maxOrder @param text @return a n gram to frequency map.""" ngram2count = dict() tokens = re.split('\\s', text) for orde...
the_stack_v2_python_sparse
parser/util/SimilarityUtils.py
oldeucryptoboi/wiktionary-parser
train
0
256ee79fc966263956ee2c6585826fefd470393a
[ "self.head = head\nself.count = 0\nslow = head\nfast = head\nwhile fast != None and fast.next != None:\n self.count += 1\n slow = slow.next\n fast = fast.next.next\nelse:\n self.count *= 2\n if fast != None:\n self.count += 1\nself.mid = slow", "import random\nrand = random.randint(0, self.c...
<|body_start_0|> self.head = head self.count = 0 slow = head fast = head while fast != None and fast.next != None: self.count += 1 slow = slow.next fast = fast.next.next else: self.count *= 2 if fast != None: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def __init__(self, head): """@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode""" <|body_0|> def getRandom(self): """Returns a random node's value. :rtype: int""" ...
stack_v2_sparse_classes_36k_train_033486
1,453
permissive
[ { "docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode", "name": "__init__", "signature": "def __init__(self, head)" }, { "docstring": "Returns a random node's value. :rtype: int", "name": "g...
2
stack_v2_sparse_classes_30k_train_006786
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode - def getRan...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode - def getRan...
48454a8e6b5b86f80e89eca1b396480df8960cfd
<|skeleton|> class Solution: def __init__(self, head): """@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode""" <|body_0|> def getRandom(self): """Returns a random node's value. :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def __init__(self, head): """@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode""" self.head = head self.count = 0 slow = head fast = head while fast != None and f...
the_stack_v2_python_sparse
leetcode/medium/linked_list_random_node/py/solution.py
lilsweetcaligula/sandbox-online-judges
train
0
52199d5344bb74983cb53ee0493b9ae79490b3d4
[ "username = request.user.get_username()\nserializer = CollaboratorSerializer(username=username, repo_base=repo_base, request=request)\ncollaborators = serializer.list_collaborators(repo_name)\nreturn Response(collaborators, status=status.HTTP_200_OK)", "username = request.user.get_username()\nserializer = Collabo...
<|body_start_0|> username = request.user.get_username() serializer = CollaboratorSerializer(username=username, repo_base=repo_base, request=request) collaborators = serializer.list_collaborators(repo_name) return Response(collaborators, status=status.HTTP_200_OK) <|end_body_0|> <|body_s...
List and create collaborators. GET to list the collaborators. Accepts: None --- POST to add a collaborator. Accepts: { "user":, "permissions": []} e.g. {"user":"foo_user", "permissions": ['SELECT', 'INSERT', 'UPDATE']}
Collaborators
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Collaborators: """List and create collaborators. GET to list the collaborators. Accepts: None --- POST to add a collaborator. Accepts: { "user":, "permissions": []} e.g. {"user":"foo_user", "permissions": ['SELECT', 'INSERT', 'UPDATE']}""" def get(self, request, repo_base, repo_name, format=...
stack_v2_sparse_classes_36k_train_033487
31,465
permissive
[ { "docstring": "Collaborators in a repo", "name": "get", "signature": "def get(self, request, repo_base, repo_name, format=None)" }, { "docstring": "Add a collaborator to a repo --- omit_serializer: true parameters: - name: user in: body type: string description: user to be added as a collaborat...
2
stack_v2_sparse_classes_30k_train_008413
Implement the Python class `Collaborators` described below. Class description: List and create collaborators. GET to list the collaborators. Accepts: None --- POST to add a collaborator. Accepts: { "user":, "permissions": []} e.g. {"user":"foo_user", "permissions": ['SELECT', 'INSERT', 'UPDATE']} Method signatures an...
Implement the Python class `Collaborators` described below. Class description: List and create collaborators. GET to list the collaborators. Accepts: None --- POST to add a collaborator. Accepts: { "user":, "permissions": []} e.g. {"user":"foo_user", "permissions": ['SELECT', 'INSERT', 'UPDATE']} Method signatures an...
f066b472c2b66cc3b868bbe433aed2d4557aea32
<|skeleton|> class Collaborators: """List and create collaborators. GET to list the collaborators. Accepts: None --- POST to add a collaborator. Accepts: { "user":, "permissions": []} e.g. {"user":"foo_user", "permissions": ['SELECT', 'INSERT', 'UPDATE']}""" def get(self, request, repo_base, repo_name, format=...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Collaborators: """List and create collaborators. GET to list the collaborators. Accepts: None --- POST to add a collaborator. Accepts: { "user":, "permissions": []} e.g. {"user":"foo_user", "permissions": ['SELECT', 'INSERT', 'UPDATE']}""" def get(self, request, repo_base, repo_name, format=None): ...
the_stack_v2_python_sparse
src/api/views.py
datahuborg/datahub
train
199
f95a7d3aa143bdedb97a0e62a5a21d23d8138c8d
[ "cmd = NodeController.MULTICHAIN_D_ARG + [admin_node_address]\ntry:\n output = run(cmd, capture_output=True, check=True)\n return re.findall('(?<=grant )(.*)(?= connect\\\\\\\\n)', str(output.stdout.strip()))[0]\nexcept CalledProcessError as err:\n raise MultiChainError(err.stderr)\nexcept Exception as err...
<|body_start_0|> cmd = NodeController.MULTICHAIN_D_ARG + [admin_node_address] try: output = run(cmd, capture_output=True, check=True) return re.findall('(?<=grant )(.*)(?= connect\\\\n)', str(output.stdout.strip()))[0] except CalledProcessError as err: raise M...
NodeController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodeController: def connect_to_admin_node(admin_node_address: str): """Initializes the connection between the current node and the admin :param admin_node_address: Node address of the admin node If successful, it returns a wallet address, which must used on the admin node to verify""" ...
stack_v2_sparse_classes_36k_train_033488
1,918
permissive
[ { "docstring": "Initializes the connection between the current node and the admin :param admin_node_address: Node address of the admin node If successful, it returns a wallet address, which must used on the admin node to verify", "name": "connect_to_admin_node", "signature": "def connect_to_admin_node(a...
2
stack_v2_sparse_classes_30k_train_011380
Implement the Python class `NodeController` described below. Class description: Implement the NodeController class. Method signatures and docstrings: - def connect_to_admin_node(admin_node_address: str): Initializes the connection between the current node and the admin :param admin_node_address: Node address of the a...
Implement the Python class `NodeController` described below. Class description: Implement the NodeController class. Method signatures and docstrings: - def connect_to_admin_node(admin_node_address: str): Initializes the connection between the current node and the admin :param admin_node_address: Node address of the a...
6be199fcaf836415b7d32ffb2cee911a9d600395
<|skeleton|> class NodeController: def connect_to_admin_node(admin_node_address: str): """Initializes the connection between the current node and the admin :param admin_node_address: Node address of the admin node If successful, it returns a wallet address, which must used on the admin node to verify""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NodeController: def connect_to_admin_node(admin_node_address: str): """Initializes the connection between the current node and the admin :param admin_node_address: Node address of the admin node If successful, it returns a wallet address, which must used on the admin node to verify""" cmd = No...
the_stack_v2_python_sparse
app/models/node/node_controller.py
talos-org/server
train
1
ca0ac5df2395bd27181475bf718f2ab609a0e096
[ "super().__init__('human_model_generation_client')\nself.bridge_cv = CvBridge()\nself.bridge_ros = ROS2Bridge()\nself.cli = self.create_client(ImgToMesh, service_name)\nwhile not self.cli.wait_for_service(timeout_sec=1.0):\n self.get_logger().info('service not available, waiting again...')\nself.req = ImgToMesh....
<|body_start_0|> super().__init__('human_model_generation_client') self.bridge_cv = CvBridge() self.bridge_ros = ROS2Bridge() self.cli = self.create_client(ImgToMesh, service_name) while not self.cli.wait_for_service(timeout_sec=1.0): self.get_logger().info('service n...
HumanModelGenerationClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HumanModelGenerationClient: def __init__(self, service_name='human_model_generation'): """Creates a ROS Client for human model generation :param service_name: The name of the service :type service_name: str""" <|body_0|> def send_request(self, img_rgb, img_msk, extract_pose)...
stack_v2_sparse_classes_36k_train_033489
5,361
permissive
[ { "docstring": "Creates a ROS Client for human model generation :param service_name: The name of the service :type service_name: str", "name": "__init__", "signature": "def __init__(self, service_name='human_model_generation')" }, { "docstring": "Send request to service assigned with the task to...
2
stack_v2_sparse_classes_30k_train_011613
Implement the Python class `HumanModelGenerationClient` described below. Class description: Implement the HumanModelGenerationClient class. Method signatures and docstrings: - def __init__(self, service_name='human_model_generation'): Creates a ROS Client for human model generation :param service_name: The name of th...
Implement the Python class `HumanModelGenerationClient` described below. Class description: Implement the HumanModelGenerationClient class. Method signatures and docstrings: - def __init__(self, service_name='human_model_generation'): Creates a ROS Client for human model generation :param service_name: The name of th...
b3d6ce670cdf63469fc5766630eb295d67b3d788
<|skeleton|> class HumanModelGenerationClient: def __init__(self, service_name='human_model_generation'): """Creates a ROS Client for human model generation :param service_name: The name of the service :type service_name: str""" <|body_0|> def send_request(self, img_rgb, img_msk, extract_pose)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HumanModelGenerationClient: def __init__(self, service_name='human_model_generation'): """Creates a ROS Client for human model generation :param service_name: The name of the service :type service_name: str""" super().__init__('human_model_generation_client') self.bridge_cv = CvBridge(...
the_stack_v2_python_sparse
projects/opendr_ws_2/src/opendr_simulation/opendr_simulation/human_model_generation_client.py
opendr-eu/opendr
train
535
4c9b987a23474eafe4ebcf335aa9b4ff6cdee589
[ "item_links = response.css(\"a[itemprop='url']::attr(href)\").extract()\nitem_links = map(lambda link: link + '.json', item_links)\nyield from response.follow_all(item_links, self.parse_details)\nnext_page = response.css(\"span[class='next'] > a::attr(href)\").get()\nif next_page is not None:\n next_page = respo...
<|body_start_0|> item_links = response.css("a[itemprop='url']::attr(href)").extract() item_links = map(lambda link: link + '.json', item_links) yield from response.follow_all(item_links, self.parse_details) next_page = response.css("span[class='next'] > a::attr(href)").get() if n...
BazicSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BazicSpider: def parse(self, response, **kwargs): """This function should extract and loop item urls. @url https://www.bazicstore.com/collections/all @returns items 0 @returns requests 48 @request https://www.bazicstore.com/collections/all/products/575.json""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_033490
2,293
no_license
[ { "docstring": "This function should extract and loop item urls. @url https://www.bazicstore.com/collections/all @returns items 0 @returns requests 48 @request https://www.bazicstore.com/collections/all/products/575.json", "name": "parse", "signature": "def parse(self, response, **kwargs)" }, { ...
2
null
Implement the Python class `BazicSpider` described below. Class description: Implement the BazicSpider class. Method signatures and docstrings: - def parse(self, response, **kwargs): This function should extract and loop item urls. @url https://www.bazicstore.com/collections/all @returns items 0 @returns requests 48 ...
Implement the Python class `BazicSpider` described below. Class description: Implement the BazicSpider class. Method signatures and docstrings: - def parse(self, response, **kwargs): This function should extract and loop item urls. @url https://www.bazicstore.com/collections/all @returns items 0 @returns requests 48 ...
025babe4a03553d720806828f89929c6e773d683
<|skeleton|> class BazicSpider: def parse(self, response, **kwargs): """This function should extract and loop item urls. @url https://www.bazicstore.com/collections/all @returns items 0 @returns requests 48 @request https://www.bazicstore.com/collections/all/products/575.json""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BazicSpider: def parse(self, response, **kwargs): """This function should extract and loop item urls. @url https://www.bazicstore.com/collections/all @returns items 0 @returns requests 48 @request https://www.bazicstore.com/collections/all/products/575.json""" item_links = response.css("a[item...
the_stack_v2_python_sparse
data_scraping/gmd/spiders/bazic.py
panky2202/scrapy-dev
train
1
8134be26b083bea97f14a1f9d00d6aa12556a004
[ "super(ConvolutionModule, self).__init__()\nassert (kernel_size - 1) % 2 == 0\nself.pointwise_conv1 = nn.Conv1d(channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias)\nself.depthwise_conv = nn.Conv1d(channels, channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2, groups=channels, bias=bia...
<|body_start_0|> super(ConvolutionModule, self).__init__() assert (kernel_size - 1) % 2 == 0 self.pointwise_conv1 = nn.Conv1d(channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias) self.depthwise_conv = nn.Conv1d(channels, channels, kernel_size, stride=1, padding=(kernel_...
ConvolutionModule in Conformer model. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernerl size of conv layers.
ConvolutionModule
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvolutionModule: """ConvolutionModule in Conformer model. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernerl size of conv layers.""" def __init__(self, channels, kernel_size, activation=nn.ReLU(), bias=True): """Construct an ConvolutionModule ob...
stack_v2_sparse_classes_36k_train_033491
37,737
permissive
[ { "docstring": "Construct an ConvolutionModule object.", "name": "__init__", "signature": "def __init__(self, channels, kernel_size, activation=nn.ReLU(), bias=True)" }, { "docstring": "Compute convolution module. Args: x (torch.Tensor): Input tensor (#batch, time, channels). Returns: torch.Tens...
2
null
Implement the Python class `ConvolutionModule` described below. Class description: ConvolutionModule in Conformer model. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernerl size of conv layers. Method signatures and docstrings: - def __init__(self, channels, kernel_size, activation...
Implement the Python class `ConvolutionModule` described below. Class description: ConvolutionModule in Conformer model. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernerl size of conv layers. Method signatures and docstrings: - def __init__(self, channels, kernel_size, activation...
31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39
<|skeleton|> class ConvolutionModule: """ConvolutionModule in Conformer model. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernerl size of conv layers.""" def __init__(self, channels, kernel_size, activation=nn.ReLU(), bias=True): """Construct an ConvolutionModule ob...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConvolutionModule: """ConvolutionModule in Conformer model. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernerl size of conv layers.""" def __init__(self, channels, kernel_size, activation=nn.ReLU(), bias=True): """Construct an ConvolutionModule object.""" ...
the_stack_v2_python_sparse
SVS/model/layers/conformer_related.py
SJTMusicTeam/SVS_system
train
85
54a1639ec9a99a0d06f7989d11bc3a6715502a5e
[ "super().__init__()\nself.class_dim = class_dim\nself.mode = mode\nif self.mode == 'weighted':\n assert weights is not None\n self.weights = torch.Tensor(weights)\nself.eps = eps", "n_dims = len(outputs_shape)\ndims = list(range(n_dims))\nif self.class_dim < 0:\n self.class_dim = n_dims + self.class_dim\...
<|body_start_0|> super().__init__() self.class_dim = class_dim self.mode = mode if self.mode == 'weighted': assert weights is not None self.weights = torch.Tensor(weights) self.eps = eps <|end_body_0|> <|body_start_1|> n_dims = len(outputs_shape) ...
The Smoothing Dice loss. ``SmoothingDiceloss = 1 - smoothing dice score`` ``smoothing dice score = 2 * intersection / (|outputs|^2 + |targets|^2)`` Criterion was inspired by https://arxiv.org/abs/1606.04797 Examples: >>> import torch >>> from catalyst.contrib.losses import SmoothingDiceLoss >>> targets = torch.abs(torc...
SmoothingDiceLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmoothingDiceLoss: """The Smoothing Dice loss. ``SmoothingDiceloss = 1 - smoothing dice score`` ``smoothing dice score = 2 * intersection / (|outputs|^2 + |targets|^2)`` Criterion was inspired by https://arxiv.org/abs/1606.04797 Examples: >>> import torch >>> from catalyst.contrib.losses import S...
stack_v2_sparse_classes_36k_train_033492
3,456
permissive
[ { "docstring": "Args: class_dim: indicates class dimention (K) for ``outputs`` and ``targets`` tensors (default = 1) mode: class summation strategy. Must be one of ['micro', 'macro', 'weighted']. If mode='micro', classes are ignored, and metric are calculated generally. If mode='macro', metric are calculated pe...
3
null
Implement the Python class `SmoothingDiceLoss` described below. Class description: The Smoothing Dice loss. ``SmoothingDiceloss = 1 - smoothing dice score`` ``smoothing dice score = 2 * intersection / (|outputs|^2 + |targets|^2)`` Criterion was inspired by https://arxiv.org/abs/1606.04797 Examples: >>> import torch >>...
Implement the Python class `SmoothingDiceLoss` described below. Class description: The Smoothing Dice loss. ``SmoothingDiceloss = 1 - smoothing dice score`` ``smoothing dice score = 2 * intersection / (|outputs|^2 + |targets|^2)`` Criterion was inspired by https://arxiv.org/abs/1606.04797 Examples: >>> import torch >>...
e99f90655d0efcf22559a46e928f0f98c9807ebf
<|skeleton|> class SmoothingDiceLoss: """The Smoothing Dice loss. ``SmoothingDiceloss = 1 - smoothing dice score`` ``smoothing dice score = 2 * intersection / (|outputs|^2 + |targets|^2)`` Criterion was inspired by https://arxiv.org/abs/1606.04797 Examples: >>> import torch >>> from catalyst.contrib.losses import S...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SmoothingDiceLoss: """The Smoothing Dice loss. ``SmoothingDiceloss = 1 - smoothing dice score`` ``smoothing dice score = 2 * intersection / (|outputs|^2 + |targets|^2)`` Criterion was inspired by https://arxiv.org/abs/1606.04797 Examples: >>> import torch >>> from catalyst.contrib.losses import SmoothingDiceL...
the_stack_v2_python_sparse
catalyst/contrib/losses/smoothing_dice.py
catalyst-team/catalyst
train
3,038
81352ea0d3000a27e1b9bcc2e81f4be3679a1305
[ "stack = []\nres = []\nfor i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n elif stack:\n res.append(stack.pop())\n res.append(i)\nres.sort()\nmax_len, i = (0, 0)\nwhile i < len(res) - 1:\n tmp = i\n while i < len(res) - 1 and res[i + 1] - res[i] == 1:\n i += 1\n ...
<|body_start_0|> stack = [] res = [] for i in range(len(s)): if s[i] == '(': stack.append(i) elif stack: res.append(stack.pop()) res.append(i) res.sort() max_len, i = (0, 0) while i < len(res) - 1: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestValidParentheses(self, s: str) -> int: """:param s: :return: 栈+排序 索引索引索引 利用栈stack存放左括号索引,进行配对 配对成功索引的放入res列表中, 对列表进行排序后寻找最长的连续 时间复杂度:O(nlog(n)),括号匹配O(n),排序复杂度O(nlog(n)), 寻找最长连续子序列O(n),总体O(nlog(n)) 空间复杂度:O(n)""" <|body_0|> def longestValidParentheses2(sel...
stack_v2_sparse_classes_36k_train_033493
3,419
no_license
[ { "docstring": ":param s: :return: 栈+排序 索引索引索引 利用栈stack存放左括号索引,进行配对 配对成功索引的放入res列表中, 对列表进行排序后寻找最长的连续 时间复杂度:O(nlog(n)),括号匹配O(n),排序复杂度O(nlog(n)), 寻找最长连续子序列O(n),总体O(nlog(n)) 空间复杂度:O(n)", "name": "longestValidParentheses", "signature": "def longestValidParentheses(self, s: str) -> int" }, { "docstri...
3
stack_v2_sparse_classes_30k_train_003183
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s: str) -> int: :param s: :return: 栈+排序 索引索引索引 利用栈stack存放左括号索引,进行配对 配对成功索引的放入res列表中, 对列表进行排序后寻找最长的连续 时间复杂度:O(nlog(n)),括号匹配O(n),排序复杂度O(nlog(n)), ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s: str) -> int: :param s: :return: 栈+排序 索引索引索引 利用栈stack存放左括号索引,进行配对 配对成功索引的放入res列表中, 对列表进行排序后寻找最长的连续 时间复杂度:O(nlog(n)),括号匹配O(n),排序复杂度O(nlog(n)), ...
65e260f0b5b396ecfc235a924c6861893c268272
<|skeleton|> class Solution: def longestValidParentheses(self, s: str) -> int: """:param s: :return: 栈+排序 索引索引索引 利用栈stack存放左括号索引,进行配对 配对成功索引的放入res列表中, 对列表进行排序后寻找最长的连续 时间复杂度:O(nlog(n)),括号匹配O(n),排序复杂度O(nlog(n)), 寻找最长连续子序列O(n),总体O(nlog(n)) 空间复杂度:O(n)""" <|body_0|> def longestValidParentheses2(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestValidParentheses(self, s: str) -> int: """:param s: :return: 栈+排序 索引索引索引 利用栈stack存放左括号索引,进行配对 配对成功索引的放入res列表中, 对列表进行排序后寻找最长的连续 时间复杂度:O(nlog(n)),括号匹配O(n),排序复杂度O(nlog(n)), 寻找最长连续子序列O(n),总体O(nlog(n)) 空间复杂度:O(n)""" stack = [] res = [] for i in range(len(s)): ...
the_stack_v2_python_sparse
leetcode/032_longestValid.py
CKZfd/LeetCode
train
1
c1a88f411645e2bf0ff79f37e8a793e670cd24df
[ "if grid[0][0] == 1 or grid[-1][-1] == 1 or (not grid):\n return -1\nqueue = [(0, 0, 1)]\ngrid[0][0] = 1\nn = len(grid)\nif n == 1:\n return 1\ndirections = [(-1, 0), (1, 0), (0, -1), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)]\nwhile len(queue) > 0:\n size = len(queue)\n for k in range(size):\n ...
<|body_start_0|> if grid[0][0] == 1 or grid[-1][-1] == 1 or (not grid): return -1 queue = [(0, 0, 1)] grid[0][0] = 1 n = len(grid) if n == 1: return 1 directions = [(-1, 0), (1, 0), (0, -1), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)] while...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def shortestPathBinaryMatrix_standard(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def shortestPathBinaryMatrix(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_033494
4,024
no_license
[ { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "shortestPathBinaryMatrix_standard", "signature": "def shortestPathBinaryMatrix_standard(self, grid)" }, { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "shortestPathBinaryMatrix", "signature": "def short...
2
stack_v2_sparse_classes_30k_train_000284
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def shortestPathBinaryMatrix_standard(self, grid): :type grid: List[List[int]] :rtype: int - def shortestPathBinaryMatrix(self, grid): :type grid: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def shortestPathBinaryMatrix_standard(self, grid): :type grid: List[List[int]] :rtype: int - def shortestPathBinaryMatrix(self, grid): :type grid: List[List[int]] :rtype: int <|...
d36655924edb9e364c956f912ba4797fb962be7e
<|skeleton|> class Solution: def shortestPathBinaryMatrix_standard(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def shortestPathBinaryMatrix(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def shortestPathBinaryMatrix_standard(self, grid): """:type grid: List[List[int]] :rtype: int""" if grid[0][0] == 1 or grid[-1][-1] == 1 or (not grid): return -1 queue = [(0, 0, 1)] grid[0][0] = 1 n = len(grid) if n == 1: return...
the_stack_v2_python_sparse
1091.BfsShortestPath.py
casssie-zhang/LeetcodeNotes
train
2
c2559715a8277a67a112867422bc740d5058d60c
[ "if cache_root and (not supports_cache_root(model)):\n warnings.warn(_get_cache_root_not_supported_message(type(model)), RuntimeWarning)\n cache_root = False\nself._cache_root = cache_root", "if isinstance(posterior.distribution, MultitaskMultivariateNormal):\n lazy_covar = extract_batch_covar(posterior....
<|body_start_0|> if cache_root and (not supports_cache_root(model)): warnings.warn(_get_cache_root_not_supported_message(type(model)), RuntimeWarning) cache_root = False self._cache_root = cache_root <|end_body_0|> <|body_start_1|> if isinstance(posterior.distribution, M...
Abstract class for acquisition functions using a cached Cholesky. Specifically, this is for acquisition functions that require sampling from the posterior P(f(X_baseline, X) | D). The Cholesky of the posterior covariance over f(X_baseline) is cached. :meta private:
CachedCholeskyMCAcquisitionFunction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CachedCholeskyMCAcquisitionFunction: """Abstract class for acquisition functions using a cached Cholesky. Specifically, this is for acquisition functions that require sampling from the posterior P(f(X_baseline, X) | D). The Cholesky of the posterior covariance over f(X_baseline) is cached. :meta ...
stack_v2_sparse_classes_36k_train_033495
7,369
permissive
[ { "docstring": "Set class attributes and perform compatibility checks. Args: model: A model. cache_root: A boolean indicating whether to cache the Cholesky. This might be overridden in the model is not compatible.", "name": "_setup", "signature": "def _setup(self, model: Model, cache_root: bool=False) -...
4
null
Implement the Python class `CachedCholeskyMCAcquisitionFunction` described below. Class description: Abstract class for acquisition functions using a cached Cholesky. Specifically, this is for acquisition functions that require sampling from the posterior P(f(X_baseline, X) | D). The Cholesky of the posterior covarian...
Implement the Python class `CachedCholeskyMCAcquisitionFunction` described below. Class description: Abstract class for acquisition functions using a cached Cholesky. Specifically, this is for acquisition functions that require sampling from the posterior P(f(X_baseline, X) | D). The Cholesky of the posterior covarian...
4cc5ed59b2e8a9c780f786830c548e05cc74d53c
<|skeleton|> class CachedCholeskyMCAcquisitionFunction: """Abstract class for acquisition functions using a cached Cholesky. Specifically, this is for acquisition functions that require sampling from the posterior P(f(X_baseline, X) | D). The Cholesky of the posterior covariance over f(X_baseline) is cached. :meta ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CachedCholeskyMCAcquisitionFunction: """Abstract class for acquisition functions using a cached Cholesky. Specifically, this is for acquisition functions that require sampling from the posterior P(f(X_baseline, X) | D). The Cholesky of the posterior covariance over f(X_baseline) is cached. :meta private:""" ...
the_stack_v2_python_sparse
botorch/acquisition/cached_cholesky.py
pytorch/botorch
train
2,891
5ebefc01e80cdd571928bceeb277005ef622e265
[ "data_dict = json.loads(request.data)\nvalidator.validate(data_dict, validator.USER)\nuser = user_controller.register(data_dict)\nuser_dto = user_schema.serialize_user(user)\nresponse = Response(response=json.dumps(user_dto), status=201, mimetype='application/json')\nreturn response", "user = user_controller.get_...
<|body_start_0|> data_dict = json.loads(request.data) validator.validate(data_dict, validator.USER) user = user_controller.register(data_dict) user_dto = user_schema.serialize_user(user) response = Response(response=json.dumps(user_dto), status=201, mimetype='application/json') ...
UserResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserResource: def post(self): """Register a new user""" <|body_0|> def get(self, user_id): """Get a user""" <|body_1|> <|end_skeleton|> <|body_start_0|> data_dict = json.loads(request.data) validator.validate(data_dict, validator.USER) ...
stack_v2_sparse_classes_36k_train_033496
4,871
no_license
[ { "docstring": "Register a new user", "name": "post", "signature": "def post(self)" }, { "docstring": "Get a user", "name": "get", "signature": "def get(self, user_id)" } ]
2
stack_v2_sparse_classes_30k_train_008823
Implement the Python class `UserResource` described below. Class description: Implement the UserResource class. Method signatures and docstrings: - def post(self): Register a new user - def get(self, user_id): Get a user
Implement the Python class `UserResource` described below. Class description: Implement the UserResource class. Method signatures and docstrings: - def post(self): Register a new user - def get(self, user_id): Get a user <|skeleton|> class UserResource: def post(self): """Register a new user""" ...
e0c8ea99886f10aea14b9ca95af8a4f42f2af493
<|skeleton|> class UserResource: def post(self): """Register a new user""" <|body_0|> def get(self, user_id): """Get a user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserResource: def post(self): """Register a new user""" data_dict = json.loads(request.data) validator.validate(data_dict, validator.USER) user = user_controller.register(data_dict) user_dto = user_schema.serialize_user(user) response = Response(response=json.du...
the_stack_v2_python_sparse
imdb_api/resources/user_resources.py
Matiasmoratti7/imdb
train
0
e69efe883225e8ab4824ebcb0e792ce7a79da91b
[ "step_metrics = OrderedDict()\nfor key in cls:\n step_metrics[key.value] = None\nreturn step_metrics", "for key in cls:\n if input_dict[key.value] is None:\n raise Exception(\"StepMetrics dict's key({})'s value is None\".format(key.value))" ]
<|body_start_0|> step_metrics = OrderedDict() for key in cls: step_metrics[key.value] = None return step_metrics <|end_body_0|> <|body_start_1|> for key in cls: if input_dict[key.value] is None: raise Exception("StepMetrics dict's key({})'s value ...
The keys for the sim trace metrics
StepMetrics
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StepMetrics: """The keys for the sim trace metrics""" def make_default_metric(cls): """Returns the default step metrics dict""" <|body_0|> def validate_dict(cls, input_dict): """Throws an exception if a key is missing""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_033497
4,235
permissive
[ { "docstring": "Returns the default step metrics dict", "name": "make_default_metric", "signature": "def make_default_metric(cls)" }, { "docstring": "Throws an exception if a key is missing", "name": "validate_dict", "signature": "def validate_dict(cls, input_dict)" } ]
2
null
Implement the Python class `StepMetrics` described below. Class description: The keys for the sim trace metrics Method signatures and docstrings: - def make_default_metric(cls): Returns the default step metrics dict - def validate_dict(cls, input_dict): Throws an exception if a key is missing
Implement the Python class `StepMetrics` described below. Class description: The keys for the sim trace metrics Method signatures and docstrings: - def make_default_metric(cls): Returns the default step metrics dict - def validate_dict(cls, input_dict): Throws an exception if a key is missing <|skeleton|> class Step...
2ce50508dd4100eaef7f8729436549a801505705
<|skeleton|> class StepMetrics: """The keys for the sim trace metrics""" def make_default_metric(cls): """Returns the default step metrics dict""" <|body_0|> def validate_dict(cls, input_dict): """Throws an exception if a key is missing""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StepMetrics: """The keys for the sim trace metrics""" def make_default_metric(cls): """Returns the default step metrics dict""" step_metrics = OrderedDict() for key in cls: step_metrics[key.value] = None return step_metrics def validate_dict(cls, input_dic...
the_stack_v2_python_sparse
bundle/markov/metrics/constants.py
aws-deepracer-community/deepracer-simapp
train
83
7d04e6311d7bf3858c0e44ed14e060ba75169e48
[ "result = DBFormatter.format(self, results)\nif len(result) == 0:\n return None\nreturn result[0][0]", "if isinstance(jobID, list):\n if len(jobID) == 0:\n return {}\n binds = []\n for entry in jobID:\n binds.append({'jobid': entry})\n result = self.dbi.processData(self.bulkSQL, binds...
<|body_start_0|> result = DBFormatter.format(self, results) if len(result) == 0: return None return result[0][0] <|end_body_0|> <|body_start_1|> if isinstance(jobID, list): if len(jobID) == 0: return {} binds = [] for entry...
_GetCouchID_ Given a job ID retrieve the couch document ID.
GetCouchID
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetCouchID: """_GetCouchID_ Given a job ID retrieve the couch document ID.""" def format(self, results): """_format_ Return the couch document ID or None if one has not been set.""" <|body_0|> def execute(self, jobID, conn=None, transaction=False): """_execute_ E...
stack_v2_sparse_classes_36k_train_033498
1,473
permissive
[ { "docstring": "_format_ Return the couch document ID or None if one has not been set.", "name": "format", "signature": "def format(self, results)" }, { "docstring": "_execute_ Execute the SQL for the given job ID and then format and return the result.", "name": "execute", "signature": "...
2
null
Implement the Python class `GetCouchID` described below. Class description: _GetCouchID_ Given a job ID retrieve the couch document ID. Method signatures and docstrings: - def format(self, results): _format_ Return the couch document ID or None if one has not been set. - def execute(self, jobID, conn=None, transactio...
Implement the Python class `GetCouchID` described below. Class description: _GetCouchID_ Given a job ID retrieve the couch document ID. Method signatures and docstrings: - def format(self, results): _format_ Return the couch document ID or None if one has not been set. - def execute(self, jobID, conn=None, transactio...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class GetCouchID: """_GetCouchID_ Given a job ID retrieve the couch document ID.""" def format(self, results): """_format_ Return the couch document ID or None if one has not been set.""" <|body_0|> def execute(self, jobID, conn=None, transaction=False): """_execute_ E...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetCouchID: """_GetCouchID_ Given a job ID retrieve the couch document ID.""" def format(self, results): """_format_ Return the couch document ID or None if one has not been set.""" result = DBFormatter.format(self, results) if len(result) == 0: return None ret...
the_stack_v2_python_sparse
src/python/WMCore/WMBS/MySQL/Jobs/GetCouchID.py
vkuznet/WMCore
train
0
8a56c1b27358a50020d7739e4fef6caaf0d43e17
[ "self.matrix = matrix\nfor row in range(len(matrix)):\n for col in range(1, len(matrix[0])):\n self.matrix[row][col] = self.matrix[row][col - 1] + self.matrix[row][col]", "original = self.matrix[row][col]\nif col != 0:\n original -= self.matrix[row][col - 1]\ndiff = original - val\nfor y in xrange(co...
<|body_start_0|> self.matrix = matrix for row in range(len(matrix)): for col in range(1, len(matrix[0])): self.matrix[row][col] = self.matrix[row][col - 1] + self.matrix[row][col] <|end_body_0|> <|body_start_1|> original = self.matrix[row][col] if col != 0: ...
NumMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """initialize your data structure here. :type matrix: List[List[int]]""" <|body_0|> def update(self, row, col, val): """update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void""" ...
stack_v2_sparse_classes_36k_train_033499
1,645
no_license
[ { "docstring": "initialize your data structure here. :type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": "update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void", "name": "update", ...
3
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]] - def update(self, row, col, val): update the element at matrix[row,col] to val. ...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]] - def update(self, row, col, val): update the element at matrix[row,col] to val. ...
6de551327f96ec4d4b63d0045281b65bbb4f5d0f
<|skeleton|> class NumMatrix: def __init__(self, matrix): """initialize your data structure here. :type matrix: List[List[int]]""" <|body_0|> def update(self, row, col, val): """update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """initialize your data structure here. :type matrix: List[List[int]]""" self.matrix = matrix for row in range(len(matrix)): for col in range(1, len(matrix[0])): self.matrix[row][col] = self.matrix[row][col - 1] + self....
the_stack_v2_python_sparse
sumRegion.py
JingweiTu/leetcode
train
0