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
201fe856d1602ceec67b645c2987f4d5af31f827
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cyyan_liuzirui_yjunchoi_yzhang71', 'cyyan_liuzirui_yjunchoi_yzhang71')\nurl = 'http://erikdemaine.org/maps/mbta/mbta.yaml'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\nmbta = yaml.load...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('cyyan_liuzirui_yjunchoi_yzhang71', 'cyyan_liuzirui_yjunchoi_yzhang71') url = 'http://erikdemaine.org/maps/mbta/mbta.yaml' response = urllib.reques...
MBTACoordinates
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MBTACoordinates: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everythi...
stack_v2_sparse_classes_36k_train_025800
3,626
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
null
Implement the Python class `MBTACoordinates` described below. Class description: Implement the MBTACoordinates class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=Non...
Implement the Python class `MBTACoordinates` described below. Class description: Implement the MBTACoordinates class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=Non...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class MBTACoordinates: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everythi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MBTACoordinates: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('cyyan_liuzirui_yjunchoi_yzhang71', ...
the_stack_v2_python_sparse
cyyan_liuzirui_yjunchoi_yzhang71/MBTACoordinates.py
ROODAY/course-2017-fal-proj
train
3
d7af4ba3267a4a41addc6ae0e6b02dd063b3c4dc
[ "self.Functions = Functions\nself.Results_keys = [key + '_' + f.__name__ for key in Functions.keys() for f in Functions[key]]\nself.partition = partition\nself.frame_keys = [key + '_' + str(j) for key in self.Results_keys for j in partition]\nself.label_name = label_name", "fn_keys = self.Functions.keys()\nnodes ...
<|body_start_0|> self.Functions = Functions self.Results_keys = [key + '_' + f.__name__ for key in Functions.keys() for f in Functions[key]] self.partition = partition self.frame_keys = [key + '_' + str(j) for key in self.Results_keys for j in partition] self.label_name = label_n...
Encapsulates methods for computing and smoothing of vectors in Hom(Vert(G),R), where G is a graph and R is the real numbers.
GraphDualVS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphDualVS: """Encapsulates methods for computing and smoothing of vectors in Hom(Vert(G),R), where G is a graph and R is the real numbers.""" def __init__(self, Functions, partition, label_name): """GraphDual class constructor. Args: Functions (dict): dictionary containing function...
stack_v2_sparse_classes_36k_train_025801
5,619
no_license
[ { "docstring": "GraphDual class constructor. Args: Functions (dict): dictionary containing functions to by applied to the vertex set of a graph G partition (numpy array): percentiles with which to partition the probability measure of the input graph G label_name (str): string giving the node attribute which act...
3
stack_v2_sparse_classes_30k_train_011651
Implement the Python class `GraphDualVS` described below. Class description: Encapsulates methods for computing and smoothing of vectors in Hom(Vert(G),R), where G is a graph and R is the real numbers. Method signatures and docstrings: - def __init__(self, Functions, partition, label_name): GraphDual class constructo...
Implement the Python class `GraphDualVS` described below. Class description: Encapsulates methods for computing and smoothing of vectors in Hom(Vert(G),R), where G is a graph and R is the real numbers. Method signatures and docstrings: - def __init__(self, Functions, partition, label_name): GraphDual class constructo...
d00d2374f45010c7dd867568ef91116d248b7e7f
<|skeleton|> class GraphDualVS: """Encapsulates methods for computing and smoothing of vectors in Hom(Vert(G),R), where G is a graph and R is the real numbers.""" def __init__(self, Functions, partition, label_name): """GraphDual class constructor. Args: Functions (dict): dictionary containing function...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraphDualVS: """Encapsulates methods for computing and smoothing of vectors in Hom(Vert(G),R), where G is a graph and R is the real numbers.""" def __init__(self, Functions, partition, label_name): """GraphDual class constructor. Args: Functions (dict): dictionary containing functions to by appli...
the_stack_v2_python_sparse
src/grafuple/pagerank/graphdualvs.py
andrewpalumbo/grafuple
train
0
60e1981a427bc6783307ac4b7812390681fd4801
[ "if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n else:\n self.lambtha = float(lambtha)\nelif type(data) is not list:\n raise TypeError('data must be a list')\nelif len(data) < 2:\n raise ValueError('data must contain multiple values')\nelse:\n ...
<|body_start_0|> if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') else: self.lambtha = float(lambtha) elif type(data) is not list: raise TypeError('data must be a list') elif len(data) < 2: ...
This class represents an exponential distribution
Exponential
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exponential: """This class represents an exponential distribution""" def __init__(self, data=None, lambtha=1.0): """This function initializes the Exponential class""" <|body_0|> def pdf(self, x): """Calculates the value of the PDF for a given time period""" ...
stack_v2_sparse_classes_36k_train_025802
1,261
no_license
[ { "docstring": "This function initializes the Exponential class", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "Calculates the value of the PDF for a given time period", "name": "pdf", "signature": "def pdf(self, x)" }, { "docstr...
3
stack_v2_sparse_classes_30k_train_003147
Implement the Python class `Exponential` described below. Class description: This class represents an exponential distribution Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): This function initializes the Exponential class - def pdf(self, x): Calculates the value of the PDF for a given...
Implement the Python class `Exponential` described below. Class description: This class represents an exponential distribution Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): This function initializes the Exponential class - def pdf(self, x): Calculates the value of the PDF for a given...
ac4f79965e65b7716029cd31a9b026c904bdef09
<|skeleton|> class Exponential: """This class represents an exponential distribution""" def __init__(self, data=None, lambtha=1.0): """This function initializes the Exponential class""" <|body_0|> def pdf(self, x): """Calculates the value of the PDF for a given time period""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Exponential: """This class represents an exponential distribution""" def __init__(self, data=None, lambtha=1.0): """This function initializes the Exponential class""" if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') ...
the_stack_v2_python_sparse
math/0x03-probability/exponential.py
tyedge/holbertonschool-machine_learning
train
0
345ff216c2dd71d49a144762e47ffd2228a6ada8
[ "if not self.request.body:\n return None\nbody = self.request.body.strip().decode(u'utf-8')\ntry:\n model = json.loads(body)\nexcept Exception:\n self.log.debug('Bad JSON: %r', body)\n self.log.error(\"Couldn't parse JSON\", exc_info=True)\n raise web.HTTPError(400, 'Invalid JSON in body of request')...
<|body_start_0|> if not self.request.body: return None body = self.request.body.strip().decode(u'utf-8') try: model = json.loads(body) except Exception: self.log.debug('Bad JSON: %r', body) self.log.error("Couldn't parse JSON", exc_info=Tru...
APIHandler
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APIHandler: def get_json_body(self): """Return the body of the request as JSON data.""" <|body_0|> def write_error(self, status_code, **kwargs): """Write JSON errors instead of HTML""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not self.request...
stack_v2_sparse_classes_36k_train_025803
1,619
permissive
[ { "docstring": "Return the body of the request as JSON data.", "name": "get_json_body", "signature": "def get_json_body(self)" }, { "docstring": "Write JSON errors instead of HTML", "name": "write_error", "signature": "def write_error(self, status_code, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_001845
Implement the Python class `APIHandler` described below. Class description: Implement the APIHandler class. Method signatures and docstrings: - def get_json_body(self): Return the body of the request as JSON data. - def write_error(self, status_code, **kwargs): Write JSON errors instead of HTML
Implement the Python class `APIHandler` described below. Class description: Implement the APIHandler class. Method signatures and docstrings: - def get_json_body(self): Return the body of the request as JSON data. - def write_error(self, status_code, **kwargs): Write JSON errors instead of HTML <|skeleton|> class AP...
e7f67bfc4f0cd8bd0ebbef013ea1526b340c253b
<|skeleton|> class APIHandler: def get_json_body(self): """Return the body of the request as JSON data.""" <|body_0|> def write_error(self, status_code, **kwargs): """Write JSON errors instead of HTML""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APIHandler: def get_json_body(self): """Return the body of the request as JSON data.""" if not self.request.body: return None body = self.request.body.strip().decode(u'utf-8') try: model = json.loads(body) except Exception: self.log.d...
the_stack_v2_python_sparse
jupyterhub/apihandlers/base.py
rgbkrk/jupyterhub
train
2
553ca9fa99ca8b43426479473f82f6a6d5328902
[ "controller = Controller()\nbuyers = controller.get()\nreturn buyers", "data = api.payload\ncontroller = Controller()\ncontroller.insert(data)" ]
<|body_start_0|> controller = Controller() buyers = controller.get() return buyers <|end_body_0|> <|body_start_1|> data = api.payload controller = Controller() controller.insert(data) <|end_body_1|>
BuyerList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuyerList: def get(self): """Return buyers list. :return:""" <|body_0|> def post(self): """Create new buyer :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> controller = Controller() buyers = controller.get() return buyers <|...
stack_v2_sparse_classes_36k_train_025804
957
no_license
[ { "docstring": "Return buyers list. :return:", "name": "get", "signature": "def get(self)" }, { "docstring": "Create new buyer :return:", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_005512
Implement the Python class `BuyerList` described below. Class description: Implement the BuyerList class. Method signatures and docstrings: - def get(self): Return buyers list. :return: - def post(self): Create new buyer :return:
Implement the Python class `BuyerList` described below. Class description: Implement the BuyerList class. Method signatures and docstrings: - def get(self): Return buyers list. :return: - def post(self): Create new buyer :return: <|skeleton|> class BuyerList: def get(self): """Return buyers list. :retur...
19d96756925e61e31833adf4b49714d7fbfa4868
<|skeleton|> class BuyerList: def get(self): """Return buyers list. :return:""" <|body_0|> def post(self): """Create new buyer :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BuyerList: def get(self): """Return buyers list. :return:""" controller = Controller() buyers = controller.get() return buyers def post(self): """Create new buyer :return:""" data = api.payload controller = Controller() controller.insert(dat...
the_stack_v2_python_sparse
app/buyer/view_buyer.py
ladin157/flask_rest_orm_example
train
0
2c82bde0852d6d4d2fdd122fae56b1aad47abeda
[ "user_kwargs = optimizer_kwargs\noptimizer_kwargs = {}\nprint(f'in {optimizer}: max_iterations = {max_iterations}')\nif optimizer == 'BFGS':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {'method': 'BFGS', 'options': {'gtol': 1e-15, 'maxiter': max_iterations}}\nelif optimizer == 'L-B...
<|body_start_0|> user_kwargs = optimizer_kwargs optimizer_kwargs = {} print(f'in {optimizer}: max_iterations = {max_iterations}') if optimizer == 'BFGS': from scipy.optimize import minimize as optimizer optimizer_kwargs = {'method': 'BFGS', 'options': {'gtol': 1e-...
Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optimization conditioners (e.g., simulated...
Regressor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Regressor: """Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optim...
stack_v2_sparse_classes_36k_train_025805
5,499
no_license
[ { "docstring": "optimizer can be specified; it should behave like a scipy.optimize optimizer. That is, it should take as its first two arguments the function to be optimized and the initial guess of the optimal parameters. Additional keyword arguments can be fed through the optimizer_kwargs dictionary.", "n...
2
stack_v2_sparse_classes_30k_val_000575
Implement the Python class `Regressor` described below. Class description: Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to ...
Implement the Python class `Regressor` described below. Class description: Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to ...
4d26767f287be6abc88dc74374003b04d509bebf
<|skeleton|> class Regressor: """Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optim...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Regressor: """Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optimization condi...
the_stack_v2_python_sparse
MLdyn/amp_patches/amp.regression.__init__.py
hopefulp/sandbox
train
1
639cb0361de1cb895de236d46e8620ddc9dc88bc
[ "self.bransje_kode_field = bransje_kode_field\nself.bransje_tekst_field = bransje_tekst_field\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nbransje_kode_field = dictionary.get('bransjeKodeField')\nbransje_tekst_field = dictionary.get('bransjeTekstField')\nfor key ...
<|body_start_0|> self.bransje_kode_field = bransje_kode_field self.bransje_tekst_field = bransje_tekst_field self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: return None bransje_kode_field = dictionary.get('bra...
Implementation of the 'BransjeData' model. TODO: type model description here. Attributes: bransje_kode_field (int): TODO: type description here. bransje_tekst_field (string): TODO: type description here.
BransjeData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BransjeData: """Implementation of the 'BransjeData' model. TODO: type model description here. Attributes: bransje_kode_field (int): TODO: type description here. bransje_tekst_field (string): TODO: type description here.""" def __init__(self, bransje_kode_field=None, bransje_tekst_field=None,...
stack_v2_sparse_classes_36k_train_025806
2,215
permissive
[ { "docstring": "Constructor for the BransjeData class", "name": "__init__", "signature": "def __init__(self, bransje_kode_field=None, bransje_tekst_field=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti...
2
null
Implement the Python class `BransjeData` described below. Class description: Implementation of the 'BransjeData' model. TODO: type model description here. Attributes: bransje_kode_field (int): TODO: type description here. bransje_tekst_field (string): TODO: type description here. Method signatures and docstrings: - d...
Implement the Python class `BransjeData` described below. Class description: Implementation of the 'BransjeData' model. TODO: type model description here. Attributes: bransje_kode_field (int): TODO: type description here. bransje_tekst_field (string): TODO: type description here. Method signatures and docstrings: - d...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class BransjeData: """Implementation of the 'BransjeData' model. TODO: type model description here. Attributes: bransje_kode_field (int): TODO: type description here. bransje_tekst_field (string): TODO: type description here.""" def __init__(self, bransje_kode_field=None, bransje_tekst_field=None,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BransjeData: """Implementation of the 'BransjeData' model. TODO: type model description here. Attributes: bransje_kode_field (int): TODO: type description here. bransje_tekst_field (string): TODO: type description here.""" def __init__(self, bransje_kode_field=None, bransje_tekst_field=None, additional_p...
the_stack_v2_python_sparse
idfy_rest_client/models/bransje_data.py
dealflowteam/Idfy
train
0
503c72178d8d2931ae0e3700e7ee3a0b5478a821
[ "result = {'result': 'NG'}\ndata = request.get_json(force=True)\nif data:\n succsee, message = CtrlQuotations().add_combination_by_quotation_id3(quotation_id, data)\n if succsee:\n result = {'result': 'OK', 'content': message}\n else:\n result['error'] = message\nelse:\n result['error'] = ...
<|body_start_0|> result = {'result': 'NG'} data = request.get_json(force=True) if data: succsee, message = CtrlQuotations().add_combination_by_quotation_id3(quotation_id, data) if succsee: result = {'result': 'OK', 'content': message} else: ...
ApiOptionCombinationInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApiOptionCombinationInfo: def post(self, quotation_id): """更新/添加此报价下的Combination :return:""" <|body_0|> def get(self, quotation_id): """获取此报价下的所有Option :return:""" <|body_1|> def delete(self, op_id): """删除此条Option :return:""" <|body_2|> ...
stack_v2_sparse_classes_36k_train_025807
10,406
no_license
[ { "docstring": "更新/添加此报价下的Combination :return:", "name": "post", "signature": "def post(self, quotation_id)" }, { "docstring": "获取此报价下的所有Option :return:", "name": "get", "signature": "def get(self, quotation_id)" }, { "docstring": "删除此条Option :return:", "name": "delete", ...
3
stack_v2_sparse_classes_30k_train_012338
Implement the Python class `ApiOptionCombinationInfo` described below. Class description: Implement the ApiOptionCombinationInfo class. Method signatures and docstrings: - def post(self, quotation_id): 更新/添加此报价下的Combination :return: - def get(self, quotation_id): 获取此报价下的所有Option :return: - def delete(self, op_id): 删除...
Implement the Python class `ApiOptionCombinationInfo` described below. Class description: Implement the ApiOptionCombinationInfo class. Method signatures and docstrings: - def post(self, quotation_id): 更新/添加此报价下的Combination :return: - def get(self, quotation_id): 获取此报价下的所有Option :return: - def delete(self, op_id): 删除...
64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11
<|skeleton|> class ApiOptionCombinationInfo: def post(self, quotation_id): """更新/添加此报价下的Combination :return:""" <|body_0|> def get(self, quotation_id): """获取此报价下的所有Option :return:""" <|body_1|> def delete(self, op_id): """删除此条Option :return:""" <|body_2|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApiOptionCombinationInfo: def post(self, quotation_id): """更新/添加此报价下的Combination :return:""" result = {'result': 'NG'} data = request.get_json(force=True) if data: succsee, message = CtrlQuotations().add_combination_by_quotation_id3(quotation_id, data) i...
the_stack_v2_python_sparse
koala/koala_server/app/api_1_0/api_quotations.py
lsn1183/web_project
train
0
008acc477c6de384db81166439581d21a3140acd
[ "if not root:\n return '[]'\nres = [root.val]\nq = collections.deque([root])\nwhile q:\n front = q.popleft()\n if front.left:\n q.append(front.left)\n if front.right:\n q.append(front.right)\n res.append(front.left.val if front.left else 'null')\n res.append(front.right.val if front....
<|body_start_0|> if not root: return '[]' res = [root.val] q = collections.deque([root]) while q: front = q.popleft() if front.left: q.append(front.left) if front.right: q.append(front.right) res....
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_025808
17,936
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_004836
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:...
035ef08434fa1ca781a6fb2f9eed3538b7d20c02
<|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 '[]' res = [root.val] q = collections.deque([root]) while q: front = q.popleft() if front.left: ...
the_stack_v2_python_sparse
leetcode_python/Tree/serialize-and-deserialize-binary-tree.py
yennanliu/CS_basics
train
64
50e8fe1dcf922c422133057104c4b1911aa73b6c
[ "super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL)\nsession = async_get_clientsession(hass)\nself.api = aiohwenergy.HomeWizardEnergy(host, clientsession=session)", "async with async_timeout.timeout(10):\n if self.api.device is None:\n await self.initialize_api()\n try:\n ...
<|body_start_0|> super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL) session = async_get_clientsession(hass) self.api = aiohwenergy.HomeWizardEnergy(host, clientsession=session) <|end_body_0|> <|body_start_1|> async with async_timeout.timeout(10): i...
Gather data for the energy device.
HWEnergyDeviceUpdateCoordinator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HWEnergyDeviceUpdateCoordinator: """Gather data for the energy device.""" def __init__(self, hass: HomeAssistant, host: str) -> None: """Initialize Update Coordinator.""" <|body_0|> async def _async_update_data(self) -> DeviceResponseEntry: """Fetch all device an...
stack_v2_sparse_classes_36k_train_025809
2,620
permissive
[ { "docstring": "Initialize Update Coordinator.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, host: str) -> None" }, { "docstring": "Fetch all device and sensor data from api.", "name": "_async_update_data", "signature": "async def _async_update_data(self) ->...
3
null
Implement the Python class `HWEnergyDeviceUpdateCoordinator` described below. Class description: Gather data for the energy device. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, host: str) -> None: Initialize Update Coordinator. - async def _async_update_data(self) -> DeviceResponseEntry...
Implement the Python class `HWEnergyDeviceUpdateCoordinator` described below. Class description: Gather data for the energy device. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, host: str) -> None: Initialize Update Coordinator. - async def _async_update_data(self) -> DeviceResponseEntry...
8f4ec89be6c2505d8a59eee44de335abe308ac9f
<|skeleton|> class HWEnergyDeviceUpdateCoordinator: """Gather data for the energy device.""" def __init__(self, hass: HomeAssistant, host: str) -> None: """Initialize Update Coordinator.""" <|body_0|> async def _async_update_data(self) -> DeviceResponseEntry: """Fetch all device an...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HWEnergyDeviceUpdateCoordinator: """Gather data for the energy device.""" def __init__(self, hass: HomeAssistant, host: str) -> None: """Initialize Update Coordinator.""" super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL) session = async_get_clientsessio...
the_stack_v2_python_sparse
homeassistant/components/homewizard/coordinator.py
JeffLIrion/home-assistant
train
5
01591f46c5e93ada52525424daaae727c206e3e7
[ "count, length = (0, len(nums))\nfor i in range(length):\n total = 0\n for j in range(i, length):\n total += nums[j]\n if total == k:\n count += 1\nreturn count", "count, total = (0, 0)\nmap = {}\nmap[0] = 1\nfor i in range(len(nums)):\n total += nums[i]\n if total - k in map:...
<|body_start_0|> count, length = (0, len(nums)) for i in range(length): total = 0 for j in range(i, length): total += nums[j] if total == k: count += 1 return count <|end_body_0|> <|body_start_1|> count, total =...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def subarray_sum_equals_k(self, nums: List[int], k: int) -> int: """找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数""" <|body_0|> def subarray_sum_equals_k2(self, nums: List[int], k: int) -> int: """找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数""" <|body_1|...
stack_v2_sparse_classes_36k_train_025810
2,172
permissive
[ { "docstring": "找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数", "name": "subarray_sum_equals_k", "signature": "def subarray_sum_equals_k(self, nums: List[int], k: int) -> int" }, { "docstring": "找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数", "name": "subarray_sum_equals_k2", "signature": "def...
2
stack_v2_sparse_classes_30k_val_000538
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarray_sum_equals_k(self, nums: List[int], k: int) -> int: 找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数 - def subarray_sum_equals_k2(self, nums: List[int], k: int) -> int: 找出...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarray_sum_equals_k(self, nums: List[int], k: int) -> int: 找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数 - def subarray_sum_equals_k2(self, nums: List[int], k: int) -> int: 找出...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def subarray_sum_equals_k(self, nums: List[int], k: int) -> int: """找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数""" <|body_0|> def subarray_sum_equals_k2(self, nums: List[int], k: int) -> int: """找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def subarray_sum_equals_k(self, nums: List[int], k: int) -> int: """找出和相同的数组 Args: nums:数组 k:固定值 Returns: 数组种数""" count, length = (0, len(nums)) for i in range(length): total = 0 for j in range(i, length): total += nums[j] ...
the_stack_v2_python_sparse
src/leetcodepython/array/subarray_sum_equals_k_560.py
zhangyu345293721/leetcode
train
101
4bfeee61d30a69d46493f289e6b65ae86ae4df2d
[ "group_fields = [f.name for f in self.fields]\nis_kwargs = {}\nfor field in kwargs.copy():\n if field not in group_fields:\n is_kwargs[field] = kwargs.pop(field)\nif is_kwargs.get('source', None) == 'manual':\n is_kwargs.pop('source')\nanswer = super(Resource, self).create(fail_on_found=fail_on_found, ...
<|body_start_0|> group_fields = [f.name for f in self.fields] is_kwargs = {} for field in kwargs.copy(): if field not in group_fields: is_kwargs[field] = kwargs.pop(field) if is_kwargs.get('source', None) == 'manual': is_kwargs.pop('source') ...
Resource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Resource: def create(self, fail_on_found=False, force_on_exists=False, **kwargs): """Create a group and, if necessary, modify the inventory source within the group.""" <|body_0|> def modify(self, pk=None, create_on_missing=False, **kwargs): """Modify a group and, if ...
stack_v2_sparse_classes_36k_train_025811
9,703
permissive
[ { "docstring": "Create a group and, if necessary, modify the inventory source within the group.", "name": "create", "signature": "def create(self, fail_on_found=False, force_on_exists=False, **kwargs)" }, { "docstring": "Modify a group and, if necessary, the inventory source within the group.", ...
5
stack_v2_sparse_classes_30k_train_003340
Implement the Python class `Resource` described below. Class description: Implement the Resource class. Method signatures and docstrings: - def create(self, fail_on_found=False, force_on_exists=False, **kwargs): Create a group and, if necessary, modify the inventory source within the group. - def modify(self, pk=None...
Implement the Python class `Resource` described below. Class description: Implement the Resource class. Method signatures and docstrings: - def create(self, fail_on_found=False, force_on_exists=False, **kwargs): Create a group and, if necessary, modify the inventory source within the group. - def modify(self, pk=None...
e6a1f62a4f33ea94ff7dd53b9690a7b3057a7a31
<|skeleton|> class Resource: def create(self, fail_on_found=False, force_on_exists=False, **kwargs): """Create a group and, if necessary, modify the inventory source within the group.""" <|body_0|> def modify(self, pk=None, create_on_missing=False, **kwargs): """Modify a group and, if ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Resource: def create(self, fail_on_found=False, force_on_exists=False, **kwargs): """Create a group and, if necessary, modify the inventory source within the group.""" group_fields = [f.name for f in self.fields] is_kwargs = {} for field in kwargs.copy(): if field n...
the_stack_v2_python_sparse
lib/tower_cli/resources/group.py
willthames/tower-cli
train
2
8f7e0dec1976d6cb361cd35f86a6a7b12fd5184f
[ "super(BaggedGaussianProcessStabilityAgent, self).__init__(candidate_data=candidate_data, seed_data=seed_data, n_query=n_query, hull_distance=hull_distance, parallel=parallel)\nself.alpha = alpha\nself.n_estimators = n_estimators\nself.max_samples = max_samples\nself.bootstrap = bootstrap\nself.GP = GaussianProcess...
<|body_start_0|> super(BaggedGaussianProcessStabilityAgent, self).__init__(candidate_data=candidate_data, seed_data=seed_data, n_query=n_query, hull_distance=hull_distance, parallel=parallel) self.alpha = alpha self.n_estimators = n_estimators self.max_samples = max_samples self....
An ensemble GP learner that can handle relatively large datasets by bagging. WIP. Current strategy is that weak GP learners are trained on random subsets of data with max 500 points (and no bootstrapping), to learn a stronger, ensemble learner that minimizes model variance. Learned model is usually stronger, and on par...
BaggedGaussianProcessStabilityAgent
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaggedGaussianProcessStabilityAgent: """An ensemble GP learner that can handle relatively large datasets by bagging. WIP. Current strategy is that weak GP learners are trained on random subsets of data with max 500 points (and no bootstrapping), to learn a stronger, ensemble learner that minimize...
stack_v2_sparse_classes_36k_train_025812
38,060
permissive
[ { "docstring": "Args: candidate_data (DataFrame): data about the candidates seed_data (DataFrame): data which to fit the Agent to n_query (int): number of hypotheses to generate hull_distance (float): hull distance as a criteria for which to deem a given material as \"stable\" parallel (bool): whether to use mu...
3
stack_v2_sparse_classes_30k_train_018863
Implement the Python class `BaggedGaussianProcessStabilityAgent` described below. Class description: An ensemble GP learner that can handle relatively large datasets by bagging. WIP. Current strategy is that weak GP learners are trained on random subsets of data with max 500 points (and no bootstrapping), to learn a s...
Implement the Python class `BaggedGaussianProcessStabilityAgent` described below. Class description: An ensemble GP learner that can handle relatively large datasets by bagging. WIP. Current strategy is that weak GP learners are trained on random subsets of data with max 500 points (and no bootstrapping), to learn a s...
905f5d577513d1ca5a54fac3d381525e0fe3576a
<|skeleton|> class BaggedGaussianProcessStabilityAgent: """An ensemble GP learner that can handle relatively large datasets by bagging. WIP. Current strategy is that weak GP learners are trained on random subsets of data with max 500 points (and no bootstrapping), to learn a stronger, ensemble learner that minimize...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaggedGaussianProcessStabilityAgent: """An ensemble GP learner that can handle relatively large datasets by bagging. WIP. Current strategy is that weak GP learners are trained on random subsets of data with max 500 points (and no bootstrapping), to learn a stronger, ensemble learner that minimizes model varia...
the_stack_v2_python_sparse
camd/agent/stability.py
apalizha/CAMD
train
0
c50de0e1e7358bde93a8dc2e7e651d674bbac8d2
[ "self.update_widgets()\ngroups = []\nfor group_class in self.groups:\n if IGroup.providedBy(group_class):\n group = group_class\n else:\n group = group_class(self.context, self.request, self)\n groups.append(group)\nregistry = self.request.registry\nfor group in sorted((adapter for name, adap...
<|body_start_0|> self.update_widgets() groups = [] for group_class in self.groups: if IGroup.providedBy(group_class): group = group_class else: group = group_class(self.context, self.request, self) groups.append(group) r...
Base groups manager mixin class
GroupManager
[ "ZPL-2.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupManager: """Base groups manager mixin class""" def update(self): """See interfaces.IForm""" <|body_0|> def extract_data(self, set_errors=True, notify=True): """See interfaces.IForm""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.update...
stack_v2_sparse_classes_36k_train_025813
4,385
permissive
[ { "docstring": "See interfaces.IForm", "name": "update", "signature": "def update(self)" }, { "docstring": "See interfaces.IForm", "name": "extract_data", "signature": "def extract_data(self, set_errors=True, notify=True)" } ]
2
null
Implement the Python class `GroupManager` described below. Class description: Base groups manager mixin class Method signatures and docstrings: - def update(self): See interfaces.IForm - def extract_data(self, set_errors=True, notify=True): See interfaces.IForm
Implement the Python class `GroupManager` described below. Class description: Base groups manager mixin class Method signatures and docstrings: - def update(self): See interfaces.IForm - def extract_data(self, set_errors=True, notify=True): See interfaces.IForm <|skeleton|> class GroupManager: """Base groups man...
e83e2ce314355f98eaf66e90ad6feccbda7934f9
<|skeleton|> class GroupManager: """Base groups manager mixin class""" def update(self): """See interfaces.IForm""" <|body_0|> def extract_data(self, set_errors=True, notify=True): """See interfaces.IForm""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupManager: """Base groups manager mixin class""" def update(self): """See interfaces.IForm""" self.update_widgets() groups = [] for group_class in self.groups: if IGroup.providedBy(group_class): group = group_class else: ...
the_stack_v2_python_sparse
src/pyams_form/group.py
Py-AMS/pyams-form
train
0
3207b24b55371b1f12e102101a7bc8a2abad83d4
[ "res = []\nif not root:\n return []\n\ndef _recur_func(node, level):\n if len(res) == level:\n res.append([])\n res[level].append(node.val)\n if node.left:\n _recur_func(node.left, level + 1)\n if node.right:\n _recur_func(node.right, level + 1)\n_recur_func(root, 0)\nreturn res"...
<|body_start_0|> res = [] if not root: return [] def _recur_func(node, level): if len(res) == level: res.append([]) res[level].append(node.val) if node.left: _recur_func(node.left, level + 1) if node.rig...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrder_recursion(self, root: TreeNode): """递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list""" <|body_0|> def levelOrder_iteration_t(self, root: TreeNode): """迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: res""" <|body_1|> def level...
stack_v2_sparse_classes_36k_train_025814
3,953
no_license
[ { "docstring": "递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list", "name": "levelOrder_recursion", "signature": "def levelOrder_recursion(self, root: TreeNode)" }, { "docstring": "迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: res", "name": "levelOrder_iteration_t", "signature": "def ...
3
stack_v2_sparse_classes_30k_train_011869
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder_recursion(self, root: TreeNode): 递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list - def levelOrder_iteration_t(self, root: TreeNode): 迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder_recursion(self, root: TreeNode): 递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list - def levelOrder_iteration_t(self, root: TreeNode): 迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :...
62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c
<|skeleton|> class Solution: def levelOrder_recursion(self, root: TreeNode): """递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list""" <|body_0|> def levelOrder_iteration_t(self, root: TreeNode): """迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: res""" <|body_1|> def level...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrder_recursion(self, root: TreeNode): """递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list""" res = [] if not root: return [] def _recur_func(node, level): if len(res) == level: res.append([]) res[level]...
the_stack_v2_python_sparse
leetcode/solved/102_.py
usnnu/python_foundation
train
0
0acb1f3221120f5e760341849cc7b200ba3aef62
[ "xml = xmlwitch.Builder()\nwith xml['test']:\n xml.LessGreater('><')\n xml.ControlCode(chr(26) + chr(0))\n xml.BadUnicode(''.join([unichr(128), unichr(65534)]))\n xml.UnicodePaired(''.join([unichr(55296), unichr(56320)]))\ns = str(xml)\nself.assertTrue(u'<LessGreater>&gt;&lt;</LessGreater>' in s)\nself....
<|body_start_0|> xml = xmlwitch.Builder() with xml['test']: xml.LessGreater('><') xml.ControlCode(chr(26) + chr(0)) xml.BadUnicode(''.join([unichr(128), unichr(65534)])) xml.UnicodePaired(''.join([unichr(55296), unichr(56320)])) s = str(xml) ...
Tests for XML generation by xmlwitch.
XmlWitchTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XmlWitchTest: """Tests for XML generation by xmlwitch.""" def testInvalidCharacters(self): """Test handling of invalid characters in XML.""" <|body_0|> def testALLTheThings111(self): """Test all other code points for well-formed XML.""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_025815
2,235
permissive
[ { "docstring": "Test handling of invalid characters in XML.", "name": "testInvalidCharacters", "signature": "def testInvalidCharacters(self)" }, { "docstring": "Test all other code points for well-formed XML.", "name": "testALLTheThings111", "signature": "def testALLTheThings111(self)" ...
2
null
Implement the Python class `XmlWitchTest` described below. Class description: Tests for XML generation by xmlwitch. Method signatures and docstrings: - def testInvalidCharacters(self): Test handling of invalid characters in XML. - def testALLTheThings111(self): Test all other code points for well-formed XML.
Implement the Python class `XmlWitchTest` described below. Class description: Tests for XML generation by xmlwitch. Method signatures and docstrings: - def testInvalidCharacters(self): Test handling of invalid characters in XML. - def testALLTheThings111(self): Test all other code points for well-formed XML. <|skele...
b01e4444f3c7f12b1af7837203b37060fd443bb7
<|skeleton|> class XmlWitchTest: """Tests for XML generation by xmlwitch.""" def testInvalidCharacters(self): """Test handling of invalid characters in XML.""" <|body_0|> def testALLTheThings111(self): """Test all other code points for well-formed XML.""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XmlWitchTest: """Tests for XML generation by xmlwitch.""" def testInvalidCharacters(self): """Test handling of invalid characters in XML.""" xml = xmlwitch.Builder() with xml['test']: xml.LessGreater('><') xml.ControlCode(chr(26) + chr(0)) xml.B...
the_stack_v2_python_sparse
tr/xmlwitch_test.py
pombredanne/catawampus-1
train
0
b84b429655ea10b82dca273339ca87934dda9a5f
[ "if path_to_config.endswith('.json'):\n return self.parse_json_config(path_to_config)\nelse:\n return None", "json_file = open(path_to_json_config)\njson_config = json.load(json_file)\njson_file.close()\nreturn json_config" ]
<|body_start_0|> if path_to_config.endswith('.json'): return self.parse_json_config(path_to_config) else: return None <|end_body_0|> <|body_start_1|> json_file = open(path_to_json_config) json_config = json.load(json_file) json_file.close() return...
The ConfigProvider provides the interface for getting the various config files i.e. via a path specification.
ConfigProvider
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigProvider: """The ConfigProvider provides the interface for getting the various config files i.e. via a path specification.""" def get_config(self, path_to_config): """Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the co...
stack_v2_sparse_classes_36k_train_025816
1,014
permissive
[ { "docstring": "Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the config file. :return: config: (Dictionary) The parsed config.", "name": "get_config", "signature": "def get_config(self, path_to_config)" }, { "docstring": "Parses the con...
2
stack_v2_sparse_classes_30k_train_021339
Implement the Python class `ConfigProvider` described below. Class description: The ConfigProvider provides the interface for getting the various config files i.e. via a path specification. Method signatures and docstrings: - def get_config(self, path_to_config): Parses the config from a file with the path: path_to_c...
Implement the Python class `ConfigProvider` described below. Class description: The ConfigProvider provides the interface for getting the various config files i.e. via a path specification. Method signatures and docstrings: - def get_config(self, path_to_config): Parses the config from a file with the path: path_to_c...
4bfea618727eb403e8b6f9863488e8b6e7d021cd
<|skeleton|> class ConfigProvider: """The ConfigProvider provides the interface for getting the various config files i.e. via a path specification.""" def get_config(self, path_to_config): """Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the co...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigProvider: """The ConfigProvider provides the interface for getting the various config files i.e. via a path specification.""" def get_config(self, path_to_config): """Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the config file. :r...
the_stack_v2_python_sparse
ConfigInput_Component/ConfigProvider.py
BonifazStuhr/CSNN
train
7
897028f25efced9aedd4c5848e44158771dffe22
[ "self.l = nums\nself.n = k\nself.last = -sys.maxsize - 1", "k = self.n\nself.l.append(val)\n\ndef quickSelect(arr, k):\n big = []\n small = []\n piv = random.randint(0, len(arr) - 1)\n temp = arr[piv]\n for i, x in enumerate(arr):\n if i == piv:\n continue\n if x > temp:\n ...
<|body_start_0|> self.l = nums self.n = k self.last = -sys.maxsize - 1 <|end_body_0|> <|body_start_1|> k = self.n self.l.append(val) def quickSelect(arr, k): big = [] small = [] piv = random.randint(0, len(arr) - 1) temp =...
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|> self.l = nums self.n = k self.last = -sys....
stack_v2_sparse_classes_36k_train_025817
1,125
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_test_001200
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...
de8f9e7a7c45e325ac0de43a4e1f711a7c6a0a0c
<|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]""" self.l = nums self.n = k self.last = -sys.maxsize - 1 def add(self, val): """:type val: int :rtype: int""" k = self.n self.l.append(val) def quickSelect(arr, ...
the_stack_v2_python_sparse
KthLargest.py
unsortedtosorted/codeChallenges
train
0
a321abfc612e56695ff34d12616d47f984048a3b
[ "left = 0\nright = len(arr) - 1\nremove_size = len(arr) - k\nwhile remove_size > 0:\n if abs(arr[left] - x) <= abs(arr[right] - x):\n right -= 1\n else:\n left += 1\n remove_size -= 1\nreturn arr[left:left + k]", "left = 0\nright = len(arr) - k\nwhile left < right:\n mid = left + right >...
<|body_start_0|> left = 0 right = len(arr) - 1 remove_size = len(arr) - k while remove_size > 0: if abs(arr[left] - x) <= abs(arr[right] - x): right -= 1 else: left += 1 remove_size -= 1 return arr[left:left + k]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: """保留 k 个差值最小元素 :param arr: :param k: :param x: :return:""" <|body_0|> def findClosestElements1(self, arr: List[int], k: int, x: int) -> List[int]: """二分查找 :param arr: :param k: :pa...
stack_v2_sparse_classes_36k_train_025818
1,883
no_license
[ { "docstring": "保留 k 个差值最小元素 :param arr: :param k: :param x: :return:", "name": "findClosestElements", "signature": "def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]" }, { "docstring": "二分查找 :param arr: :param k: :param x: :return:", "name": "findClosestElements1", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 保留 k 个差值最小元素 :param arr: :param k: :param x: :return: - def findClosestElements1(self, arr: List[int],...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 保留 k 个差值最小元素 :param arr: :param k: :param x: :return: - def findClosestElements1(self, arr: List[int],...
9acba92695c06406f12f997a720bfe1deb9464a8
<|skeleton|> class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: """保留 k 个差值最小元素 :param arr: :param k: :param x: :return:""" <|body_0|> def findClosestElements1(self, arr: List[int], k: int, x: int) -> List[int]: """二分查找 :param arr: :param k: :pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: """保留 k 个差值最小元素 :param arr: :param k: :param x: :return:""" left = 0 right = len(arr) - 1 remove_size = len(arr) - k while remove_size > 0: if abs(arr[left] - x) <= abs(arr...
the_stack_v2_python_sparse
datastructure/binary_array/FindClosestElements.py
yinhuax/leet_code
train
0
d65d60032f190380763162a27c93d2cf9b28903e
[ "re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])", "re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c...
<|body_start_0|> re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo']) result = re Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg']) <|end_body_0|> <|body_start_1|> ...
VEMS月票类型以及修改月票订单同步
TestVemsMonthTicketResync
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestVemsMonthTicketResync: """VEMS月票类型以及修改月票订单同步""" def test_createMonthTicketConfig(self, userLogin, send_data, expect): """创建自定义月票类型""" <|body_0|> def test_openMonthTicketBill(self, userLogin, send_data, expect): """用自定义月票类型开通月票""" <|body_1|> def t...
stack_v2_sparse_classes_36k_train_025819
3,060
no_license
[ { "docstring": "创建自定义月票类型", "name": "test_createMonthTicketConfig", "signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)" }, { "docstring": "用自定义月票类型开通月票", "name": "test_openMonthTicketBill", "signature": "def test_openMonthTicketBill(self, userLogin, send_d...
6
null
Implement the Python class `TestVemsMonthTicketResync` described below. Class description: VEMS月票类型以及修改月票订单同步 Method signatures and docstrings: - def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型 - def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票 - def test_...
Implement the Python class `TestVemsMonthTicketResync` described below. Class description: VEMS月票类型以及修改月票订单同步 Method signatures and docstrings: - def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型 - def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票 - def test_...
34c368c109867da26d9256bca85f872b0fac2ea7
<|skeleton|> class TestVemsMonthTicketResync: """VEMS月票类型以及修改月票订单同步""" def test_createMonthTicketConfig(self, userLogin, send_data, expect): """创建自定义月票类型""" <|body_0|> def test_openMonthTicketBill(self, userLogin, send_data, expect): """用自定义月票类型开通月票""" <|body_1|> def t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestVemsMonthTicketResync: """VEMS月票类型以及修改月票订单同步""" def test_createMonthTicketConfig(self, userLogin, send_data, expect): """创建自定义月票类型""" re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['vali...
the_stack_v2_python_sparse
test_suite/parkingConfig/vemsParking/monthTicketManage/test_monthTicketResyncVems.py
oyebino/pomp_api
train
1
664fe45bd864945570a7fd4ac5223c603e32bc3a
[ "conv1 = nn.Conv3d(Cin, Cin, kernel_size=(3, 2, 2), stride=(2, 2, 2))\nconv2 = nn.Conv3d(Cin, Cin, kernel_size=(3, 3, 2), stride=(2, 2, 2), padding=(0, 0, 1))\nconv3 = nn.Conv3d(Cin, Cin, kernel_size=(3, 3, 3), stride=(2, 2, 1), padding=(0, 0, 0))\nreturn nn.Sequential(conv1, activation_constructor(Cin, False), con...
<|body_start_0|> conv1 = nn.Conv3d(Cin, Cin, kernel_size=(3, 2, 2), stride=(2, 2, 2)) conv2 = nn.Conv3d(Cin, Cin, kernel_size=(3, 3, 2), stride=(2, 2, 2), padding=(0, 0, 1)) conv3 = nn.Conv3d(Cin, Cin, kernel_size=(3, 3, 3), stride=(2, 2, 1), padding=(0, 0, 0)) return nn.Sequential(conv1...
DownUp
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DownUp: 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, channel...
stack_v2_sparse_classes_36k_train_025820
7,226
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_007147
Implement the Python class `DownUp` described below. Class description: Implement the DownUp 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 downsample2(ac...
Implement the Python class `DownUp` described below. Class description: Implement the DownUp 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 downsample2(ac...
b4d43895229205ee2cd16b15ee20beccb33b71d6
<|skeleton|> class DownUp: 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, channel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DownUp: def downsample1(activation_constructor, Cin, channel_small): """First RAB downsample""" conv1 = nn.Conv3d(Cin, Cin, kernel_size=(3, 2, 2), stride=(2, 2, 2)) conv2 = nn.Conv3d(Cin, Cin, kernel_size=(3, 3, 2), stride=(2, 2, 2), padding=(0, 0, 1)) conv3 = nn.Conv3d(Cin, Ci...
the_stack_v2_python_sparse
src/VarDACAE/nn/CLIC_models/tucodec.py
kikyoiii/Data_Assimilation
train
0
ec53f19c80eb1e296e12949fc45f5cd3af31f792
[ "super().__init__()\nself.norm = torch.nn.InstanceNorm1d(in_channels)\nself.aux_conv = torch.nn.Sequential(torch.nn.Conv1d(aux_channels, in_channels, kernel_size, 1, bias=bias, padding=(kernel_size - 1) // 2))\nself.gated_conv = torch.nn.Sequential(torch.nn.Conv1d(in_channels, in_channels * 2, kernel_size, 1, bias=...
<|body_start_0|> super().__init__() self.norm = torch.nn.InstanceNorm1d(in_channels) self.aux_conv = torch.nn.Sequential(torch.nn.Conv1d(aux_channels, in_channels, kernel_size, 1, bias=bias, padding=(kernel_size - 1) // 2)) self.gated_conv = torch.nn.Sequential(torch.nn.Conv1d(in_channel...
TADE Layer module.
TADELayer
[ "MIT", "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TADELayer: """TADE Layer module.""" def __init__(self, in_channels=64, aux_channels=80, kernel_size=9, bias=True, upsample_factor=2, upsample_mode='nearest'): """Initilize TADE layer.""" <|body_0|> def forward(self, x, c): """Calculate forward propagation. Args: ...
stack_v2_sparse_classes_36k_train_025821
4,805
permissive
[ { "docstring": "Initilize TADE layer.", "name": "__init__", "signature": "def __init__(self, in_channels=64, aux_channels=80, kernel_size=9, bias=True, upsample_factor=2, upsample_mode='nearest')" }, { "docstring": "Calculate forward propagation. Args: x (Tensor): Input tensor (B, in_channels, T...
2
stack_v2_sparse_classes_30k_train_006873
Implement the Python class `TADELayer` described below. Class description: TADE Layer module. Method signatures and docstrings: - def __init__(self, in_channels=64, aux_channels=80, kernel_size=9, bias=True, upsample_factor=2, upsample_mode='nearest'): Initilize TADE layer. - def forward(self, x, c): Calculate forwar...
Implement the Python class `TADELayer` described below. Class description: TADE Layer module. Method signatures and docstrings: - def __init__(self, in_channels=64, aux_channels=80, kernel_size=9, bias=True, upsample_factor=2, upsample_mode='nearest'): Initilize TADE layer. - def forward(self, x, c): Calculate forwar...
c68b4590ab20eaf55e0b96b82325a90177fffd5c
<|skeleton|> class TADELayer: """TADE Layer module.""" def __init__(self, in_channels=64, aux_channels=80, kernel_size=9, bias=True, upsample_factor=2, upsample_mode='nearest'): """Initilize TADE layer.""" <|body_0|> def forward(self, x, c): """Calculate forward propagation. Args: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TADELayer: """TADE Layer module.""" def __init__(self, in_channels=64, aux_channels=80, kernel_size=9, bias=True, upsample_factor=2, upsample_mode='nearest'): """Initilize TADE layer.""" super().__init__() self.norm = torch.nn.InstanceNorm1d(in_channels) self.aux_conv = to...
the_stack_v2_python_sparse
parallel_wavegan/layers/tade_res_block.py
kan-bayashi/ParallelWaveGAN
train
1,405
19ef9eafcaee282c20d5097a625eec1dc607db6a
[ "super(InverseGamma, self).__init__(transform)\nself.covariance_prior = False\nself.alpha = alpha\nself.beta = beta", "if self.transform is not None:\n x = self.transform(x)\nreturn (-self.alpha - 1) * np.log(x) - self.beta / float(x)", "if self.transform is not None:\n x = self.transform(x)\nreturn x ** ...
<|body_start_0|> super(InverseGamma, self).__init__(transform) self.covariance_prior = False self.alpha = alpha self.beta = beta <|end_body_0|> <|body_start_1|> if self.transform is not None: x = self.transform(x) return (-self.alpha - 1) * np.log(x) - self.b...
Inverse Gamma Distribution ---- This class contains methods relating to the inverse gamma distribution for time series.
InverseGamma
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InverseGamma: """Inverse Gamma Distribution ---- This class contains methods relating to the inverse gamma distribution for time series.""" def __init__(self, alpha, beta, transform=None, **kwargs): """Parameters ---------- alpha : float Alpha parameter for the Inverse Gamma distribu...
stack_v2_sparse_classes_36k_train_025822
1,641
permissive
[ { "docstring": "Parameters ---------- alpha : float Alpha parameter for the Inverse Gamma distribution beta : float Beta parameter for the Inverse Gamma distribution transform : str Whether to apply a transformation - e.g. 'exp' or 'logit'", "name": "__init__", "signature": "def __init__(self, alpha, be...
3
stack_v2_sparse_classes_30k_train_004745
Implement the Python class `InverseGamma` described below. Class description: Inverse Gamma Distribution ---- This class contains methods relating to the inverse gamma distribution for time series. Method signatures and docstrings: - def __init__(self, alpha, beta, transform=None, **kwargs): Parameters ---------- alp...
Implement the Python class `InverseGamma` described below. Class description: Inverse Gamma Distribution ---- This class contains methods relating to the inverse gamma distribution for time series. Method signatures and docstrings: - def __init__(self, alpha, beta, transform=None, **kwargs): Parameters ---------- alp...
f5166854bb4a24c997fc2b9b4e3e37325a740d34
<|skeleton|> class InverseGamma: """Inverse Gamma Distribution ---- This class contains methods relating to the inverse gamma distribution for time series.""" def __init__(self, alpha, beta, transform=None, **kwargs): """Parameters ---------- alpha : float Alpha parameter for the Inverse Gamma distribu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InverseGamma: """Inverse Gamma Distribution ---- This class contains methods relating to the inverse gamma distribution for time series.""" def __init__(self, alpha, beta, transform=None, **kwargs): """Parameters ---------- alpha : float Alpha parameter for the Inverse Gamma distribution beta : f...
the_stack_v2_python_sparse
pyflux/families/inverse_gamma.py
ecastrow/pyflux
train
0
7c61c473589c864f500d34c6798584c548a92ca3
[ "type_str = 'Not Classical' if negate else 'Classical'\nsuper().__init__(self._syntax_for_measure(qubit), self._syntax_for_measure(cbit), pcrit, negate, type_str)\nself._expval = expval if expval is None or isinstance(expval, int) else int(expval, 2)\nif expval is not None and self._expval not in range(0, 2 ** len(...
<|body_start_0|> type_str = 'Not Classical' if negate else 'Classical' super().__init__(self._syntax_for_measure(qubit), self._syntax_for_measure(cbit), pcrit, negate, type_str) self._expval = expval if expval is None or isinstance(expval, int) else int(expval, 2) if expval is not None a...
A measurement instruction that additionally performs statistical tests on the measurement outcomes to assert whether the state is a classical state or not.
AssertClassical
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssertClassical: """A measurement instruction that additionally performs statistical tests on the measurement outcomes to assert whether the state is a classical state or not.""" def __init__(self, qubit, cbit, pcrit, expval, negate): """Constructor for AssertClassical Args: qubit(Qu...
stack_v2_sparse_classes_36k_train_025823
6,186
permissive
[ { "docstring": "Constructor for AssertClassical Args: qubit(QuantumRegister or list): quantum register cbit(ClassicalRegister or list): classical register pcrit(float): the critical p-value expval(int or string or None): the expected value If no expected value specified, then this assertion just checks that the...
2
null
Implement the Python class `AssertClassical` described below. Class description: A measurement instruction that additionally performs statistical tests on the measurement outcomes to assert whether the state is a classical state or not. Method signatures and docstrings: - def __init__(self, qubit, cbit, pcrit, expval...
Implement the Python class `AssertClassical` described below. Class description: A measurement instruction that additionally performs statistical tests on the measurement outcomes to assert whether the state is a classical state or not. Method signatures and docstrings: - def __init__(self, qubit, cbit, pcrit, expval...
8ee4f02be2ad4d3be87cbd2368d0bd509411d3e3
<|skeleton|> class AssertClassical: """A measurement instruction that additionally performs statistical tests on the measurement outcomes to assert whether the state is a classical state or not.""" def __init__(self, qubit, cbit, pcrit, expval, negate): """Constructor for AssertClassical Args: qubit(Qu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssertClassical: """A measurement instruction that additionally performs statistical tests on the measurement outcomes to assert whether the state is a classical state or not.""" def __init__(self, qubit, cbit, pcrit, expval, negate): """Constructor for AssertClassical Args: qubit(QuantumRegister...
the_stack_v2_python_sparse
qiskit/assertions/assertclassical.py
edasgupta/qiskit-terra
train
3
826631e93b6d1d4f98441237767f5aaf2ba87972
[ "expected_checksum = database.Database.ChecksumForText(hwid_config_contents)\ncontents_analyzer_inst = contents_analyzer.ContentsAnalyzer(hwid_config_contents, expected_checksum, None)\nreport = contents_analyzer_inst.ValidateIntegrity()\nif report.errors:\n raise ValidationError(report.errors)", "expected_che...
<|body_start_0|> expected_checksum = database.Database.ChecksumForText(hwid_config_contents) contents_analyzer_inst = contents_analyzer.ContentsAnalyzer(hwid_config_contents, expected_checksum, None) report = contents_analyzer_inst.ValidateIntegrity() if report.errors: raise ...
Validates HWID configs.
HwidValidator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HwidValidator: """Validates HWID configs.""" def Validate(self, hwid_config_contents): """Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.""" <|body_0|> def ValidateChang...
stack_v2_sparse_classes_36k_train_025824
3,013
permissive
[ { "docstring": "Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.", "name": "Validate", "signature": "def Validate(self, hwid_config_contents)" }, { "docstring": "Validates a HWID config change. T...
2
stack_v2_sparse_classes_30k_train_015808
Implement the Python class `HwidValidator` described below. Class description: Validates HWID configs. Method signatures and docstrings: - def Validate(self, hwid_config_contents): Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config ...
Implement the Python class `HwidValidator` described below. Class description: Validates HWID configs. Method signatures and docstrings: - def Validate(self, hwid_config_contents): Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config ...
a1b0fccd68987d8cd9c89710adc3c04b868347ec
<|skeleton|> class HwidValidator: """Validates HWID configs.""" def Validate(self, hwid_config_contents): """Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.""" <|body_0|> def ValidateChang...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HwidValidator: """Validates HWID configs.""" def Validate(self, hwid_config_contents): """Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.""" expected_checksum = database.Database.Checksum...
the_stack_v2_python_sparse
py/hwid/service/appengine/hwid_validator.py
bridder/factory
train
0
ae34b601dd5abffd6eed70cfec03203ba0653995
[ "self._station = station\nself._destinations = destinations\nself._directions = directions\nself._lines = lines\nself._products = products\nself._timeoffset = timeoffset\nself._number = number\nself._include_ubahn = 'U-Bahn' in self._products\nself._include_tram = 'Tram' in self._products\nself._include_bus = 'Bus'...
<|body_start_0|> self._station = station self._destinations = destinations self._directions = directions self._lines = lines self._products = products self._timeoffset = timeoffset self._number = number self._include_ubahn = 'U-Bahn' in self._products ...
Pull data from the mvg-live.de web page.
MVGLiveData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MVGLiveData: """Pull data from the mvg-live.de web page.""" def __init__(self, station, destinations, directions, lines, products, timeoffset, number): """Initialize the sensor.""" <|body_0|> def update(self): """Update the connection data.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_025825
6,947
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, station, destinations, directions, lines, products, timeoffset, number)" }, { "docstring": "Update the connection data.", "name": "update", "signature": "def update(self)" } ]
2
null
Implement the Python class `MVGLiveData` described below. Class description: Pull data from the mvg-live.de web page. Method signatures and docstrings: - def __init__(self, station, destinations, directions, lines, products, timeoffset, number): Initialize the sensor. - def update(self): Update the connection data.
Implement the Python class `MVGLiveData` described below. Class description: Pull data from the mvg-live.de web page. Method signatures and docstrings: - def __init__(self, station, destinations, directions, lines, products, timeoffset, number): Initialize the sensor. - def update(self): Update the connection data. ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class MVGLiveData: """Pull data from the mvg-live.de web page.""" def __init__(self, station, destinations, directions, lines, products, timeoffset, number): """Initialize the sensor.""" <|body_0|> def update(self): """Update the connection data.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MVGLiveData: """Pull data from the mvg-live.de web page.""" def __init__(self, station, destinations, directions, lines, products, timeoffset, number): """Initialize the sensor.""" self._station = station self._destinations = destinations self._directions = directions ...
the_stack_v2_python_sparse
homeassistant/components/mvglive/sensor.py
home-assistant/core
train
35,501
e6c2feacac10e77d6342b77f4e816eb8add0b1f7
[ "self.lr_scheduler = lr_scheduler\nself.print_lr = print_lr\nself.logger = logging.getLogger(name)\nself.epoch_level = epoch_level\nif not callable(step_transform):\n raise TypeError(f'step_transform must be callable but is {type(step_transform).__name__}.')\nself.step_transform = step_transform\nself._name = na...
<|body_start_0|> self.lr_scheduler = lr_scheduler self.print_lr = print_lr self.logger = logging.getLogger(name) self.epoch_level = epoch_level if not callable(step_transform): raise TypeError(f'step_transform must be callable but is {type(step_transform).__name__}.')...
Ignite handler to update the Learning Rate based on PyTorch LR scheduler.
LrScheduleHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LrScheduleHandler: """Ignite handler to update the Learning Rate based on PyTorch LR scheduler.""" def __init__(self, lr_scheduler: _LRScheduler | ReduceLROnPlateau, print_lr: bool=True, name: str | None=None, epoch_level: bool=True, step_transform: Callable[[Engine], Any]=lambda engine: ())...
stack_v2_sparse_classes_36k_train_025826
3,575
permissive
[ { "docstring": "Args: lr_scheduler: typically, lr_scheduler should be PyTorch lr_scheduler object. If customized version, must have `step` and `get_last_lr` methods. print_lr: whether to print out the latest learning rate with logging. name: identifier of logging.logger to use, if None, defaulting to ``engine.l...
3
null
Implement the Python class `LrScheduleHandler` described below. Class description: Ignite handler to update the Learning Rate based on PyTorch LR scheduler. Method signatures and docstrings: - def __init__(self, lr_scheduler: _LRScheduler | ReduceLROnPlateau, print_lr: bool=True, name: str | None=None, epoch_level: b...
Implement the Python class `LrScheduleHandler` described below. Class description: Ignite handler to update the Learning Rate based on PyTorch LR scheduler. Method signatures and docstrings: - def __init__(self, lr_scheduler: _LRScheduler | ReduceLROnPlateau, print_lr: bool=True, name: str | None=None, epoch_level: b...
e48c3e2c741fa3fc705c4425d17ac4a5afac6c47
<|skeleton|> class LrScheduleHandler: """Ignite handler to update the Learning Rate based on PyTorch LR scheduler.""" def __init__(self, lr_scheduler: _LRScheduler | ReduceLROnPlateau, print_lr: bool=True, name: str | None=None, epoch_level: bool=True, step_transform: Callable[[Engine], Any]=lambda engine: ())...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LrScheduleHandler: """Ignite handler to update the Learning Rate based on PyTorch LR scheduler.""" def __init__(self, lr_scheduler: _LRScheduler | ReduceLROnPlateau, print_lr: bool=True, name: str | None=None, epoch_level: bool=True, step_transform: Callable[[Engine], Any]=lambda engine: ()) -> None: ...
the_stack_v2_python_sparse
monai/handlers/lr_schedule_handler.py
Project-MONAI/MONAI
train
4,805
ac92d98280c94f3bc8d3d4dc39547210bc6be7bc
[ "extractor = LightSocialUrlsExtractor()\ndescription = result.get_description_from_api_history()\nextra_urls = list(result.get_urls_from_api_history())\nurls_detected, non_social_urls_detected = extractor.extract_urls(description=description, extra_urls=extra_urls, profile_username=result.username)\nresult.set_soci...
<|body_start_0|> extractor = LightSocialUrlsExtractor() description = result.get_description_from_api_history() extra_urls = list(result.get_urls_from_api_history()) urls_detected, non_social_urls_detected = extractor.extract_urls(description=description, extra_urls=extra_urls, profile_u...
This processor gets urls from description of the given InstagramProfile and finds all its corresponding social and non-social urls and stores the result in the InstagramProfile.
DetectSocialUrlsProcessor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DetectSocialUrlsProcessor: """This processor gets urls from description of the given InstagramProfile and finds all its corresponding social and non-social urls and stores the result in the InstagramProfile.""" def proceed(self, result): """This function determines condition when it ...
stack_v2_sparse_classes_36k_train_025827
30,721
no_license
[ { "docstring": "This function determines condition when it will proceed to the next Processor, Classifier or Upgrader in chain. Gets Profile as result", "name": "proceed", "signature": "def proceed(self, result)" }, { "docstring": "This function is called when performing Processor as a part of p...
2
null
Implement the Python class `DetectSocialUrlsProcessor` described below. Class description: This processor gets urls from description of the given InstagramProfile and finds all its corresponding social and non-social urls and stores the result in the InstagramProfile. Method signatures and docstrings: - def proceed(s...
Implement the Python class `DetectSocialUrlsProcessor` described below. Class description: This processor gets urls from description of the given InstagramProfile and finds all its corresponding social and non-social urls and stores the result in the InstagramProfile. Method signatures and docstrings: - def proceed(s...
2f15c4ddd8bbb112c407d222ae48746b626c674f
<|skeleton|> class DetectSocialUrlsProcessor: """This processor gets urls from description of the given InstagramProfile and finds all its corresponding social and non-social urls and stores the result in the InstagramProfile.""" def proceed(self, result): """This function determines condition when it ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DetectSocialUrlsProcessor: """This processor gets urls from description of the given InstagramProfile and finds all its corresponding social and non-social urls and stores the result in the InstagramProfile.""" def proceed(self, result): """This function determines condition when it will proceed ...
the_stack_v2_python_sparse
Projects/miami_metro/social_discovery/processors.py
TopWebGhost/Angular-Influencer
train
1
bd4f9c7481b0851c0db8a0838c371b2951fb0075
[ "if not root:\n return 'X'\nif not root.left and (not root.right):\n return str(root.val)\nl = self.serialize(root.left) if root.left else 'X'\nr = self.serialize(root.right) if root.right else 'X'\nreturn '%s(%s,%s)' % (str(root.val), l, r)", "i = data.find('(')\nif i == -1:\n if data == 'X':\n r...
<|body_start_0|> if not root: return 'X' if not root.left and (not root.right): return str(root.val) l = self.serialize(root.left) if root.left else 'X' r = self.serialize(root.right) if root.right else 'X' return '%s(%s,%s)' % (str(root.val), l, r) <|end_...
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_025828
1,499
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_018912
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:...
616939d1599b5a135747b0c4dd1f989974835f40
<|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 'X' if not root.left and (not root.right): return str(root.val) l = self.serialize(root.left) if root.left else 'X' r ...
the_stack_v2_python_sparse
297. Serialize and Deserialize Binary Tree.py
BITMystery/leetcode-journey
train
0
f734bfadb0561e90e1e3d50d833e2f8cfcbb1715
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessReviewSet()", "from .access_review_history_definition import AccessReviewHistoryDefinition\nfrom .access_review_schedule_definition import AccessReviewScheduleDefinition\nfrom .entity import Entity\nfrom .access_review_history_de...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return AccessReviewSet() <|end_body_0|> <|body_start_1|> from .access_review_history_definition import AccessReviewHistoryDefinition from .access_review_schedule_definition import AccessReviewS...
AccessReviewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccessReviewSet: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewSet: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret...
stack_v2_sparse_classes_36k_train_025829
3,028
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: AccessReviewSet", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_val...
3
stack_v2_sparse_classes_30k_train_005363
Implement the Python class `AccessReviewSet` described below. Class description: Implement the AccessReviewSet class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewSet: Creates a new instance of the appropriate class based on discriminator...
Implement the Python class `AccessReviewSet` described below. Class description: Implement the AccessReviewSet class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewSet: Creates a new instance of the appropriate class based on discriminator...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class AccessReviewSet: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewSet: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccessReviewSet: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewSet: """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: AccessRe...
the_stack_v2_python_sparse
msgraph/generated/models/access_review_set.py
microsoftgraph/msgraph-sdk-python
train
135
aa38db5eb532ae0799f852a2b06ff8f6ea10f080
[ "for i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] == target:\n return True\nreturn False", "res = []\nfor x in matrix:\n res.extend(x)\nreturn target in res", "res = []\nfor x in matrix:\n res.extend(x)\nres.sort()\nleft, right = (0, len(res) - 1)\nwhile l...
<|body_start_0|> for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] == target: return True return False <|end_body_0|> <|body_start_1|> res = [] for x in matrix: res.extend(x) return target in res...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def searchMatrix(self, matrix, target): """Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)""" <|body_0|> def searchMatrix1(self, matrix, target): """Purpose: searches 2D matrix, and returns True if target is found. ...
stack_v2_sparse_classes_36k_train_025830
1,839
no_license
[ { "docstring": "Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)", "name": "searchMatrix", "signature": "def searchMatrix(self, matrix, target)" }, { "docstring": "Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)",...
4
stack_v2_sparse_classes_30k_train_021451
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchMatrix(self, matrix, target): Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2) - def searchMatrix1(self, matrix, target): Purpo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchMatrix(self, matrix, target): Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2) - def searchMatrix1(self, matrix, target): Purpo...
95a86cbbca28d0c0f6d72d28a2f1cb5a86327934
<|skeleton|> class Solution: def searchMatrix(self, matrix, target): """Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)""" <|body_0|> def searchMatrix1(self, matrix, target): """Purpose: searches 2D matrix, and returns True if target is found. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def searchMatrix(self, matrix, target): """Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)""" for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] == target: return True ...
the_stack_v2_python_sparse
search2dMatrix.py
tashakim/puzzles_python
train
8
6fd4f345f54c15f5e60d06f342fa92e49d60f647
[ "self.path = path\nself.ext = ext\nself.read_args = []\nself.read_kwargs = {}\nif load:\n self.df = self.load_dataframe()", "if self.ext == '.csv':\n df = pd.read_csv(self.path, *self.read_args, **self.read_kwargs)\n return df.set_index(df.columns.tolist()[:-2])\nelif self.ext == '.json':\n df = pd.re...
<|body_start_0|> self.path = path self.ext = ext self.read_args = [] self.read_kwargs = {} if load: self.df = self.load_dataframe() <|end_body_0|> <|body_start_1|> if self.ext == '.csv': df = pd.read_csv(self.path, *self.read_args, **self.read_kwa...
DataFrameWrapper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataFrameWrapper: def __init__(self, path, ext, load=True): """path: file system path to the dataframe on disk ext: file extension used to interpret the file based on pandas IO load: skip loading the dataframe if False""" <|body_0|> def load_dataframe(self): """Use p...
stack_v2_sparse_classes_36k_train_025831
4,029
no_license
[ { "docstring": "path: file system path to the dataframe on disk ext: file extension used to interpret the file based on pandas IO load: skip loading the dataframe if False", "name": "__init__", "signature": "def __init__(self, path, ext, load=True)" }, { "docstring": "Use pandas IO tools to load...
4
null
Implement the Python class `DataFrameWrapper` described below. Class description: Implement the DataFrameWrapper class. Method signatures and docstrings: - def __init__(self, path, ext, load=True): path: file system path to the dataframe on disk ext: file extension used to interpret the file based on pandas IO load: ...
Implement the Python class `DataFrameWrapper` described below. Class description: Implement the DataFrameWrapper class. Method signatures and docstrings: - def __init__(self, path, ext, load=True): path: file system path to the dataframe on disk ext: file extension used to interpret the file based on pandas IO load: ...
5a56b57732ffa12ec1261a56f70820f596edb97a
<|skeleton|> class DataFrameWrapper: def __init__(self, path, ext, load=True): """path: file system path to the dataframe on disk ext: file extension used to interpret the file based on pandas IO load: skip loading the dataframe if False""" <|body_0|> def load_dataframe(self): """Use p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataFrameWrapper: def __init__(self, path, ext, load=True): """path: file system path to the dataframe on disk ext: file extension used to interpret the file based on pandas IO load: skip loading the dataframe if False""" self.path = path self.ext = ext self.read_args = [] ...
the_stack_v2_python_sparse
python/DataFrameWrapper.py
cms-analysis/HiggsAnalysis-CombinedLimit
train
59
d42fa00fd8d302fdad389f2115c77e539587fcb7
[ "self.eventlog_dirs = eventlog_dirs\nself.event_tag = event_tag\nself.output_path = output_path\nself.title = title\nself.xaxis_title = xaxis_title\nself.show_graph = show_graph\nself.end_step = end_step\nif graph_agg == GraphAggTypes.MEAN:\n self.graph_agg = np.mean\nelif graph_agg == GraphAggTypes.MEDIAN:\n ...
<|body_start_0|> self.eventlog_dirs = eventlog_dirs self.event_tag = event_tag self.output_path = output_path self.title = title self.xaxis_title = xaxis_title self.show_graph = show_graph self.end_step = end_step if graph_agg == GraphAggTypes.MEAN: ...
Builds graphs and other summary information from eventlogs.
StatsBuilder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StatsBuilder: """Builds graphs and other summary information from eventlogs.""" def __init__(self, eventlog_dirs: List[str], event_tag: str, output_path: str='.', title: str='', xaxis_title: str='steps', yaxis_title: Optional[str]=None, graph_agg: GraphAggTypes=GraphAggTypes.MEAN, output_pre...
stack_v2_sparse_classes_36k_train_025832
9,181
permissive
[ { "docstring": "Initializes StatsBuilder class. Args: eventlog_dirs: List of paths to event log directories to process. event_tag: Event to extract from the logs. output_path: Output path for artifacts, e.g. graphs and cvs files. title: Title of the graph. xaxis_title: Title for x-axis of the graph. Defaults to...
6
null
Implement the Python class `StatsBuilder` described below. Class description: Builds graphs and other summary information from eventlogs. Method signatures and docstrings: - def __init__(self, eventlog_dirs: List[str], event_tag: str, output_path: str='.', title: str='', xaxis_title: str='steps', yaxis_title: Optiona...
Implement the Python class `StatsBuilder` described below. Class description: Builds graphs and other summary information from eventlogs. Method signatures and docstrings: - def __init__(self, eventlog_dirs: List[str], event_tag: str, output_path: str='.', title: str='', xaxis_title: str='steps', yaxis_title: Optiona...
eca1093d3a047e538f17f6ab92ab4d8144284f23
<|skeleton|> class StatsBuilder: """Builds graphs and other summary information from eventlogs.""" def __init__(self, eventlog_dirs: List[str], event_tag: str, output_path: str='.', title: str='', xaxis_title: str='steps', yaxis_title: Optional[str]=None, graph_agg: GraphAggTypes=GraphAggTypes.MEAN, output_pre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StatsBuilder: """Builds graphs and other summary information from eventlogs.""" def __init__(self, eventlog_dirs: List[str], event_tag: str, output_path: str='.', title: str='', xaxis_title: str='steps', yaxis_title: Optional[str]=None, graph_agg: GraphAggTypes=GraphAggTypes.MEAN, output_prefix: str='res...
the_stack_v2_python_sparse
tools/graph_builder.py
tensorflow/agents
train
2,755
d07d3761c9b8b37d3c8762b32863e604f340e615
[ "if not os.path.isabs(filepath):\n raise exceptions.FileException('参数必须是绝对路径')\npath = filepath[0:filepath.rfind(os.sep)]\nif not os.path.isdir(path):\n try:\n os.makedirs(path)\n log.log_info('创建文件夹成功:{}'.format(path))\n except:\n log.log_error('创建文件夹失败:{}'.format(path))\nif not os.pa...
<|body_start_0|> if not os.path.isabs(filepath): raise exceptions.FileException('参数必须是绝对路径') path = filepath[0:filepath.rfind(os.sep)] if not os.path.isdir(path): try: os.makedirs(path) log.log_info('创建文件夹成功:{}'.format(path)) ex...
FileHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileHelper: def create_filepath(filepath): """功能:如果文件路径不存在就创建 :param filepath: 文件路径,需要是绝对路径 :return:""" <|body_0|> def delete_file(filepath): """功能:如果文件存在就删除该文件 注意:仅限于删除一个文件 :param filepath: 文件路径 :return:""" <|body_1|> def get_file_from_dir(file_dir, fil...
stack_v2_sparse_classes_36k_train_025833
31,475
no_license
[ { "docstring": "功能:如果文件路径不存在就创建 :param filepath: 文件路径,需要是绝对路径 :return:", "name": "create_filepath", "signature": "def create_filepath(filepath)" }, { "docstring": "功能:如果文件存在就删除该文件 注意:仅限于删除一个文件 :param filepath: 文件路径 :return:", "name": "delete_file", "signature": "def delete_file(filepath)...
5
null
Implement the Python class `FileHelper` described below. Class description: Implement the FileHelper class. Method signatures and docstrings: - def create_filepath(filepath): 功能:如果文件路径不存在就创建 :param filepath: 文件路径,需要是绝对路径 :return: - def delete_file(filepath): 功能:如果文件存在就删除该文件 注意:仅限于删除一个文件 :param filepath: 文件路径 :return:...
Implement the Python class `FileHelper` described below. Class description: Implement the FileHelper class. Method signatures and docstrings: - def create_filepath(filepath): 功能:如果文件路径不存在就创建 :param filepath: 文件路径,需要是绝对路径 :return: - def delete_file(filepath): 功能:如果文件存在就删除该文件 注意:仅限于删除一个文件 :param filepath: 文件路径 :return:...
543b1e0a567bd7094875ef8f26212c16a4378bde
<|skeleton|> class FileHelper: def create_filepath(filepath): """功能:如果文件路径不存在就创建 :param filepath: 文件路径,需要是绝对路径 :return:""" <|body_0|> def delete_file(filepath): """功能:如果文件存在就删除该文件 注意:仅限于删除一个文件 :param filepath: 文件路径 :return:""" <|body_1|> def get_file_from_dir(file_dir, fil...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileHelper: def create_filepath(filepath): """功能:如果文件路径不存在就创建 :param filepath: 文件路径,需要是绝对路径 :return:""" if not os.path.isabs(filepath): raise exceptions.FileException('参数必须是绝对路径') path = filepath[0:filepath.rfind(os.sep)] if not os.path.isdir(path): try:...
the_stack_v2_python_sparse
接口/Data/Report_Data/base/helper.py
CHENMO12/MyGithub
train
0
daf79bd8d7e9f93793bd267bb36d7d790eeca8a6
[ "def helper(remain, combi, idx):\n if remain < 0:\n return\n if remain == 0:\n res.append(combi)\n return\n if idx >= len(candidates):\n return\n helper(remain, combi, idx + 1)\n helper(remain - candidates[idx], combi + [candidates[idx]], idx)\nres = []\nhelper(target, [],...
<|body_start_0|> def helper(remain, combi, idx): if remain < 0: return if remain == 0: res.append(combi) return if idx >= len(candidates): return helper(remain, combi, idx + 1) helper(rema...
Solution_
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum_hash(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]...
stack_v2_sparse_classes_36k_train_025834
3,701
no_license
[ { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum", "signature": "def combinationSum(self, candidates, target)" }, { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum_has...
2
null
Implement the Python class `Solution_` described below. Class description: Implement the Solution_ class. Method signatures and docstrings: - def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum_hash(self, candidates, target): :type c...
Implement the Python class `Solution_` described below. Class description: Implement the Solution_ class. Method signatures and docstrings: - def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum_hash(self, candidates, target): :type c...
fab4c341486e872fb2926d1b6d50499d55e76a4a
<|skeleton|> class Solution_: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum_hash(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution_: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" def helper(remain, combi, idx): if remain < 0: return if remain == 0: res.append(combi) r...
the_stack_v2_python_sparse
leetcode/39. Combination Sum.py
lunar-r/sword-to-offer-python
train
0
019a1bc2ec210a47c12e13b9deaba9791ba4caa3
[ "self.input_dist = [5, 25, 15, 10, 15]\nself.input_fuel = [1, 2, 1, 0, 3]\nself.mpg = 10\nself.output = 4\nreturn (self.input_dist, self.input_fuel, self.mpg, self.output)", "input_dist, input_fuel, mpg, proper_output = self.setUp()\noutput = ValidStartingCity.validStartingCity(input_dist, input_fuel, mpg)\nself....
<|body_start_0|> self.input_dist = [5, 25, 15, 10, 15] self.input_fuel = [1, 2, 1, 0, 3] self.mpg = 10 self.output = 4 return (self.input_dist, self.input_fuel, self.mpg, self.output) <|end_body_0|> <|body_start_1|> input_dist, input_fuel, mpg, proper_output = self.setUp...
Class with unittests for ValidStartingCity.py
test_ValidStartingCity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class test_ValidStartingCity: """Class with unittests for ValidStartingCity.py""" def setUp(self): """SetUp values for tests.""" <|body_0|> def test_ExpectedOutput(self): """Checks if returned output is as expected.""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_025835
1,003
no_license
[ { "docstring": "SetUp values for tests.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Checks if returned output is as expected.", "name": "test_ExpectedOutput", "signature": "def test_ExpectedOutput(self)" } ]
2
stack_v2_sparse_classes_30k_train_019018
Implement the Python class `test_ValidStartingCity` described below. Class description: Class with unittests for ValidStartingCity.py Method signatures and docstrings: - def setUp(self): SetUp values for tests. - def test_ExpectedOutput(self): Checks if returned output is as expected.
Implement the Python class `test_ValidStartingCity` described below. Class description: Class with unittests for ValidStartingCity.py Method signatures and docstrings: - def setUp(self): SetUp values for tests. - def test_ExpectedOutput(self): Checks if returned output is as expected. <|skeleton|> class test_ValidSt...
3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f
<|skeleton|> class test_ValidStartingCity: """Class with unittests for ValidStartingCity.py""" def setUp(self): """SetUp values for tests.""" <|body_0|> def test_ExpectedOutput(self): """Checks if returned output is as expected.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class test_ValidStartingCity: """Class with unittests for ValidStartingCity.py""" def setUp(self): """SetUp values for tests.""" self.input_dist = [5, 25, 15, 10, 15] self.input_fuel = [1, 2, 1, 0, 3] self.mpg = 10 self.output = 4 return (self.input_dist, self.in...
the_stack_v2_python_sparse
AlgoExpert_algorithms/Medium/ValidStartingCity/test_ValidStartingCity.py
JakubKazimierski/PythonPortfolio
train
9
d122570cc7a4ad06ec150ede1434fdad4520e30f
[ "form = super(BlockCreateModifyObjectViewMixin, self).get_form()\nform.fields['categories'].queryset = form.fields['categories'].queryset.filter(organization=self.request.organization)\nform.fields['geodataset'].queryset = form.fields['geodataset'].queryset.filter(organization=self.request.organization)\nreturn for...
<|body_start_0|> form = super(BlockCreateModifyObjectViewMixin, self).get_form() form.fields['categories'].queryset = form.fields['categories'].queryset.filter(organization=self.request.organization) form.fields['geodataset'].queryset = form.fields['geodataset'].queryset.filter(organization=self...
Mixin for views that crea modify blocks
BlockCreateModifyObjectViewMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BlockCreateModifyObjectViewMixin: """Mixin for views that crea modify blocks""" def get_form(self): """Get the form, but with categories scoped to that user's org""" <|body_0|> def get_success_url(self): """Get the success URL""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_025836
5,550
permissive
[ { "docstring": "Get the form, but with categories scoped to that user's org", "name": "get_form", "signature": "def get_form(self)" }, { "docstring": "Get the success URL", "name": "get_success_url", "signature": "def get_success_url(self)" } ]
2
null
Implement the Python class `BlockCreateModifyObjectViewMixin` described below. Class description: Mixin for views that crea modify blocks Method signatures and docstrings: - def get_form(self): Get the form, but with categories scoped to that user's org - def get_success_url(self): Get the success URL
Implement the Python class `BlockCreateModifyObjectViewMixin` described below. Class description: Mixin for views that crea modify blocks Method signatures and docstrings: - def get_form(self): Get the form, but with categories scoped to that user's org - def get_success_url(self): Get the success URL <|skeleton|> c...
3af6bc9f3ff4e5dfdbb118209e877379428bc06c
<|skeleton|> class BlockCreateModifyObjectViewMixin: """Mixin for views that crea modify blocks""" def get_form(self): """Get the form, but with categories scoped to that user's org""" <|body_0|> def get_success_url(self): """Get the success URL""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BlockCreateModifyObjectViewMixin: """Mixin for views that crea modify blocks""" def get_form(self): """Get the form, but with categories scoped to that user's org""" form = super(BlockCreateModifyObjectViewMixin, self).get_form() form.fields['categories'].queryset = form.fields['c...
the_stack_v2_python_sparse
blocks/views.py
ofa/everyvoter
train
7
a3b404ab937f602ba7845f783026de003c7fa8b2
[ "nr = len(grid)\nif not nr:\n return 0\nnc = len(grid[0])\nif not nc:\n return 0\ncnt = 0\nfor i in range(nr):\n for j in range(nc):\n if grid[i][j] == '1':\n cnt += 1\n grid[i][j] = '0'\n self.expand(grid, nr, nc, i, j)\nreturn cnt", "nbs = [(i - 1, j), (i + 1, j)...
<|body_start_0|> nr = len(grid) if not nr: return 0 nc = len(grid[0]) if not nc: return 0 cnt = 0 for i in range(nr): for j in range(nc): if grid[i][j] == '1': cnt += 1 grid[i][j] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numIslands(self, grid): """:type grid: List[List[str]] :rtype: int""" <|body_0|> def expand(self, grid, nr, nc, i, j): """erase all reachable areas""" <|body_1|> <|end_skeleton|> <|body_start_0|> nr = len(grid) if not nr: ...
stack_v2_sparse_classes_36k_train_025837
2,759
no_license
[ { "docstring": ":type grid: List[List[str]] :rtype: int", "name": "numIslands", "signature": "def numIslands(self, grid)" }, { "docstring": "erase all reachable areas", "name": "expand", "signature": "def expand(self, grid, nr, nc, i, j)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numIslands(self, grid): :type grid: List[List[str]] :rtype: int - def expand(self, grid, nr, nc, i, j): erase all reachable areas
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numIslands(self, grid): :type grid: List[List[str]] :rtype: int - def expand(self, grid, nr, nc, i, j): erase all reachable areas <|skeleton|> class Solution: def numIs...
e00cf94c5b86c8cca27e3bee69ad21e727b7679b
<|skeleton|> class Solution: def numIslands(self, grid): """:type grid: List[List[str]] :rtype: int""" <|body_0|> def expand(self, grid, nr, nc, i, j): """erase all reachable areas""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numIslands(self, grid): """:type grid: List[List[str]] :rtype: int""" nr = len(grid) if not nr: return 0 nc = len(grid[0]) if not nc: return 0 cnt = 0 for i in range(nr): for j in range(nc): ...
the_stack_v2_python_sparse
search/dfs/prob200.py
binchen15/leet-python
train
1
fa7729eddfc4687c218b7d79731aa9dcbd0e12d6
[ "super(Decoder, self).__init__()\nself.attn1 = MHA(D_embed, Q, V, H, local_attn_size=local_attn_size, fwd_attn=fwd_attn, device=device)\nself.attn2 = MHA(D_embed, Q, V, H, local_attn_size=local_attn_size, fwd_attn=fwd_attn, device=device)\nself.ffwd = PFF(D_embed)\nself.dropout = nn.Dropout(p=dropout)\nself.lnorm1 ...
<|body_start_0|> super(Decoder, self).__init__() self.attn1 = MHA(D_embed, Q, V, H, local_attn_size=local_attn_size, fwd_attn=fwd_attn, device=device) self.attn2 = MHA(D_embed, Q, V, H, local_attn_size=local_attn_size, fwd_attn=fwd_attn, device=device) self.ffwd = PFF(D_embed) se...
Multi-head attention decoder based on 'Attention is All You Need' paper. [1] Masked multi-head attention of outputs [2] Multi-head attention of encoder and [1] [3] Position-wise FFN
Decoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decoder: """Multi-head attention decoder based on 'Attention is All You Need' paper. [1] Masked multi-head attention of outputs [2] Multi-head attention of encoder and [1] [3] Position-wise FFN""" def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn=True, dropout=0.5, device=N...
stack_v2_sparse_classes_36k_train_025838
2,151
no_license
[ { "docstring": "params D_embed (scalar): embedded output feature dimensions Q (int): query matrix dimension V (int): value matrix dimension H (int): number of attention heads local_attn_size (int): local attention mask size fwd_attn (bool): forward attention mask indicator device (torch.device): tensor device",...
2
stack_v2_sparse_classes_30k_train_004289
Implement the Python class `Decoder` described below. Class description: Multi-head attention decoder based on 'Attention is All You Need' paper. [1] Masked multi-head attention of outputs [2] Multi-head attention of encoder and [1] [3] Position-wise FFN Method signatures and docstrings: - def __init__(self, D_embed,...
Implement the Python class `Decoder` described below. Class description: Multi-head attention decoder based on 'Attention is All You Need' paper. [1] Masked multi-head attention of outputs [2] Multi-head attention of encoder and [1] [3] Position-wise FFN Method signatures and docstrings: - def __init__(self, D_embed,...
274ff8db17271106155e34725ae69b1a35c962b2
<|skeleton|> class Decoder: """Multi-head attention decoder based on 'Attention is All You Need' paper. [1] Masked multi-head attention of outputs [2] Multi-head attention of encoder and [1] [3] Position-wise FFN""" def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn=True, dropout=0.5, device=N...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Decoder: """Multi-head attention decoder based on 'Attention is All You Need' paper. [1] Masked multi-head attention of outputs [2] Multi-head attention of encoder and [1] [3] Position-wise FFN""" def __init__(self, D_embed, Q, V, H, local_attn_size=None, fwd_attn=True, dropout=0.5, device=None): ...
the_stack_v2_python_sparse
ml/models/Decoder.py
gravaman/fleishco
train
0
c4182521fd0cf33ba5c2dc6d4d9e865d59cac1e5
[ "self.min_size = min_size\nself.max_size = max_size\nself.inverse_uniform_sampling = inverse_uniform_sampling", "if self.inverse_uniform_sampling:\n size = int(round(1.0 / np.random.uniform(1.0 / self.max_size, 1.0 / self.min_size)))\nelse:\n size = int(round(np.random.uniform(self.min_size, self.max_size))...
<|body_start_0|> self.min_size = min_size self.max_size = max_size self.inverse_uniform_sampling = inverse_uniform_sampling <|end_body_0|> <|body_start_1|> if self.inverse_uniform_sampling: size = int(round(1.0 / np.random.uniform(1.0 / self.max_size, 1.0 / self.min_size))) ...
RandomShortSideScaleJitterVideo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomShortSideScaleJitterVideo: def __init__(self, min_size: int, max_size: int, inverse_uniform_sampling=False): """Args: min_size (int): the minimal size to scale the frames. max_size (int): the maximal size to scale the frames. inverse_uniform_sampling (bool): if True, sample uniform...
stack_v2_sparse_classes_36k_train_025839
4,601
permissive
[ { "docstring": "Args: min_size (int): the minimal size to scale the frames. max_size (int): the maximal size to scale the frames. inverse_uniform_sampling (bool): if True, sample uniformly in [1 / max_scale, 1 / min_scale] and take a reciprocal to get the scale. If False, take a uniform sample from [min_scale, ...
2
null
Implement the Python class `RandomShortSideScaleJitterVideo` described below. Class description: Implement the RandomShortSideScaleJitterVideo class. Method signatures and docstrings: - def __init__(self, min_size: int, max_size: int, inverse_uniform_sampling=False): Args: min_size (int): the minimal size to scale th...
Implement the Python class `RandomShortSideScaleJitterVideo` described below. Class description: Implement the RandomShortSideScaleJitterVideo class. Method signatures and docstrings: - def __init__(self, min_size: int, max_size: int, inverse_uniform_sampling=False): Args: min_size (int): the minimal size to scale th...
b3d6ce670cdf63469fc5766630eb295d67b3d788
<|skeleton|> class RandomShortSideScaleJitterVideo: def __init__(self, min_size: int, max_size: int, inverse_uniform_sampling=False): """Args: min_size (int): the minimal size to scale the frames. max_size (int): the maximal size to scale the frames. inverse_uniform_sampling (bool): if True, sample uniform...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomShortSideScaleJitterVideo: def __init__(self, min_size: int, max_size: int, inverse_uniform_sampling=False): """Args: min_size (int): the minimal size to scale the frames. max_size (int): the maximal size to scale the frames. inverse_uniform_sampling (bool): if True, sample uniformly in [1 / max...
the_stack_v2_python_sparse
src/opendr/perception/activity_recognition/datasets/utils/transforms.py
opendr-eu/opendr
train
535
19e9137a629b164240669984da8b2f2a640b2c37
[ "\"\"\"\n Bellman-Ford算法,这个算法TLE。时间复杂度O(ne), 空间复杂度O(n)。1108ms\n \"\"\"\ndist = [float('inf')] * N\ndist[K - 1] = 0\nfor i in range(N):\n for time in times:\n u = time[0] - 1\n v = time[1] - 1\n w = time[2]\n dist[v] = min(dist[v], dist[u] + w)\nreturn -1 if float('inf') ...
<|body_start_0|> """ Bellman-Ford算法,这个算法TLE。时间复杂度O(ne), 空间复杂度O(n)。1108ms """ dist = [float('inf')] * N dist[K - 1] = 0 for i in range(N): for time in times: u = time[0] - 1 v = time[1] - 1 w = tim...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def networkDelayTime(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_0|> def networkDelayTime2(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_1|...
stack_v2_sparse_classes_36k_train_025840
2,899
no_license
[ { "docstring": ":type times: List[List[int]] :type N: int :type K: int :rtype: int", "name": "networkDelayTime", "signature": "def networkDelayTime(self, times, N, K)" }, { "docstring": ":type times: List[List[int]] :type N: int :type K: int :rtype: int", "name": "networkDelayTime2", "si...
2
stack_v2_sparse_classes_30k_train_012903
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def networkDelayTime(self, times, N, K): :type times: List[List[int]] :type N: int :type K: int :rtype: int - def networkDelayTime2(self, times, N, K): :type times: List[List[int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def networkDelayTime(self, times, N, K): :type times: List[List[int]] :type N: int :type K: int :rtype: int - def networkDelayTime2(self, times, N, K): :type times: List[List[int...
bc602ee84a7881bce9e7da0ffb56d1138fbd8457
<|skeleton|> class Solution: def networkDelayTime(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_0|> def networkDelayTime2(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def networkDelayTime(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" """ Bellman-Ford算法,这个算法TLE。时间复杂度O(ne), 空间复杂度O(n)。1108ms """ dist = [float('inf')] * N dist[K - 1] = 0 for i in ran...
the_stack_v2_python_sparse
图/网络延迟时间743.py
jwds123/leetcode
train
0
bd0f1abfcf830758fb58ba5e12d93d44f79d7085
[ "super().__init__()\npe = torch.zeros(max_len, d_model)\nposition = torch.arange(0.0, max_len).unsqueeze(1)\ndiv_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model))\npe[:, 0::2] = torch.sin(position * div_term)\npe[:, 1::2] = torch.cos(position * div_term)\npe = torch.cat((pe, torch.zer...
<|body_start_0|> super().__init__() pe = torch.zeros(max_len, d_model) position = torch.arange(0.0, max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch....
Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction.
FixedPositionalEncoding
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FixedPositionalEncoding: """Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction.""" def __init__(self, d_model: int, max_len=5000): """:param d_model: dimensionality of the embeddings :param max...
stack_v2_sparse_classes_36k_train_025841
21,238
no_license
[ { "docstring": ":param d_model: dimensionality of the embeddings :param max_len: maximum length of the sequence", "name": "__init__", "signature": "def __init__(self, d_model: int, max_len=5000)" }, { "docstring": "Forward pass through the FixedPositionalEncoding. :param x: input of shape [batch...
2
stack_v2_sparse_classes_30k_train_017957
Implement the Python class `FixedPositionalEncoding` described below. Class description: Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction. Method signatures and docstrings: - def __init__(self, d_model: int, max_len=5000): :p...
Implement the Python class `FixedPositionalEncoding` described below. Class description: Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction. Method signatures and docstrings: - def __init__(self, d_model: int, max_len=5000): :p...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class FixedPositionalEncoding: """Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction.""" def __init__(self, d_model: int, max_len=5000): """:param d_model: dimensionality of the embeddings :param max...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FixedPositionalEncoding: """Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction.""" def __init__(self, d_model: int, max_len=5000): """:param d_model: dimensionality of the embeddings :param max_len: maximum...
the_stack_v2_python_sparse
generated/test_allegro_allRank.py
jansel/pytorch-jit-paritybench
train
35
9bae58aa8fd472afea8bd1af5ba5b89fa2afbdd9
[ "centre = nm.array(centre, dtype=nm.float64)\nnormal = nm.array(normal, dtype=nm.float64)\nnormal /= nla.norm(normal)\nname = 'circle [%s, %s, %s]' % (centre, normal, radius)\nProbe.__init__(self, name=name, share_geometry=share_geometry, centre=centre, normal=normal, radius=radius, n_point=n_point)", "out = Prob...
<|body_start_0|> centre = nm.array(centre, dtype=nm.float64) normal = nm.array(normal, dtype=nm.float64) normal /= nla.norm(normal) name = 'circle [%s, %s, %s]' % (centre, normal, radius) Probe.__init__(self, name=name, share_geometry=share_geometry, centre=centre, normal=normal,...
Probe variables along a circle. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is negative, -n_point is used as an initial gu...
CircleProbe
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CircleProbe: """Probe variables along a circle. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is nega...
stack_v2_sparse_classes_36k_train_025842
21,182
permissive
[ { "docstring": "Parameters ---------- centre : array_like The coordinates of the circle centre. normal : array_like The normal vector perpendicular to the circle plane. radius : float The radius of the circle.", "name": "__init__", "signature": "def __init__(self, centre, normal, radius, n_point, share_...
3
stack_v2_sparse_classes_30k_test_000079
Implement the Python class `CircleProbe` described below. Class description: Probe variables along a circle. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are ...
Implement the Python class `CircleProbe` described below. Class description: Probe variables along a circle. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are ...
0c2d1690e764b601b2687be1e4261b82207ca366
<|skeleton|> class CircleProbe: """Probe variables along a circle. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is nega...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CircleProbe: """Probe variables along a circle. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is negative, -n_poin...
the_stack_v2_python_sparse
sfepy/discrete/probes.py
sfepy/sfepy
train
651
339cd8ddaa62f445de9f41c45ae5d8c1c7d0026a
[ "self.nums = nums\nfor i in range(1, len(nums)):\n nums[i] = nums[i] + nums[i - 1]", "if i == 0:\n return self.nums[j]\nelse:\n return self.nums[j] - self.nums[i - 1]" ]
<|body_start_0|> self.nums = nums for i in range(1, len(nums)): nums[i] = nums[i] + nums[i - 1] <|end_body_0|> <|body_start_1|> if i == 0: return self.nums[j] else: return self.nums[j] - self.nums[i - 1] <|end_body_1|>
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.nums = nums for i in range(1, len(nums)): ...
stack_v2_sparse_classes_36k_train_025843
1,022
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, i, j)" } ]
2
null
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int <|skeleton|> class NumArray: def __init__(self, nums): ...
83c589464e0caad960679aea259681c965218d13
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumArray: def __init__(self, nums): """:type nums: List[int]""" self.nums = nums for i in range(1, len(nums)): nums[i] = nums[i] + nums[i - 1] def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" if i == 0: return self.nums[...
the_stack_v2_python_sparse
DP/303.区域和检索 -数组不可变 动态规划.py
starrye/LeetCode
train
0
6fc415cf4d04961aa26dc83591c2252ccc913db9
[ "if settings.DF_ALLOW_USER_CREATION and settings.DF_ALLOW_LOCAL_USERS:\n user = form.save()\n auth_login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')\nreturn HttpResponseRedirect(self.get_success_url())", "kwargs = {'initial': self.get_initial(), 'prefix': self.get_prefix()}\nif ...
<|body_start_0|> if settings.DF_ALLOW_USER_CREATION and settings.DF_ALLOW_LOCAL_USERS: user = form.save() auth_login(self.request, user, backend='django.contrib.auth.backends.ModelBackend') return HttpResponseRedirect(self.get_success_url()) <|end_body_0|> <|body_start_1|> ...
SignupView
[ "LicenseRef-scancode-cecill-b-en" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignupView: def form_valid(self, form): """Security check complete. Create the user and log it in.""" <|body_0|> def get_form_kwargs(self): """Returns the keyword arguments for instantiating the form.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_025844
3,582
permissive
[ { "docstring": "Security check complete. Create the user and log it in.", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "Returns the keyword arguments for instantiating the form.", "name": "get_form_kwargs", "signature": "def get_form_kwargs(self)" }...
2
stack_v2_sparse_classes_30k_val_001129
Implement the Python class `SignupView` described below. Class description: Implement the SignupView class. Method signatures and docstrings: - def form_valid(self, form): Security check complete. Create the user and log it in. - def get_form_kwargs(self): Returns the keyword arguments for instantiating the form.
Implement the Python class `SignupView` described below. Class description: Implement the SignupView class. Method signatures and docstrings: - def form_valid(self, form): Security check complete. Create the user and log it in. - def get_form_kwargs(self): Returns the keyword arguments for instantiating the form. <|...
919c915230dee4f1530778fe555555168db6f254
<|skeleton|> class SignupView: def form_valid(self, form): """Security check complete. Create the user and log it in.""" <|body_0|> def get_form_kwargs(self): """Returns the keyword arguments for instantiating the form.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SignupView: def form_valid(self, form): """Security check complete. Create the user and log it in.""" if settings.DF_ALLOW_USER_CREATION and settings.DF_ALLOW_LOCAL_USERS: user = form.save() auth_login(self.request, user, backend='django.contrib.auth.backends.ModelBacke...
the_stack_v2_python_sparse
djangofloor/views/auth.py
d9pouces/django-floor
train
12
23191e1c4686794977bef71b4803dc9a4f457fe8
[ "result_address = '测试时间:{}测试用例名称是{},测试结果是: '.format(TestDivision.now, inspect.stack()[0][3])\nexcept_result = 0.5\nmsg = '测试两正数相除'\ntry:\n result = MathNum(5, 10).two_division()\n self.assertEqual(except_result, result, msg=msg)\nexcept AssertionError as a:\n file.write('\\n{}不通过,原因是{}\\n'.format(result_ad...
<|body_start_0|> result_address = '测试时间:{}测试用例名称是{},测试结果是: '.format(TestDivision.now, inspect.stack()[0][3]) except_result = 0.5 msg = '测试两正数相除' try: result = MathNum(5, 10).two_division() self.assertEqual(except_result, result, msg=msg) except AssertionEr...
测试两数相除的类
TestDivision
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDivision: """测试两数相除的类""" def test_two_positive_division(self): """两正数相除 :return: 当前测试用例的名称及测试结果""" <|body_0|> def test_two_negative(self): """两负数相除 :return: 当前测试用例的名称及测试结果""" <|body_1|> def test_positive_negative(self): """一正数一负数相除 :retur...
stack_v2_sparse_classes_36k_train_025845
7,448
no_license
[ { "docstring": "两正数相除 :return: 当前测试用例的名称及测试结果", "name": "test_two_positive_division", "signature": "def test_two_positive_division(self)" }, { "docstring": "两负数相除 :return: 当前测试用例的名称及测试结果", "name": "test_two_negative", "signature": "def test_two_negative(self)" }, { "docstring": "...
4
stack_v2_sparse_classes_30k_train_009252
Implement the Python class `TestDivision` described below. Class description: 测试两数相除的类 Method signatures and docstrings: - def test_two_positive_division(self): 两正数相除 :return: 当前测试用例的名称及测试结果 - def test_two_negative(self): 两负数相除 :return: 当前测试用例的名称及测试结果 - def test_positive_negative(self): 一正数一负数相除 :return: 当前测试用例的名称及测试...
Implement the Python class `TestDivision` described below. Class description: 测试两数相除的类 Method signatures and docstrings: - def test_two_positive_division(self): 两正数相除 :return: 当前测试用例的名称及测试结果 - def test_two_negative(self): 两负数相除 :return: 当前测试用例的名称及测试结果 - def test_positive_negative(self): 一正数一负数相除 :return: 当前测试用例的名称及测试...
79408b1eb1599349d6b23ddc4307bb5780f9669c
<|skeleton|> class TestDivision: """测试两数相除的类""" def test_two_positive_division(self): """两正数相除 :return: 当前测试用例的名称及测试结果""" <|body_0|> def test_two_negative(self): """两负数相除 :return: 当前测试用例的名称及测试结果""" <|body_1|> def test_positive_negative(self): """一正数一负数相除 :retur...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestDivision: """测试两数相除的类""" def test_two_positive_division(self): """两正数相除 :return: 当前测试用例的名称及测试结果""" result_address = '测试时间:{}测试用例名称是{},测试结果是: '.format(TestDivision.now, inspect.stack()[0][3]) except_result = 0.5 msg = '测试两正数相除' try: result = MathNum(...
the_stack_v2_python_sparse
WebAPI/lesson_14_0426.py
grassroadsZ/PythonStudy
train
0
3f93dee11e7348859c4ee9f4ff1eb15af10b5a41
[ "a = self._reshape(x)\nskew = scipy.stats.skew(a, nan_policy='omit')\nreturn skew", "N = xr.zeros_like(output)\nM1 = xr.zeros_like(output)\nM2 = xr.zeros_like(output)\nM3 = xr.zeros_like(output)\ncheck_empty = True\nfor x in xs:\n Nx = np.isfinite(x).sum(dim=self._dims)\n M1x = x.mean(dim=self._dims)\n E...
<|body_start_0|> a = self._reshape(x) skew = scipy.stats.skew(a, nan_policy='omit') return skew <|end_body_0|> <|body_start_1|> N = xr.zeros_like(output) M1 = xr.zeros_like(output) M2 = xr.zeros_like(output) M3 = xr.zeros_like(output) check_empty = True ...
Computes the skew across dimension(s) TODO NaN behavior when there is NO data (currently different in reduce and reduce_chunked)
Skew
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Skew: """Computes the skew across dimension(s) TODO NaN behavior when there is NO data (currently different in reduce and reduce_chunked)""" def reduce(self, x): """Computes the skew across dimension(s) Parameters ---------- x : UnitsDataArray Source data. Returns ------- UnitsDataAr...
stack_v2_sparse_classes_36k_train_025846
34,643
permissive
[ { "docstring": "Computes the skew across dimension(s) Parameters ---------- x : UnitsDataArray Source data. Returns ------- UnitsDataArray Skew of the source data over dims", "name": "reduce", "signature": "def reduce(self, x)" }, { "docstring": "Computes the skew across a chunk Parameters -----...
2
stack_v2_sparse_classes_30k_train_009274
Implement the Python class `Skew` described below. Class description: Computes the skew across dimension(s) TODO NaN behavior when there is NO data (currently different in reduce and reduce_chunked) Method signatures and docstrings: - def reduce(self, x): Computes the skew across dimension(s) Parameters ---------- x ...
Implement the Python class `Skew` described below. Class description: Computes the skew across dimension(s) TODO NaN behavior when there is NO data (currently different in reduce and reduce_chunked) Method signatures and docstrings: - def reduce(self, x): Computes the skew across dimension(s) Parameters ---------- x ...
66d8ec7a9086e39347e32922e15a3f59cb055415
<|skeleton|> class Skew: """Computes the skew across dimension(s) TODO NaN behavior when there is NO data (currently different in reduce and reduce_chunked)""" def reduce(self, x): """Computes the skew across dimension(s) Parameters ---------- x : UnitsDataArray Source data. Returns ------- UnitsDataAr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Skew: """Computes the skew across dimension(s) TODO NaN behavior when there is NO data (currently different in reduce and reduce_chunked)""" def reduce(self, x): """Computes the skew across dimension(s) Parameters ---------- x : UnitsDataArray Source data. Returns ------- UnitsDataArray Skew of t...
the_stack_v2_python_sparse
podpac/core/algorithm/stats.py
creare-com/podpac
train
48
3b440ab0571bce7f6bc749145afbabe5ccfbfc3e
[ "for key in data:\n value = data[key]\n if isinstance(value, uuid.UUID):\n data[key] = data[key].hex\nreturn data", "unwanted_fields = ['resource_type']\nfor field in unwanted_fields:\n if field in data:\n data.pop(field)\nreturn data" ]
<|body_start_0|> for key in data: value = data[key] if isinstance(value, uuid.UUID): data[key] = data[key].hex return data <|end_body_0|> <|body_start_1|> unwanted_fields = ['resource_type'] for field in unwanted_fields: if field in da...
Class for serializing and deserializing GroupChat models.
GroupChatSchema
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupChatSchema: """Class for serializing and deserializing GroupChat models.""" def convert_uuid_to_hex(self, data, **kwargs): """Convert all UUID fields to their 32-character hexadecimal equivalent.""" <|body_0|> def strip_unwanted_fields(self, data, many, **kwargs): ...
stack_v2_sparse_classes_36k_train_025847
1,817
no_license
[ { "docstring": "Convert all UUID fields to their 32-character hexadecimal equivalent.", "name": "convert_uuid_to_hex", "signature": "def convert_uuid_to_hex(self, data, **kwargs)" }, { "docstring": "Remove unwanted fields from the input data before deserialization.", "name": "strip_unwanted_...
2
stack_v2_sparse_classes_30k_test_000920
Implement the Python class `GroupChatSchema` described below. Class description: Class for serializing and deserializing GroupChat models. Method signatures and docstrings: - def convert_uuid_to_hex(self, data, **kwargs): Convert all UUID fields to their 32-character hexadecimal equivalent. - def strip_unwanted_field...
Implement the Python class `GroupChatSchema` described below. Class description: Class for serializing and deserializing GroupChat models. Method signatures and docstrings: - def convert_uuid_to_hex(self, data, **kwargs): Convert all UUID fields to their 32-character hexadecimal equivalent. - def strip_unwanted_field...
55ce20945bea8a6348bea64726aaf209936723c2
<|skeleton|> class GroupChatSchema: """Class for serializing and deserializing GroupChat models.""" def convert_uuid_to_hex(self, data, **kwargs): """Convert all UUID fields to their 32-character hexadecimal equivalent.""" <|body_0|> def strip_unwanted_fields(self, data, many, **kwargs): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupChatSchema: """Class for serializing and deserializing GroupChat models.""" def convert_uuid_to_hex(self, data, **kwargs): """Convert all UUID fields to their 32-character hexadecimal equivalent.""" for key in data: value = data[key] if isinstance(value, uuid....
the_stack_v2_python_sparse
api/app/schemas/group_chat.py
EricMontague/Flask-Chat-Server
train
0
f9e05cc1bbfbe611d3785949ff87568079704d9a
[ "self.hass = hass\nself.loaded: dict[str, set[str]] = {}\nself.cache: dict[str, dict[str, dict[str, Any]]] = {}", "components_to_load = components - self.loaded.setdefault(language, set())\nif components_to_load:\n await self._async_load(language, components_to_load)\ncached = self.cache.get(language, {})\nret...
<|body_start_0|> self.hass = hass self.loaded: dict[str, set[str]] = {} self.cache: dict[str, dict[str, dict[str, Any]]] = {} <|end_body_0|> <|body_start_1|> components_to_load = components - self.loaded.setdefault(language, set()) if components_to_load: await self._...
Cache for flattened translations.
_TranslationCache
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _TranslationCache: """Cache for flattened translations.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize the cache.""" <|body_0|> async def async_fetch(self, language: str, category: str, components: set[str]) -> list[dict[str, dict[str, Any]]]: ...
stack_v2_sparse_classes_36k_train_025848
10,520
permissive
[ { "docstring": "Initialize the cache.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant) -> None" }, { "docstring": "Load resources into the cache.", "name": "async_fetch", "signature": "async def async_fetch(self, language: str, category: str, components: set[st...
4
stack_v2_sparse_classes_30k_train_017296
Implement the Python class `_TranslationCache` described below. Class description: Cache for flattened translations. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant) -> None: Initialize the cache. - async def async_fetch(self, language: str, category: str, components: set[str]) -> list[dict...
Implement the Python class `_TranslationCache` described below. Class description: Cache for flattened translations. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant) -> None: Initialize the cache. - async def async_fetch(self, language: str, category: str, components: set[str]) -> list[dict...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class _TranslationCache: """Cache for flattened translations.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize the cache.""" <|body_0|> async def async_fetch(self, language: str, category: str, components: set[str]) -> list[dict[str, dict[str, Any]]]: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _TranslationCache: """Cache for flattened translations.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize the cache.""" self.hass = hass self.loaded: dict[str, set[str]] = {} self.cache: dict[str, dict[str, dict[str, Any]]] = {} async def async_fetch(s...
the_stack_v2_python_sparse
homeassistant/helpers/translation.py
home-assistant/core
train
35,501
fe92d06a52de1b051d244e5cb360594f948fe353
[ "url = self.ip + '/api/scm/auth/scm/scmPoD/detailList.do'\nparams = {'status': 'NotReceived', 'poCode': order_no}\nr = self.s.post(url=url, params=params)\nreturn r.json()", "url = self.ip + '/api/scm//auth/scm/scmPoD/receive.do'\nparams = {'status': 'Received', 'deliveryDay': get_future_date(7), 'ids': ids}\nr =...
<|body_start_0|> url = self.ip + '/api/scm/auth/scm/scmPoD/detailList.do' params = {'status': 'NotReceived', 'poCode': order_no} r = self.s.post(url=url, params=params) return r.json() <|end_body_0|> <|body_start_1|> url = self.ip + '/api/scm//auth/scm/scmPoD/receive.do' ...
B2BPurchaseOrder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class B2BPurchaseOrder: def purchase_order_search_by_no(self, order_no): """通过采购订单号查询采购订单明细 :param order_no: 采购订单号 :return:""" <|body_0|> def receive_purchase_order(self, ids): """供应商订单确认 :param ids: 明细id :return:""" <|body_1|> def return_purchase_order(self, ...
stack_v2_sparse_classes_36k_train_025849
2,159
no_license
[ { "docstring": "通过采购订单号查询采购订单明细 :param order_no: 采购订单号 :return:", "name": "purchase_order_search_by_no", "signature": "def purchase_order_search_by_no(self, order_no)" }, { "docstring": "供应商订单确认 :param ids: 明细id :return:", "name": "receive_purchase_order", "signature": "def receive_purch...
4
stack_v2_sparse_classes_30k_train_002353
Implement the Python class `B2BPurchaseOrder` described below. Class description: Implement the B2BPurchaseOrder class. Method signatures and docstrings: - def purchase_order_search_by_no(self, order_no): 通过采购订单号查询采购订单明细 :param order_no: 采购订单号 :return: - def receive_purchase_order(self, ids): 供应商订单确认 :param ids: 明细id...
Implement the Python class `B2BPurchaseOrder` described below. Class description: Implement the B2BPurchaseOrder class. Method signatures and docstrings: - def purchase_order_search_by_no(self, order_no): 通过采购订单号查询采购订单明细 :param order_no: 采购订单号 :return: - def receive_purchase_order(self, ids): 供应商订单确认 :param ids: 明细id...
26d2ae773a999fd8446e18f9c0719d46402b19aa
<|skeleton|> class B2BPurchaseOrder: def purchase_order_search_by_no(self, order_no): """通过采购订单号查询采购订单明细 :param order_no: 采购订单号 :return:""" <|body_0|> def receive_purchase_order(self, ids): """供应商订单确认 :param ids: 明细id :return:""" <|body_1|> def return_purchase_order(self, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class B2BPurchaseOrder: def purchase_order_search_by_no(self, order_no): """通过采购订单号查询采购订单明细 :param order_no: 采购订单号 :return:""" url = self.ip + '/api/scm/auth/scm/scmPoD/detailList.do' params = {'status': 'NotReceived', 'poCode': order_no} r = self.s.post(url=url, params=params) ...
the_stack_v2_python_sparse
api/B2B_purchase_order_api.py
Leofighting/dimi_api_test
train
0
bc0c37a5a6bf26fda0a65dfba39db72884249506
[ "from ..document import DocumentArray\nfrom ....helper import dunder_get\nrv = defaultdict(DocumentArray)\nfor doc in self:\n if '__' in tag:\n value = dunder_get(doc.tags, tag)\n elif tag in doc.tags:\n value = doc.tags[tag]\n else:\n continue\n rv[value].append(doc)\nreturn dict(r...
<|body_start_0|> from ..document import DocumentArray from ....helper import dunder_get rv = defaultdict(DocumentArray) for doc in self: if '__' in tag: value = dunder_get(doc.tags, tag) elif tag in doc.tags: value = doc.tags[tag] ...
These helpers yield groups of :class:`DocumentArray` from a source :class:`DocumentArray` or :class:`DocumentArrayMemmap`.
GroupMixin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupMixin: """These helpers yield groups of :class:`DocumentArray` from a source :class:`DocumentArray` or :class:`DocumentArrayMemmap`.""" def split(self, tag: str) -> Dict[Any, 'DocumentArray']: """Split the `DocumentArray` into multiple DocumentArray according to the tag value of...
stack_v2_sparse_classes_36k_train_025850
2,509
permissive
[ { "docstring": "Split the `DocumentArray` into multiple DocumentArray according to the tag value of each `Document`. :param tag: the tag name to split stored in tags. :return: a dict where Documents with the same value on `tag` are grouped together, their orders are preserved from the original :class:`DocumentA...
2
stack_v2_sparse_classes_30k_train_012814
Implement the Python class `GroupMixin` described below. Class description: These helpers yield groups of :class:`DocumentArray` from a source :class:`DocumentArray` or :class:`DocumentArrayMemmap`. Method signatures and docstrings: - def split(self, tag: str) -> Dict[Any, 'DocumentArray']: Split the `DocumentArray` ...
Implement the Python class `GroupMixin` described below. Class description: These helpers yield groups of :class:`DocumentArray` from a source :class:`DocumentArray` or :class:`DocumentArrayMemmap`. Method signatures and docstrings: - def split(self, tag: str) -> Dict[Any, 'DocumentArray']: Split the `DocumentArray` ...
34c34acfb0115ad2ec4cc8e2e9a86c521855612f
<|skeleton|> class GroupMixin: """These helpers yield groups of :class:`DocumentArray` from a source :class:`DocumentArray` or :class:`DocumentArrayMemmap`.""" def split(self, tag: str) -> Dict[Any, 'DocumentArray']: """Split the `DocumentArray` into multiple DocumentArray according to the tag value of...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupMixin: """These helpers yield groups of :class:`DocumentArray` from a source :class:`DocumentArray` or :class:`DocumentArrayMemmap`.""" def split(self, tag: str) -> Dict[Any, 'DocumentArray']: """Split the `DocumentArray` into multiple DocumentArray according to the tag value of each `Docume...
the_stack_v2_python_sparse
jina/types/arrays/mixins/group.py
amitesh1as/jina
train
0
b6d6e1dc2feb8c424badfe8c136b515eb2baa3e2
[ "self.snake = [(0, 0)]\nself.width, self.height = (width, height)\nself.food = food\nself.count = 0", "cur_x, cur_y = (self.snake[-1][0], self.snake[-1][1])\nif direction == 'U':\n cur_x -= 1\nelif direction == 'L':\n cur_y -= 1\nelif direction == 'R':\n cur_y += 1\nelse:\n cur_x += 1\nif 0 <= cur_x <...
<|body_start_0|> self.snake = [(0, 0)] self.width, self.height = (width, height) self.food = food self.count = 0 <|end_body_0|> <|body_start_1|> cur_x, cur_y = (self.snake[-1][0], self.snake[-1][1]) if direction == 'U': cur_x -= 1 elif direction == 'L...
SnakeGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_36k_train_025851
2,007
no_license
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]", ...
2
null
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
580366c7de5f27a931930aeec5e08aa043aa1d54
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :...
the_stack_v2_python_sparse
353-Design-Snake-Game/solution.py
z502185331/leetcode-python
train
0
b8e32084075628aabe93b5fb6edd926c9f013dad
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LinkedResource()", "from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'applicationName': lambda n: setattr(self, 'application_name', n.get_str_value()), 'displayName': lambda n: setattr...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return LinkedResource() <|end_body_0|> <|body_start_1|> from .entity import Entity from .entity import Entity fields: Dict[str, Callable[[Any], None]] = {'applicationName': lambda n: se...
LinkedResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkedResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LinkedResource: """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 Retur...
stack_v2_sparse_classes_36k_train_025852
2,733
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: LinkedResource", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_valu...
3
null
Implement the Python class `LinkedResource` described below. Class description: Implement the LinkedResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LinkedResource: Creates a new instance of the appropriate class based on discriminator va...
Implement the Python class `LinkedResource` described below. Class description: Implement the LinkedResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LinkedResource: Creates a new instance of the appropriate class based on discriminator va...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class LinkedResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LinkedResource: """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 Retur...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinkedResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LinkedResource: """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: LinkedReso...
the_stack_v2_python_sparse
msgraph/generated/models/linked_resource.py
microsoftgraph/msgraph-sdk-python
train
135
5f477eaf8233cc0cd2d72366b75ff88c2b2b54f7
[ "db = self.request.app['db']\nisolate_id = isolate_id.rstrip('.fa')\nif self.request.path.endswith('.fa'):\n try:\n filename, fasta = await get_data_from_req(self.request).otus.get_isolate_fasta(otu_id, isolate_id)\n except ResourceNotFoundError as err:\n if 'does not exist' in str(err):\n ...
<|body_start_0|> db = self.request.app['db'] isolate_id = isolate_id.rstrip('.fa') if self.request.path.endswith('.fa'): try: filename, fasta = await get_data_from_req(self.request).otus.get_isolate_fasta(otu_id, isolate_id) except ResourceNotFoundError as...
IsolateView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IsolateView: async def get(self, otu_id: str, isolate_id: str, /) -> Union[r200[OTUIsolate], r404]: """Get an isolate. Fetches the details of an isolate. A FASTA file containing all sequences in the isolate can be downloaded by appending `.fa` to the path.""" <|body_0|> asyn...
stack_v2_sparse_classes_36k_train_025853
16,946
permissive
[ { "docstring": "Get an isolate. Fetches the details of an isolate. A FASTA file containing all sequences in the isolate can be downloaded by appending `.fa` to the path.", "name": "get", "signature": "async def get(self, otu_id: str, isolate_id: str, /) -> Union[r200[OTUIsolate], r404]" }, { "do...
3
null
Implement the Python class `IsolateView` described below. Class description: Implement the IsolateView class. Method signatures and docstrings: - async def get(self, otu_id: str, isolate_id: str, /) -> Union[r200[OTUIsolate], r404]: Get an isolate. Fetches the details of an isolate. A FASTA file containing all sequen...
Implement the Python class `IsolateView` described below. Class description: Implement the IsolateView class. Method signatures and docstrings: - async def get(self, otu_id: str, isolate_id: str, /) -> Union[r200[OTUIsolate], r404]: Get an isolate. Fetches the details of an isolate. A FASTA file containing all sequen...
1d17d2ba570cf5487e7514bec29250a5b368bb0a
<|skeleton|> class IsolateView: async def get(self, otu_id: str, isolate_id: str, /) -> Union[r200[OTUIsolate], r404]: """Get an isolate. Fetches the details of an isolate. A FASTA file containing all sequences in the isolate can be downloaded by appending `.fa` to the path.""" <|body_0|> asyn...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IsolateView: async def get(self, otu_id: str, isolate_id: str, /) -> Union[r200[OTUIsolate], r404]: """Get an isolate. Fetches the details of an isolate. A FASTA file containing all sequences in the isolate can be downloaded by appending `.fa` to the path.""" db = self.request.app['db'] ...
the_stack_v2_python_sparse
virtool/otus/api.py
virtool/virtool
train
45
eed1f56088fe29b3dd51b95f2696fb74890ddf4d
[ "invalid = self.get_invalid(instance)\nif invalid:\n raise RuntimeError('Nodes found with non-unique asset IDs: {0}'.format(invalid))", "others = [i for i in list(instance.context) if i is not instance and set(cls.families) & get_families(i)]\nif not others:\n return []\nother_ids = defaultdict(list)\nfor o...
<|body_start_0|> invalid = self.get_invalid(instance) if invalid: raise RuntimeError('Nodes found with non-unique asset IDs: {0}'.format(invalid)) <|end_body_0|> <|body_start_1|> others = [i for i in list(instance.context) if i is not instance and set(cls.families) & get_families(i)...
Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This will *NOT* validate against previous publishes or publishes be...
ValidateNodeIdsUniqueInstanceClash
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidateNodeIdsUniqueInstanceClash: """Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This ...
stack_v2_sparse_classes_36k_train_025854
2,944
no_license
[ { "docstring": "Process all meshes", "name": "process", "signature": "def process(self, instance)" }, { "docstring": "Return the member nodes that are invalid", "name": "get_invalid", "signature": "def get_invalid(cls, instance)" } ]
2
stack_v2_sparse_classes_30k_train_015513
Implement the Python class `ValidateNodeIdsUniqueInstanceClash` described below. Class description: Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DI...
Implement the Python class `ValidateNodeIdsUniqueInstanceClash` described below. Class description: Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DI...
fa1a22297c1b2cfd48c88372958360fe4004524b
<|skeleton|> class ValidateNodeIdsUniqueInstanceClash: """Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidateNodeIdsUniqueInstanceClash: """Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This will *NOT* va...
the_stack_v2_python_sparse
colorbleed/plugins/maya/publish/validate_node_ids_unique_in_asset.py
BigRoy/colorbleed-config
train
3
f961ef060265ee1a174f567cfba68f6c9227eaec
[ "try:\n for file in os.listdir(directory):\n if file.endswith('.js'):\n filepath = '%s/%s' % (directory, file)\n self._get_data_from_file(filepath)\n self.file_count += 1\nexcept OSError as e:\n raise IngestError(e)\nif self.file_count == 0:\n raise IngestError('No ....
<|body_start_0|> try: for file in os.listdir(directory): if file.endswith('.js'): filepath = '%s/%s' % (directory, file) self._get_data_from_file(filepath) self.file_count += 1 except OSError as e: raise ...
Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and May, the format changed to what we call version ...
Version1TweetIngester
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Version1TweetIngester: """Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and...
stack_v2_sparse_classes_36k_train_025855
11,221
permissive
[ { "docstring": "Goes through all the *.js files in `directory` and puts the tweet data inside into self.tweets_data. No data is saved to the database until we've successfully loaded JSON from all of the files. Keyword arguments: directory -- The directory to load the files from. Raises: IngestError -- If the di...
2
null
Implement the Python class `Version1TweetIngester` described below. Class description: Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from...
Implement the Python class `Version1TweetIngester` described below. Class description: Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from...
57ee6f6657b41705af71ef67924d8ef06c60ae4f
<|skeleton|> class Version1TweetIngester: """Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Version1TweetIngester: """Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and May, the for...
the_stack_v2_python_sparse
ditto/twitter/ingest.py
philgyford/django-ditto
train
59
f0337af9270b1b3b116473f9e2107ff38b28ea9b
[ "data = super(ZavodnikPridaniForm, self).clean()\nclovek, created = Clovek.objects.get_or_create(prijmeni=data['prijmeni'], jmeno=data['jmeno'], narozen=data['narozen'], defaults={'pohlavi': data['pohlavi']})\nself.instance.clovek = clovek\nreturn data", "from django.forms.utils import ErrorDict\nself._errors = E...
<|body_start_0|> data = super(ZavodnikPridaniForm, self).clean() clovek, created = Clovek.objects.get_or_create(prijmeni=data['prijmeni'], jmeno=data['jmeno'], narozen=data['narozen'], defaults={'pohlavi': data['pohlavi']}) self.instance.clovek = clovek return data <|end_body_0|> <|body...
ZavodnikPridaniForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZavodnikPridaniForm: def clean(self): """z důvodu validace se `Clovek` vytvari uz v `clean` funkci""" <|body_0|> def full_clean(self): """prepsani defaultni funkce - pokud nejsou splneny podminky pro policka, pak preskoc dalsi kontrolu""" <|body_1|> def ...
stack_v2_sparse_classes_36k_train_025856
6,107
no_license
[ { "docstring": "z důvodu validace se `Clovek` vytvari uz v `clean` funkci", "name": "clean", "signature": "def clean(self)" }, { "docstring": "prepsani defaultni funkce - pokud nejsou splneny podminky pro policka, pak preskoc dalsi kontrolu", "name": "full_clean", "signature": "def full_...
4
stack_v2_sparse_classes_30k_train_013842
Implement the Python class `ZavodnikPridaniForm` described below. Class description: Implement the ZavodnikPridaniForm class. Method signatures and docstrings: - def clean(self): z důvodu validace se `Clovek` vytvari uz v `clean` funkci - def full_clean(self): prepsani defaultni funkce - pokud nejsou splneny podminky...
Implement the Python class `ZavodnikPridaniForm` described below. Class description: Implement the ZavodnikPridaniForm class. Method signatures and docstrings: - def clean(self): z důvodu validace se `Clovek` vytvari uz v `clean` funkci - def full_clean(self): prepsani defaultni funkce - pokud nejsou splneny podminky...
b3d6bfa0090cbb2a546a632e735b98ae653efc7d
<|skeleton|> class ZavodnikPridaniForm: def clean(self): """z důvodu validace se `Clovek` vytvari uz v `clean` funkci""" <|body_0|> def full_clean(self): """prepsani defaultni funkce - pokud nejsou splneny podminky pro policka, pak preskoc dalsi kontrolu""" <|body_1|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ZavodnikPridaniForm: def clean(self): """z důvodu validace se `Clovek` vytvari uz v `clean` funkci""" data = super(ZavodnikPridaniForm, self).clean() clovek, created = Clovek.objects.get_or_create(prijmeni=data['prijmeni'], jmeno=data['jmeno'], narozen=data['narozen'], defaults={'pohla...
the_stack_v2_python_sparse
zavodnici/forms.py
gumish/hanes
train
0
c00fe289eb2b02751a4404bf79361e1a4a5837bc
[ "sport = self.kwargs.get('sport')\nplayer_id = self.kwargs.get('player')\nsite_sport_manager = sports.classes.SiteSportManager()\nsite_sport = site_sport_manager.get_site_sport(sport)\nplayer_class = site_sport_manager.get_player_class(site_sport)\ntry:\n player = player_class.objects.get(pk=player_id)\nexcept p...
<|body_start_0|> sport = self.kwargs.get('sport') player_id = self.kwargs.get('player') site_sport_manager = sports.classes.SiteSportManager() site_sport = site_sport_manager.get_site_sport(sport) player_class = site_sport_manager.get_player_class(site_sport) try: ...
PlayerHistoryMlbAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlayerHistoryMlbAPIView: def get_mlb_player(self): """:return: sports.mlb.models.Player instance for the player id , if found""" <|body_0|> def get_serializer_class(self): """override for having to set the self.serializer_class""" <|body_1|> def get_play...
stack_v2_sparse_classes_36k_train_025857
26,966
no_license
[ { "docstring": ":return: sports.mlb.models.Player instance for the player id , if found", "name": "get_mlb_player", "signature": "def get_mlb_player(self)" }, { "docstring": "override for having to set the self.serializer_class", "name": "get_serializer_class", "signature": "def get_seri...
3
null
Implement the Python class `PlayerHistoryMlbAPIView` described below. Class description: Implement the PlayerHistoryMlbAPIView class. Method signatures and docstrings: - def get_mlb_player(self): :return: sports.mlb.models.Player instance for the player id , if found - def get_serializer_class(self): override for hav...
Implement the Python class `PlayerHistoryMlbAPIView` described below. Class description: Implement the PlayerHistoryMlbAPIView class. Method signatures and docstrings: - def get_mlb_player(self): :return: sports.mlb.models.Player instance for the player id , if found - def get_serializer_class(self): override for hav...
4796fa9d88b56f80def011e2b043ce595bfce8c4
<|skeleton|> class PlayerHistoryMlbAPIView: def get_mlb_player(self): """:return: sports.mlb.models.Player instance for the player id , if found""" <|body_0|> def get_serializer_class(self): """override for having to set the self.serializer_class""" <|body_1|> def get_play...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlayerHistoryMlbAPIView: def get_mlb_player(self): """:return: sports.mlb.models.Player instance for the player id , if found""" sport = self.kwargs.get('sport') player_id = self.kwargs.get('player') site_sport_manager = sports.classes.SiteSportManager() site_sport = si...
the_stack_v2_python_sparse
sports/views.py
nakamotohideyoshi/draftboard-web
train
0
43bf693141882344e27d5de1f5f969d02f326407
[ "Thread.__init__(self)\nself.router = router\nself.daemon = True", "logging.info('%sCheck if Router is online ...', LoggerSetup.get_log_deep(1))\ntry:\n Dhclient.update_ip(self.router.vlan_iface_name)\n self._test_connection()\nexcept FileExistsError:\n self._test_connection()\nexcept Exception:\n log...
<|body_start_0|> Thread.__init__(self) self.router = router self.daemon = True <|end_body_0|> <|body_start_1|> logging.info('%sCheck if Router is online ...', LoggerSetup.get_log_deep(1)) try: Dhclient.update_ip(self.router.vlan_iface_name) self._test_con...
Checks if the given Router is online and sets the Mode (normal, configuration).
RouterOnline
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RouterOnline: """Checks if the given Router is online and sets the Mode (normal, configuration).""" def __init__(self, router: Router): """:param router: Router-Obj""" <|body_0|> def run(self): """Uses the Dhlcient to get an IP from a given Router and tries to co...
stack_v2_sparse_classes_36k_train_025858
2,967
no_license
[ { "docstring": ":param router: Router-Obj", "name": "__init__", "signature": "def __init__(self, router: Router)" }, { "docstring": "Uses the Dhlcient to get an IP from a given Router and tries to connect to.", "name": "run", "signature": "def run(self)" }, { "docstring": "Sends ...
3
stack_v2_sparse_classes_30k_train_012854
Implement the Python class `RouterOnline` described below. Class description: Checks if the given Router is online and sets the Mode (normal, configuration). Method signatures and docstrings: - def __init__(self, router: Router): :param router: Router-Obj - def run(self): Uses the Dhlcient to get an IP from a given R...
Implement the Python class `RouterOnline` described below. Class description: Checks if the given Router is online and sets the Mode (normal, configuration). Method signatures and docstrings: - def __init__(self, router: Router): :param router: Router-Obj - def run(self): Uses the Dhlcient to get an IP from a given R...
551fb53a6d4f865f076d9485e7290699d988731c
<|skeleton|> class RouterOnline: """Checks if the given Router is online and sets the Mode (normal, configuration).""" def __init__(self, router: Router): """:param router: Router-Obj""" <|body_0|> def run(self): """Uses the Dhlcient to get an IP from a given Router and tries to co...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RouterOnline: """Checks if the given Router is online and sets the Mode (normal, configuration).""" def __init__(self, router: Router): """:param router: Router-Obj""" Thread.__init__(self) self.router = router self.daemon = True def run(self): """Uses the Dhl...
the_stack_v2_python_sparse
util/router_online.py
PumucklOnTheAir/TestFramework
train
9
316b38d68c75ded560cd263860b445d2afea53c7
[ "res = self.session.query(FubInfo).filter(FubInfo.code == code)\nres = res.all()\nif len(res) > 0:\n return res[0]\nelse:\n return None", "temp = FubInfo(name=fubinfo.name, code=fubinfo.no, remark='', lat=fubinfo.lat, lon=fubinfo.lon, area='n', isShow=True)\nself.session.add(temp)\nself.session.flush()\nsel...
<|body_start_0|> res = self.session.query(FubInfo).filter(FubInfo.code == code) res = res.all() if len(res) > 0: return res[0] else: return None <|end_body_0|> <|body_start_1|> temp = FubInfo(name=fubinfo.name, code=fubinfo.no, remark='', lat=fubinfo.lat,...
BuoInfoBLL
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuoInfoBLL: def isExist(self, code): """判断指定code是否已经 存在数据库中,不存在则创建 :param code: :return:""" <|body_0|> def create(self, fubinfo): """写入 :param fubinfo: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = self.session.query(FubInfo).filter...
stack_v2_sparse_classes_36k_train_025859
2,413
no_license
[ { "docstring": "判断指定code是否已经 存在数据库中,不存在则创建 :param code: :return:", "name": "isExist", "signature": "def isExist(self, code)" }, { "docstring": "写入 :param fubinfo: :return:", "name": "create", "signature": "def create(self, fubinfo)" } ]
2
stack_v2_sparse_classes_30k_train_017954
Implement the Python class `BuoInfoBLL` described below. Class description: Implement the BuoInfoBLL class. Method signatures and docstrings: - def isExist(self, code): 判断指定code是否已经 存在数据库中,不存在则创建 :param code: :return: - def create(self, fubinfo): 写入 :param fubinfo: :return:
Implement the Python class `BuoInfoBLL` described below. Class description: Implement the BuoInfoBLL class. Method signatures and docstrings: - def isExist(self, code): 判断指定code是否已经 存在数据库中,不存在则创建 :param code: :return: - def create(self, fubinfo): 写入 :param fubinfo: :return: <|skeleton|> class BuoInfoBLL: def is...
c84e26a8f280a7931b6198afaf1641a1bd0d7402
<|skeleton|> class BuoInfoBLL: def isExist(self, code): """判断指定code是否已经 存在数据库中,不存在则创建 :param code: :return:""" <|body_0|> def create(self, fubinfo): """写入 :param fubinfo: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BuoInfoBLL: def isExist(self, code): """判断指定code是否已经 存在数据库中,不存在则创建 :param code: :return:""" res = self.session.query(FubInfo).filter(FubInfo.code == code) res = res.all() if len(res) > 0: return res[0] else: return None def create(self, fubi...
the_stack_v2_python_sparse
byRabbitMQ/core/bll.py
evaseemefly/GridForecastSys
train
1
c147a2b746def4c944fee5dd763cdf7043d1dddb
[ "session = Session()\ntry:\n item = session.query(Organization).get(organization_code)\n if item is None:\n raise falcon.HTTPNotFound()\n resp.media = {'data': item.asdict()}\nfinally:\n session.close()", "session = Session()\ntry:\n organization = session.query(Organization).get(organizatio...
<|body_start_0|> session = Session() try: item = session.query(Organization).get(organization_code) if item is None: raise falcon.HTTPNotFound() resp.media = {'data': item.asdict()} finally: session.close() <|end_body_0|> <|body_st...
GET and PATCH an organization.
Item
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Item: """GET and PATCH an organization.""" def on_get(self, req, resp, organization_code): """GETs a single organization by its code. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of organization to re...
stack_v2_sparse_classes_36k_train_025860
7,046
no_license
[ { "docstring": "GETs a single organization by its code. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of organization to retrieve.", "name": "on_get", "signature": "def on_get(self, req, resp, organization_code)" }, {...
2
stack_v2_sparse_classes_30k_train_000706
Implement the Python class `Item` described below. Class description: GET and PATCH an organization. Method signatures and docstrings: - def on_get(self, req, resp, organization_code): GETs a single organization by its code. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation....
Implement the Python class `Item` described below. Class description: GET and PATCH an organization. Method signatures and docstrings: - def on_get(self, req, resp, organization_code): GETs a single organization by its code. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation....
62723133595829230e5b589431a32cda3b092460
<|skeleton|> class Item: """GET and PATCH an organization.""" def on_get(self, req, resp, organization_code): """GETs a single organization by its code. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of organization to re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Item: """GET and PATCH an organization.""" def on_get(self, req, resp, organization_code): """GETs a single organization by its code. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of organization to retrieve.""" ...
the_stack_v2_python_sparse
knoweak/api/resources/organization.py
psvaiter/knoweak-api
train
0
d3179f6608465ee67ea41c6f5cd149eb8f50a1e3
[ "token = create_and_login()\nresponse = self.client.get(USER_URL, HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token)\ncheck_response_without_uuid(response, HTTP_200_OK, EXPECTED_CONTENT, extra_keys=['last_login', 'date_joined'])", "expected_content = deepcopy(EXPECTED_CONTENT)\nexpected_content['first_name'] = 'Di...
<|body_start_0|> token = create_and_login() response = self.client.get(USER_URL, HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token) check_response_without_uuid(response, HTTP_200_OK, EXPECTED_CONTENT, extra_keys=['last_login', 'date_joined']) <|end_body_0|> <|body_start_1|> expected_cont...
The user gets her account's User data, and changes some attributes.
GetPut
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetPut: """The user gets her account's User data, and changes some attributes.""" def test_get(self): """Get data from the default created account.""" <|body_0|> def test_change_one_field(self): """Change one field in the account.""" <|body_1|> def t...
stack_v2_sparse_classes_36k_train_025861
19,841
permissive
[ { "docstring": "Get data from the default created account.", "name": "test_get", "signature": "def test_get(self)" }, { "docstring": "Change one field in the account.", "name": "test_change_one_field", "signature": "def test_change_one_field(self)" }, { "docstring": "Get data fro...
6
stack_v2_sparse_classes_30k_train_005216
Implement the Python class `GetPut` described below. Class description: The user gets her account's User data, and changes some attributes. Method signatures and docstrings: - def test_get(self): Get data from the default created account. - def test_change_one_field(self): Change one field in the account. - def test_...
Implement the Python class `GetPut` described below. Class description: The user gets her account's User data, and changes some attributes. Method signatures and docstrings: - def test_get(self): Get data from the default created account. - def test_change_one_field(self): Change one field in the account. - def test_...
d7f1f1f1ff926148d2aa541d0bd4758173aa76d5
<|skeleton|> class GetPut: """The user gets her account's User data, and changes some attributes.""" def test_get(self): """Get data from the default created account.""" <|body_0|> def test_change_one_field(self): """Change one field in the account.""" <|body_1|> def t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetPut: """The user gets her account's User data, and changes some attributes.""" def test_get(self): """Get data from the default created account.""" token = create_and_login() response = self.client.get(USER_URL, HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % token) check_re...
the_stack_v2_python_sparse
goldstone/user/tests.py
leftees/goldstone-server
train
0
8ebfc9661330150d52cd5c7e1d87a0f04bc80704
[ "self.host = host\nself.port = port\nself.kwargs = kwargs\nself._handle_request = handle_request\nself._handle_disconnect = handle_disconnect\nself._file_hashes = dict()\nself._connection_ids = dict()", "event_loop = asyncio.get_event_loop()\nstart_server = websockets.serve(self._serve, self.host, self.port, **se...
<|body_start_0|> self.host = host self.port = port self.kwargs = kwargs self._handle_request = handle_request self._handle_disconnect = handle_disconnect self._file_hashes = dict() self._connection_ids = dict() <|end_body_0|> <|body_start_1|> event_loop =...
Server side of the CommunicationEngine. The communication engine manages the connection between the remote and local side of the transport layer. The server will be executed on the remote side.
CommunicationEngineServer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommunicationEngineServer: """Server side of the CommunicationEngine. The communication engine manages the connection between the remote and local side of the transport layer. The server will be executed on the remote side.""" def __init__(self, host, port, handle_request, handle_disconnect,...
stack_v2_sparse_classes_36k_train_025862
9,739
permissive
[ { "docstring": "Construct the communication engine's server. Args: host (str): The hostname. port (int): The port. handle_request (Callable): Handles the requests of the user. Signature: command(str), data(str), temp_directory(str), user(UUID). handle_disconnect (Callable[UUID(user)]): Gets called when a user d...
4
null
Implement the Python class `CommunicationEngineServer` described below. Class description: Server side of the CommunicationEngine. The communication engine manages the connection between the remote and local side of the transport layer. The server will be executed on the remote side. Method signatures and docstrings:...
Implement the Python class `CommunicationEngineServer` described below. Class description: Server side of the CommunicationEngine. The communication engine manages the connection between the remote and local side of the transport layer. The server will be executed on the remote side. Method signatures and docstrings:...
17a6bbabbe972c63a75cdfca15deeee41840cd31
<|skeleton|> class CommunicationEngineServer: """Server side of the CommunicationEngine. The communication engine manages the connection between the remote and local side of the transport layer. The server will be executed on the remote side.""" def __init__(self, host, port, handle_request, handle_disconnect,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommunicationEngineServer: """Server side of the CommunicationEngine. The communication engine manages the connection between the remote and local side of the transport layer. The server will be executed on the remote side.""" def __init__(self, host, port, handle_request, handle_disconnect, **kwargs): ...
the_stack_v2_python_sparse
osp/core/session/transport/communication_engine.py
tareq97/osp-core
train
0
403432ad1af7debf921f448fec32b13c2f4896ae
[ "if fname.endswith('.gz'):\n with gzip.open(fname, 'rt') as fasta:\n return [line.strip() for line in fasta if not line.startswith('>')]\nelse:\n with open(fname, 'r') as fasta:\n return [line.strip() for line in fasta if not line.startswith('>')]", "TMPDIR = os.environ.get('TMPDIR')\nbasename...
<|body_start_0|> if fname.endswith('.gz'): with gzip.open(fname, 'rt') as fasta: return [line.strip() for line in fasta if not line.startswith('>')] else: with open(fname, 'r') as fasta: return [line.strip() for line in fasta if not line.startswith...
Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information.
AlignmentSummary
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlignmentSummary: """Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information.""" def get_sequences(self, fname): """Get a list of sequences from FASTA file.""" <|body_0|> def r...
stack_v2_sparse_classes_36k_train_025863
4,769
permissive
[ { "docstring": "Get a list of sequences from FASTA file.", "name": "get_sequences", "signature": "def get_sequences(self, fname)" }, { "docstring": "Run analysis.", "name": "run", "signature": "def run(self, inputs, outputs)" } ]
2
null
Implement the Python class `AlignmentSummary` described below. Class description: Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information. Method signatures and docstrings: - def get_sequences(self, fname): Get a list of se...
Implement the Python class `AlignmentSummary` described below. Class description: Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information. Method signatures and docstrings: - def get_sequences(self, fname): Get a list of se...
4f881f852064a841c337fa60b2084659fe58b6ba
<|skeleton|> class AlignmentSummary: """Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information.""" def get_sequences(self, fname): """Get a list of sequences from FASTA file.""" <|body_0|> def r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AlignmentSummary: """Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information.""" def get_sequences(self, fname): """Get a list of sequences from FASTA file.""" if fname.endswith('.gz'): ...
the_stack_v2_python_sparse
resolwe_bio/processes/support_processors/alignment_summary.py
genialis/resolwe-bio
train
18
b7cca5844f05efd9daa6149ef1711c851bc68da1
[ "serializer = Serializer(settings.SECRET_KEY, 300)\nsecret_str = serializer.dumps({'key': key})\nsecret_str = secret_str.decode()\nreturn secret_str", "serializer = Serializer(settings.SECRET_KEY, 300)\ntry:\n data = serializer.loads(secret_str)\nexcept BadData:\n return None\nreturn data.get('key')" ]
<|body_start_0|> serializer = Serializer(settings.SECRET_KEY, 300) secret_str = serializer.dumps({'key': key}) secret_str = secret_str.decode() return secret_str <|end_body_0|> <|body_start_1|> serializer = Serializer(settings.SECRET_KEY, 300) try: data = ser...
一个对敏感信息加密和解密的小工具
SecretTool
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecretTool: """一个对敏感信息加密和解密的小工具""" def encryption(key): """返回秘闻""" <|body_0|> def decryption(secret_str): """返回原文""" <|body_1|> <|end_skeleton|> <|body_start_0|> serializer = Serializer(settings.SECRET_KEY, 300) secret_str = serializer.d...
stack_v2_sparse_classes_36k_train_025864
1,607
no_license
[ { "docstring": "返回秘闻", "name": "encryption", "signature": "def encryption(key)" }, { "docstring": "返回原文", "name": "decryption", "signature": "def decryption(secret_str)" } ]
2
stack_v2_sparse_classes_30k_train_012838
Implement the Python class `SecretTool` described below. Class description: 一个对敏感信息加密和解密的小工具 Method signatures and docstrings: - def encryption(key): 返回秘闻 - def decryption(secret_str): 返回原文
Implement the Python class `SecretTool` described below. Class description: 一个对敏感信息加密和解密的小工具 Method signatures and docstrings: - def encryption(key): 返回秘闻 - def decryption(secret_str): 返回原文 <|skeleton|> class SecretTool: """一个对敏感信息加密和解密的小工具""" def encryption(key): """返回秘闻""" <|body_0|> ...
a8fb0fc2352e0c71bab756a06c5a8babd8c350da
<|skeleton|> class SecretTool: """一个对敏感信息加密和解密的小工具""" def encryption(key): """返回秘闻""" <|body_0|> def decryption(secret_str): """返回原文""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecretTool: """一个对敏感信息加密和解密的小工具""" def encryption(key): """返回秘闻""" serializer = Serializer(settings.SECRET_KEY, 300) secret_str = serializer.dumps({'key': key}) secret_str = secret_str.decode() return secret_str def decryption(secret_str): """返回原文""" ...
the_stack_v2_python_sparse
meiduo_mall/meiduo_mall/utils/tools.py
zhangjian-ai/meiduo
train
22
a00d5ddef611e1319e745dbe5ae4f910280cd417
[ "super(VanillaEncoder, self).__init__()\nself.conv1 = PointNetConv2Layer(64, momentum)\nself.conv2 = PointNetConv2Layer(64, momentum)\nself.conv3 = PointNetConv2Layer(64, momentum)\nself.conv4 = PointNetConv2Layer(128, momentum)\nself.conv5 = PointNetConv2Layer(1024, momentum)", "x = tf.expand_dims(inputs, axis=2...
<|body_start_0|> super(VanillaEncoder, self).__init__() self.conv1 = PointNetConv2Layer(64, momentum) self.conv2 = PointNetConv2Layer(64, momentum) self.conv3 = PointNetConv2Layer(64, momentum) self.conv4 = PointNetConv2Layer(128, momentum) self.conv5 = PointNetConv2Layer...
The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/pointnet_cls_basic.py
VanillaEncoder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VanillaEncoder: """The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/pointnet_cls_basic.py""" def __init_...
stack_v2_sparse_classes_36k_train_025865
9,332
permissive
[ { "docstring": "Constructs a VanillaEncoder keras layer. Args: momentum: the momentum used for the batch normalization layer.", "name": "__init__", "signature": "def __init__(self, momentum: float=0.5)" }, { "docstring": "Computes the PointNet features. Args: inputs: a dense tensor of size `[B,N...
2
stack_v2_sparse_classes_30k_test_000941
Implement the Python class `VanillaEncoder` described below. Class description: The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/po...
Implement the Python class `VanillaEncoder` described below. Class description: The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/po...
1b0203eb538f2b6a1013ec7736d0d548416f059a
<|skeleton|> class VanillaEncoder: """The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/pointnet_cls_basic.py""" def __init_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VanillaEncoder: """The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/pointnet_cls_basic.py""" def __init__(self, momen...
the_stack_v2_python_sparse
tensorflow_graphics/nn/layer/pointnet.py
tensorflow/graphics
train
2,920
676dca1fdcbbc3d5e42b964e989964d8c00c3e16
[ "if model._meta.app_label == 'sale_portal_ingestion':\n return 'sale_portal_ingestion'\nreturn None", "if model._meta.app_label == 'sale_portal_ingestion':\n return 'sale_portal_ingestion'\nreturn None", "if obj1._meta.app_label == 'sale_portal_ingestion' or obj2._meta.app_label == 'sale_portal_ingestion'...
<|body_start_0|> if model._meta.app_label == 'sale_portal_ingestion': return 'sale_portal_ingestion' return None <|end_body_0|> <|body_start_1|> if model._meta.app_label == 'sale_portal_ingestion': return 'sale_portal_ingestion' return None <|end_body_1|> <|body...
DBRouter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBRouter: def db_for_read(self, model, **hints): """Attempts to read auth models go to auth_db.""" <|body_0|> def db_for_write(self, model, **hints): """Attempts to write auth models go to auth_db.""" <|body_1|> def allow_relation(self, obj1, obj2, **hin...
stack_v2_sparse_classes_36k_train_025866
1,165
no_license
[ { "docstring": "Attempts to read auth models go to auth_db.", "name": "db_for_read", "signature": "def db_for_read(self, model, **hints)" }, { "docstring": "Attempts to write auth models go to auth_db.", "name": "db_for_write", "signature": "def db_for_write(self, model, **hints)" }, ...
4
null
Implement the Python class `DBRouter` described below. Class description: Implement the DBRouter class. Method signatures and docstrings: - def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db. - def db_for_write(self, model, **hints): Attempts to write auth models go to auth_db. - def al...
Implement the Python class `DBRouter` described below. Class description: Implement the DBRouter class. Method signatures and docstrings: - def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db. - def db_for_write(self, model, **hints): Attempts to write auth models go to auth_db. - def al...
da84f508b6b1aa3d23c9bff74926c7521f786408
<|skeleton|> class DBRouter: def db_for_read(self, model, **hints): """Attempts to read auth models go to auth_db.""" <|body_0|> def db_for_write(self, model, **hints): """Attempts to write auth models go to auth_db.""" <|body_1|> def allow_relation(self, obj1, obj2, **hin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBRouter: def db_for_read(self, model, **hints): """Attempts to read auth models go to auth_db.""" if model._meta.app_label == 'sale_portal_ingestion': return 'sale_portal_ingestion' return None def db_for_write(self, model, **hints): """Attempts to write auth ...
the_stack_v2_python_sparse
sale_portal/sale_portal_ingestion/dbrouters.py
Longdh57/django2-restframework
train
0
1cb10c41d4f9d7a769f4f038005cf1fc737ce22a
[ "include_ips = qpbool(self.form.cleaned_data['include_ips'])\ninclude_networks = qpbool(value)\nif not all([include_networks, include_ips]):\n if include_networks:\n return queryset.filter(is_ip=False)\n else:\n return queryset.exclude(is_ip=False)\nreturn queryset", "include_ips = qpbool(valu...
<|body_start_0|> include_ips = qpbool(self.form.cleaned_data['include_ips']) include_networks = qpbool(value) if not all([include_networks, include_ips]): if include_networks: return queryset.filter(is_ip=False) else: return queryset.exclud...
Filter for Network objects.
NetworkFilter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkFilter: """Filter for Network objects.""" def filter_include_networks(self, queryset, name, value): """Converts ``include_networks`` to queryset filters.""" <|body_0|> def filter_include_ips(self, queryset, name, value): """Converts ``include_ips`` to quer...
stack_v2_sparse_classes_36k_train_025867
8,091
permissive
[ { "docstring": "Converts ``include_networks`` to queryset filters.", "name": "filter_include_networks", "signature": "def filter_include_networks(self, queryset, name, value)" }, { "docstring": "Converts ``include_ips`` to queryset filters.", "name": "filter_include_ips", "signature": "d...
4
stack_v2_sparse_classes_30k_train_005866
Implement the Python class `NetworkFilter` described below. Class description: Filter for Network objects. Method signatures and docstrings: - def filter_include_networks(self, queryset, name, value): Converts ``include_networks`` to queryset filters. - def filter_include_ips(self, queryset, name, value): Converts ``...
Implement the Python class `NetworkFilter` described below. Class description: Filter for Network objects. Method signatures and docstrings: - def filter_include_networks(self, queryset, name, value): Converts ``include_networks`` to queryset filters. - def filter_include_ips(self, queryset, name, value): Converts ``...
941b11f84f5c0d210f638654a6ed34a5610af22a
<|skeleton|> class NetworkFilter: """Filter for Network objects.""" def filter_include_networks(self, queryset, name, value): """Converts ``include_networks`` to queryset filters.""" <|body_0|> def filter_include_ips(self, queryset, name, value): """Converts ``include_ips`` to quer...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkFilter: """Filter for Network objects.""" def filter_include_networks(self, queryset, name, value): """Converts ``include_networks`` to queryset filters.""" include_ips = qpbool(self.form.cleaned_data['include_ips']) include_networks = qpbool(value) if not all([incl...
the_stack_v2_python_sparse
nsot/api/filters.py
dropbox/nsot
train
414
65937d1d3e8bc30c1ea2a0f07d8db8c77fb5c87f
[ "super().__init__()\nif isinstance(num_particles, (tuple, list)):\n num_alpha = num_particles[0]\n num_beta = num_particles[1]\nelse:\n num_alpha = num_particles // 2\n num_beta = num_particles // 2\npar_1 = 1 if (num_alpha + num_beta) % 2 == 0 else -1\npar_2 = 1 if num_alpha % 2 == 0 else -1\nself._tap...
<|body_start_0|> super().__init__() if isinstance(num_particles, (tuple, list)): num_alpha = num_particles[0] num_beta = num_particles[1] else: num_alpha = num_particles // 2 num_beta = num_particles // 2 par_1 = 1 if (num_alpha + num_beta)...
Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonians when the spin orbitals are ordered in two s...
TwoQubitReduction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwoQubitReduction: """Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonian...
stack_v2_sparse_classes_36k_train_025868
3,640
permissive
[ { "docstring": "Args: num_particles: number of particles, if it is a list, the first number is alpha and the second number if beta.", "name": "__init__", "signature": "def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]])" }, { "docstring": "Converts the Operator to tapered o...
2
null
Implement the Python class `TwoQubitReduction` described below. Class description: Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and b...
Implement the Python class `TwoQubitReduction` described below. Class description: Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and b...
0b51250e219ca303654fc28a318c21366584ccd3
<|skeleton|> class TwoQubitReduction: """Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonian...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TwoQubitReduction: """Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonians when the sp...
the_stack_v2_python_sparse
qiskit/opflow/converters/two_qubit_reduction.py
1ucian0/qiskit-terra
train
6
93da4b86a05c52a760cafc7230f40c4621db56a3
[ "super().__init__(config)\nself.len_obj = self.config.get_type('msg_len')\nself.desc_obj = self.config.get_type('msg_desc')\nself.id_obj = self.config.get_type('ch_id')", "assert isinstance(data, ChData), 'Encoder handling incorrect type'\nch_temp = data.get_template()\nself.desc_obj.val = DataDescType['FW_PACKET...
<|body_start_0|> super().__init__(config) self.len_obj = self.config.get_type('msg_len') self.desc_obj = self.config.get_type('msg_desc') self.id_obj = self.config.get_type('ch_id') <|end_body_0|> <|body_start_1|> assert isinstance(data, ChData), 'Encoder handling incorrect type...
Encoder class for channel data
ChEncoder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChEncoder: """Encoder class for channel data""" def __init__(self, config=None): """Constructor Args: config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None passed, defaults are used. Returns: An initialized ChEncoder ...
stack_v2_sparse_classes_36k_train_025869
2,856
permissive
[ { "docstring": "Constructor Args: config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None passed, defaults are used. Returns: An initialized ChEncoder object", "name": "__init__", "signature": "def __init__(self, config=None)" }, { ...
2
null
Implement the Python class `ChEncoder` described below. Class description: Encoder class for channel data Method signatures and docstrings: - def __init__(self, config=None): Constructor Args: config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None pass...
Implement the Python class `ChEncoder` described below. Class description: Encoder class for channel data Method signatures and docstrings: - def __init__(self, config=None): Constructor Args: config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None pass...
aa663303327587146390dde67b83b9bf4e916d54
<|skeleton|> class ChEncoder: """Encoder class for channel data""" def __init__(self, config=None): """Constructor Args: config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None passed, defaults are used. Returns: An initialized ChEncoder ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChEncoder: """Encoder class for channel data""" def __init__(self, config=None): """Constructor Args: config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None passed, defaults are used. Returns: An initialized ChEncoder object""" ...
the_stack_v2_python_sparse
Gds/src/fprime_gds/common/encoders/ch_encoder.py
suriyaa/fprime
train
1
4cda076d3f0a913eed1477992b8e1ea07e13b317
[ "assert features.is_contiguous()\nassert indices.is_contiguous()\nassert weight.is_contiguous()\nB, c, m = features.size()\nn = indices.size(1)\nctx.three_interpolate_for_backward = (indices, weight, m)\noutput = torch.cuda.FloatTensor(B, c, n)\next_module.three_interpolate_forward(features, indices, weight, output...
<|body_start_0|> assert features.is_contiguous() assert indices.is_contiguous() assert weight.is_contiguous() B, c, m = features.size() n = indices.size(1) ctx.three_interpolate_for_backward = (indices, weight, m) output = torch.cuda.FloatTensor(B, c, n) e...
Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.
ThreeInterpolate
[ "Apache-2.0", "GPL-1.0-or-later", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThreeInterpolate: """Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.""" def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """Arg...
stack_v2_sparse_classes_36k_train_025870
5,652
permissive
[ { "docstring": "Args: features (torch.Tensor): (B, C, M) Features descriptors to be interpolated. indices (torch.Tensor): (B, n, 3) indices of three nearest neighbor features for the target features. weight (torch.Tensor): (B, n, 3) weights of three nearest neighbor features for the target features. Returns: to...
2
null
Implement the Python class `ThreeInterpolate` described below. Class description: Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details. Method signatures and docstrings: - def forward(ctx: Any, features: torch.Tensor, indices:...
Implement the Python class `ThreeInterpolate` described below. Class description: Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details. Method signatures and docstrings: - def forward(ctx: Any, features: torch.Tensor, indices:...
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class ThreeInterpolate: """Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.""" def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """Arg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThreeInterpolate: """Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.""" def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """Args: features (...
the_stack_v2_python_sparse
PyTorch/contrib/cv/semantic_segmentation/MMseg-swin/mmcv/mmcv/ops/three_interpolate.py
Ascend/ModelZoo-PyTorch
train
23
641b5745f9e236a70e3c24927b5d8a91ab5bf332
[ "assert isinstance(tensors, list)\nif len(tensors) > 0:\n assert not isinstance(tensors[0], list)\nself.tensors = tensors\nself.tensor_type = tensor_type", "if len(self.tensors) == 0:\n return None\nassert not isinstance(self.tensors[0], list)\nreturn self.tensors[0]" ]
<|body_start_0|> assert isinstance(tensors, list) if len(tensors) > 0: assert not isinstance(tensors[0], list) self.tensors = tensors self.tensor_type = tensor_type <|end_body_0|> <|body_start_1|> if len(self.tensors) == 0: return None assert not ...
TensorIO
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TensorIO: def __init__(self, tensors, tensor_type=AVERAGED_SCALAR): """:param tensors: 1D list of tensors. :param type: Int. Can be either AVERAGED_SCALAR, SUMMED_SCALAR, or BATCH. AVERAGED_SCALAR types are scalars that have been averaged together. SUMMED_SCALAR types are scalars that ha...
stack_v2_sparse_classes_36k_train_025871
11,710
no_license
[ { "docstring": ":param tensors: 1D list of tensors. :param type: Int. Can be either AVERAGED_SCALAR, SUMMED_SCALAR, or BATCH. AVERAGED_SCALAR types are scalars that have been averaged together. SUMMED_SCALAR types are scalars that have been summed together. BATCH types are tensors with the 0th dimension as the ...
2
stack_v2_sparse_classes_30k_test_000056
Implement the Python class `TensorIO` described below. Class description: Implement the TensorIO class. Method signatures and docstrings: - def __init__(self, tensors, tensor_type=AVERAGED_SCALAR): :param tensors: 1D list of tensors. :param type: Int. Can be either AVERAGED_SCALAR, SUMMED_SCALAR, or BATCH. AVERAGED_S...
Implement the Python class `TensorIO` described below. Class description: Implement the TensorIO class. Method signatures and docstrings: - def __init__(self, tensors, tensor_type=AVERAGED_SCALAR): :param tensors: 1D list of tensors. :param type: Int. Can be either AVERAGED_SCALAR, SUMMED_SCALAR, or BATCH. AVERAGED_S...
494d503c729ba018614fc742f1aee1e48d37127e
<|skeleton|> class TensorIO: def __init__(self, tensors, tensor_type=AVERAGED_SCALAR): """:param tensors: 1D list of tensors. :param type: Int. Can be either AVERAGED_SCALAR, SUMMED_SCALAR, or BATCH. AVERAGED_SCALAR types are scalars that have been averaged together. SUMMED_SCALAR types are scalars that ha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TensorIO: def __init__(self, tensors, tensor_type=AVERAGED_SCALAR): """:param tensors: 1D list of tensors. :param type: Int. Can be either AVERAGED_SCALAR, SUMMED_SCALAR, or BATCH. AVERAGED_SCALAR types are scalars that have been averaged together. SUMMED_SCALAR types are scalars that have been summed...
the_stack_v2_python_sparse
common/utils/multi_gpu.py
NeedsMorePie/interpolator
train
2
aeb7f367b308b038e0e223872475cca9b121c1be
[ "config = configparser.ConfigParser()\nconfig.read(configfile, encoding='utf8')\nself.inception_password = config.get('inception', 'inception_password')\nself.inception_port = config['inception']['inception_port']\nself.inception_user = config['inception']['inception_user']\nself.inception_host = config['inception'...
<|body_start_0|> config = configparser.ConfigParser() config.read(configfile, encoding='utf8') self.inception_password = config.get('inception', 'inception_password') self.inception_port = config['inception']['inception_port'] self.inception_user = config['inception']['inception_...
inception使用
InceptionClass
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InceptionClass: """inception使用""" def __init__(self): """初始化函数,获取配置文件内容""" <|body_0|> def CheckSql(self, **kwargs): """:param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :return: 返回inception检查的结果"...
stack_v2_sparse_classes_36k_train_025872
3,658
no_license
[ { "docstring": "初始化函数,获取配置文件内容", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ":param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :return: 返回inception检查的结果", "name": "CheckSql", "signature": "de...
2
stack_v2_sparse_classes_30k_train_007375
Implement the Python class `InceptionClass` described below. Class description: inception使用 Method signatures and docstrings: - def __init__(self): 初始化函数,获取配置文件内容 - def CheckSql(self, **kwargs): :param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :retu...
Implement the Python class `InceptionClass` described below. Class description: inception使用 Method signatures and docstrings: - def __init__(self): 初始化函数,获取配置文件内容 - def CheckSql(self, **kwargs): :param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :retu...
f23fa1760d80a0c900a6b599c405cf7edef7a654
<|skeleton|> class InceptionClass: """inception使用""" def __init__(self): """初始化函数,获取配置文件内容""" <|body_0|> def CheckSql(self, **kwargs): """:param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :return: 返回inception检查的结果"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InceptionClass: """inception使用""" def __init__(self): """初始化函数,获取配置文件内容""" config = configparser.ConfigParser() config.read(configfile, encoding='utf8') self.inception_password = config.get('inception', 'inception_password') self.inception_port = config['inception'...
the_stack_v2_python_sparse
drf_api/app/instance/action.py
Rob-Bao/sqlaudit
train
0
5ee2a4233e9fca44dce3a8965849d22fb13e2484
[ "if isinstance(self.values, SeriesParameter):\n self.dim = self.values.dim\n self.symbol = self.values.symbol\n self.values = self.values.values\n return\nif isinstance(self.values, tuple):\n self.dim = self.values[1]\n self.values = Q_(self.values[0])\nif not isinstance(self.values, (pint.Quantit...
<|body_start_0|> if isinstance(self.values, SeriesParameter): self.dim = self.values.dim self.symbol = self.values.symbol self.values = self.values.values return if isinstance(self.values, tuple): self.dim = self.values[1] self.valu...
Describes a parameter/coordinate of a Series and convert between formats. The input value gets stored as either quantity or DataArray. (DataArray is stored 'as is', other inputs will be converted to quantities). In addition, the desired dimension on the Parameter and an optional symbol representation for math expressio...
SeriesParameter
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeriesParameter: """Describes a parameter/coordinate of a Series and convert between formats. The input value gets stored as either quantity or DataArray. (DataArray is stored 'as is', other inputs will be converted to quantities). In addition, the desired dimension on the Parameter and an option...
stack_v2_sparse_classes_36k_train_025873
34,655
permissive
[ { "docstring": "Convert inputs and validate values.", "name": "__post_init__", "signature": "def __post_init__(self)" }, { "docstring": "Get the units information of the parameter.", "name": "units", "signature": "def units(self) -> pint.Unit" }, { "docstring": "Get the parameter...
5
null
Implement the Python class `SeriesParameter` described below. Class description: Describes a parameter/coordinate of a Series and convert between formats. The input value gets stored as either quantity or DataArray. (DataArray is stored 'as is', other inputs will be converted to quantities). In addition, the desired d...
Implement the Python class `SeriesParameter` described below. Class description: Describes a parameter/coordinate of a Series and convert between formats. The input value gets stored as either quantity or DataArray. (DataArray is stored 'as is', other inputs will be converted to quantities). In addition, the desired d...
7bc16a196ee669822f3663f3c7a08f6bbd0c76d5
<|skeleton|> class SeriesParameter: """Describes a parameter/coordinate of a Series and convert between formats. The input value gets stored as either quantity or DataArray. (DataArray is stored 'as is', other inputs will be converted to quantities). In addition, the desired dimension on the Parameter and an option...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SeriesParameter: """Describes a parameter/coordinate of a Series and convert between formats. The input value gets stored as either quantity or DataArray. (DataArray is stored 'as is', other inputs will be converted to quantities). In addition, the desired dimension on the Parameter and an optional symbol rep...
the_stack_v2_python_sparse
weldx/core/generic_series.py
BAMWelDX/weldx
train
20
b8e6aaeb20d50a4216913d6592c3b612ef703f91
[ "params = base.get_params(('event', 'type', 'unit', 'interval'), locals(), serialize_param)\nrequest = http.Request('GET', 'events/', params)\nreturn (request, parsers.parse_json)", "params = base.get_params(('type', 'limit'), locals(), serialize_param)\nrequest = http.Request('GET', 'events/top/', params)\nretur...
<|body_start_0|> params = base.get_params(('event', 'type', 'unit', 'interval'), locals(), serialize_param) request = http.Request('GET', 'events/', params) return (request, parsers.parse_json) <|end_body_0|> <|body_start_1|> params = base.get_params(('type', 'limit'), locals(), seriali...
Events
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Events: def get(self, event, type, unit, interval): """Fetch event data.""" <|body_0|> def top(self, type, limit=None): """Fetch the top events for today.""" <|body_1|> def names(self, type, limit=None): """Fetch the most common events over the l...
stack_v2_sparse_classes_36k_train_025874
7,208
permissive
[ { "docstring": "Fetch event data.", "name": "get", "signature": "def get(self, event, type, unit, interval)" }, { "docstring": "Fetch the top events for today.", "name": "top", "signature": "def top(self, type, limit=None)" }, { "docstring": "Fetch the most common events over the...
3
null
Implement the Python class `Events` described below. Class description: Implement the Events class. Method signatures and docstrings: - def get(self, event, type, unit, interval): Fetch event data. - def top(self, type, limit=None): Fetch the top events for today. - def names(self, type, limit=None): Fetch the most c...
Implement the Python class `Events` described below. Class description: Implement the Events class. Method signatures and docstrings: - def get(self, event, type, unit, interval): Fetch event data. - def top(self, type, limit=None): Fetch the top events for today. - def names(self, type, limit=None): Fetch the most c...
25caa745a104c8dc209584fa359294c65dbf88bb
<|skeleton|> class Events: def get(self, event, type, unit, interval): """Fetch event data.""" <|body_0|> def top(self, type, limit=None): """Fetch the top events for today.""" <|body_1|> def names(self, type, limit=None): """Fetch the most common events over the l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Events: def get(self, event, type, unit, interval): """Fetch event data.""" params = base.get_params(('event', 'type', 'unit', 'interval'), locals(), serialize_param) request = http.Request('GET', 'events/', params) return (request, parsers.parse_json) def top(self, type, ...
the_stack_v2_python_sparse
libsaas/services/mixpanel/resources.py
piplcom/libsaas
train
1
e6c14faeadb0f8bc3e2ae7a00ce5931e4d2b03eb
[ "data = self.request\narticle = ndb.Key(urlsafe=article_key).get()\nlearning_goal = ndb.Key(urlsafe=learning_goal_key).get()\nlearning_goal.domain = int(data.get('domain'))\nlearning_goal.domainFromLiteratureReview = int(data.get('domainFromLiteratureReview'))\nlearning_goal.support = int(data.get('support'))\nlear...
<|body_start_0|> data = self.request article = ndb.Key(urlsafe=article_key).get() learning_goal = ndb.Key(urlsafe=learning_goal_key).get() learning_goal.domain = int(data.get('domain')) learning_goal.domainFromLiteratureReview = int(data.get('domainFromLiteratureReview')) ...
ArticleGoalHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArticleGoalHandler: def post(self, article_key, learning_goal_key): """article = ndb.Key(urlsafe=key).get() article.findings = self.request.get('findings') article.purpose = self.request.get('purpose') article.recommendations = self.request.get('recommendations') article.star = self.requ...
stack_v2_sparse_classes_36k_train_025875
8,563
no_license
[ { "docstring": "article = ndb.Key(urlsafe=key).get() article.findings = self.request.get('findings') article.purpose = self.request.get('purpose') article.recommendations = self.request.get('recommendations') article.star = self.request.get('star') != '' article.audience = self.request.get_all('audience') artic...
2
stack_v2_sparse_classes_30k_test_000592
Implement the Python class `ArticleGoalHandler` described below. Class description: Implement the ArticleGoalHandler class. Method signatures and docstrings: - def post(self, article_key, learning_goal_key): article = ndb.Key(urlsafe=key).get() article.findings = self.request.get('findings') article.purpose = self.re...
Implement the Python class `ArticleGoalHandler` described below. Class description: Implement the ArticleGoalHandler class. Method signatures and docstrings: - def post(self, article_key, learning_goal_key): article = ndb.Key(urlsafe=key).get() article.findings = self.request.get('findings') article.purpose = self.re...
0f0bdf4973e63a2c12cf8f05e4d45f06683c4520
<|skeleton|> class ArticleGoalHandler: def post(self, article_key, learning_goal_key): """article = ndb.Key(urlsafe=key).get() article.findings = self.request.get('findings') article.purpose = self.request.get('purpose') article.recommendations = self.request.get('recommendations') article.star = self.requ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArticleGoalHandler: def post(self, article_key, learning_goal_key): """article = ndb.Key(urlsafe=key).get() article.findings = self.request.get('findings') article.purpose = self.request.get('purpose') article.recommendations = self.request.get('recommendations') article.star = self.request.get('star'...
the_stack_v2_python_sparse
site_database/article_goals.py
everydaycomputing/everydaycomputing.org
train
1
8bbf99349863bc26c0a81f7d18978a15d112189f
[ "input_stream_ids = {f'input_{idx}': ik for idx, ik in enumerate(input_stream_keys)}\nassert 'dim' in config, \"SqueezeModule relies on 'dim' value.\\n Not found in config.\"\nsuper(SqueezeModule, self).__init__(id=id, type='SqueezeModule', config=config, input_stream_ids=input_stream_ids)\nself.sque...
<|body_start_0|> input_stream_ids = {f'input_{idx}': ik for idx, ik in enumerate(input_stream_keys)} assert 'dim' in config, "SqueezeModule relies on 'dim' value.\n Not found in config." super(SqueezeModule, self).__init__(id=id, type='SqueezeModule', config=config, input_stream_i...
SqueezeModule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SqueezeModule: def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): """Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - "dim": List of None/Tuple/List/torch.Size representing th...
stack_v2_sparse_classes_36k_train_025876
2,766
permissive
[ { "docstring": "Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - \"dim\": List of None/Tuple/List/torch.Size representing the index of the dimension to squeeze for each input stream. If multiple input streams are proposed but only one...
2
stack_v2_sparse_classes_30k_train_005003
Implement the Python class `SqueezeModule` described below. Class description: Implement the SqueezeModule class. Method signatures and docstrings: - def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): Squeeze input streams data (beware the batch dimension if it is equal to 1...). :p...
Implement the Python class `SqueezeModule` described below. Class description: Implement the SqueezeModule class. Method signatures and docstrings: - def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): Squeeze input streams data (beware the batch dimension if it is equal to 1...). :p...
afe22da2ac20c0d24e93b4dbd1f1ad61374d1a6c
<|skeleton|> class SqueezeModule: def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): """Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - "dim": List of None/Tuple/List/torch.Size representing th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SqueezeModule: def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): """Squeeze input streams data (beware the batch dimension if it is equal to 1...). :param config: Dict of parameters. Expectes: - "dim": List of None/Tuple/List/torch.Size representing the index of the...
the_stack_v2_python_sparse
ReferentialGym/modules/squeeze_module.py
mk788/ReferentialGym
train
0
5e529dbd895398551c9be8f898244e599748cfb5
[ "self.db_connect = kwargs.get('db_connect')\nif self.db_connect is None:\n raise ValueError('db_connect is required in the handler.')\nself.con = psycopg2.connect(self.db_connect)\nself.cur = self.con.cursor()\nif self.cur is None:\n raise ValueError('cursor has not been opened.')\nself.sql_create_table = kwa...
<|body_start_0|> self.db_connect = kwargs.get('db_connect') if self.db_connect is None: raise ValueError('db_connect is required in the handler.') self.con = psycopg2.connect(self.db_connect) self.cur = self.con.cursor() if self.cur is None: raise ValueErr...
e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo password=demo1
db_connector
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class db_connector: """e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo...
stack_v2_sparse_classes_36k_train_025877
1,935
permissive
[ { "docstring": "db_connect is mandate.", "name": "db_init", "signature": "def db_init(self, **kwargs)" }, { "docstring": "this method will call self.make_insert_string(). the value of make_insert_string method: None: ignore this data. (string): insert SQL", "name": "db_submit", "signatur...
2
stack_v2_sparse_classes_30k_train_010916
Implement the Python class `db_connector` described below. Class description: e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0....
Implement the Python class `db_connector` described below. Class description: e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0....
f473be5bc88a2dab0b1dbe6734ec70b71fd8b48b
<|skeleton|> class db_connector: """e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class db_connector: """e.g. from db_postgres import db_connector class handler(connector_postgres): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_connect="parameter_for_connect") p.submit(kv_data) e.g. of <parameter_for_connect> host=127.0.0.1 port=5432 dbname=postgres user=demo password=dem...
the_stack_v2_python_sparse
db_connectors/db_connector_postgres.py
just-kuna/lorawan-ssas
train
0
4e39c062fb33e2f8a77f52961eef1c3eb7c4fd7a
[ "from atom import Atom\nself._center = Atom('atomic')\nself._center.position = center\nself._radius = radius", "distance_from_surface = abs(self._radius - distance(atom, self._center))\nif distance_from_surface <= cutoff_distance:\n return True\nelse:\n return False", "distance_from_center = distance(atom...
<|body_start_0|> from atom import Atom self._center = Atom('atomic') self._center.position = center self._radius = radius <|end_body_0|> <|body_start_1|> distance_from_surface = abs(self._radius - distance(atom, self._center)) if distance_from_surface <= cutoff_distance:...
Write Later
Sphere
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sphere: """Write Later""" def __init__(self, center, radius): """Write Later""" <|body_0|> def nearest_neighbor(self, atom, cutoff_distance): """Write Later""" <|body_1|> def in_shape(self, atom): """Write Later""" <|body_2|> def...
stack_v2_sparse_classes_36k_train_025878
8,615
no_license
[ { "docstring": "Write Later", "name": "__init__", "signature": "def __init__(self, center, radius)" }, { "docstring": "Write Later", "name": "nearest_neighbor", "signature": "def nearest_neighbor(self, atom, cutoff_distance)" }, { "docstring": "Write Later", "name": "in_shape...
4
stack_v2_sparse_classes_30k_train_001927
Implement the Python class `Sphere` described below. Class description: Write Later Method signatures and docstrings: - def __init__(self, center, radius): Write Later - def nearest_neighbor(self, atom, cutoff_distance): Write Later - def in_shape(self, atom): Write Later - def random_position_on_surface(self, cutoff...
Implement the Python class `Sphere` described below. Class description: Write Later Method signatures and docstrings: - def __init__(self, center, radius): Write Later - def nearest_neighbor(self, atom, cutoff_distance): Write Later - def in_shape(self, atom): Write Later - def random_position_on_surface(self, cutoff...
602c292f30398fd7f80accce6b436af3799b00c9
<|skeleton|> class Sphere: """Write Later""" def __init__(self, center, radius): """Write Later""" <|body_0|> def nearest_neighbor(self, atom, cutoff_distance): """Write Later""" <|body_1|> def in_shape(self, atom): """Write Later""" <|body_2|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sphere: """Write Later""" def __init__(self, center, radius): """Write Later""" from atom import Atom self._center = Atom('atomic') self._center.position = center self._radius = radius def nearest_neighbor(self, atom, cutoff_distance): """Write Later""...
the_stack_v2_python_sparse
space.py
drzeus99/lmpsdata2
train
0
a1623696811522ee6a5b6f19121ee08b52afc7c8
[ "self.train_df = train_df\nself.val_df = val_df\nself.test_df = test_df\nself.label_columns = label_columns\nif label_columns is not None:\n self.label_columns_indices = {name: i for i, name in enumerate(label_columns)}\nself.column_indices = {name: i for i, name in enumerate(train_df.columns)}\nself.input_width...
<|body_start_0|> self.train_df = train_df self.val_df = val_df self.test_df = test_df self.label_columns = label_columns if label_columns is not None: self.label_columns_indices = {name: i for i, name in enumerate(label_columns)} self.column_indices = {name: i...
WindowGenerator Class
WindowGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowGenerator: """WindowGenerator Class""" def __init__(self, input_width, label_width, shift, train_df, val_df, test_df, label_columns=None): """Class constructor Arguments: -input_width -label_width -shift - train_df is the train values - val_df is the validation values - test_df...
stack_v2_sparse_classes_36k_train_025879
7,134
no_license
[ { "docstring": "Class constructor Arguments: -input_width -label_width -shift - train_df is the train values - val_df is the validation values - test_df is the test values - label_columns", "name": "__init__", "signature": "def __init__(self, input_width, label_width, shift, train_df, val_df, test_df, l...
4
stack_v2_sparse_classes_30k_train_012343
Implement the Python class `WindowGenerator` described below. Class description: WindowGenerator Class Method signatures and docstrings: - def __init__(self, input_width, label_width, shift, train_df, val_df, test_df, label_columns=None): Class constructor Arguments: -input_width -label_width -shift - train_df is the...
Implement the Python class `WindowGenerator` described below. Class description: WindowGenerator Class Method signatures and docstrings: - def __init__(self, input_width, label_width, shift, train_df, val_df, test_df, label_columns=None): Class constructor Arguments: -input_width -label_width -shift - train_df is the...
fc2cec306961f7ca2448965ddd3a2f656bbe10c7
<|skeleton|> class WindowGenerator: """WindowGenerator Class""" def __init__(self, input_width, label_width, shift, train_df, val_df, test_df, label_columns=None): """Class constructor Arguments: -input_width -label_width -shift - train_df is the train values - val_df is the validation values - test_df...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WindowGenerator: """WindowGenerator Class""" def __init__(self, input_width, label_width, shift, train_df, val_df, test_df, label_columns=None): """Class constructor Arguments: -input_width -label_width -shift - train_df is the train values - val_df is the validation values - test_df is the test ...
the_stack_v2_python_sparse
supervised_learning/0x0E-time_series/forecast_btc.py
dalexach/holbertonschool-machine_learning
train
2
b34232f3efbb7c2a39774ced02fb876516e47467
[ "super().__init__(parent)\nself.chb_pv1 = _QCheckBox(' PV1 ')\nself.chb_pv2 = _QCheckBox(' PV2 ')\nself.chb_output1 = _QCheckBox(' Output1')\nself.chb_output2 = _QCheckBox(' Output2')\nself.add_widgets_next_to_table([self.chb_pv1, self.chb_pv2, self.chb_output1, self.chb_output2])\nself.set_table_column_size(120)\n...
<|body_start_0|> super().__init__(parent) self.chb_pv1 = _QCheckBox(' PV1 ') self.chb_pv2 = _QCheckBox(' PV2 ') self.chb_output1 = _QCheckBox(' Output1') self.chb_output2 = _QCheckBox(' Output2') self.add_widgets_next_to_table([self.chb_pv1, self.chb_pv2, self.chb_output1...
Air Conditioning Widget class for the Hall Bench Control application.
AirConditioningWidget
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AirConditioningWidget: """Air Conditioning Widget class for the Hall Bench Control application.""" def __init__(self, parent=None): """Set up the ui and signal/slot connections.""" <|body_0|> def closeEvent(self, event): """Overwrite closeEvent method.""" ...
stack_v2_sparse_classes_36k_train_025880
5,163
no_license
[ { "docstring": "Set up the ui and signal/slot connections.", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": "Overwrite closeEvent method.", "name": "closeEvent", "signature": "def closeEvent(self, event)" }, { "docstring": "Check connection."...
5
stack_v2_sparse_classes_30k_test_000179
Implement the Python class `AirConditioningWidget` described below. Class description: Air Conditioning Widget class for the Hall Bench Control application. Method signatures and docstrings: - def __init__(self, parent=None): Set up the ui and signal/slot connections. - def closeEvent(self, event): Overwrite closeEve...
Implement the Python class `AirConditioningWidget` described below. Class description: Air Conditioning Widget class for the Hall Bench Control application. Method signatures and docstrings: - def __init__(self, parent=None): Set up the ui and signal/slot connections. - def closeEvent(self, event): Overwrite closeEve...
25a9256522ea82e181639294e6d23ab2372a76b4
<|skeleton|> class AirConditioningWidget: """Air Conditioning Widget class for the Hall Bench Control application.""" def __init__(self, parent=None): """Set up the ui and signal/slot connections.""" <|body_0|> def closeEvent(self, event): """Overwrite closeEvent method.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AirConditioningWidget: """Air Conditioning Widget class for the Hall Bench Control application.""" def __init__(self, parent=None): """Set up the ui and signal/slot connections.""" super().__init__(parent) self.chb_pv1 = _QCheckBox(' PV1 ') self.chb_pv2 = _QCheckBox(' PV2 ...
the_stack_v2_python_sparse
hallbench/gui/airconditioningwidget.py
lnls-ima/hall-bench-control
train
1
7392fa97ce9e3303a318008b1a56948c22613bac
[ "dp = [[[0 for _ in range(3)] for _ in range(2)] for _ in range(n + 1)]\ndp[1][0][0] = 1\ndp[1][0][1] = 1\ndp[1][0][2] = 0\ndp[1][1][0] = 1\ndp[1][1][1] = 0\ndp[1][1][2] = 0\nmod = 10 ** 9 + 7\nfor i in range(2, n + 1):\n dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod\n dp[i][0][1] ...
<|body_start_0|> dp = [[[0 for _ in range(3)] for _ in range(2)] for _ in range(n + 1)] dp[1][0][0] = 1 dp[1][0][1] = 1 dp[1][0][2] = 0 dp[1][1][0] = 1 dp[1][1][1] = 0 dp[1][1][2] = 0 mod = 10 ** 9 + 7 for i in range(2, n + 1): dp[i][0]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def checkRecord(self, n: int) -> int: """动态规划, dp[i][j][k] i 表示第i个字符,j 表示 A出现的次数, k表示L连续出现的次数 合法状态 1. 没有出现过A,且前2次没有出现L 2. 没有出现过A,且最近一次是L 3. 没有出现过A,且最近两次是L 4. 出现过A,且前2次没有出现L 5. 出现过A,且最近一次是L 6. 出现过A,且最近两次是L :param n: :return:""" <|body_0|> def checkRecord1(self, n: i...
stack_v2_sparse_classes_36k_train_025881
3,117
no_license
[ { "docstring": "动态规划, dp[i][j][k] i 表示第i个字符,j 表示 A出现的次数, k表示L连续出现的次数 合法状态 1. 没有出现过A,且前2次没有出现L 2. 没有出现过A,且最近一次是L 3. 没有出现过A,且最近两次是L 4. 出现过A,且前2次没有出现L 5. 出现过A,且最近一次是L 6. 出现过A,且最近两次是L :param n: :return:", "name": "checkRecord", "signature": "def checkRecord(self, n: int) -> int" }, { "docstring": "空...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkRecord(self, n: int) -> int: 动态规划, dp[i][j][k] i 表示第i个字符,j 表示 A出现的次数, k表示L连续出现的次数 合法状态 1. 没有出现过A,且前2次没有出现L 2. 没有出现过A,且最近一次是L 3. 没有出现过A,且最近两次是L 4. 出现过A,且前2次没有出现L 5. 出现过A,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkRecord(self, n: int) -> int: 动态规划, dp[i][j][k] i 表示第i个字符,j 表示 A出现的次数, k表示L连续出现的次数 合法状态 1. 没有出现过A,且前2次没有出现L 2. 没有出现过A,且最近一次是L 3. 没有出现过A,且最近两次是L 4. 出现过A,且前2次没有出现L 5. 出现过A,...
9acba92695c06406f12f997a720bfe1deb9464a8
<|skeleton|> class Solution: def checkRecord(self, n: int) -> int: """动态规划, dp[i][j][k] i 表示第i个字符,j 表示 A出现的次数, k表示L连续出现的次数 合法状态 1. 没有出现过A,且前2次没有出现L 2. 没有出现过A,且最近一次是L 3. 没有出现过A,且最近两次是L 4. 出现过A,且前2次没有出现L 5. 出现过A,且最近一次是L 6. 出现过A,且最近两次是L :param n: :return:""" <|body_0|> def checkRecord1(self, n: i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def checkRecord(self, n: int) -> int: """动态规划, dp[i][j][k] i 表示第i个字符,j 表示 A出现的次数, k表示L连续出现的次数 合法状态 1. 没有出现过A,且前2次没有出现L 2. 没有出现过A,且最近一次是L 3. 没有出现过A,且最近两次是L 4. 出现过A,且前2次没有出现L 5. 出现过A,且最近一次是L 6. 出现过A,且最近两次是L :param n: :return:""" dp = [[[0 for _ in range(3)] for _ in range(2)] for _ in ...
the_stack_v2_python_sparse
datastructure/dp_exercise/CheckRecord.py
yinhuax/leet_code
train
0
50830ff154af20e2f581efa6f8121df3a594122b
[ "out = self.nanoutput()\ndffs = {}\nfor cs in config.stimuli():\n stim = self.analysis('stim_dff_%s' % cs)\n dffs[cs] = np.copy(stim) if stim is not None else None\n if np.sum(np.invert(np.isfinite(dffs[cs]))) > 4:\n stim = self.analysis('stim_dff_all_%s' % cs)\n dffs[cs] = np.copy(stim) if s...
<|body_start_0|> out = self.nanoutput() dffs = {} for cs in config.stimuli(): stim = self.analysis('stim_dff_%s' % cs) dffs[cs] = np.copy(stim) if stim is not None else None if np.sum(np.invert(np.isfinite(dffs[cs]))) > 4: stim = self.analysis(...
Sort
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sort: def run(self, date): """Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values""" <|body_0|> def simple(dffs, preferred_order): """Return a simple sort based on preferred resp...
stack_v2_sparse_classes_36k_train_025882
2,623
no_license
[ { "docstring": "Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values", "name": "run", "signature": "def run(self, date)" }, { "docstring": "Return a simple sort based on preferred response category with an in...
2
null
Implement the Python class `Sort` described below. Class description: Implement the Sort class. Method signatures and docstrings: - def run(self, date): Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values - def simple(dffs, prefe...
Implement the Python class `Sort` described below. Class description: Implement the Sort class. Method signatures and docstrings: - def run(self, date): Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values - def simple(dffs, prefe...
c4e9699fb78db7bd7cc14bc1bd6bd7d2b4e3a16b
<|skeleton|> class Sort: def run(self, date): """Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values""" <|body_0|> def simple(dffs, preferred_order): """Return a simple sort based on preferred resp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sort: def run(self, date): """Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values""" out = self.nanoutput() dffs = {} for cs in config.stimuli(): stim = self.analysis('stim_dff_...
the_stack_v2_python_sparse
pool/analyses/sort.py
jzaremba/pool
train
0
73b9f37b2888c0eebedf8901e6c37496711bbe52
[ "self.episodes = []\nself.max_length = max_length\nself.timesteps = 0\nself.length = length", "self.timesteps += batch.count\nepisodes = batch.split_by_episode()\nfor i, e in enumerate(episodes):\n episodes[i] = self.preprocess_episode(e)\nself.episodes.extend(episodes)\nif len(self.episodes) > self.max_length...
<|body_start_0|> self.episodes = [] self.max_length = max_length self.timesteps = 0 self.length = length <|end_body_0|> <|body_start_1|> self.timesteps += batch.count episodes = batch.split_by_episode() for i, e in enumerate(episodes): episodes[i] = s...
EpisodicBuffer
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EpisodicBuffer: def __init__(self, max_length: int=1000, length: int=50): """Data structure that stores episodes and samples chunks of size length from episodes Args: max_length: Maximum episodes it can store length: Episode chunking lengh in sample()""" <|body_0|> def add(s...
stack_v2_sparse_classes_36k_train_025883
8,885
permissive
[ { "docstring": "Data structure that stores episodes and samples chunks of size length from episodes Args: max_length: Maximum episodes it can store length: Episode chunking lengh in sample()", "name": "__init__", "signature": "def __init__(self, max_length: int=1000, length: int=50)" }, { "docst...
4
stack_v2_sparse_classes_30k_train_007068
Implement the Python class `EpisodicBuffer` described below. Class description: Implement the EpisodicBuffer class. Method signatures and docstrings: - def __init__(self, max_length: int=1000, length: int=50): Data structure that stores episodes and samples chunks of size length from episodes Args: max_length: Maximu...
Implement the Python class `EpisodicBuffer` described below. Class description: Implement the EpisodicBuffer class. Method signatures and docstrings: - def __init__(self, max_length: int=1000, length: int=50): Data structure that stores episodes and samples chunks of size length from episodes Args: max_length: Maximu...
a03cd14a50d87d58effea1d749391af530d7609c
<|skeleton|> class EpisodicBuffer: def __init__(self, max_length: int=1000, length: int=50): """Data structure that stores episodes and samples chunks of size length from episodes Args: max_length: Maximum episodes it can store length: Episode chunking lengh in sample()""" <|body_0|> def add(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EpisodicBuffer: def __init__(self, max_length: int=1000, length: int=50): """Data structure that stores episodes and samples chunks of size length from episodes Args: max_length: Maximum episodes it can store length: Episode chunking lengh in sample()""" self.episodes = [] self.max_len...
the_stack_v2_python_sparse
rllib/agents/dreamer/dreamer.py
ray-project/maze-raylit
train
5
650a01d2bb406b8130ca3b47d07a5d55d6cef788
[ "o = super(ValidatorBase, cls).__new__(cls)\no._defer = v is None\no._methods_chain = []\nreturn o", "if self._defer:\n self._methods_chain.append((_method, args, kw))\n return None if _method.__name__ == '__init__' else self\nreturn _method(self, *args, **kw)", "if self._defer:\n self._defer = False\n...
<|body_start_0|> o = super(ValidatorBase, cls).__new__(cls) o._defer = v is None o._methods_chain = [] return o <|end_body_0|> <|body_start_1|> if self._defer: self._methods_chain.append((_method, args, kw)) return None if _method.__name__ == '__init__' e...
"A hackish base class to allow both direct and deferred calls of methods For compatibility with the old and new way to built a validation chain. Examples: - Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10) - New validation with lazy calls: valid = IntValidator().greater_than(10)
ValidatorBase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidatorBase: """"A hackish base class to allow both direct and deferred calls of methods For compatibility with the old and new way to built a validation chain. Examples: - Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10) - New validation with lazy calls: val...
stack_v2_sparse_classes_36k_train_025884
11,080
permissive
[ { "docstring": "Method called before ``__init__`` If a ``v`` value is passed, all the methods will be directly called else, the method calls will be recorded and called later In: - ``v`` -- optional value to validate - ``args``, ``kw`` -- ``__init__`` parameters Return: - an instance", "name": "__new__", ...
3
null
Implement the Python class `ValidatorBase` described below. Class description: "A hackish base class to allow both direct and deferred calls of methods For compatibility with the old and new way to built a validation chain. Examples: - Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10...
Implement the Python class `ValidatorBase` described below. Class description: "A hackish base class to allow both direct and deferred calls of methods For compatibility with the old and new way to built a validation chain. Examples: - Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10...
9e251f053c4edeb46b59b46d22049b29d1498727
<|skeleton|> class ValidatorBase: """"A hackish base class to allow both direct and deferred calls of methods For compatibility with the old and new way to built a validation chain. Examples: - Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10) - New validation with lazy calls: val...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidatorBase: """"A hackish base class to allow both direct and deferred calls of methods For compatibility with the old and new way to built a validation chain. Examples: - Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10) - New validation with lazy calls: valid = IntValid...
the_stack_v2_python_sparse
cifrado/web/codigo/Python/virtualenv-15.1.0/NAGARE_HOME/Lib/site-packages/nagare-0.5.1-py2.7.egg/nagare/validator.py
SanchezRuizCarlosEduardo/disor
train
0
a04602d4b49965827af4506445df421977399b1c
[ "self.name = name\nself.dictionary = Dictionary()\nself.emotion = Emotion(self.dictionary)\nself.res_random = RandomResponder('Random', self.dictionary)\nself.res_what = RepeatResponder('Repeat', self.dictionary)\nself.res_pattern = PatternResponder('Pattern', self.dictionary)", "self.emotion.update(input)\nx = r...
<|body_start_0|> self.name = name self.dictionary = Dictionary() self.emotion = Emotion(self.dictionary) self.res_random = RandomResponder('Random', self.dictionary) self.res_what = RepeatResponder('Repeat', self.dictionary) self.res_pattern = PatternResponder('Pattern', ...
ピティナの本体クラス
Ptna
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ptna: """ピティナの本体クラス""" def __init__(self, name): """Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前""" <|body_0|> def dialogue(self, input): """応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 戻り値 応答文字列""" ...
stack_v2_sparse_classes_36k_train_025885
3,517
no_license
[ { "docstring": "Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前", "name": "__init__", "signature": "def __init__(self, name)" }, { "docstring": "応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 戻り値 応答文字列", "name": "dialogue", "signature": ...
2
stack_v2_sparse_classes_30k_train_015672
Implement the Python class `Ptna` described below. Class description: ピティナの本体クラス Method signatures and docstrings: - def __init__(self, name): Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前 - def dialogue(self, input): 応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 ...
Implement the Python class `Ptna` described below. Class description: ピティナの本体クラス Method signatures and docstrings: - def __init__(self, name): Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前 - def dialogue(self, input): 応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 ...
26126c02cfa0dc4c0db726f2f2cabb162511a5b5
<|skeleton|> class Ptna: """ピティナの本体クラス""" def __init__(self, name): """Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前""" <|body_0|> def dialogue(self, input): """応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 戻り値 応答文字列""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Ptna: """ピティナの本体クラス""" def __init__(self, name): """Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前""" self.name = name self.dictionary = Dictionary() self.emotion = Emotion(self.dictionary) self.res_random = RandomResponder('Random',...
the_stack_v2_python_sparse
normal/PythonAI/chap05/sec04/Ptna5_4_1___7/ptna.py
munezou/PycharmProject
train
2
7092048a73a9146af736c2ccc02ff9bb52841129
[ "if nvars is None:\n nvars = [(256, 256), (64, 64)]\nif len(nvars) != 2:\n raise ProblemError('this is a 2d example, got %s' % nvars)\nif nvars[0] != nvars[1]:\n raise ProblemError('need a square domain, got %s' % nvars)\nif nvars[0] % 2 != 0:\n raise ProblemError('the setup requires nvars = 2^p per dim...
<|body_start_0|> if nvars is None: nvars = [(256, 256), (64, 64)] if len(nvars) != 2: raise ProblemError('this is a 2d example, got %s' % nvars) if nvars[0] != nvars[1]: raise ProblemError('need a square domain, got %s' % nvars) if nvars[0] % 2 != 0: ...
Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Parameters ---------- nvars : int Number of unknowns in the problem. nu : float Problem parameter. eps : float Problem parameter. radius : float Radius of the circles. L : int Denotes the period of the function to be ...
allencahn2d_imex
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class allencahn2d_imex: """Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Parameters ---------- nvars : int Number of unknowns in the problem. nu : float Problem parameter. eps : float Problem parameter. radius : float Radius of the circles. L : i...
stack_v2_sparse_classes_36k_train_025886
8,359
permissive
[ { "docstring": "Initialization routine", "name": "__init__", "signature": "def __init__(self, nvars=None, nu=2, eps=0.04, radius=0.25, L=1.0, init_type='circle')" }, { "docstring": "Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the nu...
4
null
Implement the Python class `allencahn2d_imex` described below. Class description: Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Parameters ---------- nvars : int Number of unknowns in the problem. nu : float Problem parameter. eps : float Problem parameter. radi...
Implement the Python class `allencahn2d_imex` described below. Class description: Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Parameters ---------- nvars : int Number of unknowns in the problem. nu : float Problem parameter. eps : float Problem parameter. radi...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class allencahn2d_imex: """Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Parameters ---------- nvars : int Number of unknowns in the problem. nu : float Problem parameter. eps : float Problem parameter. radius : float Radius of the circles. L : i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class allencahn2d_imex: """Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Parameters ---------- nvars : int Number of unknowns in the problem. nu : float Problem parameter. eps : float Problem parameter. radius : float Radius of the circles. L : int Denotes th...
the_stack_v2_python_sparse
pySDC/implementations/problem_classes/AllenCahn_2D_FFT.py
Parallel-in-Time/pySDC
train
30
d2b63c275a078488156c48a0f353c3c4064d8997
[ "if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(username=username, email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(username=username, email=email, password=password)\nuser.is_superuser = ...
<|body_start_0|> if not email: raise ValueError('Users must have an email address') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user ...
MyUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyUserManager: def create_user(self, username, email, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, username, email, password=None): """Creates and saves a superuser with the giv...
stack_v2_sparse_classes_36k_train_025887
4,522
no_license
[ { "docstring": "Creates and saves a User with the given email, date of birth and password.", "name": "create_user", "signature": "def create_user(self, username, email, password=None)" }, { "docstring": "Creates and saves a superuser with the given email, date of birth and password.", "name"...
2
stack_v2_sparse_classes_30k_test_000257
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superuser(self, username,...
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superuser(self, username,...
097f886bf5694167b351234c63e542cdfef29bf2
<|skeleton|> class MyUserManager: def create_user(self, username, email, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, username, email, password=None): """Creates and saves a superuser with the giv...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyUserManager: def create_user(self, username, email, password=None): """Creates and saves a User with the given email, date of birth and password.""" if not email: raise ValueError('Users must have an email address') user = self.model(username=username, email=self.normaliz...
the_stack_v2_python_sparse
users/models.py
backend-python-camp-autumn-2021/team-A
train
0
dbecf6ea91e93334e94accc4d0590f14f25209d7
[ "super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)", "initializer = tf.keras.initializers.Zeros()\nhidden_...
<|body_start_0|> super(RNNEncoder, self).__init__() self.batch = batch self.units = units self.embedding = tf.keras.layers.Embedding(vocab, embedding) self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True) <|end_bod...
RNN Encoder part of the translation model
RNNEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNEncoder: """RNN Encoder part of the translation model""" def __init__(self, vocab, embedding, units, batch): """initialized the variables Arg: - vocab: int the size of the input vocabulary - embedding: int dimensionality of the embedding vector - units: int the number of hidden un...
stack_v2_sparse_classes_36k_train_025888
2,412
no_license
[ { "docstring": "initialized the variables Arg: - vocab: int the size of the input vocabulary - embedding: int dimensionality of the embedding vector - units: int the number of hidden units in the RNN cell - batch: int representing the batch size Public instance attributes: - batch: the batch size - units: the n...
3
stack_v2_sparse_classes_30k_train_008960
Implement the Python class `RNNEncoder` described below. Class description: RNN Encoder part of the translation model Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): initialized the variables Arg: - vocab: int the size of the input vocabulary - embedding: int dimensionality of ...
Implement the Python class `RNNEncoder` described below. Class description: RNN Encoder part of the translation model Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): initialized the variables Arg: - vocab: int the size of the input vocabulary - embedding: int dimensionality of ...
1d86c9606371697854878b833b810d73c9af7ee7
<|skeleton|> class RNNEncoder: """RNN Encoder part of the translation model""" def __init__(self, vocab, embedding, units, batch): """initialized the variables Arg: - vocab: int the size of the input vocabulary - embedding: int dimensionality of the embedding vector - units: int the number of hidden un...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNNEncoder: """RNN Encoder part of the translation model""" def __init__(self, vocab, embedding, units, batch): """initialized the variables Arg: - vocab: int the size of the input vocabulary - embedding: int dimensionality of the embedding vector - units: int the number of hidden units in the RN...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/0-rnn_encoder.py
macoyulloa/holbertonschool-machine_learning
train
0
4a49afe0dc80b5a7285413af6570fa8f57137faa
[ "self.name = name\nself.verbose_name = verbose_name or name.capitalize()\nself.icon = icon", "action = QtGui.QAction(parent)\naction.setData(self.name)\naction.setText(unicode(self.verbose_name))\naction.setIconVisibleInMenu(False)\nreturn action" ]
<|body_start_0|> self.name = name self.verbose_name = verbose_name or name.capitalize() self.icon = icon <|end_body_0|> <|body_start_1|> action = QtGui.QAction(parent) action.setData(self.name) action.setText(unicode(self.verbose_name)) action.setIconVisibleInMen...
A mode is a way in which an action can be triggered, a print action could be triggered as 'Export to PDF' or 'Export to Word'. None always represents the default mode. .. attribute:: name a string representing the mode to the developer and the authentication system. this name will be used in the :class:`GuiContext` .. ...
Mode
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mode: """A mode is a way in which an action can be triggered, a print action could be triggered as 'Export to PDF' or 'Export to Word'. None always represents the default mode. .. attribute:: name a string representing the mode to the developer and the authentication system. this name will be use...
stack_v2_sparse_classes_36k_train_025889
14,016
no_license
[ { "docstring": ":param name: the name of the mode, as it will be passed to the gui_run and model_run method :param verbose_name: the name shown to the user :param icon: the icon of the mode", "name": "__init__", "signature": "def __init__(self, name, verbose_name=None, icon=None)" }, { "docstrin...
2
stack_v2_sparse_classes_30k_train_004045
Implement the Python class `Mode` described below. Class description: A mode is a way in which an action can be triggered, a print action could be triggered as 'Export to PDF' or 'Export to Word'. None always represents the default mode. .. attribute:: name a string representing the mode to the developer and the authe...
Implement the Python class `Mode` described below. Class description: A mode is a way in which an action can be triggered, a print action could be triggered as 'Export to PDF' or 'Export to Word'. None always represents the default mode. .. attribute:: name a string representing the mode to the developer and the authe...
13247b093d0916510110fad2bb08acc38998e7c6
<|skeleton|> class Mode: """A mode is a way in which an action can be triggered, a print action could be triggered as 'Export to PDF' or 'Export to Word'. None always represents the default mode. .. attribute:: name a string representing the mode to the developer and the authentication system. this name will be use...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mode: """A mode is a way in which an action can be triggered, a print action could be triggered as 'Export to PDF' or 'Export to Word'. None always represents the default mode. .. attribute:: name a string representing the mode to the developer and the authentication system. this name will be used in the :cla...
the_stack_v2_python_sparse
pdf_ex/Lib/site-packages/camelot/admin/action/base.py
rustydigg918/gstr_extractor
train
1
f3af6060bcf0177a9e8349661f82dcce5a4e453f
[ "context = super(SocialInteractionPostSettings, self).get_context_data(project_id, *args, **kwargs)\nauth_users = SocialAccount.objects.filter(user=self.request.user, provider__in=['twitter', 'facebook'])\ncontext['auth_users'] = auth_users\ncontext['status_types'] = {value: key for key, value in STATUS}.keys()\nre...
<|body_start_0|> context = super(SocialInteractionPostSettings, self).get_context_data(project_id, *args, **kwargs) auth_users = SocialAccount.objects.filter(user=self.request.user, provider__in=['twitter', 'facebook']) context['auth_users'] = auth_users context['status_types'] = {value:...
Provides the form to update the social interaction settings.
SocialInteractionPostSettings
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SocialInteractionPostSettings: """Provides the form to update the social interaction settings.""" def get_context_data(self, project_id, *args, **kwargs): """Return the context to render the view. Add Twitter and Facebook social accounts of a user to the context. Parameters ---------...
stack_v2_sparse_classes_36k_train_025890
23,621
permissive
[ { "docstring": "Return the context to render the view. Add Twitter and Facebook social accounts of a user to the context. Parameters ---------- project_id : int Identifies the project in the database. Returns ------- dict Context.", "name": "get_context_data", "signature": "def get_context_data(self, pr...
2
stack_v2_sparse_classes_30k_val_000875
Implement the Python class `SocialInteractionPostSettings` described below. Class description: Provides the form to update the social interaction settings. Method signatures and docstrings: - def get_context_data(self, project_id, *args, **kwargs): Return the context to render the view. Add Twitter and Facebook socia...
Implement the Python class `SocialInteractionPostSettings` described below. Class description: Provides the form to update the social interaction settings. Method signatures and docstrings: - def get_context_data(self, project_id, *args, **kwargs): Return the context to render the view. Add Twitter and Facebook socia...
16d31b5207de9f699fc01054baad1fe65ad1c3ca
<|skeleton|> class SocialInteractionPostSettings: """Provides the form to update the social interaction settings.""" def get_context_data(self, project_id, *args, **kwargs): """Return the context to render the view. Add Twitter and Facebook social accounts of a user to the context. Parameters ---------...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SocialInteractionPostSettings: """Provides the form to update the social interaction settings.""" def get_context_data(self, project_id, *args, **kwargs): """Return the context to render the view. Add Twitter and Facebook social accounts of a user to the context. Parameters ---------- project_id ...
the_stack_v2_python_sparse
geokey/socialinteractions/views.py
NeolithEra/geokey
train
0
a551fb1ccc5e8e449033e9df480158dfe3c56ae3
[ "self._data = sys_array.array('i', [0] * M * N)\nself._rows = M\nself._cols = N", "row, col = self._validate_key(key)\nprint('Row: ', row)\nprint('_cols ', self._cols)\nprint('col ', col)\nprint('getItem Return: ', self._data[row * self._cols + col])\nreturn self._data[row * self._cols + col]", "row, col = self...
<|body_start_0|> self._data = sys_array.array('i', [0] * M * N) self._rows = M self._cols = N <|end_body_0|> <|body_start_1|> row, col = self._validate_key(key) print('Row: ', row) print('_cols ', self._cols) print('col ', col) print('getItem Return: ', s...
array
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class array: def __init__(self, M, N): """Create an M-element list of N-element row lists.""" <|body_0|> def __getitem__(self, key): """Returns the appropriate element for a two-element subscript tuple.""" <|body_1|> def __setitem__(self, key, value): ...
stack_v2_sparse_classes_36k_train_025891
2,459
no_license
[ { "docstring": "Create an M-element list of N-element row lists.", "name": "__init__", "signature": "def __init__(self, M, N)" }, { "docstring": "Returns the appropriate element for a two-element subscript tuple.", "name": "__getitem__", "signature": "def __getitem__(self, key)" }, {...
4
stack_v2_sparse_classes_30k_train_016461
Implement the Python class `array` described below. Class description: Implement the array class. Method signatures and docstrings: - def __init__(self, M, N): Create an M-element list of N-element row lists. - def __getitem__(self, key): Returns the appropriate element for a two-element subscript tuple. - def __seti...
Implement the Python class `array` described below. Class description: Implement the array class. Method signatures and docstrings: - def __init__(self, M, N): Create an M-element list of N-element row lists. - def __getitem__(self, key): Returns the appropriate element for a two-element subscript tuple. - def __seti...
7306581d542d6d045a9b2e6377ade0fc5ab8bc0e
<|skeleton|> class array: def __init__(self, M, N): """Create an M-element list of N-element row lists.""" <|body_0|> def __getitem__(self, key): """Returns the appropriate element for a two-element subscript tuple.""" <|body_1|> def __setitem__(self, key, value): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class array: def __init__(self, M, N): """Create an M-element list of N-element row lists.""" self._data = sys_array.array('i', [0] * M * N) self._rows = M self._cols = N def __getitem__(self, key): """Returns the appropriate element for a two-element subscript tuple."""...
the_stack_v2_python_sparse
PythonHomeWork/Py4/Py4_Lesson02/src/arr_array.py
rduvalwa5/OReillyPy
train
0
dd00f3505094dacc1b37dc592a15f97599f8b75a
[ "role_id_list = self.initial_data.get('role_id_list')\nif role_id_list:\n role_count = Role.objects.filter(id__in=role_id_list).count()\n if len(role_id_list) != role_count:\n raise SystemGlobalException(status_code_message_obj=StatusCodeMessage.ROLE_NOT_MATCH)\n attrs['role_id_list'] = role_id_list...
<|body_start_0|> role_id_list = self.initial_data.get('role_id_list') if role_id_list: role_count = Role.objects.filter(id__in=role_id_list).count() if len(role_id_list) != role_count: raise SystemGlobalException(status_code_message_obj=StatusCodeMessage.ROLE_NOT_...
新建用户序列化器
UserCreateSerializers
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserCreateSerializers: """新建用户序列化器""" def validate(self, attrs): """多字段验证方法 :param attrs: 请求体转换后的OrderedDict :return: attrs""" <|body_0|> def create(self, validated_data): """创建用户 :param validated_data: 字段验证通过后的数据 :return: instance""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k_train_025892
6,368
no_license
[ { "docstring": "多字段验证方法 :param attrs: 请求体转换后的OrderedDict :return: attrs", "name": "validate", "signature": "def validate(self, attrs)" }, { "docstring": "创建用户 :param validated_data: 字段验证通过后的数据 :return: instance", "name": "create", "signature": "def create(self, validated_data)" } ]
2
stack_v2_sparse_classes_30k_train_010121
Implement the Python class `UserCreateSerializers` described below. Class description: 新建用户序列化器 Method signatures and docstrings: - def validate(self, attrs): 多字段验证方法 :param attrs: 请求体转换后的OrderedDict :return: attrs - def create(self, validated_data): 创建用户 :param validated_data: 字段验证通过后的数据 :return: instance
Implement the Python class `UserCreateSerializers` described below. Class description: 新建用户序列化器 Method signatures and docstrings: - def validate(self, attrs): 多字段验证方法 :param attrs: 请求体转换后的OrderedDict :return: attrs - def create(self, validated_data): 创建用户 :param validated_data: 字段验证通过后的数据 :return: instance <|skeleto...
bb85b52598d68956bde8756c8321ade7b8479ba7
<|skeleton|> class UserCreateSerializers: """新建用户序列化器""" def validate(self, attrs): """多字段验证方法 :param attrs: 请求体转换后的OrderedDict :return: attrs""" <|body_0|> def create(self, validated_data): """创建用户 :param validated_data: 字段验证通过后的数据 :return: instance""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserCreateSerializers: """新建用户序列化器""" def validate(self, attrs): """多字段验证方法 :param attrs: 请求体转换后的OrderedDict :return: attrs""" role_id_list = self.initial_data.get('role_id_list') if role_id_list: role_count = Role.objects.filter(id__in=role_id_list).count() ...
the_stack_v2_python_sparse
rbac_v1/v1/rbac_app/serializers/user_serializers.py
huiiiuh/huihuiproject
train
0
5f31c53665618560ad7de4dd2c2c9bf591afe89f
[ "if not root:\n return []\nqueue = deque([(0, root)])\nret = []\nwhile queue:\n l, n = queue.popleft()\n if l < len(ret):\n ret[l].append(n.val)\n else:\n ret.append([n.val])\n if n.children:\n for c in n.children:\n queue.append((l + 1, c))\nreturn ret", "if not roo...
<|body_start_0|> if not root: return [] queue = deque([(0, root)]) ret = [] while queue: l, n = queue.popleft() if l < len(ret): ret[l].append(n.val) else: ret.append([n.val]) if n.children: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: """04/28/2020 23:57""" <|body_0|> def levelOrder(self, root: 'Node') -> List[List[int]]: """08/23/2021 15:04""" <|body_1|> def levelOrder(self, root: 'Node') -> List[List[int]]: """...
stack_v2_sparse_classes_36k_train_025893
4,519
no_license
[ { "docstring": "04/28/2020 23:57", "name": "levelOrder", "signature": "def levelOrder(self, root: 'Node') -> List[List[int]]" }, { "docstring": "08/23/2021 15:04", "name": "levelOrder", "signature": "def levelOrder(self, root: 'Node') -> List[List[int]]" }, { "docstring": "09/18/...
3
stack_v2_sparse_classes_30k_train_010490
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root: 'Node') -> List[List[int]]: 04/28/2020 23:57 - def levelOrder(self, root: 'Node') -> List[List[int]]: 08/23/2021 15:04 - def levelOrder(self, root: 'No...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root: 'Node') -> List[List[int]]: 04/28/2020 23:57 - def levelOrder(self, root: 'Node') -> List[List[int]]: 08/23/2021 15:04 - def levelOrder(self, root: 'No...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: """04/28/2020 23:57""" <|body_0|> def levelOrder(self, root: 'Node') -> List[List[int]]: """08/23/2021 15:04""" <|body_1|> def levelOrder(self, root: 'Node') -> List[List[int]]: """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: """04/28/2020 23:57""" if not root: return [] queue = deque([(0, root)]) ret = [] while queue: l, n = queue.popleft() if l < len(ret): ret[l].append(n.va...
the_stack_v2_python_sparse
leetcode/solved/764_N-ary_Tree_Level_Order_Traversal/solution.py
sungminoh/algorithms
train
0
408fc3b5744bb847103df1fc469d56ae910bd846
[ "super(Net, self).__init__()\nself.num_channels = params.num_channels\nself.conv1 = nn.Conv2d(3, self.num_channels, 3, stride=1, padding=1)\nself.bn1 = nn.BatchNorm2d(self.num_channels)\nself.conv2 = nn.Conv2d(self.num_channels, self.num_channels * 2, 3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(self.num_chan...
<|body_start_0|> super(Net, self).__init__() self.num_channels = params.num_channels self.conv1 = nn.Conv2d(3, self.num_channels, 3, stride=1, padding=1) self.bn1 = nn.BatchNorm2d(self.num_channels) self.conv2 = nn.Conv2d(self.num_channels, self.num_channels * 2, 3, stride=1, pad...
This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to apply functions such as F.relu,...
Net
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Net: """This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to ...
stack_v2_sparse_classes_36k_train_025894
4,649
no_license
[ { "docstring": "We define an convolutional network that predicts the sign from an image. The components required are: - an embedding layer: this layer maps each index in range(params.vocab_size) to a params.embedding_dim vector - lstm: applying the LSTM on the sequential input returns an output for each token i...
2
null
Implement the Python class `Net` described below. Class description: This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward functi...
Implement the Python class `Net` described below. Class description: This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward functi...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class Net: """This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Net: """This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to apply functio...
the_stack_v2_python_sparse
generated/test_cs230_stanford_cs230_code_examples.py
jansel/pytorch-jit-paritybench
train
35
558da74f688a07962ff0daed37e5a3ae620a8a58
[ "if not root:\n return []\nn_last = last = root\n_queue = [root]\nresult, temp = ([], [])\nwhile _queue:\n node = _queue.pop(0)\n temp.append(node.val)\n if node.left:\n _queue.append(node.left)\n n_last = node.left\n if node.right:\n _queue.append(node.right)\n n_last = n...
<|body_start_0|> if not root: return [] n_last = last = root _queue = [root] result, temp = ([], []) while _queue: node = _queue.pop(0) temp.append(node.val) if node.left: _queue.append(node.left) n_l...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def levelOrder1(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: ...
stack_v2_sparse_classes_36k_train_025895
1,591
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "levelOrder", "signature": "def levelOrder(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "levelOrder1", "signature": "def levelOrder1(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_001125
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def levelOrder1(self, root): :type root: TreeNode :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def levelOrder1(self, root): :type root: TreeNode :rtype: List[List[int]] <|skeleton|> class Solution:...
9687f8e743a8b6396fff192f22b5256d1025f86b
<|skeleton|> class Solution: def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def levelOrder1(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" if not root: return [] n_last = last = root _queue = [root] result, temp = ([], []) while _queue: node = _queue.pop(0) temp.append(node.v...
the_stack_v2_python_sparse
2017/graph/bfs/binary-tree-level-order-traversal.py
buhuipao/LeetCode
train
5
b0288d915642e58ee4c56f2011056b7002ce162a
[ "exporter = tsert_export(filename)\nexporter.set_electrode_positions(self.electrode_positions)\nexporter.set_topography(self.topography)\nexporter.add_data(self.data, version, **kwargs)\nexporter.add_metadata(self.metadata)", "logger.info('Exporting to pygimli DataContainer')\nlogger.info('{} data will be exporte...
<|body_start_0|> exporter = tsert_export(filename) exporter.set_electrode_positions(self.electrode_positions) exporter.set_topography(self.topography) exporter.add_data(self.data, version, **kwargs) exporter.add_metadata(self.metadata) <|end_body_0|> <|body_start_1|> log...
ERTExporters
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ERTExporters: def export_tsert(self, filename, version, **kwargs): """Export data to TSERT""" <|body_0|> def export_to_pygimli_scheme(self, norrec='nor', timestep=None): """Export the data into a pygimili.DataContainerERT object. For now, do NOT set any sensor positi...
stack_v2_sparse_classes_36k_train_025896
12,616
permissive
[ { "docstring": "Export data to TSERT", "name": "export_tsert", "signature": "def export_tsert(self, filename, version, **kwargs)" }, { "docstring": "Export the data into a pygimili.DataContainerERT object. For now, do NOT set any sensor positions Parameters ---------- Returns -------", "name...
2
stack_v2_sparse_classes_30k_test_000140
Implement the Python class `ERTExporters` described below. Class description: Implement the ERTExporters class. Method signatures and docstrings: - def export_tsert(self, filename, version, **kwargs): Export data to TSERT - def export_to_pygimli_scheme(self, norrec='nor', timestep=None): Export the data into a pygimi...
Implement the Python class `ERTExporters` described below. Class description: Implement the ERTExporters class. Method signatures and docstrings: - def export_tsert(self, filename, version, **kwargs): Export data to TSERT - def export_to_pygimli_scheme(self, norrec='nor', timestep=None): Export the data into a pygimi...
adecc344837c0bf53c5e005a97c2c231b6f9eac2
<|skeleton|> class ERTExporters: def export_tsert(self, filename, version, **kwargs): """Export data to TSERT""" <|body_0|> def export_to_pygimli_scheme(self, norrec='nor', timestep=None): """Export the data into a pygimili.DataContainerERT object. For now, do NOT set any sensor positi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ERTExporters: def export_tsert(self, filename, version, **kwargs): """Export data to TSERT""" exporter = tsert_export(filename) exporter.set_electrode_positions(self.electrode_positions) exporter.set_topography(self.topography) exporter.add_data(self.data, version, **kw...
the_stack_v2_python_sparse
lib/reda/containers/ERT.py
geophysics-ubonn/reda
train
14
5b2de20438b8f1835ceb6d563893c1643416b2d6
[ "it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\n[self.n, self.d] = map(int, uinput().split())\nl, s = (self.n, 2)\ninp = ' '.join((uinput() for i in range(l))).split()\nself.numm = [[int(inp[i]) for i in range(j, l * s, s)...
<|body_start_0|> it = iter(test_inputs.split('\n')) if test_inputs else None def uinput(): return next(it) if it else sys.stdin.readline().rstrip() [self.n, self.d] = map(int, uinput().split()) l, s = (self.n, 2) inp = ' '.join((uinput() for i in range(l))).split() ...
Company representation
Company
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Company: """Company representation""" def __init__(self, test_inputs=None): """Default constructor""" <|body_0|> def calculate(self): """Main calcualtion function of the class""" <|body_1|> <|end_skeleton|> <|body_start_0|> it = iter(test_inputs...
stack_v2_sparse_classes_36k_train_025897
3,763
permissive
[ { "docstring": "Default constructor", "name": "__init__", "signature": "def __init__(self, test_inputs=None)" }, { "docstring": "Main calcualtion function of the class", "name": "calculate", "signature": "def calculate(self)" } ]
2
stack_v2_sparse_classes_30k_val_000113
Implement the Python class `Company` described below. Class description: Company representation Method signatures and docstrings: - def __init__(self, test_inputs=None): Default constructor - def calculate(self): Main calcualtion function of the class
Implement the Python class `Company` described below. Class description: Company representation Method signatures and docstrings: - def __init__(self, test_inputs=None): Default constructor - def calculate(self): Main calcualtion function of the class <|skeleton|> class Company: """Company representation""" ...
ae02ea872ca91ef98630cc172a844b82cc56f621
<|skeleton|> class Company: """Company representation""" def __init__(self, test_inputs=None): """Default constructor""" <|body_0|> def calculate(self): """Main calcualtion function of the class""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Company: """Company representation""" def __init__(self, test_inputs=None): """Default constructor""" it = iter(test_inputs.split('\n')) if test_inputs else None def uinput(): return next(it) if it else sys.stdin.readline().rstrip() [self.n, self.d] = map(int,...
the_stack_v2_python_sparse
codeforces/580B_company.py
snsokolov/contests
train
1
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6
[ "key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY_TEAM)\nserializer = ContentLibraryAddPermissionByEmailSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\ntry:\n user = User.objects.get(emai...
<|body_start_0|> key = LibraryLocatorV2.from_string(lib_key_str) api.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY_TEAM) serializer = ContentLibraryAddPermissionByEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True...
View to get the list of users/groups who can access and edit the content library. Note also the 'allow_public_' settings which can be edited by PATCHing the library itself (LibraryDetailsView.patch).
LibraryTeamView
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LibraryTeamView: """View to get the list of users/groups who can access and edit the content library. Note also the 'allow_public_' settings which can be edited by PATCHing the library itself (LibraryDetailsView.patch).""" def post(self, request, lib_key_str): """Add a user to this c...
stack_v2_sparse_classes_36k_train_025898
42,120
permissive
[ { "docstring": "Add a user to this content library via email, with permissions specified in the request body.", "name": "post", "signature": "def post(self, request, lib_key_str)" }, { "docstring": "Get the list of users and groups who have permissions to view and edit this library.", "name"...
2
null
Implement the Python class `LibraryTeamView` described below. Class description: View to get the list of users/groups who can access and edit the content library. Note also the 'allow_public_' settings which can be edited by PATCHing the library itself (LibraryDetailsView.patch). Method signatures and docstrings: - d...
Implement the Python class `LibraryTeamView` described below. Class description: View to get the list of users/groups who can access and edit the content library. Note also the 'allow_public_' settings which can be edited by PATCHing the library itself (LibraryDetailsView.patch). Method signatures and docstrings: - d...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class LibraryTeamView: """View to get the list of users/groups who can access and edit the content library. Note also the 'allow_public_' settings which can be edited by PATCHing the library itself (LibraryDetailsView.patch).""" def post(self, request, lib_key_str): """Add a user to this c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LibraryTeamView: """View to get the list of users/groups who can access and edit the content library. Note also the 'allow_public_' settings which can be edited by PATCHing the library itself (LibraryDetailsView.patch).""" def post(self, request, lib_key_str): """Add a user to this content librar...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py
luque/better-ways-of-thinking-about-software
train
3
6e6408893207a3ae9634aff5985f9527d690e142
[ "button_list = [u'业务管理', u'投注卡管理', u'投注卡信息', u'展开']\nself.click_button_for_one(button_list[0])\nsleep(2)\nself.click_more_button_for_one(button_list[1:4])", "if info_list[0] != u'':\n self.input_text_message_for_inside_text(u'请输入投注卡编号', info_list[0])\nif info_list[1] != u'':\n self.open_list_menu_by_inside_...
<|body_start_0|> button_list = [u'业务管理', u'投注卡管理', u'投注卡信息', u'展开'] self.click_button_for_one(button_list[0]) sleep(2) self.click_more_button_for_one(button_list[1:4]) <|end_body_0|> <|body_start_1|> if info_list[0] != u'': self.input_text_message_for_inside_text(u'请...
投注卡信息页面
cardInformationPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class cardInformationPage: """投注卡信息页面""" def open_card_information(self): """打开投注卡信息页面""" <|body_0|> def search_card_information(self, info_list): """投注卡信息查询""" <|body_1|> def switch_to_card_information(self): """切换至投注卡信息查页面""" <|body_2|> ...
stack_v2_sparse_classes_36k_train_025899
1,510
no_license
[ { "docstring": "打开投注卡信息页面", "name": "open_card_information", "signature": "def open_card_information(self)" }, { "docstring": "投注卡信息查询", "name": "search_card_information", "signature": "def search_card_information(self, info_list)" }, { "docstring": "切换至投注卡信息查页面", "name": "sw...
3
stack_v2_sparse_classes_30k_train_004779
Implement the Python class `cardInformationPage` described below. Class description: 投注卡信息页面 Method signatures and docstrings: - def open_card_information(self): 打开投注卡信息页面 - def search_card_information(self, info_list): 投注卡信息查询 - def switch_to_card_information(self): 切换至投注卡信息查页面
Implement the Python class `cardInformationPage` described below. Class description: 投注卡信息页面 Method signatures and docstrings: - def open_card_information(self): 打开投注卡信息页面 - def search_card_information(self, info_list): 投注卡信息查询 - def switch_to_card_information(self): 切换至投注卡信息查页面 <|skeleton|> class cardInformationPag...
dcae68955b2857bbfe411145432865c57561c9ef
<|skeleton|> class cardInformationPage: """投注卡信息页面""" def open_card_information(self): """打开投注卡信息页面""" <|body_0|> def search_card_information(self, info_list): """投注卡信息查询""" <|body_1|> def switch_to_card_information(self): """切换至投注卡信息查页面""" <|body_2|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class cardInformationPage: """投注卡信息页面""" def open_card_information(self): """打开投注卡信息页面""" button_list = [u'业务管理', u'投注卡管理', u'投注卡信息', u'展开'] self.click_button_for_one(button_list[0]) sleep(2) self.click_more_button_for_one(button_list[1:4]) def search_card_informati...
the_stack_v2_python_sparse
genlot_vlt2/pages/Business_management/card_balance_page/card_manage_card_information_page.py
bbwdi/auto
train
1