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
e45b19d283a19e1481e4bb4fd4799eb77dd719b0
[ "self.full_course_name = full_course_name\nself.course_name = course_name\nself.course_visibility = course_visibility\nself.begin_day = begin_day\nself.begin_month = begin_month\nself.begin_year = begin_year\nself.end_day = end_day\nself.end_month = end_month\nself.end_year = end_year\nself.id_course = id_course\ns...
<|body_start_0|> self.full_course_name = full_course_name self.course_name = course_name self.course_visibility = course_visibility self.begin_day = begin_day self.begin_month = begin_month self.begin_year = begin_year self.end_day = end_day self.end_month...
CreateCourse
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateCourse: def __init__(self, full_course_name=None, course_name=None, course_visibility=None, begin_day=None, begin_month=None, begin_year=None, end_day=None, end_month=None, end_year=None, id_course=None, description_field=None, image_url=None, group_mode=None, forced_group_mode=None, tags_...
stack_v2_sparse_classes_36k_train_010800
2,824
permissive
[ { "docstring": "Construct data.", "name": "__init__", "signature": "def __init__(self, full_course_name=None, course_name=None, course_visibility=None, begin_day=None, begin_month=None, begin_year=None, end_day=None, end_month=None, end_year=None, id_course=None, description_field=None, image_url=None, ...
2
stack_v2_sparse_classes_30k_train_008928
Implement the Python class `CreateCourse` described below. Class description: Implement the CreateCourse class. Method signatures and docstrings: - def __init__(self, full_course_name=None, course_name=None, course_visibility=None, begin_day=None, begin_month=None, begin_year=None, end_day=None, end_month=None, end_y...
Implement the Python class `CreateCourse` described below. Class description: Implement the CreateCourse class. Method signatures and docstrings: - def __init__(self, full_course_name=None, course_name=None, course_visibility=None, begin_day=None, begin_month=None, begin_year=None, end_day=None, end_month=None, end_y...
8cd0a53fffe797c47d3b14cc3300c610467432e3
<|skeleton|> class CreateCourse: def __init__(self, full_course_name=None, course_name=None, course_visibility=None, begin_day=None, begin_month=None, begin_year=None, end_day=None, end_month=None, end_year=None, id_course=None, description_field=None, image_url=None, group_mode=None, forced_group_mode=None, tags_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateCourse: def __init__(self, full_course_name=None, course_name=None, course_visibility=None, begin_day=None, begin_month=None, begin_year=None, end_day=None, end_month=None, end_year=None, id_course=None, description_field=None, image_url=None, group_mode=None, forced_group_mode=None, tags_courses=None):...
the_stack_v2_python_sparse
models/create_course.py
KKashpovski/test_moodle_project
train
0
7005c822ae60f7d78627e0cc0aad1ba3ed363604
[ "super(Padding3DLayer, self).__init__()\nassert isinstance(input_shape, tuple) and len(input_shape) == 3, '\"input_shape\" should be a tuple with three values.'\nassert isinstance(output_shape, tuple) and len(output_shape) == 3, '\"output_shape\" should be a tuple with three values.'\nassert isinstance(padding, tup...
<|body_start_0|> super(Padding3DLayer, self).__init__() assert isinstance(input_shape, tuple) and len(input_shape) == 3, '"input_shape" should be a tuple with three values.' assert isinstance(output_shape, tuple) and len(output_shape) == 3, '"output_shape" should be a tuple with three values.' ...
This class implements padding for 3D representation. If you use this class for padding before convolution, better use 'half' or 'int' or (int1, int2) for border_mode in Convolution3D. Convolution3D layer only supports symmetric padding (which is major), but this class also supports non symmetric padding.
Padding3DLayer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Padding3DLayer: """This class implements padding for 3D representation. If you use this class for padding before convolution, better use 'half' or 'int' or (int1, int2) for border_mode in Convolution3D. Convolution3D layer only supports symmetric padding (which is major), but this class also supp...
stack_v2_sparse_classes_36k_train_010801
13,244
permissive
[ { "docstring": "This function initializes the class. Input is 4D tensor, output is 4D tensor. Parameters ---------- input_shape: tuple a tuple of three values, i.e., (input channel, input width, input height). output_shape: tuple a tuple of three values, i.e., (output channel, output width, output height). outp...
2
stack_v2_sparse_classes_30k_val_000203
Implement the Python class `Padding3DLayer` described below. Class description: This class implements padding for 3D representation. If you use this class for padding before convolution, better use 'half' or 'int' or (int1, int2) for border_mode in Convolution3D. Convolution3D layer only supports symmetric padding (wh...
Implement the Python class `Padding3DLayer` described below. Class description: This class implements padding for 3D representation. If you use this class for padding before convolution, better use 'half' or 'int' or (int1, int2) for border_mode in Convolution3D. Convolution3D layer only supports symmetric padding (wh...
7585261dd1b1c6c99dada5d2d1aabf482e89e880
<|skeleton|> class Padding3DLayer: """This class implements padding for 3D representation. If you use this class for padding before convolution, better use 'half' or 'int' or (int1, int2) for border_mode in Convolution3D. Convolution3D layer only supports symmetric padding (which is major), but this class also supp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Padding3DLayer: """This class implements padding for 3D representation. If you use this class for padding before convolution, better use 'half' or 'int' or (int1, int2) for border_mode in Convolution3D. Convolution3D layer only supports symmetric padding (which is major), but this class also supports non symm...
the_stack_v2_python_sparse
lemontree/layers/convolution.py
khshim/lemontree
train
3
168eeb3f89a2dc60636c84947d56f87f4c12dc7f
[ "super(IndexPdf, self).adjust_style(font_size)\nself.style.index = deepcopy(self.style.normal)\nself.style.index.firstLineIndent = -2 * self.style.index.fontSize\nself.style.index.leftIndent = 2 * self.style.index.fontSize", "last_title = None\ncategories = notices.session.query(Category)\nif notices.categories:\...
<|body_start_0|> super(IndexPdf, self).adjust_style(font_size) self.style.index = deepcopy(self.style.normal) self.style.index.firstLineIndent = -2 * self.style.index.fontSize self.style.index.leftIndent = 2 * self.style.index.fontSize <|end_body_0|> <|body_start_1|> last_title ...
IndexPdf
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IndexPdf: def adjust_style(self, font_size=10): """Adds styles for notices.""" <|body_0|> def category_index(self, notices): """Adds a category index.""" <|body_1|> def organization_index(self, notices): """Adds an organization index.""" ...
stack_v2_sparse_classes_36k_train_010802
20,177
permissive
[ { "docstring": "Adds styles for notices.", "name": "adjust_style", "signature": "def adjust_style(self, font_size=10)" }, { "docstring": "Adds a category index.", "name": "category_index", "signature": "def category_index(self, notices)" }, { "docstring": "Adds an organization in...
4
null
Implement the Python class `IndexPdf` described below. Class description: Implement the IndexPdf class. Method signatures and docstrings: - def adjust_style(self, font_size=10): Adds styles for notices. - def category_index(self, notices): Adds a category index. - def organization_index(self, notices): Adds an organi...
Implement the Python class `IndexPdf` described below. Class description: Implement the IndexPdf class. Method signatures and docstrings: - def adjust_style(self, font_size=10): Adds styles for notices. - def category_index(self, notices): Adds a category index. - def organization_index(self, notices): Adds an organi...
c706b38d5b67692b4146cdf14ef24d971a32c6b8
<|skeleton|> class IndexPdf: def adjust_style(self, font_size=10): """Adds styles for notices.""" <|body_0|> def category_index(self, notices): """Adds a category index.""" <|body_1|> def organization_index(self, notices): """Adds an organization index.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IndexPdf: def adjust_style(self, font_size=10): """Adds styles for notices.""" super(IndexPdf, self).adjust_style(font_size) self.style.index = deepcopy(self.style.normal) self.style.index.firstLineIndent = -2 * self.style.index.fontSize self.style.index.leftIndent = 2 ...
the_stack_v2_python_sparse
src/onegov/gazette/pdf.py
OneGov/onegov-cloud
train
17
2121b8177cdb8cea3502d73a936cfce37826daf8
[ "self.after = after\nself.before = before\nself.changes = changes", "if dictionary is None:\n return None\nafter = cohesity_management_sdk.models.protection_job.ProtectionJob.from_dictionary(dictionary.get('after')) if dictionary.get('after') else None\nbefore = cohesity_management_sdk.models.protection_job.Pr...
<|body_start_0|> self.after = after self.before = before self.changes = changes <|end_body_0|> <|body_start_1|> if dictionary is None: return None after = cohesity_management_sdk.models.protection_job.ProtectionJob.from_dictionary(dictionary.get('after')) if dictiona...
Implementation of the 'ProtectionJobAuditTrail' model. Specifies the fields for Protection job audit Response. Attributes: after (ProtectionJob): Specifies the audit logs for Protection Job after change. before (ProtectionJob): Specifies the audit logs for Protection Job before change. changes (list of ChangesEnum): Sp...
ProtectionJobAuditTrail
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProtectionJobAuditTrail: """Implementation of the 'ProtectionJobAuditTrail' model. Specifies the fields for Protection job audit Response. Attributes: after (ProtectionJob): Specifies the audit logs for Protection Job after change. before (ProtectionJob): Specifies the audit logs for Protection J...
stack_v2_sparse_classes_36k_train_010803
4,155
permissive
[ { "docstring": "Constructor for the ProtectionJobAuditTrail class", "name": "__init__", "signature": "def __init__(self, after=None, before=None, changes=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of th...
2
null
Implement the Python class `ProtectionJobAuditTrail` described below. Class description: Implementation of the 'ProtectionJobAuditTrail' model. Specifies the fields for Protection job audit Response. Attributes: after (ProtectionJob): Specifies the audit logs for Protection Job after change. before (ProtectionJob): Sp...
Implement the Python class `ProtectionJobAuditTrail` described below. Class description: Implementation of the 'ProtectionJobAuditTrail' model. Specifies the fields for Protection job audit Response. Attributes: after (ProtectionJob): Specifies the audit logs for Protection Job after change. before (ProtectionJob): Sp...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ProtectionJobAuditTrail: """Implementation of the 'ProtectionJobAuditTrail' model. Specifies the fields for Protection job audit Response. Attributes: after (ProtectionJob): Specifies the audit logs for Protection Job after change. before (ProtectionJob): Specifies the audit logs for Protection J...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProtectionJobAuditTrail: """Implementation of the 'ProtectionJobAuditTrail' model. Specifies the fields for Protection job audit Response. Attributes: after (ProtectionJob): Specifies the audit logs for Protection Job after change. before (ProtectionJob): Specifies the audit logs for Protection Job before cha...
the_stack_v2_python_sparse
cohesity_management_sdk/models/protection_job_audit_trail.py
cohesity/management-sdk-python
train
24
de5cc6767c3f9066a3bc76aa323be54addad780c
[ "try:\n firewallController = FirewallController()\n json_data = json.dumps(firewallController.get_interface_ipv4Configuration(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, mimetype=...
<|body_start_0|> try: firewallController = FirewallController() json_data = json.dumps(firewallController.get_interface_ipv4Configuration(id)) resp = Response(json_data, status=200, mimetype='application/json') return resp except ValueError as ve: ...
Interface_ifEntry_Ipv4Configuration
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interface_ifEntry_Ipv4Configuration: def get(self, id): """Get the ipv4 configuration of an interface""" <|body_0|> def put(self, id): """Update the ipv4 configuration of an interface""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_36k_train_010804
12,460
no_license
[ { "docstring": "Get the ipv4 configuration of an interface", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update the ipv4 configuration of an interface", "name": "put", "signature": "def put(self, id)" } ]
2
null
Implement the Python class `Interface_ifEntry_Ipv4Configuration` described below. Class description: Implement the Interface_ifEntry_Ipv4Configuration class. Method signatures and docstrings: - def get(self, id): Get the ipv4 configuration of an interface - def put(self, id): Update the ipv4 configuration of an inter...
Implement the Python class `Interface_ifEntry_Ipv4Configuration` described below. Class description: Implement the Interface_ifEntry_Ipv4Configuration class. Method signatures and docstrings: - def get(self, id): Get the ipv4 configuration of an interface - def put(self, id): Update the ipv4 configuration of an inter...
6070e3cb6bf957e04f5d8267db11f3296410e18e
<|skeleton|> class Interface_ifEntry_Ipv4Configuration: def get(self, id): """Get the ipv4 configuration of an interface""" <|body_0|> def put(self, id): """Update the ipv4 configuration of an interface""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Interface_ifEntry_Ipv4Configuration: def get(self, id): """Get the ipv4 configuration of an interface""" try: firewallController = FirewallController() json_data = json.dumps(firewallController.get_interface_ipv4Configuration(id)) resp = Response(json_data, ...
the_stack_v2_python_sparse
configuration-agent/firewall/rest_api/resources/interface.py
ReliableLion/frog4-configurable-vnf
train
0
9d85404ab72d306bf8bac59c3b89bce3ebf45b0c
[ "tests = [[True, 'civic'], [True, 'ivicc'], [False, 'civil'], [False, 'livci']]\nfor valid, string in tests:\n self.assertEqual(valid, could_be_a_palindrome(string), '%s should be %s' % (string, valid))", "tests = [[False, 'canal'], [True, 'a man a plan a canal panama'], [True, 'amanaplanacanalpanama'], [False...
<|body_start_0|> tests = [[True, 'civic'], [True, 'ivicc'], [False, 'civil'], [False, 'livci']] for valid, string in tests: self.assertEqual(valid, could_be_a_palindrome(string), '%s should be %s' % (string, valid)) <|end_body_0|> <|body_start_1|> tests = [[False, 'canal'], [True, '...
TestPermutationPalindrome
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPermutationPalindrome: def test_0givenexample(self): """test the given example""" <|body_0|> def test_1simpletons(self): """some more simple tests""" <|body_1|> <|end_skeleton|> <|body_start_0|> tests = [[True, 'civic'], [True, 'ivicc'], [False,...
stack_v2_sparse_classes_36k_train_010805
2,805
no_license
[ { "docstring": "test the given example", "name": "test_0givenexample", "signature": "def test_0givenexample(self)" }, { "docstring": "some more simple tests", "name": "test_1simpletons", "signature": "def test_1simpletons(self)" } ]
2
stack_v2_sparse_classes_30k_train_008399
Implement the Python class `TestPermutationPalindrome` described below. Class description: Implement the TestPermutationPalindrome class. Method signatures and docstrings: - def test_0givenexample(self): test the given example - def test_1simpletons(self): some more simple tests
Implement the Python class `TestPermutationPalindrome` described below. Class description: Implement the TestPermutationPalindrome class. Method signatures and docstrings: - def test_0givenexample(self): test the given example - def test_1simpletons(self): some more simple tests <|skeleton|> class TestPermutationPal...
aaf9b57dd957bc8756c97453dd35c01e8609e276
<|skeleton|> class TestPermutationPalindrome: def test_0givenexample(self): """test the given example""" <|body_0|> def test_1simpletons(self): """some more simple tests""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPermutationPalindrome: def test_0givenexample(self): """test the given example""" tests = [[True, 'civic'], [True, 'ivicc'], [False, 'civil'], [False, 'livci']] for valid, string in tests: self.assertEqual(valid, could_be_a_palindrome(string), '%s should be %s' % (strin...
the_stack_v2_python_sparse
30-permutation-palindrome.py
jerryasher-challenges/challenge-interviewcake
train
11
feab6b7ac7e81d8e37db3ad125b21ce662fc585f
[ "method = 'GET'\npath = self.path(key)\ntry:\n response = (yield from self.req_handler(method, path))\n result = (yield from response.json())\n return Value(**result)\nexcept InvalidPath:\n raise KeyError('%r does not exists' % key)", "if not isinstance(values, dict):\n raise ValueError('values mus...
<|body_start_0|> method = 'GET' path = self.path(key) try: response = (yield from self.req_handler(method, path)) result = (yield from response.json()) return Value(**result) except InvalidPath: raise KeyError('%r does not exists' % key) <|...
Store arbitrary secrets within the configured physical storage. The generic backend allows for writing keys with arbitrary values. The only value that special is the ``lease`` key, which can be provided with any key to restrict the lease time of the secret. This is useful to ensure clients periodically renew so that ke...
GenericBackend
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GenericBackend: """Store arbitrary secrets within the configured physical storage. The generic backend allows for writing keys with arbitrary values. The only value that special is the ``lease`` key, which can be provided with any key to restrict the lease time of the secret. This is useful to en...
stack_v2_sparse_classes_36k_train_010806
2,012
permissive
[ { "docstring": "Reads the value of the key at the given path. Parameters: key (str): The key to read Returns: Value: The key value", "name": "read", "signature": "def read(self, key)" }, { "docstring": "Update the value of the key at the given path. Parameters: key (str): The key to read values ...
3
stack_v2_sparse_classes_30k_train_020668
Implement the Python class `GenericBackend` described below. Class description: Store arbitrary secrets within the configured physical storage. The generic backend allows for writing keys with arbitrary values. The only value that special is the ``lease`` key, which can be provided with any key to restrict the lease t...
Implement the Python class `GenericBackend` described below. Class description: Store arbitrary secrets within the configured physical storage. The generic backend allows for writing keys with arbitrary values. The only value that special is the ``lease`` key, which can be provided with any key to restrict the lease t...
03e1bfb6f0404dcf97ce87a98c539027c4e78a37
<|skeleton|> class GenericBackend: """Store arbitrary secrets within the configured physical storage. The generic backend allows for writing keys with arbitrary values. The only value that special is the ``lease`` key, which can be provided with any key to restrict the lease time of the secret. This is useful to en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GenericBackend: """Store arbitrary secrets within the configured physical storage. The generic backend allows for writing keys with arbitrary values. The only value that special is the ``lease`` key, which can be provided with any key to restrict the lease time of the secret. This is useful to ensure clients ...
the_stack_v2_python_sparse
aiovault/v1/secret/backends/generic.py
johnnoone/aiovault
train
1
23493924c4e4de8f84ce32737278f80842fcc872
[ "self.kwargs = deepcopy(kwargs)\nbond_network = _get_bond_featurizer(nfeat_bond, n_bond_types, bond_embedding_dim, rbf_type, kwargs)\nif nfeat_atom is None:\n if n_atom_types is None or atom_embedding_dim is None:\n raise ValueError('Either specify nfeat_atom or n_atom_types and atom_embedding_dim')\n ...
<|body_start_0|> self.kwargs = deepcopy(kwargs) bond_network = _get_bond_featurizer(nfeat_bond, n_bond_types, bond_embedding_dim, rbf_type, kwargs) if nfeat_atom is None: if n_atom_types is None or atom_embedding_dim is None: raise ValueError('Either specify nfeat_ato...
Graph featurizer that does several things to convert an initial graph with atomic number atom attributes and bond distance bond attributes to a graph with proper feature dimensions
GraphFeaturizer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphFeaturizer: """Graph featurizer that does several things to convert an initial graph with atomic number atom attributes and bond distance bond attributes to a graph with proper feature dimensions""" def __init__(self, nfeat_bond: Optional[int]=None, nfeat_atom: Optional[int]=None, nfeat...
stack_v2_sparse_classes_36k_train_010807
8,920
permissive
[ { "docstring": "Args: nfeat_bond (int): bond feature dimension nfeat_atom (int): atom feature dimension nfeat_state (int): state feature dimension n_bond_types (int): number of bond types, used only when the bond is categorical n_atom_types (int): number of atom types n_state_types (int): number of state types,...
2
stack_v2_sparse_classes_30k_train_012714
Implement the Python class `GraphFeaturizer` described below. Class description: Graph featurizer that does several things to convert an initial graph with atomic number atom attributes and bond distance bond attributes to a graph with proper feature dimensions Method signatures and docstrings: - def __init__(self, n...
Implement the Python class `GraphFeaturizer` described below. Class description: Graph featurizer that does several things to convert an initial graph with atomic number atom attributes and bond distance bond attributes to a graph with proper feature dimensions Method signatures and docstrings: - def __init__(self, n...
1f89ecb564b2691c810cd106c3476b15a8699bb7
<|skeleton|> class GraphFeaturizer: """Graph featurizer that does several things to convert an initial graph with atomic number atom attributes and bond distance bond attributes to a graph with proper feature dimensions""" def __init__(self, nfeat_bond: Optional[int]=None, nfeat_atom: Optional[int]=None, nfeat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraphFeaturizer: """Graph featurizer that does several things to convert an initial graph with atomic number atom attributes and bond distance bond attributes to a graph with proper feature dimensions""" def __init__(self, nfeat_bond: Optional[int]=None, nfeat_atom: Optional[int]=None, nfeat_state: Optio...
the_stack_v2_python_sparse
m3gnet/layers/_gn.py
materialsvirtuallab/m3gnet
train
175
a8b8280fba60718b8440b4a0db8a88b178dfa5d7
[ "if comment.ACOrobot:\n user = {'usname': comment.ACOrobot, 'robot': 1}\nelse:\n usid = comment.USid\n from WeiDian.service.SUser import SUser\n from WeiDian.service.SSuperUser import SSuperUser\n if comment.ACOparentid:\n user = SSuperUser().get_one_super_by_suid(usid)\n if user:\n ...
<|body_start_0|> if comment.ACOrobot: user = {'usname': comment.ACOrobot, 'robot': 1} else: usid = comment.USid from WeiDian.service.SUser import SUser from WeiDian.service.SSuperUser import SSuperUser if comment.ACOparentid: us...
BaseActivityCommentControl
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseActivityCommentControl: def fill_user(self, comment): """给对象添加一个用户字段""" <|body_0|> def fill_comment_apply_for(self, comment): """"如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性""" <|body_1|> <|end_skeleton|> <|body_start_0|> if comment.ACOrobot: ...
stack_v2_sparse_classes_36k_train_010808
26,132
no_license
[ { "docstring": "给对象添加一个用户字段", "name": "fill_user", "signature": "def fill_user(self, comment)" }, { "docstring": "\"如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性", "name": "fill_comment_apply_for", "signature": "def fill_comment_apply_for(self, comment)" } ]
2
stack_v2_sparse_classes_30k_train_018373
Implement the Python class `BaseActivityCommentControl` described below. Class description: Implement the BaseActivityCommentControl class. Method signatures and docstrings: - def fill_user(self, comment): 给对象添加一个用户字段 - def fill_comment_apply_for(self, comment): "如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性
Implement the Python class `BaseActivityCommentControl` described below. Class description: Implement the BaseActivityCommentControl class. Method signatures and docstrings: - def fill_user(self, comment): 给对象添加一个用户字段 - def fill_comment_apply_for(self, comment): "如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性 <|skeleton|> clas...
50c95b9b8ba10d911e00b521affa4309f5dc20ec
<|skeleton|> class BaseActivityCommentControl: def fill_user(self, comment): """给对象添加一个用户字段""" <|body_0|> def fill_comment_apply_for(self, comment): """"如果既是评论又是回复则添加一个'所回复用户(这里的用户是管理员)'属性""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseActivityCommentControl: def fill_user(self, comment): """给对象添加一个用户字段""" if comment.ACOrobot: user = {'usname': comment.ACOrobot, 'robot': 1} else: usid = comment.USid from WeiDian.service.SUser import SUser from WeiDian.service.SSuper...
the_stack_v2_python_sparse
WeiDian/control/BaseControl.py
clove2han/Weidian
train
0
4cab7b05fa0ab8fe840339c322c25ff66c8c7cfb
[ "super().__init__(step_name=step_name, df=df, sensitive_att=sensitive_att, target_col=target_col)\nif fair_aware:\n aif_df = BinaryLabelDataset(df=df, label_names=[target_col], protected_attribute_names=[sensitive_att])\n fitted_step = step.fit(aif_df)\n input_score = False\nelse:\n if len(instance_weig...
<|body_start_0|> super().__init__(step_name=step_name, df=df, sensitive_att=sensitive_att, target_col=target_col) if fair_aware: aif_df = BinaryLabelDataset(df=df, label_names=[target_col], protected_attribute_names=[sensitive_att]) fitted_step = step.fit(aif_df) inpu...
Model
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: def __init__(self, step_name, step, df, target_col, instance_weights=[], hyper_tune=False, param_grid={}, sensitive_att=None, fair_aware=False, target_positive=1): """:param step_name: str, name of the current input step. :param step: object of the initialized class. :param df: pa...
stack_v2_sparse_classes_36k_train_010809
4,091
no_license
[ { "docstring": ":param step_name: str, name of the current input step. :param step: object of the initialized class. :param df: pandas dataframe, stores the data. :param target_col: str, the name of the target attribute. :param instance_weights: list of float in [0,1], each float represents the weight of the sa...
2
stack_v2_sparse_classes_30k_train_010202
Implement the Python class `Model` described below. Class description: Implement the Model class. Method signatures and docstrings: - def __init__(self, step_name, step, df, target_col, instance_weights=[], hyper_tune=False, param_grid={}, sensitive_att=None, fair_aware=False, target_positive=1): :param step_name: st...
Implement the Python class `Model` described below. Class description: Implement the Model class. Method signatures and docstrings: - def __init__(self, step_name, step, df, target_col, instance_weights=[], hyper_tune=False, param_grid={}, sensitive_att=None, fair_aware=False, target_positive=1): :param step_name: st...
064c07972dcdd7ae7d4f268bcbde63389be2a9c9
<|skeleton|> class Model: def __init__(self, step_name, step, df, target_col, instance_weights=[], hyper_tune=False, param_grid={}, sensitive_att=None, fair_aware=False, target_positive=1): """:param step_name: str, name of the current input step. :param step: object of the initialized class. :param df: pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Model: def __init__(self, step_name, step, df, target_col, instance_weights=[], hyper_tune=False, param_grid={}, sensitive_att=None, fair_aware=False, target_positive=1): """:param step_name: str, name of the current input step. :param step: object of the initialized class. :param df: pandas dataframe...
the_stack_v2_python_sparse
pipeline/model/inprocessor.py
tinluu/Fairness_Labels_for_ML_Pipelines
train
0
57123a3979a91f44fab4a987790e3edbb472b151
[ "Process.__init__(self)\nself.patron = patron\nself.referencia = referencia\nself.inicio = inicio\nself.similitud = similitud\nself.q = q", "coincidencias = distancias_Hamming(self.referencia, self.patron, self.similitud)\nfor c in coincidencias:\n self.q.put(c + self.inicio)" ]
<|body_start_0|> Process.__init__(self) self.patron = patron self.referencia = referencia self.inicio = inicio self.similitud = similitud self.q = q <|end_body_0|> <|body_start_1|> coincidencias = distancias_Hamming(self.referencia, self.patron, self.similitud) ...
CalculaDistancias
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CalculaDistancias: def __init__(self, referencia, patron, inicio, similitud, q): """Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en ...
stack_v2_sparse_classes_36k_train_010810
7,566
no_license
[ { "docstring": "Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en la cadena de referencia. - inicio (tipo integer): posición absoluta de la secuencia en la qu...
2
stack_v2_sparse_classes_30k_train_000204
Implement the Python class `CalculaDistancias` described below. Class description: Implement the CalculaDistancias class. Method signatures and docstrings: - def __init__(self, referencia, patron, inicio, similitud, q): Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo strin...
Implement the Python class `CalculaDistancias` described below. Class description: Implement the CalculaDistancias class. Method signatures and docstrings: - def __init__(self, referencia, patron, inicio, similitud, q): Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo strin...
bb906dcdaa39c0580f14bb6cef0956e7acd536ea
<|skeleton|> class CalculaDistancias: def __init__(self, referencia, patron, inicio, similitud, q): """Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CalculaDistancias: def __init__(self, referencia, patron, inicio, similitud, q): """Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en la cadena de r...
the_stack_v2_python_sparse
search-distances/distancias.py
nevinwu/IT-code
train
0
8b208bf3a284d5782f2906755dfdca28b6e155a3
[ "range = kwargs.pop('range', None)\nsuper(RayTransform, self).__init__(reco_space=domain, proj_space=range, geometry=geometry, variant='forward', **kwargs)\nif self.impl.startswith('astra'):\n backend, data_impl = self.impl.split('_')\n if data_impl == 'cuda':\n if self._astra_wrapper is None:\n ...
<|body_start_0|> range = kwargs.pop('range', None) super(RayTransform, self).__init__(reco_space=domain, proj_space=range, geometry=geometry, variant='forward', **kwargs) if self.impl.startswith('astra'): backend, data_impl = self.impl.split('_') if data_impl == 'cuda': ...
Discrete Ray transform between L^p spaces.
RayTransform
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RayTransform: """Discrete Ray transform between L^p spaces.""" def __init__(self, domain, geometry, **kwargs): """Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geomet...
stack_v2_sparse_classes_36k_train_010811
23,312
permissive
[ { "docstring": "Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geometry of the transform, containing information about the operator range (projection/sinogram space). Other Parameters -----------...
3
stack_v2_sparse_classes_30k_train_018148
Implement the Python class `RayTransform` described below. Class description: Discrete Ray transform between L^p spaces. Method signatures and docstrings: - def __init__(self, domain, geometry, **kwargs): Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the doma...
Implement the Python class `RayTransform` described below. Class description: Discrete Ray transform between L^p spaces. Method signatures and docstrings: - def __init__(self, domain, geometry, **kwargs): Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the doma...
cb9f08f105285a56337fa21f275aa3a15fcd74ab
<|skeleton|> class RayTransform: """Discrete Ray transform between L^p spaces.""" def __init__(self, domain, geometry, **kwargs): """Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geomet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RayTransform: """Discrete Ray transform between L^p spaces.""" def __init__(self, domain, geometry, **kwargs): """Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geometry of the tra...
the_stack_v2_python_sparse
fastatomography/tomo/operators/ray_trafo.py
PhilippPelz/fasta-tomography
train
2
ed8f626aba1e318d05f926d28d1af6063a763364
[ "super(translate_seqs, self).__init__(input_types=self._input_types, output_types=self._output_types, data_types=self._data_types)\nself._formatted_params()\nmoltype = get_moltype(moltype)\nassert moltype.label.lower() in ('dna', 'rna'), 'Invalid moltype'\nself._moltype = moltype\nself._gc = get_code(gc)\nself._tri...
<|body_start_0|> super(translate_seqs, self).__init__(input_types=self._input_types, output_types=self._output_types, data_types=self._data_types) self._formatted_params() moltype = get_moltype(moltype) assert moltype.label.lower() in ('dna', 'rna'), 'Invalid moltype' self._molty...
Translates sequences, assumes in correct reading frame.
translate_seqs
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class translate_seqs: """Translates sequences, assumes in correct reading frame.""" def __init__(self, moltype='dna', gc=DEFAULT, allow_rc=False, trim_terminal_stop=True): """generates aa sequences Parameters ---------- moltype : str molecular type, must be either DNA or RNA gc identifier ...
stack_v2_sparse_classes_36k_train_010812
9,445
permissive
[ { "docstring": "generates aa sequences Parameters ---------- moltype : str molecular type, must be either DNA or RNA gc identifier for a genetic code or a genetic code instance trim_terminal_stop : bool exclude terminal stop codon from seqs Returns ------- A sequence collection. Sequences that could not be tran...
2
stack_v2_sparse_classes_30k_train_016202
Implement the Python class `translate_seqs` described below. Class description: Translates sequences, assumes in correct reading frame. Method signatures and docstrings: - def __init__(self, moltype='dna', gc=DEFAULT, allow_rc=False, trim_terminal_stop=True): generates aa sequences Parameters ---------- moltype : str...
Implement the Python class `translate_seqs` described below. Class description: Translates sequences, assumes in correct reading frame. Method signatures and docstrings: - def __init__(self, moltype='dna', gc=DEFAULT, allow_rc=False, trim_terminal_stop=True): generates aa sequences Parameters ---------- moltype : str...
e200ed18a7fbc317abf7ebe76871fb2a7004375c
<|skeleton|> class translate_seqs: """Translates sequences, assumes in correct reading frame.""" def __init__(self, moltype='dna', gc=DEFAULT, allow_rc=False, trim_terminal_stop=True): """generates aa sequences Parameters ---------- moltype : str molecular type, must be either DNA or RNA gc identifier ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class translate_seqs: """Translates sequences, assumes in correct reading frame.""" def __init__(self, moltype='dna', gc=DEFAULT, allow_rc=False, trim_terminal_stop=True): """generates aa sequences Parameters ---------- moltype : str molecular type, must be either DNA or RNA gc identifier for a genetic...
the_stack_v2_python_sparse
src/cogent3/app/translate.py
cogent3/c3test
train
0
ed2ae09a932a04cab6416112802b5220c621265d
[ "super().__init__()\nimport sklearn\nimport sklearn.naive_bayes\nself.model = sklearn.naive_bayes.GaussianNB", "specs = super(GaussianNB, cls).getInputSpecification()\nspecs.description = 'The \\\\\\\\textit{GaussianNB} classifier implements the Gaussian Naive Bayes\\n algorithm for classi...
<|body_start_0|> super().__init__() import sklearn import sklearn.naive_bayes self.model = sklearn.naive_bayes.GaussianNB <|end_body_0|> <|body_start_1|> specs = super(GaussianNB, cls).getInputSpecification() specs.description = 'The \\\\textit{GaussianNB} classifier imp...
GaussianNB Classifier Gaussian Naive Bayes (GaussianNB) classifier
GaussianNB
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaussianNB: """GaussianNB Classifier Gaussian Naive Bayes (GaussianNB) classifier""" def __init__(self): """Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None""" <|body_0|> def getInputSpecification(cls): """Method ...
stack_v2_sparse_classes_36k_train_010813
4,253
permissive
[ { "docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for...
3
null
Implement the Python class `GaussianNB` described below. Class description: GaussianNB Classifier Gaussian Naive Bayes (GaussianNB) classifier Method signatures and docstrings: - def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None - def getInputSpecif...
Implement the Python class `GaussianNB` described below. Class description: GaussianNB Classifier Gaussian Naive Bayes (GaussianNB) classifier Method signatures and docstrings: - def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None - def getInputSpecif...
2b16e7aa3325fe84cab2477947a951414c635381
<|skeleton|> class GaussianNB: """GaussianNB Classifier Gaussian Naive Bayes (GaussianNB) classifier""" def __init__(self): """Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None""" <|body_0|> def getInputSpecification(cls): """Method ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GaussianNB: """GaussianNB Classifier Gaussian Naive Bayes (GaussianNB) classifier""" def __init__(self): """Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None""" super().__init__() import sklearn import sklearn.naive_bayes ...
the_stack_v2_python_sparse
ravenframework/SupervisedLearning/ScikitLearn/NaiveBayes/GaussianNBClassifier.py
idaholab/raven
train
201
286b58d160d6098874228f0de2eda41b674026c5
[ "if model._meta.app_label == self.appname:\n return self.db_name\nreturn None", "if model._meta.app_label == self.appname:\n return self.db_name\nreturn None", "if obj1._meta.app_label == self.appname or obj2._meta.app_label == self.appname:\n return True\nreturn None", "if app_label == self.appname:...
<|body_start_0|> if model._meta.app_label == self.appname: return self.db_name return None <|end_body_0|> <|body_start_1|> if model._meta.app_label == self.appname: return self.db_name return None <|end_body_1|> <|body_start_2|> if obj1._meta.app_label =...
Router
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Router: def db_for_read(self, model, **hints): """Attempts to read self.appname models go to model.db.""" <|body_0|> def db_for_write(self, model, **hints): """Attempts to write self.appname models go to model.db.""" <|body_1|> def allow_relation(self, o...
stack_v2_sparse_classes_36k_train_010814
1,715
no_license
[ { "docstring": "Attempts to read self.appname models go to model.db.", "name": "db_for_read", "signature": "def db_for_read(self, model, **hints)" }, { "docstring": "Attempts to write self.appname models go to model.db.", "name": "db_for_write", "signature": "def db_for_write(self, model...
4
stack_v2_sparse_classes_30k_train_001544
Implement the Python class `Router` described below. Class description: Implement the Router class. Method signatures and docstrings: - def db_for_read(self, model, **hints): Attempts to read self.appname models go to model.db. - def db_for_write(self, model, **hints): Attempts to write self.appname models go to mode...
Implement the Python class `Router` described below. Class description: Implement the Router class. Method signatures and docstrings: - def db_for_read(self, model, **hints): Attempts to read self.appname models go to model.db. - def db_for_write(self, model, **hints): Attempts to write self.appname models go to mode...
7cf818076b67cf6d4e40192b6bbe7db547005c96
<|skeleton|> class Router: def db_for_read(self, model, **hints): """Attempts to read self.appname models go to model.db.""" <|body_0|> def db_for_write(self, model, **hints): """Attempts to write self.appname models go to model.db.""" <|body_1|> def allow_relation(self, o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Router: def db_for_read(self, model, **hints): """Attempts to read self.appname models go to model.db.""" if model._meta.app_label == self.appname: return self.db_name return None def db_for_write(self, model, **hints): """Attempts to write self.appname models ...
the_stack_v2_python_sparse
apps_cenco/db_local/router.py
robCastro/academica_cenco
train
0
9309412e768fdbbe709dce3618e4c50de1d63568
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('emmaliu_gaotian_xli33_yuyangl', 'emmaliu_gaotian_xli33_yuyangl')\ntweetsData = repo.emmaliu_gaotian_xli33_yuyangl.tweets.find()\nfollowers_num = []\nlist_num = []\ni = 0\nfor item in tweetsData:\n fol...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('emmaliu_gaotian_xli33_yuyangl', 'emmaliu_gaotian_xli33_yuyangl') tweetsData = repo.emmaliu_gaotian_xli33_yuyangl.tweets.find() followers_num = [] ...
computeCorrelation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class computeCorrelation: 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 every...
stack_v2_sparse_classes_36k_train_010815
4,118
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 `computeCorrelation` described below. Class description: Implement the computeCorrelation 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(), startTi...
Implement the Python class `computeCorrelation` described below. Class description: Implement the computeCorrelation 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(), startTi...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class computeCorrelation: 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 every...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class computeCorrelation: 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('emmaliu_gaotian_xli33_yuyangl', ...
the_stack_v2_python_sparse
emmaliu_gaotian_xli33_yuyangl/computeCorrelation.py
maximega/course-2019-spr-proj
train
2
a4455ec84136a4cb858c39da7c7bc3bc1dc2e02a
[ "self._release_repos = ['product-configs', 'MediaSDK', 'media-driver']\nself._root_dir = pathlib.Path(root_dir)\nself._repo = repo\nself._branch = branch\nself._revision = revision\nself._target_branch = target_branch\nself._build_event = build_event\nself._commit_time = datetime.strptime(commit_time, '%Y-%m-%d %H:...
<|body_start_0|> self._release_repos = ['product-configs', 'MediaSDK', 'media-driver'] self._root_dir = pathlib.Path(root_dir) self._repo = repo self._branch = branch self._revision = revision self._target_branch = target_branch self._build_event = build_event ...
Prepare manifest
ManifestRunner
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ManifestRunner: """Prepare manifest""" def __init__(self, root_dir, repo, branch, revision, target_branch, build_event, commit_time): """:param root_dir: Directory where repositories will be extracted :type root_dir: String :param repo: Repository name :type repo: Repository name :pa...
stack_v2_sparse_classes_36k_train_010816
9,449
permissive
[ { "docstring": ":param root_dir: Directory where repositories will be extracted :type root_dir: String :param repo: Repository name :type repo: Repository name :param branch: Branch name :type branch: Branch name :param revision: Revision of a commit :type revision: Revision of a commit :param target_branch: Ta...
6
stack_v2_sparse_classes_30k_train_013789
Implement the Python class `ManifestRunner` described below. Class description: Prepare manifest Method signatures and docstrings: - def __init__(self, root_dir, repo, branch, revision, target_branch, build_event, commit_time): :param root_dir: Directory where repositories will be extracted :type root_dir: String :pa...
Implement the Python class `ManifestRunner` described below. Class description: Prepare manifest Method signatures and docstrings: - def __init__(self, root_dir, repo, branch, revision, target_branch, build_event, commit_time): :param root_dir: Directory where repositories will be extracted :type root_dir: String :pa...
0753703482ef61e9202ec8814836dc03112dea3e
<|skeleton|> class ManifestRunner: """Prepare manifest""" def __init__(self, root_dir, repo, branch, revision, target_branch, build_event, commit_time): """:param root_dir: Directory where repositories will be extracted :type root_dir: String :param repo: Repository name :type repo: Repository name :pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ManifestRunner: """Prepare manifest""" def __init__(self, root_dir, repo, branch, revision, target_branch, build_event, commit_time): """:param root_dir: Directory where repositories will be extracted :type root_dir: String :param repo: Repository name :type repo: Repository name :param branch: B...
the_stack_v2_python_sparse
build_scripts/manifest_runner.py
Intel-Media-SDK/infrastructure
train
9
decaf7766abd15ff16b9418cdf72feb7e18dc8fc
[ "qs = super(ReleaseViewSet, self).filter_queryset(qs)\nif getattr(self, 'order_queryset', False):\n return sorted(qs, key=models.Release.version_sort_key)\nreturn qs", "response = super(ReleaseViewSet, self).create(request, *args, **kwargs)\nif response.status_code == status.HTTP_201_CREATED:\n signals.rele...
<|body_start_0|> qs = super(ReleaseViewSet, self).filter_queryset(qs) if getattr(self, 'order_queryset', False): return sorted(qs, key=models.Release.version_sort_key) return qs <|end_body_0|> <|body_start_1|> response = super(ReleaseViewSet, self).create(request, *args, **k...
An API endpoint providing access to releases. Each release can reference either a product version or a base product (or both). There references are done via human-readable `product_version_id` or `base_product_id`. Composes belonging to given release are referenced via `compose_id`. The list of associated composes incl...
ReleaseViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReleaseViewSet: """An API endpoint providing access to releases. Each release can reference either a product version or a base product (or both). There references are done via human-readable `product_version_id` or `base_product_id`. Composes belonging to given release are referenced via `compose...
stack_v2_sparse_classes_36k_train_010817
31,272
permissive
[ { "docstring": "If the viewset instance has attribute `order_queryset` set to True, this method returns a list of releases ordered by version. Otherwise it will return an unsorted queryset. (It is not possible to sort unconditionally as get_object() will at some point call this method and fail unless it receive...
4
stack_v2_sparse_classes_30k_train_007364
Implement the Python class `ReleaseViewSet` described below. Class description: An API endpoint providing access to releases. Each release can reference either a product version or a base product (or both). There references are done via human-readable `product_version_id` or `base_product_id`. Composes belonging to gi...
Implement the Python class `ReleaseViewSet` described below. Class description: An API endpoint providing access to releases. Each release can reference either a product version or a base product (or both). There references are done via human-readable `product_version_id` or `base_product_id`. Composes belonging to gi...
af79f73c30fa5f5709ba03d584b7a49b83166b81
<|skeleton|> class ReleaseViewSet: """An API endpoint providing access to releases. Each release can reference either a product version or a base product (or both). There references are done via human-readable `product_version_id` or `base_product_id`. Composes belonging to given release are referenced via `compose...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReleaseViewSet: """An API endpoint providing access to releases. Each release can reference either a product version or a base product (or both). There references are done via human-readable `product_version_id` or `base_product_id`. Composes belonging to given release are referenced via `compose_id`. The lis...
the_stack_v2_python_sparse
pdc/apps/release/views.py
product-definition-center/product-definition-center
train
19
52199d5344bb74983cb53ee0493b9ae79490b3d4
[ "username = request.user.get_username()\nserializer = RepoSerializer(username, repo_base, request)\nreturn Response(serializer.describe_repo(repo_name), status=status.HTTP_200_OK)", "username = request.user.get_username()\nserializer = RepoSerializer(username, repo_base, request)\nserializer.delete_repo(repo_name...
<|body_start_0|> username = request.user.get_username() serializer = RepoSerializer(username, repo_base, request) return Response(serializer.describe_repo(repo_name), status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> username = request.user.get_username() serializer = R...
A specific repo of a specific user
Repo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Repo: """A specific repo of a specific user""" def get(self, request, repo_base, repo_name, format=None): """Views, tables, collaborators, and files in a repo""" <|body_0|> def delete(self, request, repo_base, repo_name, format=None): """Delete a repo""" ...
stack_v2_sparse_classes_36k_train_010818
31,465
permissive
[ { "docstring": "Views, tables, collaborators, and files in a repo", "name": "get", "signature": "def get(self, request, repo_base, repo_name, format=None)" }, { "docstring": "Delete a repo", "name": "delete", "signature": "def delete(self, request, repo_base, repo_name, format=None)" }...
3
stack_v2_sparse_classes_30k_train_007780
Implement the Python class `Repo` described below. Class description: A specific repo of a specific user Method signatures and docstrings: - def get(self, request, repo_base, repo_name, format=None): Views, tables, collaborators, and files in a repo - def delete(self, request, repo_base, repo_name, format=None): Dele...
Implement the Python class `Repo` described below. Class description: A specific repo of a specific user Method signatures and docstrings: - def get(self, request, repo_base, repo_name, format=None): Views, tables, collaborators, and files in a repo - def delete(self, request, repo_base, repo_name, format=None): Dele...
f066b472c2b66cc3b868bbe433aed2d4557aea32
<|skeleton|> class Repo: """A specific repo of a specific user""" def get(self, request, repo_base, repo_name, format=None): """Views, tables, collaborators, and files in a repo""" <|body_0|> def delete(self, request, repo_base, repo_name, format=None): """Delete a repo""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Repo: """A specific repo of a specific user""" def get(self, request, repo_base, repo_name, format=None): """Views, tables, collaborators, and files in a repo""" username = request.user.get_username() serializer = RepoSerializer(username, repo_base, request) return Respons...
the_stack_v2_python_sparse
src/api/views.py
datahuborg/datahub
train
199
96cb64fe19a2458d2b26084cb87240ba9bfc0ba7
[ "self.k = k\nself.nums = nums\nheapify(self.nums)\nwhile len(self.nums) > self.k:\n heappop(self.nums)", "if len(self.nums) < self.k:\n heappush(self.nums, val)\n heapify(self.nums)\nelse:\n top = float('-inf')\n if len(self.nums) > 0:\n top = self.nums[0]\n if top < val:\n heaprep...
<|body_start_0|> self.k = k self.nums = nums heapify(self.nums) while len(self.nums) > self.k: heappop(self.nums) <|end_body_0|> <|body_start_1|> if len(self.nums) < self.k: heappush(self.nums, val) heapify(self.nums) else: ...
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.k = k self.nums = nums heapify(self.n...
stack_v2_sparse_classes_36k_train_010819
1,491
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
null
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...
45c8f279d2ae78f70029dbce243bef989e243af2
<|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.k = k self.nums = nums heapify(self.nums) while len(self.nums) > self.k: heappop(self.nums) def add(self, val): """:type val: int :rtype: int""" if le...
the_stack_v2_python_sparse
heap/703.kth-largest-element-in-a-stream.py
JesseYule/leetcodePractice
train
0
ddaefb9f68a76406d8b6eee2a6f40227fc31972f
[ "if 'type_id' not in request.query_params or not request.query_params['type_id']:\n return JSONResponse(get_data_format(msg='商品类型编号不能为空'))\ntry:\n type_id = int(request.query_params['type_id'])\n pt = ProductType.objects.get(id=type_id)\nexcept ProductType.DoesNotExist:\n return Response(get_data_format...
<|body_start_0|> if 'type_id' not in request.query_params or not request.query_params['type_id']: return JSONResponse(get_data_format(msg='商品类型编号不能为空')) try: type_id = int(request.query_params['type_id']) pt = ProductType.objects.get(id=type_id) except Product...
ProductViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProductViewSet: def home(self, request): """@api {get} /fenggou/products/home/ 商城首页 @apiName FenggouProductsHome @apiGroup FenggouProducts @apiDescription **疯购首页**</br> @apiParam {int} type_id 商品类型编号""" <|body_0|> def product_detail(self, request): """@api {get} /fen...
stack_v2_sparse_classes_36k_train_010820
5,287
no_license
[ { "docstring": "@api {get} /fenggou/products/home/ 商城首页 @apiName FenggouProductsHome @apiGroup FenggouProducts @apiDescription **疯购首页**</br> @apiParam {int} type_id 商品类型编号", "name": "home", "signature": "def home(self, request)" }, { "docstring": "@api {get} /fenggou/products/detail/ 商品详情接口 @api...
2
stack_v2_sparse_classes_30k_train_006630
Implement the Python class `ProductViewSet` described below. Class description: Implement the ProductViewSet class. Method signatures and docstrings: - def home(self, request): @api {get} /fenggou/products/home/ 商城首页 @apiName FenggouProductsHome @apiGroup FenggouProducts @apiDescription **疯购首页**</br> @apiParam {int} ...
Implement the Python class `ProductViewSet` described below. Class description: Implement the ProductViewSet class. Method signatures and docstrings: - def home(self, request): @api {get} /fenggou/products/home/ 商城首页 @apiName FenggouProductsHome @apiGroup FenggouProducts @apiDescription **疯购首页**</br> @apiParam {int} ...
d241d1d3b40f72d1bd6b1412d2ad9546f414ffcf
<|skeleton|> class ProductViewSet: def home(self, request): """@api {get} /fenggou/products/home/ 商城首页 @apiName FenggouProductsHome @apiGroup FenggouProducts @apiDescription **疯购首页**</br> @apiParam {int} type_id 商品类型编号""" <|body_0|> def product_detail(self, request): """@api {get} /fen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProductViewSet: def home(self, request): """@api {get} /fenggou/products/home/ 商城首页 @apiName FenggouProductsHome @apiGroup FenggouProducts @apiDescription **疯购首页**</br> @apiParam {int} type_id 商品类型编号""" if 'type_id' not in request.query_params or not request.query_params['type_id']: ...
the_stack_v2_python_sparse
madhaus/apps/fenggou/views.py
CPerZheng/firstproject
train
0
9f2c1da0b01bb124c3fb58992fffbd3cc738827e
[ "log_win_level = LEGACY_CONF['Debug']['window_log_level']\ntry:\n after_export = AfterExport(LEGACY_CONF.get_int('General', 'after_export_action', 0))\nexcept ValueError:\n after_export = AfterExport.NORMAL\nres = {}\nfor field in gen_opts_bool:\n try:\n section: str = field.metadata['legacy']\n ...
<|body_start_0|> log_win_level = LEGACY_CONF['Debug']['window_log_level'] try: after_export = AfterExport(LEGACY_CONF.get_int('General', 'after_export_action', 0)) except ValueError: after_export = AfterExport.NORMAL res = {} for field in gen_opts_bool: ...
General app config options, mainly booleans. These are all changed in the options window.
GenOptions
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GenOptions: """General app config options, mainly booleans. These are all changed in the options window.""" def parse_legacy(cls, conf: Property) -> Dict[str, 'GenOptions']: """Parse from the GEN_OPTS config file.""" <|body_0|> def parse_kv1(cls, data: Property, version:...
stack_v2_sparse_classes_36k_train_010821
6,430
no_license
[ { "docstring": "Parse from the GEN_OPTS config file.", "name": "parse_legacy", "signature": "def parse_legacy(cls, conf: Property) -> Dict[str, 'GenOptions']" }, { "docstring": "Parse KV1 values.", "name": "parse_kv1", "signature": "def parse_kv1(cls, data: Property, version: int) -> 'Ge...
5
stack_v2_sparse_classes_30k_train_015390
Implement the Python class `GenOptions` described below. Class description: General app config options, mainly booleans. These are all changed in the options window. Method signatures and docstrings: - def parse_legacy(cls, conf: Property) -> Dict[str, 'GenOptions']: Parse from the GEN_OPTS config file. - def parse_k...
Implement the Python class `GenOptions` described below. Class description: General app config options, mainly booleans. These are all changed in the options window. Method signatures and docstrings: - def parse_legacy(cls, conf: Property) -> Dict[str, 'GenOptions']: Parse from the GEN_OPTS config file. - def parse_k...
9f9219934b8f4af3c03d0080fad6078a18f3d530
<|skeleton|> class GenOptions: """General app config options, mainly booleans. These are all changed in the options window.""" def parse_legacy(cls, conf: Property) -> Dict[str, 'GenOptions']: """Parse from the GEN_OPTS config file.""" <|body_0|> def parse_kv1(cls, data: Property, version:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GenOptions: """General app config options, mainly booleans. These are all changed in the options window.""" def parse_legacy(cls, conf: Property) -> Dict[str, 'GenOptions']: """Parse from the GEN_OPTS config file.""" log_win_level = LEGACY_CONF['Debug']['window_log_level'] try: ...
the_stack_v2_python_sparse
src/config/gen_opts.py
BEEmod/BEE2.4
train
276
e97712a7aca25abde5f4f7d7b25bfa57b79575dc
[ "serializer_class = getattr(self, 'request_serializer', self.get_serializer_class())\nkwargs['context'] = self.get_serializer_context()\nreturn serializer_class(*args, **kwargs)", "serializer_class = getattr(self, 'response_serializer', self.get_serializer_class())\nkwargs['context'] = self.get_serializer_context...
<|body_start_0|> serializer_class = getattr(self, 'request_serializer', self.get_serializer_class()) kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) <|end_body_0|> <|body_start_1|> serializer_class = getattr(self, 'response_serializer', self.ge...
JSONView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSONView: def get_request_serializer(self, *args, **kwargs): """Return the serializer instance that should be used for validating and deserializing input (from the Request).""" <|body_0|> def get_response_serializer(self, *args, **kwargs): """Return the serializer in...
stack_v2_sparse_classes_36k_train_010822
15,301
permissive
[ { "docstring": "Return the serializer instance that should be used for validating and deserializing input (from the Request).", "name": "get_request_serializer", "signature": "def get_request_serializer(self, *args, **kwargs)" }, { "docstring": "Return the serializer instance that should be used...
3
stack_v2_sparse_classes_30k_train_003834
Implement the Python class `JSONView` described below. Class description: Implement the JSONView class. Method signatures and docstrings: - def get_request_serializer(self, *args, **kwargs): Return the serializer instance that should be used for validating and deserializing input (from the Request). - def get_respons...
Implement the Python class `JSONView` described below. Class description: Implement the JSONView class. Method signatures and docstrings: - def get_request_serializer(self, *args, **kwargs): Return the serializer instance that should be used for validating and deserializing input (from the Request). - def get_respons...
bee9d283d0932dd845cbc9c7c090dde794d2ecbc
<|skeleton|> class JSONView: def get_request_serializer(self, *args, **kwargs): """Return the serializer instance that should be used for validating and deserializing input (from the Request).""" <|body_0|> def get_response_serializer(self, *args, **kwargs): """Return the serializer in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JSONView: def get_request_serializer(self, *args, **kwargs): """Return the serializer instance that should be used for validating and deserializing input (from the Request).""" serializer_class = getattr(self, 'request_serializer', self.get_serializer_class()) kwargs['context'] = self....
the_stack_v2_python_sparse
laxy_backend/view_mixins.py
MonashBioinformaticsPlatform/laxy
train
3
a0f170e0462876d67e0764539264cb32df322445
[ "self.test_app = create_app(DATABASE_NAME='test_analytics', TESTING=True)\nself.testing_client = self.test_app.test_client()\nself.testing_client_context = self.test_app.app_context()\nself.testing_client_context.push()\nself.dummy_user = Users('Joey', 'joey@FCC.com', Users.generate_hash('1234'.encode('utf8')).deco...
<|body_start_0|> self.test_app = create_app(DATABASE_NAME='test_analytics', TESTING=True) self.testing_client = self.test_app.test_client() self.testing_client_context = self.test_app.app_context() self.testing_client_context.push() self.dummy_user = Users('Joey', 'joey@FCC.com',...
Test user can reset their password using the forgot password endpoint
ForgotPasswordTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForgotPasswordTestCase: """Test user can reset their password using the forgot password endpoint""" def setUp(self): """Create testing client version of flask app and persist a temporary user""" <|body_0|> def tearDown(self): """Remove temporary user from databas...
stack_v2_sparse_classes_36k_train_010823
2,026
permissive
[ { "docstring": "Create testing client version of flask app and persist a temporary user", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Remove temporary user from database", "name": "tearDown", "signature": "def tearDown(self)" }, { "docstring": "Test forgot ...
4
stack_v2_sparse_classes_30k_train_003644
Implement the Python class `ForgotPasswordTestCase` described below. Class description: Test user can reset their password using the forgot password endpoint Method signatures and docstrings: - def setUp(self): Create testing client version of flask app and persist a temporary user - def tearDown(self): Remove tempor...
Implement the Python class `ForgotPasswordTestCase` described below. Class description: Test user can reset their password using the forgot password endpoint Method signatures and docstrings: - def setUp(self): Create testing client version of flask app and persist a temporary user - def tearDown(self): Remove tempor...
5d123691d1f25d0b85e20e4e8293266bf23c9f8a
<|skeleton|> class ForgotPasswordTestCase: """Test user can reset their password using the forgot password endpoint""" def setUp(self): """Create testing client version of flask app and persist a temporary user""" <|body_0|> def tearDown(self): """Remove temporary user from databas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ForgotPasswordTestCase: """Test user can reset their password using the forgot password endpoint""" def setUp(self): """Create testing client version of flask app and persist a temporary user""" self.test_app = create_app(DATABASE_NAME='test_analytics', TESTING=True) self.testing_...
the_stack_v2_python_sparse
Analytics/test_forgot_password.py
thanosbnt/SharingCitiesDashboard
train
0
59d7c86b451795ef58ab70fe0e5c01fcd04648be
[ "self.schedulers = schedulers\nself.optimizer = optimizer\nfor s in self.schedulers:\n for group in optimizer.param_groups:\n group.setdefault('initial_' + s.key, group[s.key])", "for s in self.schedulers:\n for group in self.optimizer.param_groups:\n group[s.key] = group['initial_' + s.key] *...
<|body_start_0|> self.schedulers = schedulers self.optimizer = optimizer for s in self.schedulers: for group in optimizer.param_groups: group.setdefault('initial_' + s.key, group[s.key]) <|end_body_0|> <|body_start_1|> for s in self.schedulers: fo...
PyTorch optimizer scheduler.
PyTorchScheduler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyTorchScheduler: """PyTorch optimizer scheduler.""" def __init__(self, schedulers: List[SchedulerInterface], optimizer: Optimizer): """Initialize class.""" <|body_0|> def step(self, n_iter: int): """Update optimizer by scheduling.""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k_train_010824
801
permissive
[ { "docstring": "Initialize class.", "name": "__init__", "signature": "def __init__(self, schedulers: List[SchedulerInterface], optimizer: Optimizer)" }, { "docstring": "Update optimizer by scheduling.", "name": "step", "signature": "def step(self, n_iter: int)" } ]
2
null
Implement the Python class `PyTorchScheduler` described below. Class description: PyTorch optimizer scheduler. Method signatures and docstrings: - def __init__(self, schedulers: List[SchedulerInterface], optimizer: Optimizer): Initialize class. - def step(self, n_iter: int): Update optimizer by scheduling.
Implement the Python class `PyTorchScheduler` described below. Class description: PyTorch optimizer scheduler. Method signatures and docstrings: - def __init__(self, schedulers: List[SchedulerInterface], optimizer: Optimizer): Initialize class. - def step(self, n_iter: int): Update optimizer by scheduling. <|skeleto...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class PyTorchScheduler: """PyTorch optimizer scheduler.""" def __init__(self, schedulers: List[SchedulerInterface], optimizer: Optimizer): """Initialize class.""" <|body_0|> def step(self, n_iter: int): """Update optimizer by scheduling.""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PyTorchScheduler: """PyTorch optimizer scheduler.""" def __init__(self, schedulers: List[SchedulerInterface], optimizer: Optimizer): """Initialize class.""" self.schedulers = schedulers self.optimizer = optimizer for s in self.schedulers: for group in optimizer...
the_stack_v2_python_sparse
espnet/scheduler/pytorch.py
espnet/espnet
train
7,242
f956ab56d187f07cb3bc4e117798eb0ef42dc2ef
[ "n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\nif n == 2 or n == 3:\n return max(nums)\nreturn max(self.rob1(nums[:n - 1]), self.rob1(nums[1:]))", "n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\nif n == 2:\n return max(nums)\nelse:\n dp = [0] * n\n ...
<|body_start_0|> n = len(nums) if n == 0: return 0 if n == 1: return nums[0] if n == 2 or n == 3: return max(nums) return max(self.rob1(nums[:n - 1]), self.rob1(nums[1:])) <|end_body_0|> <|body_start_1|> n = len(nums) if n == 0...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob1(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) if n == 0: return 0 ...
stack_v2_sparse_classes_36k_train_010825
837
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "rob1", "signature": "def rob1(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_013566
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def rob1(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def rob1(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def rob(self, nums): "...
15f012927dc34b5d751af6633caa5e8882d26ff7
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob1(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" n = len(nums) if n == 0: return 0 if n == 1: return nums[0] if n == 2 or n == 3: return max(nums) return max(self.rob1(nums[:n - 1]), self.rob1(nums[1:])) ...
the_stack_v2_python_sparse
python/213.HouseRobberII.py
MaxPoon/Leetcode
train
15
274de74f7470bb14f31e1ce7232b44bf91253879
[ "ret = re.match('^1[35678]\\\\d{9}$', phone)\nif ret:\n return True\nelse:\n return False", "ret = re.match('^\\\\w+@(\\\\w+.)+(com|cn|net)$', email)\nif ret:\n return True\nelse:\n return False", "if len(pass1) <= 20:\n if pass1 == pass2:\n return False\n else:\n return '两次密码不一致...
<|body_start_0|> ret = re.match('^1[35678]\\d{9}$', phone) if ret: return True else: return False <|end_body_0|> <|body_start_1|> ret = re.match('^\\w+@(\\w+.)+(com|cn|net)$', email) if ret: return True else: return False <...
Validator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Validator: def vali_user_phone(cls, phone): """验证手机号 return: True or False""" <|body_0|> def vali_user_email(cls, email): """验证邮箱 return: True or False""" <|body_1|> def vali_user_password(cls, pass1, pass2): """验证密码 pass1: 密码 pass2: 再次确认的密码 retu...
stack_v2_sparse_classes_36k_train_010826
1,010
no_license
[ { "docstring": "验证手机号 return: True or False", "name": "vali_user_phone", "signature": "def vali_user_phone(cls, phone)" }, { "docstring": "验证邮箱 return: True or False", "name": "vali_user_email", "signature": "def vali_user_email(cls, email)" }, { "docstring": "验证密码 pass1: 密码 pass...
3
stack_v2_sparse_classes_30k_train_010680
Implement the Python class `Validator` described below. Class description: Implement the Validator class. Method signatures and docstrings: - def vali_user_phone(cls, phone): 验证手机号 return: True or False - def vali_user_email(cls, email): 验证邮箱 return: True or False - def vali_user_password(cls, pass1, pass2): 验证密码 pas...
Implement the Python class `Validator` described below. Class description: Implement the Validator class. Method signatures and docstrings: - def vali_user_phone(cls, phone): 验证手机号 return: True or False - def vali_user_email(cls, email): 验证邮箱 return: True or False - def vali_user_password(cls, pass1, pass2): 验证密码 pas...
6648df93ec978516826573d3bb8222224f837bb4
<|skeleton|> class Validator: def vali_user_phone(cls, phone): """验证手机号 return: True or False""" <|body_0|> def vali_user_email(cls, email): """验证邮箱 return: True or False""" <|body_1|> def vali_user_password(cls, pass1, pass2): """验证密码 pass1: 密码 pass2: 再次确认的密码 retu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Validator: def vali_user_phone(cls, phone): """验证手机号 return: True or False""" ret = re.match('^1[35678]\\d{9}$', phone) if ret: return True else: return False def vali_user_email(cls, email): """验证邮箱 return: True or False""" ret = re...
the_stack_v2_python_sparse
app/libs/validator.py
Lcd7/TimeZoom
train
1
e96945fababa77d483574550ab01855da9d66d98
[ "permission = AdministerOrganizationPermission(orgname)\nif permission.can():\n organization = model.organization.get_organization(orgname)\n if not organization.stripe_id:\n raise NotFound()\n return {'fields': get_invoice_fields(organization)[0]}\nabort(403)", "permission = AdministerOrganizatio...
<|body_start_0|> permission = AdministerOrganizationPermission(orgname) if permission.can(): organization = model.organization.get_organization(orgname) if not organization.stripe_id: raise NotFound() return {'fields': get_invoice_fields(organization)[...
Resource for listing and creating an organization's custom invoice fields.
OrganizationInvoiceFieldList
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrganizationInvoiceFieldList: """Resource for listing and creating an organization's custom invoice fields.""" def get(self, orgname): """List the invoice fields for the organization.""" <|body_0|> def post(self, orgname): """Creates a new invoice field.""" ...
stack_v2_sparse_classes_36k_train_010827
33,890
permissive
[ { "docstring": "List the invoice fields for the organization.", "name": "get", "signature": "def get(self, orgname)" }, { "docstring": "Creates a new invoice field.", "name": "post", "signature": "def post(self, orgname)" } ]
2
stack_v2_sparse_classes_30k_train_007261
Implement the Python class `OrganizationInvoiceFieldList` described below. Class description: Resource for listing and creating an organization's custom invoice fields. Method signatures and docstrings: - def get(self, orgname): List the invoice fields for the organization. - def post(self, orgname): Creates a new in...
Implement the Python class `OrganizationInvoiceFieldList` described below. Class description: Resource for listing and creating an organization's custom invoice fields. Method signatures and docstrings: - def get(self, orgname): List the invoice fields for the organization. - def post(self, orgname): Creates a new in...
e400a0c22c5f89dd35d571654b13d262b1f6e3b3
<|skeleton|> class OrganizationInvoiceFieldList: """Resource for listing and creating an organization's custom invoice fields.""" def get(self, orgname): """List the invoice fields for the organization.""" <|body_0|> def post(self, orgname): """Creates a new invoice field.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrganizationInvoiceFieldList: """Resource for listing and creating an organization's custom invoice fields.""" def get(self, orgname): """List the invoice fields for the organization.""" permission = AdministerOrganizationPermission(orgname) if permission.can(): organi...
the_stack_v2_python_sparse
endpoints/api/billing.py
quay/quay
train
2,363
cbb68f037ae229abc9c7ed04ac115f7dc54e1a4d
[ "def help(root):\n if not root:\n res.append('#')\n return ','.join(res)\n res.append(str(root.val))\n help(root.left)\n help(root.right)\n return ','.join(res)\nres = []\nreturn help(root)", "def help(nodes):\n value = nodes.pop(0)\n if value == '#':\n return None\n r...
<|body_start_0|> def help(root): if not root: res.append('#') return ','.join(res) res.append(str(root.val)) help(root.left) help(root.right) return ','.join(res) res = [] return help(root) <|end_body_0|>...
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_010828
1,378
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_test_000501
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:...
7f4917bd2c0581d02f68a6407fdb5d3a5926fd4e
<|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""" def help(root): if not root: res.append('#') return ','.join(res) res.append(str(root.val)) help(root.left) ...
the_stack_v2_python_sparse
297.二叉树的序列化与反序列化.py
icevivian/Hello_offer
train
0
55f2fac48190665cf1b95037673e862225a2f573
[ "self.id = id\nself.title = title\nself.description = description\nself.mtype = mtype\nself.file_name = file_name\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nid = dictionary.get('id')\ntitle = dictionary.get('title')\ndescription = dictionary.get('description')\...
<|body_start_0|> self.id = id self.title = title self.description = description self.mtype = mtype self.file_name = file_name self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type description here. file_name (string): TODO: type descri...
AttachmentListItem
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttachmentListItem: """Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type descripti...
stack_v2_sparse_classes_36k_train_010829
2,692
permissive
[ { "docstring": "Constructor for the AttachmentListItem class", "name": "__init__", "signature": "def __init__(self, id=None, title=None, description=None, mtype=None, file_name=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionar...
2
null
Implement the Python class `AttachmentListItem` described below. Class description: Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description h...
Implement the Python class `AttachmentListItem` described below. Class description: Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description h...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class AttachmentListItem: """Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type descripti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttachmentListItem: """Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type description here. file...
the_stack_v2_python_sparse
idfy_rest_client/models/attachment_list_item.py
dealflowteam/Idfy
train
0
69983b1438bd09f0de31c3901bd2f2d91eae6415
[ "if not os.path.exists(filepath):\n return None\nreturn xml.dom.minidom.parse(file=filepath)", "if node.hasAttribute(attr):\n return node.getAttribute(attr)\nelse:\n return default_val" ]
<|body_start_0|> if not os.path.exists(filepath): return None return xml.dom.minidom.parse(file=filepath) <|end_body_0|> <|body_start_1|> if node.hasAttribute(attr): return node.getAttribute(attr) else: return default_val <|end_body_1|>
XmlConfig
[ "WTFPL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XmlConfig: def dom(self, filepath): """打开文件并获取dom :param filepath: 文件路径 :return:""" <|body_0|> def get_node_attr(self, node, attr, default_val): """获取xml节点的属性值 :param node: xml node :param attr: 属性名称 :param default_val: 默认属性值 :return:""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_36k_train_010830
682
permissive
[ { "docstring": "打开文件并获取dom :param filepath: 文件路径 :return:", "name": "dom", "signature": "def dom(self, filepath)" }, { "docstring": "获取xml节点的属性值 :param node: xml node :param attr: 属性名称 :param default_val: 默认属性值 :return:", "name": "get_node_attr", "signature": "def get_node_attr(self, nod...
2
null
Implement the Python class `XmlConfig` described below. Class description: Implement the XmlConfig class. Method signatures and docstrings: - def dom(self, filepath): 打开文件并获取dom :param filepath: 文件路径 :return: - def get_node_attr(self, node, attr, default_val): 获取xml节点的属性值 :param node: xml node :param attr: 属性名称 :para...
Implement the Python class `XmlConfig` described below. Class description: Implement the XmlConfig class. Method signatures and docstrings: - def dom(self, filepath): 打开文件并获取dom :param filepath: 文件路径 :return: - def get_node_attr(self, node, attr, default_val): 获取xml节点的属性值 :param node: xml node :param attr: 属性名称 :para...
50d0d313f52206ae1d6a575e6d9833b08bc9037c
<|skeleton|> class XmlConfig: def dom(self, filepath): """打开文件并获取dom :param filepath: 文件路径 :return:""" <|body_0|> def get_node_attr(self, node, attr, default_val): """获取xml节点的属性值 :param node: xml node :param attr: 属性名称 :param default_val: 默认属性值 :return:""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XmlConfig: def dom(self, filepath): """打开文件并获取dom :param filepath: 文件路径 :return:""" if not os.path.exists(filepath): return None return xml.dom.minidom.parse(file=filepath) def get_node_attr(self, node, attr, default_val): """获取xml节点的属性值 :param node: xml node :...
the_stack_v2_python_sparse
play/py/mul_datasource_db/base/xml_config.py
MuggleWei/Hakuna_Matata
train
0
24e38dfbd7c7d4f8642274b6fc8910979aed7da9
[ "real_item_id = self.get_argument('real_item_id')\nif not real_item_id:\n return\nremark = self.get_argument('return_remark')\nreturn_amount = Decimal(self.get_argument('return_amount'))\npart_refund_price = self.get_argument('refund_part_price')\nif part_refund_price and Decimal(part_refund_price) > 0:\n ret...
<|body_start_0|> real_item_id = self.get_argument('real_item_id') if not real_item_id: return remark = self.get_argument('return_remark') return_amount = Decimal(self.get_argument('return_amount')) part_refund_price = self.get_argument('refund_part_price') if ...
RealGoodsRefundHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RealGoodsRefundHandler: def post(self): """处理退款、退货""" <|body_0|> def handleRefundOfNoSend(self, real_item, remark, return_amount): """处理退款""" <|body_1|> <|end_skeleton|> <|body_start_0|> real_item_id = self.get_argument('real_item_id') if no...
stack_v2_sparse_classes_36k_train_010831
9,076
no_license
[ { "docstring": "处理退款、退货", "name": "post", "signature": "def post(self)" }, { "docstring": "处理退款", "name": "handleRefundOfNoSend", "signature": "def handleRefundOfNoSend(self, real_item, remark, return_amount)" } ]
2
stack_v2_sparse_classes_30k_val_000272
Implement the Python class `RealGoodsRefundHandler` described below. Class description: Implement the RealGoodsRefundHandler class. Method signatures and docstrings: - def post(self): 处理退款、退货 - def handleRefundOfNoSend(self, real_item, remark, return_amount): 处理退款
Implement the Python class `RealGoodsRefundHandler` described below. Class description: Implement the RealGoodsRefundHandler class. Method signatures and docstrings: - def post(self): 处理退款、退货 - def handleRefundOfNoSend(self, real_item, remark, return_amount): 处理退款 <|skeleton|> class RealGoodsRefundHandler: def ...
daf260ecd5adf553490a8ac6b389a74439234b6a
<|skeleton|> class RealGoodsRefundHandler: def post(self): """处理退款、退货""" <|body_0|> def handleRefundOfNoSend(self, real_item, remark, return_amount): """处理退款""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RealGoodsRefundHandler: def post(self): """处理退款、退货""" real_item_id = self.get_argument('real_item_id') if not real_item_id: return remark = self.get_argument('return_remark') return_amount = Decimal(self.get_argument('return_amount')) part_refund_pri...
the_stack_v2_python_sparse
apps/op/controllers/real/return_entry.py
xutaoding/osp_autumn
train
0
3ecbcc4ca3484d0558a50e1cd78137a70499ac10
[ "if not vector_space_homspace.is_VectorSpaceHomspace(homspace):\n raise TypeError('homspace must be a vector space hom space, not {0}'.format(homspace))\nif isinstance(A, matrix_morphism.MatrixMorphism):\n A = A.matrix()\nif not is_Matrix(A):\n msg = 'input must be a matrix representation or another matrix...
<|body_start_0|> if not vector_space_homspace.is_VectorSpaceHomspace(homspace): raise TypeError('homspace must be a vector space hom space, not {0}'.format(homspace)) if isinstance(A, matrix_morphism.MatrixMorphism): A = A.matrix() if not is_Matrix(A): msg = '...
VectorSpaceMorphism
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VectorSpaceMorphism: def __init__(self, homspace, A): """Create a linear transformation, a morphism between vector spaces. INPUT: - ``homspace`` - a homspace (of vector spaces) to serve as a parent for the linear transformation and a home for the domain and codomain of the morphism - ``A...
stack_v2_sparse_classes_36k_train_010832
35,375
no_license
[ { "docstring": "Create a linear transformation, a morphism between vector spaces. INPUT: - ``homspace`` - a homspace (of vector spaces) to serve as a parent for the linear transformation and a home for the domain and codomain of the morphism - ``A`` - a matrix representing the linear transformation, which will ...
4
null
Implement the Python class `VectorSpaceMorphism` described below. Class description: Implement the VectorSpaceMorphism class. Method signatures and docstrings: - def __init__(self, homspace, A): Create a linear transformation, a morphism between vector spaces. INPUT: - ``homspace`` - a homspace (of vector spaces) to ...
Implement the Python class `VectorSpaceMorphism` described below. Class description: Implement the VectorSpaceMorphism class. Method signatures and docstrings: - def __init__(self, homspace, A): Create a linear transformation, a morphism between vector spaces. INPUT: - ``homspace`` - a homspace (of vector spaces) to ...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class VectorSpaceMorphism: def __init__(self, homspace, A): """Create a linear transformation, a morphism between vector spaces. INPUT: - ``homspace`` - a homspace (of vector spaces) to serve as a parent for the linear transformation and a home for the domain and codomain of the morphism - ``A...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VectorSpaceMorphism: def __init__(self, homspace, A): """Create a linear transformation, a morphism between vector spaces. INPUT: - ``homspace`` - a homspace (of vector spaces) to serve as a parent for the linear transformation and a home for the domain and codomain of the morphism - ``A`` - a matrix ...
the_stack_v2_python_sparse
sage/src/sage/modules/vector_space_morphism.py
bopopescu/geosci
train
0
a720ef949a749fc7d2deb750ac7b1f849c13f087
[ "self.window_size = window_size\nself.observations = observations\nsuper().__init__()", "mean_pitch = np.mean(pv_arr)\npv_arr -= mean_pitch\nreturn float(mean_pitch)", "time_to_advance = window_size / (num_obs - 1)\npv_arr = np.empty(num_obs, dtype=float)\ncurrent_delta = track[start_index].time\ncurrent_index ...
<|body_start_0|> self.window_size = window_size self.observations = observations super().__init__() <|end_body_0|> <|body_start_1|> mean_pitch = np.mean(pv_arr) pv_arr -= mean_pitch return float(mean_pitch) <|end_body_1|> <|body_start_2|> time_to_advance = windo...
PitchVectorSegmenter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PitchVectorSegmenter: def __init__(self, window_size: float, observations: int): """A Segmenter which divides a MIDI file into several overlapping multidimensional vectors. Each vector is based on observations of the pitch within a ``window_size`` time window. Args: window_size: The size...
stack_v2_sparse_classes_36k_train_010833
5,679
no_license
[ { "docstring": "A Segmenter which divides a MIDI file into several overlapping multidimensional vectors. Each vector is based on observations of the pitch within a ``window_size`` time window. Args: window_size: The size of the window, in seconds observations: The number of observations, or dimensions, in each ...
4
stack_v2_sparse_classes_30k_train_001065
Implement the Python class `PitchVectorSegmenter` described below. Class description: Implement the PitchVectorSegmenter class. Method signatures and docstrings: - def __init__(self, window_size: float, observations: int): A Segmenter which divides a MIDI file into several overlapping multidimensional vectors. Each v...
Implement the Python class `PitchVectorSegmenter` described below. Class description: Implement the PitchVectorSegmenter class. Method signatures and docstrings: - def __init__(self, window_size: float, observations: int): A Segmenter which divides a MIDI file into several overlapping multidimensional vectors. Each v...
f78b35274f49f6ae54ca7bc02691ab5db45eda36
<|skeleton|> class PitchVectorSegmenter: def __init__(self, window_size: float, observations: int): """A Segmenter which divides a MIDI file into several overlapping multidimensional vectors. Each vector is based on observations of the pitch within a ``window_size`` time window. Args: window_size: The size...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PitchVectorSegmenter: def __init__(self, window_size: float, observations: int): """A Segmenter which divides a MIDI file into several overlapping multidimensional vectors. Each vector is based on observations of the pitch within a ``window_size`` time window. Args: window_size: The size of the window...
the_stack_v2_python_sparse
project/algorithms/pitch_vector/pitch_vector_segmenter.py
jamesb456/final-year-project
train
0
a52f91dbb9cda4724de7e2dd31d4382edaa3deba
[ "p0 = list1\np1 = list2\nh0 = ListNode(-1)\nh = h0\nwhile p0 != None and p1 != None:\n if p0.val < p1.val:\n h.next = p0\n p0 = p0.next\n else:\n h.next = p1\n p1 = p1.next\n h = h.next\nif p0 != None:\n h.next = p0\nif p1 != None:\n h.next = p1\nreturn h0.next", "p0 = h...
<|body_start_0|> p0 = list1 p1 = list2 h0 = ListNode(-1) h = h0 while p0 != None and p1 != None: if p0.val < p1.val: h.next = p0 p0 = p0.next else: h.next = p1 p1 = p1.next h = h.n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeKListsTwo(self, list1, list2): """使用归并的思想中的并处理""" <|body_0|> def midOfNode(self, head): """链表拆分成两半,返回后半部分""" <|body_1|> def sortList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_2|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_010834
1,544
no_license
[ { "docstring": "使用归并的思想中的并处理", "name": "mergeKListsTwo", "signature": "def mergeKListsTwo(self, list1, list2)" }, { "docstring": "链表拆分成两半,返回后半部分", "name": "midOfNode", "signature": "def midOfNode(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKListsTwo(self, list1, list2): 使用归并的思想中的并处理 - def midOfNode(self, head): 链表拆分成两半,返回后半部分 - def sortList(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKListsTwo(self, list1, list2): 使用归并的思想中的并处理 - def midOfNode(self, head): 链表拆分成两半,返回后半部分 - def sortList(self, head): :type head: ListNode :rtype: ListNode <|skeleton|> c...
4b30dd6a3f683c8dc71a85f7b947232613a28dc1
<|skeleton|> class Solution: def mergeKListsTwo(self, list1, list2): """使用归并的思想中的并处理""" <|body_0|> def midOfNode(self, head): """链表拆分成两半,返回后半部分""" <|body_1|> def sortList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mergeKListsTwo(self, list1, list2): """使用归并的思想中的并处理""" p0 = list1 p1 = list2 h0 = ListNode(-1) h = h0 while p0 != None and p1 != None: if p0.val < p1.val: h.next = p0 p0 = p0.next else: ...
the_stack_v2_python_sparse
链表排序_归并的方法.py
saintifly/leetcode
train
0
3022ddf851225d4782231737bcfd0a5dcc33cfd9
[ "for i in range(len(flowerbed)):\n if (i == 0 or flowerbed[i - 1] == 0) and flowerbed[i] == 0 and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):\n flowerbed[i] = 1\n n -= 1\n if n <= 0:\n return True\nreturn n <= 0", "planted = n\nnot_planted = n\nfor x in flowerbed:\n if not x:...
<|body_start_0|> for i in range(len(flowerbed)): if (i == 0 or flowerbed[i - 1] == 0) and flowerbed[i] == 0 and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0): flowerbed[i] = 1 n -= 1 if n <= 0: return True return n <= 0 <|end_b...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: """Jan 31, 2022 14:52""" <|body_0|> def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: """Apr 23, 2023 18:53""" <|body_1|> <|end_skeleton|> <|body_start_0|> for...
stack_v2_sparse_classes_36k_train_010835
2,070
no_license
[ { "docstring": "Jan 31, 2022 14:52", "name": "canPlaceFlowers", "signature": "def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool" }, { "docstring": "Apr 23, 2023 18:53", "name": "canPlaceFlowers", "signature": "def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool"...
2
stack_v2_sparse_classes_30k_train_017018
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: Jan 31, 2022 14:52 - def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: Apr 23, 2023 18:53
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: Jan 31, 2022 14:52 - def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: Apr 23, 2023 18:53 <|skele...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: """Jan 31, 2022 14:52""" <|body_0|> def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: """Apr 23, 2023 18:53""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: """Jan 31, 2022 14:52""" for i in range(len(flowerbed)): if (i == 0 or flowerbed[i - 1] == 0) and flowerbed[i] == 0 and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0): flowerbed[i] = 1 ...
the_stack_v2_python_sparse
leetcode/solved/605_Can_Place_Flowers/solution.py
sungminoh/algorithms
train
0
6949bdf6ca55ebad1ea60dd73eef4c0d4fb4b958
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ImportedWindowsAutopilotDeviceIdentity()", "from .entity import Entity\nfrom .imported_windows_autopilot_device_identity_state import ImportedWindowsAutopilotDeviceIdentityState\nfrom .entity import Entity\nfrom .imported_windows_autop...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return ImportedWindowsAutopilotDeviceIdentity() <|end_body_0|> <|body_start_1|> from .entity import Entity from .imported_windows_autopilot_device_identity_state import ImportedWindowsAutopilot...
Imported windows autopilot devices.
ImportedWindowsAutopilotDeviceIdentity
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImportedWindowsAutopilotDeviceIdentity: """Imported windows autopilot devices.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: """Creates a new instance of the appropriate class based on discriminator value Args:...
stack_v2_sparse_classes_36k_train_010836
4,071
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: ImportedWindowsAutopilotDeviceIdentity", "name": "create_from_discriminator_value", "signature": "def create...
3
stack_v2_sparse_classes_30k_train_009677
Implement the Python class `ImportedWindowsAutopilotDeviceIdentity` described below. Class description: Imported windows autopilot devices. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: Creates a new instance of...
Implement the Python class `ImportedWindowsAutopilotDeviceIdentity` described below. Class description: Imported windows autopilot devices. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: Creates a new instance of...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class ImportedWindowsAutopilotDeviceIdentity: """Imported windows autopilot devices.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: """Creates a new instance of the appropriate class based on discriminator value Args:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImportedWindowsAutopilotDeviceIdentity: """Imported windows autopilot devices.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: ...
the_stack_v2_python_sparse
msgraph/generated/models/imported_windows_autopilot_device_identity.py
microsoftgraph/msgraph-sdk-python
train
135
57ce823873b2e36e23400d4f93f8530526edd37a
[ "root = etree.Element('templates')\ncharacters = []\nfor node in data:\n if node.object.object_type == ObjectType.CHARACTER:\n scenario = node.object.DAO()().get(node.object.id, None, node.id, node.object.object_type)\n root = scenario.XmlClass()().create_xml(scenario, path=path)\n elif node.obj...
<|body_start_0|> root = etree.Element('templates') characters = [] for node in data: if node.object.object_type == ObjectType.CHARACTER: scenario = node.object.DAO()().get(node.object.id, None, node.id, node.object.object_type) root = scenario.XmlClass...
Class that handle import and export for and from XML
ParserHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParserHandler: """Class that handle import and export for and from XML""" def create_xml(self, data: list, path: str=None): """Create xml file from objects :param data: list of objects, full created :param path: path where XML file will be created""" <|body_0|> def impor...
stack_v2_sparse_classes_36k_train_010837
3,799
no_license
[ { "docstring": "Create xml file from objects :param data: list of objects, full created :param path: path where XML file will be created", "name": "create_xml", "signature": "def create_xml(self, data: list, path: str=None)" }, { "docstring": "Import object from xml file :param file_path: file t...
3
null
Implement the Python class `ParserHandler` described below. Class description: Class that handle import and export for and from XML Method signatures and docstrings: - def create_xml(self, data: list, path: str=None): Create xml file from objects :param data: list of objects, full created :param path: path where XML ...
Implement the Python class `ParserHandler` described below. Class description: Class that handle import and export for and from XML Method signatures and docstrings: - def create_xml(self, data: list, path: str=None): Create xml file from objects :param data: list of objects, full created :param path: path where XML ...
40b088e061042599cbb30373ac229d37dddc01e6
<|skeleton|> class ParserHandler: """Class that handle import and export for and from XML""" def create_xml(self, data: list, path: str=None): """Create xml file from objects :param data: list of objects, full created :param path: path where XML file will be created""" <|body_0|> def impor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParserHandler: """Class that handle import and export for and from XML""" def create_xml(self, data: list, path: str=None): """Create xml file from objects :param data: list of objects, full created :param path: path where XML file will be created""" root = etree.Element('templates') ...
the_stack_v2_python_sparse
Program/data/xml/ParserHandler.py
Wilson194/DeskChar
train
0
ec0e29b35151c9d2df8589121a6d5d3cbfb73e8b
[ "self.message_history_reached_end = False\nself._message_history_collector = None\nself._message_keep_limit = message_keep_limit\nself.messages = None", "if self._message_keep_limit != message_keep_limit:\n if message_keep_limit == 0:\n new_messages = None\n else:\n old_messages = self.message...
<|body_start_0|> self.message_history_reached_end = False self._message_history_collector = None self._message_keep_limit = message_keep_limit self.messages = None <|end_body_0|> <|body_start_1|> if self._message_keep_limit != message_keep_limit: if message_keep_limi...
Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the channel's message history. message_history_r...
MessageHistory
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MessageHistory: """Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the ch...
stack_v2_sparse_classes_36k_train_010838
6,011
permissive
[ { "docstring": "Creates a nwe message history instance with it's default values. Parameters ---------- message_keep_limit : `int` The amount of messages to keep.", "name": "__init__", "signature": "def __init__(self, message_keep_limit)" }, { "docstring": "Sets the amount of messages to keep by ...
2
stack_v2_sparse_classes_30k_train_004998
Implement the Python class `MessageHistory` described below. Class description: Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``Message...
Implement the Python class `MessageHistory` described below. Class description: Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``Message...
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class MessageHistory: """Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the ch...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MessageHistory: """Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the channel's messa...
the_stack_v2_python_sparse
hata/discord/channel/message_history.py
HuyaneMatsu/hata
train
3
65c0a72828d6c08bc08fe98b5e51ce1dc776a97c
[ "pre_product = []\np = 1\nfor n in nums:\n pre_product.append(p)\n p *= n\npost_product = []\np = 1\nfor n in nums[::-1]:\n post_product.append(p)\n p *= n\nres = []\nfor pre, post in zip(pre_product, post_product[::-1]):\n res.append(pre * post)\nreturn res", "res = []\np = 1\nfor n in nums:\n ...
<|body_start_0|> pre_product = [] p = 1 for n in nums: pre_product.append(p) p *= n post_product = [] p = 1 for n in nums[::-1]: post_product.append(p) p *= n res = [] for pre, post in zip(pre_product, post_p...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def product_except_self(self, nums): """O(n) time without division.""" <|body_0|> def product_except_self_less_space(self, nums): """Without building the post_product list, modify in place.""" <|body_1|> <|end_skeleton|> <|body_start_0|> p...
stack_v2_sparse_classes_36k_train_010839
1,138
no_license
[ { "docstring": "O(n) time without division.", "name": "product_except_self", "signature": "def product_except_self(self, nums)" }, { "docstring": "Without building the post_product list, modify in place.", "name": "product_except_self_less_space", "signature": "def product_except_self_le...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def product_except_self(self, nums): O(n) time without division. - def product_except_self_less_space(self, nums): Without building the post_product list, modify in place.
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def product_except_self(self, nums): O(n) time without division. - def product_except_self_less_space(self, nums): Without building the post_product list, modify in place. <|ske...
5625e6396b746255f3343253c75447ead95879c7
<|skeleton|> class Solution: def product_except_self(self, nums): """O(n) time without division.""" <|body_0|> def product_except_self_less_space(self, nums): """Without building the post_product list, modify in place.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def product_except_self(self, nums): """O(n) time without division.""" pre_product = [] p = 1 for n in nums: pre_product.append(p) p *= n post_product = [] p = 1 for n in nums[::-1]: post_product.append(p) ...
the_stack_v2_python_sparse
238_product_of_array_except_self/solution.py
FluffyFu/Leetcode
train
0
1551cf21b02340673adabca151988a906dc0f1ae
[ "for i in range(1, len(array)):\n while i > 0 and array[i] < array[i - 1]:\n array[i], array[i - 1] = (array[i - 1], array[i])\n i -= 1", "for i, val in enumerate(array):\n while i > 0 and val < array[i - 1]:\n array[i] = array[i - 1]\n i -= 1\n array[i] = val", "j = 0\nfor ...
<|body_start_0|> for i in range(1, len(array)): while i > 0 and array[i] < array[i - 1]: array[i], array[i - 1] = (array[i - 1], array[i]) i -= 1 <|end_body_0|> <|body_start_1|> for i, val in enumerate(array): while i > 0 and val < array[i - 1]: ...
Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort
Insertion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Insertion: """Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort""" def insertion(array): """Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time com...
stack_v2_sparse_classes_36k_train_010840
14,101
no_license
[ { "docstring": "Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time complexity: best O(n), avg and worst O(n^2)", "name": "insertion", "signature": "def insertion(array)" }, { "docstring": "Improves per...
3
stack_v2_sparse_classes_30k_train_000575
Implement the Python class `Insertion` described below. Class description: Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort Method signatures and docstrings: - def insertion(array): Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the sam...
Implement the Python class `Insertion` described below. Class description: Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort Method signatures and docstrings: - def insertion(array): Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the sam...
c88059dc66297af577ad2b8afa4e0ac0ad622915
<|skeleton|> class Insertion: """Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort""" def insertion(array): """Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time com...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Insertion: """Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort""" def insertion(array): """Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time complexity: best...
the_stack_v2_python_sparse
codes/BuildLinks1.02/test_input/sort_codes/pysort.py
DaHuO/Supergraph
train
2
cda531a991cd09accc9ce899899ab21ee5683e93
[ "if root == None:\n return ''\nstack = []\nstack.append([root, 0])\ns = ''\nwhile len(stack) > 0:\n node, level = stack[-1]\n if level == 0:\n stack[-1][1] += 1\n if node.left:\n stack.append([node.left, 0])\n elif level == 1:\n stack[-1][1] += 1\n if node.right:\n...
<|body_start_0|> if root == None: return '' stack = [] stack.append([root, 0]) s = '' while len(stack) > 0: node, level = stack[-1] if level == 0: stack[-1][1] += 1 if node.left: stack.append(...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode): """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str): """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if root == None: retu...
stack_v2_sparse_classes_36k_train_010841
1,986
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode)" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str)" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode): Encodes a tree to a single string. - def deserialize(self, data: str): Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode): Encodes a tree to a single string. - def deserialize(self, data: str): Decodes your encoded data to tree. <|skeleton|> class Codec: def seria...
aefc8006ccac4a4720dda1bd932a04fd1880ec9d
<|skeleton|> class Codec: def serialize(self, root: TreeNode): """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str): """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode): """Encodes a tree to a single string.""" if root == None: return '' stack = [] stack.append([root, 0]) s = '' while len(stack) > 0: node, level = stack[-1] if level == 0: ...
the_stack_v2_python_sparse
BST/serialize_deserialize_using_stack.py
viswan29/Leetcode
train
0
8cf94462b2b84ebd056b60bd9f37cebb8b25487f
[ "super().__init__()\nself.hass = hass\nself.gateway = gateway", "stack = []\nif record.levelno >= logging.WARN and (not record.exc_info):\n stack = [f for f, _, _, _ in traceback.extract_stack()]\nhass_path: str = HOMEASSISTANT_PATH[0]\nconfig_dir = self.hass.config.config_dir\npaths_re = re.compile('(?:{})/(....
<|body_start_0|> super().__init__() self.hass = hass self.gateway = gateway <|end_body_0|> <|body_start_1|> stack = [] if record.levelno >= logging.WARN and (not record.exc_info): stack = [f for f, _, _, _ in traceback.extract_stack()] hass_path: str = HOMEAS...
Log handler for error messages.
LogRelayHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogRelayHandler: """Log handler for error messages.""" def __init__(self, hass: HomeAssistant, gateway: ZHAGateway) -> None: """Initialize a new LogErrorHandler.""" <|body_0|> def emit(self, record: LogRecord) -> None: """Relay log message via dispatcher.""" ...
stack_v2_sparse_classes_36k_train_010842
31,557
permissive
[ { "docstring": "Initialize a new LogErrorHandler.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, gateway: ZHAGateway) -> None" }, { "docstring": "Relay log message via dispatcher.", "name": "emit", "signature": "def emit(self, record: LogRecord) -> None" } ...
2
null
Implement the Python class `LogRelayHandler` described below. Class description: Log handler for error messages. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, gateway: ZHAGateway) -> None: Initialize a new LogErrorHandler. - def emit(self, record: LogRecord) -> None: Relay log message vi...
Implement the Python class `LogRelayHandler` described below. Class description: Log handler for error messages. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, gateway: ZHAGateway) -> None: Initialize a new LogErrorHandler. - def emit(self, record: LogRecord) -> None: Relay log message vi...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class LogRelayHandler: """Log handler for error messages.""" def __init__(self, hass: HomeAssistant, gateway: ZHAGateway) -> None: """Initialize a new LogErrorHandler.""" <|body_0|> def emit(self, record: LogRecord) -> None: """Relay log message via dispatcher.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogRelayHandler: """Log handler for error messages.""" def __init__(self, hass: HomeAssistant, gateway: ZHAGateway) -> None: """Initialize a new LogErrorHandler.""" super().__init__() self.hass = hass self.gateway = gateway def emit(self, record: LogRecord) -> None: ...
the_stack_v2_python_sparse
homeassistant/components/zha/core/gateway.py
home-assistant/core
train
35,501
6b2a29f5ab7864e5e7739ca549e07087601edf21
[ "n = len(prec)\nself.level = [None] * n\nself.level[0] = 0\nfor u in range(1, n):\n self.level[u] = 1 + self.level[prec[u]]\ndepth = log2ceil(max((self.level[u] for u in range(n)))) + 1\nself.anc = [[0] * n for _ in range(depth)]\nfor u in range(n):\n self.anc[0][u] = prec[u]\nfor k in range(1, depth):\n f...
<|body_start_0|> n = len(prec) self.level = [None] * n self.level[0] = 0 for u in range(1, n): self.level[u] = 1 + self.level[prec[u]] depth = log2ceil(max((self.level[u] for u in range(n)))) + 1 self.anc = [[0] * n for _ in range(depth)] for u in rang...
Lowest common ancestor data structure using shortcuts to ancestors
LowestCommonAncestorShortcuts
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LowestCommonAncestorShortcuts: """Lowest common ancestor data structure using shortcuts to ancestors""" def __init__(self, prec): """builds the structure from a given tree :param prec: father for every node, with prec[0] = 0 :assumes: prec[node] < node :complexity: O(n log n), with n...
stack_v2_sparse_classes_36k_train_010843
3,713
permissive
[ { "docstring": "builds the structure from a given tree :param prec: father for every node, with prec[0] = 0 :assumes: prec[node] < node :complexity: O(n log n), with n = len(nodes)", "name": "__init__", "signature": "def __init__(self, prec)" }, { "docstring": ":returns: the lowest common ancest...
2
null
Implement the Python class `LowestCommonAncestorShortcuts` described below. Class description: Lowest common ancestor data structure using shortcuts to ancestors Method signatures and docstrings: - def __init__(self, prec): builds the structure from a given tree :param prec: father for every node, with prec[0] = 0 :a...
Implement the Python class `LowestCommonAncestorShortcuts` described below. Class description: Lowest common ancestor data structure using shortcuts to ancestors Method signatures and docstrings: - def __init__(self, prec): builds the structure from a given tree :param prec: father for every node, with prec[0] = 0 :a...
634645707ebf2489356009a6f91f012b55b1ee39
<|skeleton|> class LowestCommonAncestorShortcuts: """Lowest common ancestor data structure using shortcuts to ancestors""" def __init__(self, prec): """builds the structure from a given tree :param prec: father for every node, with prec[0] = 0 :assumes: prec[node] < node :complexity: O(n log n), with n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LowestCommonAncestorShortcuts: """Lowest common ancestor data structure using shortcuts to ancestors""" def __init__(self, prec): """builds the structure from a given tree :param prec: father for every node, with prec[0] = 0 :assumes: prec[node] < node :complexity: O(n log n), with n = len(nodes)...
the_stack_v2_python_sparse
tryalgo/lowest_common_ancestor.py
jilljenn/tryalgo
train
390
ac92d98280c94f3bc8d3d4dc39547210bc6be7bc
[ "try:\n result.find_existing_platform_ids()\n return True\nexcept:\n return False", "log.info('Started %s.pipeline(profile_id=%s, route=%s)', type(self).__name__, profile_id, route)\ntry:\n profile = InstagramProfile.objects.get(id=profile_id)\nexcept InstagramProfile.DoesNotExist:\n log.error('Ins...
<|body_start_0|> try: result.find_existing_platform_ids() return True except: return False <|end_body_0|> <|body_start_1|> log.info('Started %s.pipeline(profile_id=%s, route=%s)', type(self).__name__, profile_id, route) try: profile = Inst...
This processor detects existing platforms for the given InstagramProfile and saves its ids to InstagramProfile.
DetectExistingPlatformsProcessor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DetectExistingPlatformsProcessor: """This processor detects existing platforms for the given InstagramProfile and saves its ids to InstagramProfile.""" def proceed(self, result): """This function determines condition when it will proceed to the next Processor, Classifier or Upgrader ...
stack_v2_sparse_classes_36k_train_010844
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 `DetectExistingPlatformsProcessor` described below. Class description: This processor detects existing platforms for the given InstagramProfile and saves its ids to InstagramProfile. Method signatures and docstrings: - def proceed(self, result): This function determines condition when it wi...
Implement the Python class `DetectExistingPlatformsProcessor` described below. Class description: This processor detects existing platforms for the given InstagramProfile and saves its ids to InstagramProfile. Method signatures and docstrings: - def proceed(self, result): This function determines condition when it wi...
2f15c4ddd8bbb112c407d222ae48746b626c674f
<|skeleton|> class DetectExistingPlatformsProcessor: """This processor detects existing platforms for the given InstagramProfile and saves its ids to InstagramProfile.""" def proceed(self, result): """This function determines condition when it will proceed to the next Processor, Classifier or Upgrader ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DetectExistingPlatformsProcessor: """This processor detects existing platforms for the given InstagramProfile and saves its ids to InstagramProfile.""" def proceed(self, result): """This function determines condition when it will proceed to the next Processor, Classifier or Upgrader in chain. get...
the_stack_v2_python_sparse
Projects/miami_metro/social_discovery/processors.py
TopWebGhost/Angular-Influencer
train
1
63674f287632baa99b4736c3f1e17aaff0840a6a
[ "seller = Shop_Seller(id=shopId).get()\nif seller:\n seller = marshal(seller, output_shop)\n return Response(data=seller)\nelse:\n return Response(code=HttpStatus.HTTP_404_NOT_FOUND, message='无符合条件的商家')", "seller = Shop_Seller(id=shopId).get()\nif current_user.has_role('superadmin') or (current_user.scho...
<|body_start_0|> seller = Shop_Seller(id=shopId).get() if seller: seller = marshal(seller, output_shop) return Response(data=seller) else: return Response(code=HttpStatus.HTTP_404_NOT_FOUND, message='无符合条件的商家') <|end_body_0|> <|body_start_1|> seller =...
Info
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Info: def get(self, shopId): """根据商家id获取商家信息 :param shopId: :return:""" <|body_0|> def patch(self, shopId): """修改商家信息 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> seller = Shop_Seller(id=shopId).get() if seller: selle...
stack_v2_sparse_classes_36k_train_010845
14,722
no_license
[ { "docstring": "根据商家id获取商家信息 :param shopId: :return:", "name": "get", "signature": "def get(self, shopId)" }, { "docstring": "修改商家信息 :return:", "name": "patch", "signature": "def patch(self, shopId)" } ]
2
stack_v2_sparse_classes_30k_train_021592
Implement the Python class `Info` described below. Class description: Implement the Info class. Method signatures and docstrings: - def get(self, shopId): 根据商家id获取商家信息 :param shopId: :return: - def patch(self, shopId): 修改商家信息 :return:
Implement the Python class `Info` described below. Class description: Implement the Info class. Method signatures and docstrings: - def get(self, shopId): 根据商家id获取商家信息 :param shopId: :return: - def patch(self, shopId): 修改商家信息 :return: <|skeleton|> class Info: def get(self, shopId): """根据商家id获取商家信息 :para...
34a2bf4a51cc40a22dd43cb5eb88af7c2f2c5120
<|skeleton|> class Info: def get(self, shopId): """根据商家id获取商家信息 :param shopId: :return:""" <|body_0|> def patch(self, shopId): """修改商家信息 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Info: def get(self, shopId): """根据商家id获取商家信息 :param shopId: :return:""" seller = Shop_Seller(id=shopId).get() if seller: seller = marshal(seller, output_shop) return Response(data=seller) else: return Response(code=HttpStatus.HTTP_404_NOT_FOU...
the_stack_v2_python_sparse
App/Shop/Controller/ShopResource.py
Vulcanhy/api.grooo-master
train
0
6dbda99f4d3ff13cdd81df908ed2f84ff5c35818
[ "effective_area = effective_area.to_value(u.m ** 2)\nmin_effective_area = min_effective_area.to_value(u.m ** 2)\nself.min_effective_area = min_effective_area\neffective_area[effective_area < self.min_effective_area] = self.min_effective_area\neffective_area = np.log(effective_area)\nsuper().__init__(grid_points=gri...
<|body_start_0|> effective_area = effective_area.to_value(u.m ** 2) min_effective_area = min_effective_area.to_value(u.m ** 2) self.min_effective_area = min_effective_area effective_area[effective_area < self.min_effective_area] = self.min_effective_area effective_area = np.log(e...
EffectiveAreaEstimator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EffectiveAreaEstimator: def __init__(self, grid_points, effective_area, interpolator_cls=GridDataInterpolator, interpolator_kwargs=None, extrapolator_cls=None, extrapolator_kwargs=None, min_effective_area=1 * u.m ** 2): """Estimator class for effective areas. Takes a grid of effective ar...
stack_v2_sparse_classes_36k_train_010846
27,909
permissive
[ { "docstring": "Estimator class for effective areas. Takes a grid of effective areas for a bunch of different parameters and inter-/extrapolates (log) effective areas to given value of those parameters. Parameters ---------- grid_points: np.ndarray, shape=(n_points, n_dims): Grid points at which interpolation t...
2
stack_v2_sparse_classes_30k_train_012183
Implement the Python class `EffectiveAreaEstimator` described below. Class description: Implement the EffectiveAreaEstimator class. Method signatures and docstrings: - def __init__(self, grid_points, effective_area, interpolator_cls=GridDataInterpolator, interpolator_kwargs=None, extrapolator_cls=None, extrapolator_k...
Implement the Python class `EffectiveAreaEstimator` described below. Class description: Implement the EffectiveAreaEstimator class. Method signatures and docstrings: - def __init__(self, grid_points, effective_area, interpolator_cls=GridDataInterpolator, interpolator_kwargs=None, extrapolator_cls=None, extrapolator_k...
12a609566230d01a68a822aad38f080b60c473ce
<|skeleton|> class EffectiveAreaEstimator: def __init__(self, grid_points, effective_area, interpolator_cls=GridDataInterpolator, interpolator_kwargs=None, extrapolator_cls=None, extrapolator_kwargs=None, min_effective_area=1 * u.m ** 2): """Estimator class for effective areas. Takes a grid of effective ar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EffectiveAreaEstimator: def __init__(self, grid_points, effective_area, interpolator_cls=GridDataInterpolator, interpolator_kwargs=None, extrapolator_cls=None, extrapolator_kwargs=None, min_effective_area=1 * u.m ** 2): """Estimator class for effective areas. Takes a grid of effective areas for a bunc...
the_stack_v2_python_sparse
pyirf/interpolation/component_estimators.py
cta-observatory/pyirf
train
13
8110bf869ef019ace883d7fb958fc6b6c37c2a8c
[ "val = self.cleaned_data.get('user')\nuser = UserInfo.objects.filter(username=val).first()\nif user:\n raise ValidationError('用户已经存在')\nelse:\n return val", "val = self.cleaned_data.get('pwd')\nif val.isdigit():\n raise ValidationError('密码不能为纯数字')\nelse:\n return val", "pwd = self.cleaned_data.get('...
<|body_start_0|> val = self.cleaned_data.get('user') user = UserInfo.objects.filter(username=val).first() if user: raise ValidationError('用户已经存在') else: return val <|end_body_0|> <|body_start_1|> val = self.cleaned_data.get('pwd') if val.isdigit()...
UserForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserForm: def clean_user(self): """判断用户名是否重复""" <|body_0|> def clean_pwd(self): """判断用户密码是否为纯数字""" <|body_1|> def clean(self): """判断两次输入的密码是否相同""" <|body_2|> def clean_email(self): """判断邮箱是否与QQ邮箱""" <|body_3|> <|end_...
stack_v2_sparse_classes_36k_train_010847
4,784
no_license
[ { "docstring": "判断用户名是否重复", "name": "clean_user", "signature": "def clean_user(self)" }, { "docstring": "判断用户密码是否为纯数字", "name": "clean_pwd", "signature": "def clean_pwd(self)" }, { "docstring": "判断两次输入的密码是否相同", "name": "clean", "signature": "def clean(self)" }, { ...
4
stack_v2_sparse_classes_30k_train_013208
Implement the Python class `UserForm` described below. Class description: Implement the UserForm class. Method signatures and docstrings: - def clean_user(self): 判断用户名是否重复 - def clean_pwd(self): 判断用户密码是否为纯数字 - def clean(self): 判断两次输入的密码是否相同 - def clean_email(self): 判断邮箱是否与QQ邮箱
Implement the Python class `UserForm` described below. Class description: Implement the UserForm class. Method signatures and docstrings: - def clean_user(self): 判断用户名是否重复 - def clean_pwd(self): 判断用户密码是否为纯数字 - def clean(self): 判断两次输入的密码是否相同 - def clean_email(self): 判断邮箱是否与QQ邮箱 <|skeleton|> class UserForm: def c...
7698f8ce260439abb3cbdf478586fa1888791a61
<|skeleton|> class UserForm: def clean_user(self): """判断用户名是否重复""" <|body_0|> def clean_pwd(self): """判断用户密码是否为纯数字""" <|body_1|> def clean(self): """判断两次输入的密码是否相同""" <|body_2|> def clean_email(self): """判断邮箱是否与QQ邮箱""" <|body_3|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserForm: def clean_user(self): """判断用户名是否重复""" val = self.cleaned_data.get('user') user = UserInfo.objects.filter(username=val).first() if user: raise ValidationError('用户已经存在') else: return val def clean_pwd(self): """判断用户密码是否为纯数字""...
the_stack_v2_python_sparse
python练习/django exercise/cms/first/views.py
JacksonMike/python_exercise
train
0
9f051cc4f04772819c8207608b1f7d5f69f4f996
[ "super(FPN, self).__init__()\nself.inner_blocks = []\nself.layer_blocks = []\nfor idx, in_channels in enumerate(in_channels_list, 1):\n inner_block = 'fpn_inner{}'.format(idx)\n layer_block = 'fpn_layer{}'.format(idx)\n if in_channels == 0:\n continue\n inner_block_module = conv_block(in_channels...
<|body_start_0|> super(FPN, self).__init__() self.inner_blocks = [] self.layer_blocks = [] for idx, in_channels in enumerate(in_channels_list, 1): inner_block = 'fpn_inner{}'.format(idx) layer_block = 'fpn_layer{}'.format(idx) if in_channels == 0: ...
Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive
FPN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FPN: """Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive""" def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None): """Arguments: in_channels_list (list[int...
stack_v2_sparse_classes_36k_train_010848
10,890
permissive
[ { "docstring": "Arguments: in_channels_list (list[int]): number of channels for each feature map that will be fed out_channels (int): number of channels of the FPN representation top_blocks (nn.Module or None): if provided, an extra operation will be performed on the output of the last (smallest resolution) FPN...
2
null
Implement the Python class `FPN` described below. Class description: Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive Method signatures and docstrings: - def __init__(self, in_channels_list, out_channels, conv_block...
Implement the Python class `FPN` described below. Class description: Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive Method signatures and docstrings: - def __init__(self, in_channels_list, out_channels, conv_block...
54e0821e73f67be5360c36f01229a123c34ab3b3
<|skeleton|> class FPN: """Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive""" def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None): """Arguments: in_channels_list (list[int...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FPN: """Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive""" def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None): """Arguments: in_channels_list (list[int]): number of...
the_stack_v2_python_sparse
AnchorFree/FCOS/models/asff.py
Le1kk/ObjectDetection
train
0
d7c20511daef565075a9d6db95be30728e9bf467
[ "self.supported_attr = f5_virtualservice_attributes['VS_supported_attr']\nself.ignore_for_value = f5_virtualservice_attributes['VS_ignore_for_value']\nself.unsupported_types = f5_virtualservice_attributes['VS_unsupported_types']\nself.vs_na_attr = f5_virtualservice_attributes['VS_na_attr']\nself.vs_indirect_attr = ...
<|body_start_0|> self.supported_attr = f5_virtualservice_attributes['VS_supported_attr'] self.ignore_for_value = f5_virtualservice_attributes['VS_ignore_for_value'] self.unsupported_types = f5_virtualservice_attributes['VS_unsupported_types'] self.vs_na_attr = f5_virtualservice_attribute...
class for vs conversion for v11 version
VSConfigConvV11
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VSConfigConvV11: """class for vs conversion for v11 version""" def __init__(self, f5_virtualservice_attributes, prefix, con_snatpool, custom_mappings, distinct_app_profile): """:param f5_virtualservice_attributes: yaml attribute file for object :param prefix: prefix for object :param...
stack_v2_sparse_classes_36k_train_010849
49,577
permissive
[ { "docstring": ":param f5_virtualservice_attributes: yaml attribute file for object :param prefix: prefix for object :param con_snatpool: flag for snat conversion :param custom_mappings: custom config to migrate irules", "name": "__init__", "signature": "def __init__(self, f5_virtualservice_attributes, ...
3
null
Implement the Python class `VSConfigConvV11` described below. Class description: class for vs conversion for v11 version Method signatures and docstrings: - def __init__(self, f5_virtualservice_attributes, prefix, con_snatpool, custom_mappings, distinct_app_profile): :param f5_virtualservice_attributes: yaml attribut...
Implement the Python class `VSConfigConvV11` described below. Class description: class for vs conversion for v11 version Method signatures and docstrings: - def __init__(self, f5_virtualservice_attributes, prefix, con_snatpool, custom_mappings, distinct_app_profile): :param f5_virtualservice_attributes: yaml attribut...
f2386af42908d3c503ec0ec6f1b00f2095b0b004
<|skeleton|> class VSConfigConvV11: """class for vs conversion for v11 version""" def __init__(self, f5_virtualservice_attributes, prefix, con_snatpool, custom_mappings, distinct_app_profile): """:param f5_virtualservice_attributes: yaml attribute file for object :param prefix: prefix for object :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VSConfigConvV11: """class for vs conversion for v11 version""" def __init__(self, f5_virtualservice_attributes, prefix, con_snatpool, custom_mappings, distinct_app_profile): """:param f5_virtualservice_attributes: yaml attribute file for object :param prefix: prefix for object :param con_snatpool...
the_stack_v2_python_sparse
python/avi/migrationtools/f5_converter/vs_converter.py
vmware/alb-sdk
train
30
a7d182b1f7306bd17a60d4829a749ec58ebd4878
[ "super(ModelEmbeddings, self).__init__()\nself.word_embed_size = word_embed_size\nself.vocab = vocab\nself.e_char = 50\npadding_idx = self.vocab.char_pad\nself.char_embedding = nn.Embedding(len(self.vocab.char2id), self.e_char, padding_idx=padding_idx)\nself.cnn = CNN(embed_size=self.e_char, num_filter=self.word_em...
<|body_start_0|> super(ModelEmbeddings, self).__init__() self.word_embed_size = word_embed_size self.vocab = vocab self.e_char = 50 padding_idx = self.vocab.char_pad self.char_embedding = nn.Embedding(len(self.vocab.char2id), self.e_char, padding_idx=padding_idx) ...
Class that converts input words to their CNN-based embeddings.
ModelEmbeddings
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelEmbeddings: """Class that converts input words to their CNN-based embeddings.""" def __init__(self, word_embed_size, vocab): """Init the Embedding layer for one language @param word_embed_size (int): Embedding size (dimensionality) for the output word @param vocab (VocabEntry): ...
stack_v2_sparse_classes_36k_train_010850
5,488
no_license
[ { "docstring": "Init the Embedding layer for one language @param word_embed_size (int): Embedding size (dimensionality) for the output word @param vocab (VocabEntry): VocabEntry object. See vocab.py for documentation. Hints: - You may find len(self.vocab.char2id) useful when create the embedding", "name": "...
2
stack_v2_sparse_classes_30k_train_015893
Implement the Python class `ModelEmbeddings` described below. Class description: Class that converts input words to their CNN-based embeddings. Method signatures and docstrings: - def __init__(self, word_embed_size, vocab): Init the Embedding layer for one language @param word_embed_size (int): Embedding size (dimens...
Implement the Python class `ModelEmbeddings` described below. Class description: Class that converts input words to their CNN-based embeddings. Method signatures and docstrings: - def __init__(self, word_embed_size, vocab): Init the Embedding layer for one language @param word_embed_size (int): Embedding size (dimens...
a91fd21582b3ac5d8fcaf1f12c4f0814cc4675db
<|skeleton|> class ModelEmbeddings: """Class that converts input words to their CNN-based embeddings.""" def __init__(self, word_embed_size, vocab): """Init the Embedding layer for one language @param word_embed_size (int): Embedding size (dimensionality) for the output word @param vocab (VocabEntry): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelEmbeddings: """Class that converts input words to their CNN-based embeddings.""" def __init__(self, word_embed_size, vocab): """Init the Embedding layer for one language @param word_embed_size (int): Embedding size (dimensionality) for the output word @param vocab (VocabEntry): VocabEntry ob...
the_stack_v2_python_sparse
2020 Spring:natural language process/EXP 4:CNN-based NMT/代码/model_embeddings.py
huochf/Course-Experiments
train
0
e5f16ab42246ccbdd6206fc64668c979c27528dc
[ "words.sort()\nvalid_words, longest_word = ({''}, '')\nfor word in words:\n if word[:-1] in valid_words:\n valid_words.add(word)\n if len(word) > len(longest_word):\n longest_word = word\nreturn longest_word", "trie = Trie()\nfor word in words:\n trie.add(word)\nreturn trie.bfs()" ]
<|body_start_0|> words.sort() valid_words, longest_word = ({''}, '') for word in words: if word[:-1] in valid_words: valid_words.add(word) if len(word) > len(longest_word): longest_word = word return longest_word <|end_body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestWord1(self, words): """:type words: List[str] :rtype: str""" <|body_0|> def longestWord2(self, words): """:type words: List[str] :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> words.sort() valid_words, longe...
stack_v2_sparse_classes_36k_train_010851
4,497
no_license
[ { "docstring": ":type words: List[str] :rtype: str", "name": "longestWord1", "signature": "def longestWord1(self, words)" }, { "docstring": ":type words: List[str] :rtype: str", "name": "longestWord2", "signature": "def longestWord2(self, words)" } ]
2
stack_v2_sparse_classes_30k_train_011123
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestWord1(self, words): :type words: List[str] :rtype: str - def longestWord2(self, words): :type words: List[str] :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestWord1(self, words): :type words: List[str] :rtype: str - def longestWord2(self, words): :type words: List[str] :rtype: str <|skeleton|> class Solution: def longe...
b1764cd62e1c8cb062869992d9eaa8b2d2fdf9c2
<|skeleton|> class Solution: def longestWord1(self, words): """:type words: List[str] :rtype: str""" <|body_0|> def longestWord2(self, words): """:type words: List[str] :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestWord1(self, words): """:type words: List[str] :rtype: str""" words.sort() valid_words, longest_word = ({''}, '') for word in words: if word[:-1] in valid_words: valid_words.add(word) if len(word) > len(longest_wor...
the_stack_v2_python_sparse
leetcode/trie/easy/720. Longest Word in Dictionary.py
Hk4Fun/algorithm_offer
train
1
e616810b04cb4ad7032222d0c7ca68e924b193fe
[ "super(NNBlock, self).__init__()\nself.n_layers = len(arch) - 1\nself.activation = activation\nself.device = 'cuda' if torch.cuda.is_available() else 'cpu'\nfor i in range(self.n_layers):\n self.add_module('Linear_{}'.format(i), torch.nn.Linear(arch[i], arch[i + 1]).to(self.device))", "for i in range(self.n_la...
<|body_start_0|> super(NNBlock, self).__init__() self.n_layers = len(arch) - 1 self.activation = activation self.device = 'cuda' if torch.cuda.is_available() else 'cpu' for i in range(self.n_layers): self.add_module('Linear_{}'.format(i), torch.nn.Linear(arch[i], arch...
NNBlock
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NNBlock: def __init__(self, arch, activation=torch.nn.ReLU()): """:param arch: architecture of the nn_block :param activation: activation function""" <|body_0|> def forward(self, x): """:param x: input of nn :return: output of nn""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k_train_010852
10,752
permissive
[ { "docstring": ":param arch: architecture of the nn_block :param activation: activation function", "name": "__init__", "signature": "def __init__(self, arch, activation=torch.nn.ReLU())" }, { "docstring": ":param x: input of nn :return: output of nn", "name": "forward", "signature": "def...
2
null
Implement the Python class `NNBlock` described below. Class description: Implement the NNBlock class. Method signatures and docstrings: - def __init__(self, arch, activation=torch.nn.ReLU()): :param arch: architecture of the nn_block :param activation: activation function - def forward(self, x): :param x: input of nn...
Implement the Python class `NNBlock` described below. Class description: Implement the NNBlock class. Method signatures and docstrings: - def __init__(self, arch, activation=torch.nn.ReLU()): :param arch: architecture of the nn_block :param activation: activation function - def forward(self, x): :param x: input of nn...
cf536bb0d245982b72e4416ea329419e59baf1c9
<|skeleton|> class NNBlock: def __init__(self, arch, activation=torch.nn.ReLU()): """:param arch: architecture of the nn_block :param activation: activation function""" <|body_0|> def forward(self, x): """:param x: input of nn :return: output of nn""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NNBlock: def __init__(self, arch, activation=torch.nn.ReLU()): """:param arch: architecture of the nn_block :param activation: activation function""" super(NNBlock, self).__init__() self.n_layers = len(arch) - 1 self.activation = activation self.device = 'cuda' if torch...
the_stack_v2_python_sparse
multiscale_HiTS-master/src/ResNet.py
msaad1311/PDEs-using-NN
train
0
984f6777f87e0bf400601914fd86028e2d49b73c
[ "err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'\nerr_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'\nif not isinstance(style_image, np.ndarray):\n raise TypeError(err_m1)\nif len(style_image.shape) != 3 or style_image.shape[2] != 3:\n raise TypeError(err_m1)\nif not isi...
<|body_start_0|> err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)' err_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)' if not isinstance(style_image, np.ndarray): raise TypeError(err_m1) if len(style_image.shape) != 3 or style_image.shape[2...
Performs task for neural style transfer
NST
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NST: """Performs task for neural style transfer""" def __init__(self, style_image, content_image, alpha=10000.0, beta=1): """constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:...
stack_v2_sparse_classes_36k_train_010853
4,785
no_license
[ { "docstring": "constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for style cost", "name": "__init__", "signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"...
4
null
Implement the Python class `NST` described below. Class description: Performs task for neural style transfer Method signatures and docstrings: - def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont...
Implement the Python class `NST` described below. Class description: Performs task for neural style transfer Method signatures and docstrings: - def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont...
e20b284d5f1841952104d7d9a0274cff80eb304d
<|skeleton|> class NST: """Performs task for neural style transfer""" def __init__(self, style_image, content_image, alpha=10000.0, beta=1): """constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NST: """Performs task for neural style transfer""" def __init__(self, style_image, content_image, alpha=10000.0, beta=1): """constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for s...
the_stack_v2_python_sparse
supervised_learning/0x0C-neural_style_transfer/2-neural_style.py
jgadelugo/holbertonschool-machine_learning
train
1
10a99c45ff439865eda09df35df7b5fef493f86a
[ "if not isinstance(samples_info_sets, pd.Series):\n raise ValueError('The samples_info_sets param must be a pd.Series.')\nsuper().__init__(n_splits, shuffle=False, random_state=None)\nself.samples_info_sets = samples_info_sets\nself.pct_embargo = pct_embargo", "if X.shape[0] != self.samples_info_sets.shape[0]:...
<|body_start_0|> if not isinstance(samples_info_sets, pd.Series): raise ValueError('The samples_info_sets param must be a pd.Series.') super().__init__(n_splits, shuffle=False, random_state=None) self.samples_info_sets = samples_info_sets self.pct_embargo = pct_embargo <|end_...
Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.
PurgedKFold
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PurgedKFold: """Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.""" def __init__(self, n_splits: int=3, samples_info_sets: pd.Seri...
stack_v2_sparse_classes_36k_train_010854
19,555
permissive
[ { "docstring": "Initialize. :param n_splits: (int) The number of splits. Default to 3 :param samples_info_sets: (pd.Series) The information range on which each record is constructed from *samples_info_sets.index*: Time when the information extraction started. *samples_info_sets.value*: Time when the information...
2
stack_v2_sparse_classes_30k_train_008043
Implement the Python class `PurgedKFold` described below. Class description: Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between. Method signatures and docstrin...
Implement the Python class `PurgedKFold` described below. Class description: Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between. Method signatures and docstrin...
046c47d995da08b1003bba3f9c07d5bfb73d9c1f
<|skeleton|> class PurgedKFold: """Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.""" def __init__(self, n_splits: int=3, samples_info_sets: pd.Seri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PurgedKFold: """Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.""" def __init__(self, n_splits: int=3, samples_info_sets: pd.Series=None, pct_...
the_stack_v2_python_sparse
src/collection/mlfinlab/cross_validation/cross_validation.py
Ta-nu-ki/dissertacao
train
0
3fa03dd5ad6daf41bbdc4c2bcd75f80472f3b255
[ "super().__init__(name='control_network')\nself._activation = activation\nself._proprio_keys = proprio_keys\nself._proprio_encoder = acme_networks.LayerNormMLP([proprio_encoder_size])", "if not isinstance(inputs, dict):\n inputs = {'inputs': inputs}\nproprio_input = []\nif self._proprio_keys is None:\n self...
<|body_start_0|> super().__init__(name='control_network') self._activation = activation self._proprio_keys = proprio_keys self._proprio_encoder = acme_networks.LayerNormMLP([proprio_encoder_size]) <|end_body_0|> <|body_start_1|> if not isinstance(inputs, dict): input...
Image, proprio and optionally action encoder used for actors and critics.
ControlNetwork
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ControlNetwork: """Image, proprio and optionally action encoder used for actors and critics.""" def __init__(self, proprio_encoder_size: int, proprio_keys=None, activation=tf.nn.elu): """Creates a ControlNetwork. Args: proprio_encoder_size: Size of the linear layer for the proprio en...
stack_v2_sparse_classes_36k_train_010855
3,163
permissive
[ { "docstring": "Creates a ControlNetwork. Args: proprio_encoder_size: Size of the linear layer for the proprio encoder. proprio_keys: Optional list of names of proprioceptive observations. Defaults to all observations. Note that if this is specified, any observation not contained in proprio_keys will be ignored...
2
null
Implement the Python class `ControlNetwork` described below. Class description: Image, proprio and optionally action encoder used for actors and critics. Method signatures and docstrings: - def __init__(self, proprio_encoder_size: int, proprio_keys=None, activation=tf.nn.elu): Creates a ControlNetwork. Args: proprio_...
Implement the Python class `ControlNetwork` described below. Class description: Image, proprio and optionally action encoder used for actors and critics. Method signatures and docstrings: - def __init__(self, proprio_encoder_size: int, proprio_keys=None, activation=tf.nn.elu): Creates a ControlNetwork. Args: proprio_...
a6ef8053380d6aa19aaae14b93f013ae9762d057
<|skeleton|> class ControlNetwork: """Image, proprio and optionally action encoder used for actors and critics.""" def __init__(self, proprio_encoder_size: int, proprio_keys=None, activation=tf.nn.elu): """Creates a ControlNetwork. Args: proprio_encoder_size: Size of the linear layer for the proprio en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ControlNetwork: """Image, proprio and optionally action encoder used for actors and critics.""" def __init__(self, proprio_encoder_size: int, proprio_keys=None, activation=tf.nn.elu): """Creates a ControlNetwork. Args: proprio_encoder_size: Size of the linear layer for the proprio encoder. propri...
the_stack_v2_python_sparse
rl_unplugged/networks.py
sethuramanio/deepmind-research
train
1
6661c2efe6c274c3a0629693f4c40c6fd560146d
[ "self.map_func = map_func\nself.reduce_func = reduce_func\nself.pool = multiprocessing.Pool(num_workers)", "partitioned_data = collections.defaultdict(list)\nfor key, value in mapped_values:\n partitioned_data[key].append(value)\nreturn partitioned_data.items()", "map_responses = self.pool.map(self.map_func,...
<|body_start_0|> self.map_func = map_func self.reduce_func = reduce_func self.pool = multiprocessing.Pool(num_workers) <|end_body_0|> <|body_start_1|> partitioned_data = collections.defaultdict(list) for key, value in mapped_values: partitioned_data[key].append(value...
SimpleMapReduce
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleMapReduce: def __init__(self, map_func, reduce_func, num_workers=None): """map_func Funzione che mappa gli input a dati intermedi. Riceve come argomento un valore in input e ritorna un tupla con la chiave ed il valore che devono essere ridotti. reduce_func Funzione per ridurre la v...
stack_v2_sparse_classes_36k_train_010856
2,143
no_license
[ { "docstring": "map_func Funzione che mappa gli input a dati intermedi. Riceve come argomento un valore in input e ritorna un tupla con la chiave ed il valore che devono essere ridotti. reduce_func Funzione per ridurre la versione partizionata di dati intermedi verso il risultato finale. Riceve come argomento u...
3
null
Implement the Python class `SimpleMapReduce` described below. Class description: Implement the SimpleMapReduce class. Method signatures and docstrings: - def __init__(self, map_func, reduce_func, num_workers=None): map_func Funzione che mappa gli input a dati intermedi. Riceve come argomento un valore in input e rito...
Implement the Python class `SimpleMapReduce` described below. Class description: Implement the SimpleMapReduce class. Method signatures and docstrings: - def __init__(self, map_func, reduce_func, num_workers=None): map_func Funzione che mappa gli input a dati intermedi. Riceve come argomento un valore in input e rito...
c725df4a2aa2e799a969e90c64898f08b7eaad7d
<|skeleton|> class SimpleMapReduce: def __init__(self, map_func, reduce_func, num_workers=None): """map_func Funzione che mappa gli input a dati intermedi. Riceve come argomento un valore in input e ritorna un tupla con la chiave ed il valore che devono essere ridotti. reduce_func Funzione per ridurre la v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimpleMapReduce: def __init__(self, map_func, reduce_func, num_workers=None): """map_func Funzione che mappa gli input a dati intermedi. Riceve come argomento un valore in input e ritorna un tupla con la chiave ed il valore che devono essere ridotti. reduce_func Funzione per ridurre la versione partiz...
the_stack_v2_python_sparse
dumpscripts/multiprocessing_mapreduce.py
robertopauletto/PyMOTW-it_3.0
train
4
70a757cb3053e98927737103d3e5a8f7837bea53
[ "sysdefpath = os.path.join(os.environ['TEST_DATA'], 'data', 'compile', 'sysdefs', 'canonical_system_definition.xml')\nsysDef = sysdef.api.SystemDefinition(sysdefpath)\nbsl = compilation.BinarySizeLogger(sysDef)\nself.assertRaises(Exception, bsl.read_output_binaries_per_unit, '')", "sysdefpath = os.path.join(os.en...
<|body_start_0|> sysdefpath = os.path.join(os.environ['TEST_DATA'], 'data', 'compile', 'sysdefs', 'canonical_system_definition.xml') sysDef = sysdef.api.SystemDefinition(sysdefpath) bsl = compilation.BinarySizeLogger(sysDef) self.assertRaises(Exception, bsl.read_output_binaries_per_unit,...
Unit test case for compilation.py
CompilationTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompilationTest: """Unit test case for compilation.py""" def test_read_op_bins_per_unt_empty_logs_lst(self): """Testing read_output_binaries_per_unit method with empty log list""" <|body_0|> def test_read_output_binaries_per_unit(self): """Testing read_output_bin...
stack_v2_sparse_classes_36k_train_010857
4,044
no_license
[ { "docstring": "Testing read_output_binaries_per_unit method with empty log list", "name": "test_read_op_bins_per_unt_empty_logs_lst", "signature": "def test_read_op_bins_per_unt_empty_logs_lst(self)" }, { "docstring": "Testing read_output_binaries_per_unit method", "name": "test_read_output...
5
null
Implement the Python class `CompilationTest` described below. Class description: Unit test case for compilation.py Method signatures and docstrings: - def test_read_op_bins_per_unt_empty_logs_lst(self): Testing read_output_binaries_per_unit method with empty log list - def test_read_output_binaries_per_unit(self): Te...
Implement the Python class `CompilationTest` described below. Class description: Unit test case for compilation.py Method signatures and docstrings: - def test_read_op_bins_per_unt_empty_logs_lst(self): Testing read_output_binaries_per_unit method with empty log list - def test_read_output_binaries_per_unit(self): Te...
f458a4ce83f74d603362fe6b71eaa647ccc62fee
<|skeleton|> class CompilationTest: """Unit test case for compilation.py""" def test_read_op_bins_per_unt_empty_logs_lst(self): """Testing read_output_binaries_per_unit method with empty log list""" <|body_0|> def test_read_output_binaries_per_unit(self): """Testing read_output_bin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompilationTest: """Unit test case for compilation.py""" def test_read_op_bins_per_unt_empty_logs_lst(self): """Testing read_output_binaries_per_unit method with empty log list""" sysdefpath = os.path.join(os.environ['TEST_DATA'], 'data', 'compile', 'sysdefs', 'canonical_system_definition...
the_stack_v2_python_sparse
buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_compilation.py
anagovitsyn/oss.FCL.sftools.dev.build
train
0
1ed75a3cda50fce400d05b3abb50a2edd983269f
[ "current = head\nh, current = self.swap(current)\nwhile current:\n _, current = self.swap(current)\nreturn h", "if not n1:\n return (n1, None)\nif n1.next:\n n2 = n1.next\nelse:\n return (n1, None)\ntmp = n2.next\nn2.next = n1\nn1.next = tmp\nif tmp:\n if tmp.next:\n n1.next = tmp.next\nretu...
<|body_start_0|> current = head h, current = self.swap(current) while current: _, current = self.swap(current) return h <|end_body_0|> <|body_start_1|> if not n1: return (n1, None) if n1.next: n2 = n1.next else: ret...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def swapPairs(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def swap(self, n1): """返回 head, n2.next :param n1: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> current = head h, current = self.swap(cur...
stack_v2_sparse_classes_36k_train_010858
820
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "swapPairs", "signature": "def swapPairs(self, head)" }, { "docstring": "返回 head, n2.next :param n1: :return:", "name": "swap", "signature": "def swap(self, n1)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs(self, head): :type head: ListNode :rtype: ListNode - def swap(self, n1): 返回 head, n2.next :param n1: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs(self, head): :type head: ListNode :rtype: ListNode - def swap(self, n1): 返回 head, n2.next :param n1: :return: <|skeleton|> class Solution: def swapPairs(self,...
9f53994d8a123003d5f12a76cf375982cee52806
<|skeleton|> class Solution: def swapPairs(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def swap(self, n1): """返回 head, n2.next :param n1: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def swapPairs(self, head): """:type head: ListNode :rtype: ListNode""" current = head h, current = self.swap(current) while current: _, current = self.swap(current) return h def swap(self, n1): """返回 head, n2.next :param n1: :return:""...
the_stack_v2_python_sparse
Algorithms/Q24_Swap_Nodes_in_Pairs.py
filosfino/leetcode
train
1
0f377d37f94e834223763080b8e6f0ae9ba01c55
[ "self._qbincalc(e_final, self._qbbo)\nindata = indata.as_(vectorType)\ninerrs = inerrs.as_(vectorType)\nred.ERebinAllInOne_call(self._rebinner._templateType, self._rebinner._handle, self._qbbo._handle, self._qbbn._handle, indata._handle, inerrs._handle, outdata._handle, outerrs._handle)\nreturn", "self._dphi = dp...
<|body_start_0|> self._qbincalc(e_final, self._qbbo) indata = indata.as_(vectorType) inerrs = inerrs.as_(vectorType) red.ERebinAllInOne_call(self._rebinner._templateType, self._rebinner._handle, self._qbbo._handle, self._qbbn._handle, indata._handle, inerrs._handle, outdata._handle, oute...
QRebinner
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QRebinner: def __call__(self, e_final, indata, outdata, inerrs, outerrs): """my_QRebinDriver( e_final, indata, outdata, inerrs, outerrs) Rebin some data from S(Phi, e_final) to S(Q, e_final). Inputs: e_final( float, final neutron energy in meV) indata (StdVector, input data, unchanged) o...
stack_v2_sparse_classes_36k_train_010859
3,154
no_license
[ { "docstring": "my_QRebinDriver( e_final, indata, outdata, inerrs, outerrs) Rebin some data from S(Phi, e_final) to S(Q, e_final). Inputs: e_final( float, final neutron energy in meV) indata (StdVector, input data, unchanged) outdata (StdVector, output data, CHANGED) inerrs (StdVector, input errors squared, unc...
2
null
Implement the Python class `QRebinner` described below. Class description: Implement the QRebinner class. Method signatures and docstrings: - def __call__(self, e_final, indata, outdata, inerrs, outerrs): my_QRebinDriver( e_final, indata, outdata, inerrs, outerrs) Rebin some data from S(Phi, e_final) to S(Q, e_final)...
Implement the Python class `QRebinner` described below. Class description: Implement the QRebinner class. Method signatures and docstrings: - def __call__(self, e_final, indata, outdata, inerrs, outerrs): my_QRebinDriver( e_final, indata, outdata, inerrs, outerrs) Rebin some data from S(Phi, e_final) to S(Q, e_final)...
7ba4ce07a5a4645942192b4b81f7afcae505db90
<|skeleton|> class QRebinner: def __call__(self, e_final, indata, outdata, inerrs, outerrs): """my_QRebinDriver( e_final, indata, outdata, inerrs, outerrs) Rebin some data from S(Phi, e_final) to S(Q, e_final). Inputs: e_final( float, final neutron energy in meV) indata (StdVector, input data, unchanged) o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QRebinner: def __call__(self, e_final, indata, outdata, inerrs, outerrs): """my_QRebinDriver( e_final, indata, outdata, inerrs, outerrs) Rebin some data from S(Phi, e_final) to S(Q, e_final). Inputs: e_final( float, final neutron energy in meV) indata (StdVector, input data, unchanged) outdata (StdVec...
the_stack_v2_python_sparse
histogrammode/reduction/vectorCompat/QRebinner.py
danse-inelastic/DrChops
train
0
45fb47d589f1a367fc0a307b064a16c6db4a2372
[ "data = Webcam.objects.all()\nserializer = WebcamSerializer(data, many=True, context={'request': request})\nreturn Response(serializer.data, status=status.HTTP_200_OK)", "try:\n webcam = Webcam.objects.get(slug=pk)\n serializer = WebcamSerializer(webcam, many=False, context={'request': request})\n return...
<|body_start_0|> data = Webcam.objects.all() serializer = WebcamSerializer(data, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> try: webcam = Webcam.objects.get(slug=pk) seriali...
Webcams list
Webcams
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Webcams: """Webcams list""" def list(self, request): """Gets the webcams list""" <|body_0|> def retrieve(self, request, pk=None): """Gets single webcam data""" <|body_1|> <|end_skeleton|> <|body_start_0|> data = Webcam.objects.all() seri...
stack_v2_sparse_classes_36k_train_010860
1,539
no_license
[ { "docstring": "Gets the webcams list", "name": "list", "signature": "def list(self, request)" }, { "docstring": "Gets single webcam data", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" } ]
2
null
Implement the Python class `Webcams` described below. Class description: Webcams list Method signatures and docstrings: - def list(self, request): Gets the webcams list - def retrieve(self, request, pk=None): Gets single webcam data
Implement the Python class `Webcams` described below. Class description: Webcams list Method signatures and docstrings: - def list(self, request): Gets the webcams list - def retrieve(self, request, pk=None): Gets single webcam data <|skeleton|> class Webcams: """Webcams list""" def list(self, request): ...
a6becc62eaf5c96e146431631c0d081600e7c5d3
<|skeleton|> class Webcams: """Webcams list""" def list(self, request): """Gets the webcams list""" <|body_0|> def retrieve(self, request, pk=None): """Gets single webcam data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Webcams: """Webcams list""" def list(self, request): """Gets the webcams list""" data = Webcam.objects.all() serializer = WebcamSerializer(data, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) def retrieve(self, req...
the_stack_v2_python_sparse
torinometeo/webcam/views.py
TorinoMeteo/tm-website
train
0
d6b7024ca1ea424ceefc9bf26e934ebec152892b
[ "self.screen = screen\nself.x = x\nself.y = y\nself.vx = vx\nself.vy = vy\nself.collisions = 0", "if self.x - self.r <= 0 or self.x + self.r >= SCREEN_WIDTH:\n self.vx = -self.vx\n self.x += self.vx\n self.collisions += 1\nif self.y - self.r <= 0 or self.y + self.r >= SCREEN_HEIGHT:\n self.vy = -self....
<|body_start_0|> self.screen = screen self.x = x self.y = y self.vx = vx self.vy = vy self.collisions = 0 <|end_body_0|> <|body_start_1|> if self.x - self.r <= 0 or self.x + self.r >= SCREEN_WIDTH: self.vx = -self.vx self.x += self.vx ...
Object
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Object: def __init__(self, screen: pygame.Surface, x: int, y: int, vx: int, vy: int): """Конструктор класса Object Args: screen - экран, на котором отрисовывается объект x - начальное положение объекта по горизонтали y - начальное положение объекта по вертикали vx - стартовая скорость по...
stack_v2_sparse_classes_36k_train_010861
25,132
no_license
[ { "docstring": "Конструктор класса Object Args: screen - экран, на котором отрисовывается объект x - начальное положение объекта по горизонтали y - начальное положение объекта по вертикали vx - стартовая скорость по горизонтальной оси vy - стартовая скорость по вертикальной оси", "name": "__init__", "si...
2
stack_v2_sparse_classes_30k_train_005744
Implement the Python class `Object` described below. Class description: Implement the Object class. Method signatures and docstrings: - def __init__(self, screen: pygame.Surface, x: int, y: int, vx: int, vy: int): Конструктор класса Object Args: screen - экран, на котором отрисовывается объект x - начальное положение...
Implement the Python class `Object` described below. Class description: Implement the Object class. Method signatures and docstrings: - def __init__(self, screen: pygame.Surface, x: int, y: int, vx: int, vy: int): Конструктор класса Object Args: screen - экран, на котором отрисовывается объект x - начальное положение...
e9c955c890a9775431e9a27a494bea774fe2bbb2
<|skeleton|> class Object: def __init__(self, screen: pygame.Surface, x: int, y: int, vx: int, vy: int): """Конструктор класса Object Args: screen - экран, на котором отрисовывается объект x - начальное положение объекта по горизонтали y - начальное положение объекта по вертикали vx - стартовая скорость по...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Object: def __init__(self, screen: pygame.Surface, x: int, y: int, vx: int, vy: int): """Конструктор класса Object Args: screen - экран, на котором отрисовывается объект x - начальное положение объекта по горизонтали y - начальное положение объекта по вертикали vx - стартовая скорость по горизонтально...
the_stack_v2_python_sparse
lab 9/guns.py
GenosseBlaackberry/MIPT_B02-113
train
0
9d5ee497391326c719306c3c4c0c02b16c544220
[ "try:\n login = True if 'login' in request.session else False\n return render(request, 'staff/sup_user_add.html', {'login': login})\nexcept Exception as e:\n logger.error(e, exc_info=True)\n return render(request, '404-error-page.html')", "try:\n user = User.objects.filter(email__iexact=request.dat...
<|body_start_0|> try: login = True if 'login' in request.session else False return render(request, 'staff/sup_user_add.html', {'login': login}) except Exception as e: logger.error(e, exc_info=True) return render(request, '404-error-page.html') <|end_body_0...
SuperUserAddView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuperUserAddView: def get(self, request): """Gwt super user list view""" <|body_0|> def post(self, request): """Create super user""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: login = True if 'login' in request.session else False ...
stack_v2_sparse_classes_36k_train_010862
7,575
no_license
[ { "docstring": "Gwt super user list view", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create super user", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_005241
Implement the Python class `SuperUserAddView` described below. Class description: Implement the SuperUserAddView class. Method signatures and docstrings: - def get(self, request): Gwt super user list view - def post(self, request): Create super user
Implement the Python class `SuperUserAddView` described below. Class description: Implement the SuperUserAddView class. Method signatures and docstrings: - def get(self, request): Gwt super user list view - def post(self, request): Create super user <|skeleton|> class SuperUserAddView: def get(self, request): ...
367cccca72f0eae6c3ccb70fabb371dc905f915e
<|skeleton|> class SuperUserAddView: def get(self, request): """Gwt super user list view""" <|body_0|> def post(self, request): """Create super user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SuperUserAddView: def get(self, request): """Gwt super user list view""" try: login = True if 'login' in request.session else False return render(request, 'staff/sup_user_add.html', {'login': login}) except Exception as e: logger.error(e, exc_info=Tr...
the_stack_v2_python_sparse
staff/views/sup_user_view.py
vshaladhav97/first_kick
train
0
01627473b422a441a17a979212c1f4becc5f189f
[ "filter_list, update_list = parse_and_validate_bulk_update_arguments(filter, update)\nassert filter_list == expected_output[0]\nassert update_list == expected_output[1]", "with pytest.raises(DemistoException) as e:\n parse_and_validate_bulk_update_arguments(filter, update)\n assert error_message in str(e.va...
<|body_start_0|> filter_list, update_list = parse_and_validate_bulk_update_arguments(filter, update) assert filter_list == expected_output[0] assert update_list == expected_output[1] <|end_body_0|> <|body_start_1|> with pytest.raises(DemistoException) as e: parse_and_validat...
Class for bulk_update_query_command UTs.
TestBulkUpdateQueryCommands
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestBulkUpdateQueryCommands: """Class for bulk_update_query_command UTs.""" def test_parse_and_validate_bulk_update_arguments(self, filter, update, expected_output): """Given: valid arguments for bulk update command When: running mongodb-bulk-update command in XSOAR Then: parse_and_v...
stack_v2_sparse_classes_36k_train_010863
17,096
permissive
[ { "docstring": "Given: valid arguments for bulk update command When: running mongodb-bulk-update command in XSOAR Then: parse_and_validate_bulk_update_arguments will parse validate the filter and update arguments", "name": "test_parse_and_validate_bulk_update_arguments", "signature": "def test_parse_and...
3
null
Implement the Python class `TestBulkUpdateQueryCommands` described below. Class description: Class for bulk_update_query_command UTs. Method signatures and docstrings: - def test_parse_and_validate_bulk_update_arguments(self, filter, update, expected_output): Given: valid arguments for bulk update command When: runni...
Implement the Python class `TestBulkUpdateQueryCommands` described below. Class description: Class for bulk_update_query_command UTs. Method signatures and docstrings: - def test_parse_and_validate_bulk_update_arguments(self, filter, update, expected_output): Given: valid arguments for bulk update command When: runni...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestBulkUpdateQueryCommands: """Class for bulk_update_query_command UTs.""" def test_parse_and_validate_bulk_update_arguments(self, filter, update, expected_output): """Given: valid arguments for bulk update command When: running mongodb-bulk-update command in XSOAR Then: parse_and_v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestBulkUpdateQueryCommands: """Class for bulk_update_query_command UTs.""" def test_parse_and_validate_bulk_update_arguments(self, filter, update, expected_output): """Given: valid arguments for bulk update command When: running mongodb-bulk-update command in XSOAR Then: parse_and_validate_bulk_...
the_stack_v2_python_sparse
Packs/MongoDB/Integrations/MongoDB/MongoDB_test.py
demisto/content
train
1,023
3c22ab963880eb2ce67863e8d014ed2fbe898fbd
[ "def middle(nums, left, right):\n if left <= right:\n if nums[left] <= nums[right]:\n min = nums[left]\n else:\n mid = (left + right) // 2\n if nums[mid] < nums[right]:\n min = middle(nums, left, mid)\n else:\n min = middle(n...
<|body_start_0|> def middle(nums, left, right): if left <= right: if nums[left] <= nums[right]: min = nums[left] else: mid = (left + right) // 2 if nums[mid] < nums[right]: min = middl...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMin(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findMin2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> def middle(nums, left, right): if left <...
stack_v2_sparse_classes_36k_train_010864
1,183
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findMin", "signature": "def findMin(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "findMin2", "signature": "def findMin2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_007443
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMin(self, nums): :type nums: List[int] :rtype: int - def findMin2(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMin(self, nums): :type nums: List[int] :rtype: int - def findMin2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def findMin(self, nums...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def findMin(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findMin2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findMin(self, nums): """:type nums: List[int] :rtype: int""" def middle(nums, left, right): if left <= right: if nums[left] <= nums[right]: min = nums[left] else: mid = (left + right) // 2 ...
the_stack_v2_python_sparse
153. Find Minimum in Rotated Sorted Array/findMin.py
Macielyoung/LeetCode
train
1
77be81f485de3cc749b82d5d23332a6b7ee748df
[ "half = (target + 1) // 2\narr = []\nfor i in range(1, half):\n sum = 0\n for j in range(i, half + 1):\n sum += j\n if sum > target:\n break\n elif sum == target:\n subarr = [k for k in range(i, j + 1)]\n arr.append(subarr)\n break\nreturn arr",...
<|body_start_0|> half = (target + 1) // 2 arr = [] for i in range(1, half): sum = 0 for j in range(i, half + 1): sum += j if sum > target: break elif sum == target: subarr = [k for k i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: """执行用时 :432 ms, 在所有 Python3 提交中击败了27.47%的用户 内存消耗 :13.4 MB, 在所有 Python3 提交中击败了100.00%的用户 :param target: :return:""" <|body_0|> def findContinuousSequence2(self, target: int) -> List[List[int]]: ...
stack_v2_sparse_classes_36k_train_010865
4,844
no_license
[ { "docstring": "执行用时 :432 ms, 在所有 Python3 提交中击败了27.47%的用户 内存消耗 :13.4 MB, 在所有 Python3 提交中击败了100.00%的用户 :param target: :return:", "name": "findContinuousSequence", "signature": "def findContinuousSequence(self, target: int) -> List[List[int]]" }, { "docstring": "执行用时 :164 ms, 在所有 Python3 提交中击败了69....
5
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findContinuousSequence(self, target: int) -> List[List[int]]: 执行用时 :432 ms, 在所有 Python3 提交中击败了27.47%的用户 内存消耗 :13.4 MB, 在所有 Python3 提交中击败了100.00%的用户 :param target: :return: - ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findContinuousSequence(self, target: int) -> List[List[int]]: 执行用时 :432 ms, 在所有 Python3 提交中击败了27.47%的用户 内存消耗 :13.4 MB, 在所有 Python3 提交中击败了100.00%的用户 :param target: :return: - ...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: """执行用时 :432 ms, 在所有 Python3 提交中击败了27.47%的用户 内存消耗 :13.4 MB, 在所有 Python3 提交中击败了100.00%的用户 :param target: :return:""" <|body_0|> def findContinuousSequence2(self, target: int) -> List[List[int]]: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: """执行用时 :432 ms, 在所有 Python3 提交中击败了27.47%的用户 内存消耗 :13.4 MB, 在所有 Python3 提交中击败了100.00%的用户 :param target: :return:""" half = (target + 1) // 2 arr = [] for i in range(1, half): sum = 0 ...
the_stack_v2_python_sparse
LeetCode/1543. 和为s的连续正数序列.py
yiming1012/MyLeetCode
train
2
641fc5ccae14d39fcb46af24add83e19271d92d7
[ "self.abbr_dict = dict()\nfor word in dictionary:\n if len(word) < 3:\n abbr = word\n else:\n abbr = word[0] + str(len(word) - 2) + word[-1]\n if abbr not in self.abbr_dict.keys():\n self.abbr_dict[abbr] = set()\n self.abbr_dict[abbr].add(word)", "if len(word) < 3:\n abbr = wor...
<|body_start_0|> self.abbr_dict = dict() for word in dictionary: if len(word) < 3: abbr = word else: abbr = word[0] + str(len(word) - 2) + word[-1] if abbr not in self.abbr_dict.keys(): self.abbr_dict[abbr] = set() ...
ValidWordAbbr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 1) empty abbr_dict, r...
stack_v2_sparse_classes_36k_train_010866
1,314
no_license
[ { "docstring": ":type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": ":type word: str :rtype: bool A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 1) empty abbr_dict, return True for all ...
2
stack_v2_sparse_classes_30k_train_021680
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool A word's abbreviation is unique if no other word fr...
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool A word's abbreviation is unique if no other word fr...
08c6d27498e35f636045fed05a6f94b760ab69ca
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 1) empty abbr_dict, r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" self.abbr_dict = dict() for word in dictionary: if len(word) < 3: abbr = word else: abbr = word[0] + str(len(word) - 2) + word[-1] if abb...
the_stack_v2_python_sparse
solutions/design/288.Unique.Word.Abbreviation.py
ljia2/leetcode.py
train
0
183a03f7f47983f55d47a6675ab8bdf4f518e454
[ "query_ass_field = TestCaseAssField.query.get(ass_field_id)\nif not query_ass_field:\n return api_result(code=400, message='字段断言id:{}数据不存在'.format(ass_field_id))\nreturn api_result(code=200, message='操作成功', data=query_ass_field.to_json())", "data = request.get_json()\nassert_description = data.get('assert_desc...
<|body_start_0|> query_ass_field = TestCaseAssField.query.get(ass_field_id) if not query_ass_field: return api_result(code=400, message='字段断言id:{}数据不存在'.format(ass_field_id)) return api_result(code=200, message='操作成功', data=query_ass_field.to_json()) <|end_body_0|> <|body_start_1|> ...
字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "expect_val_type": "1", "rule": "==" }, { "assert_ke...
FieldAssertionRuleApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FieldAssertionRuleApi: """字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "ex...
stack_v2_sparse_classes_36k_train_010867
17,166
no_license
[ { "docstring": "字段断言明细", "name": "get", "signature": "def get(self, ass_field_id)" }, { "docstring": "字段断言新增", "name": "post", "signature": "def post(self)" }, { "docstring": "字段断言编辑", "name": "put", "signature": "def put(self)" }, { "docstring": "字段断言规则删除", "...
4
null
Implement the Python class `FieldAssertionRuleApi` described below. Class description: 字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "...
Implement the Python class `FieldAssertionRuleApi` described below. Class description: 字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "...
df76812885d7d7f3a5269e3f7c652db6a9f3c3ad
<|skeleton|> class FieldAssertionRuleApi: """字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "ex...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FieldAssertionRuleApi: """字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "expect_val_type...
the_stack_v2_python_sparse
app/api/case_ass_rule_api/case_ass_rule_api.py
chengzizhen/ExileTestPlatformServer
train
0
aac51635317a042b84071a39ee4ac215bcf827a9
[ "serial_port = await AsyncSerial.create(port=port, baud_rate=TC_BAUDRATE, timeout=DEFAULT_TC_TIMEOUT, loop=loop, reset_buffer_before_write=False)\nconnection_temp = SerialConnection(serial=serial_port, port=port, name=port, ack=TC_GEN2_SERIAL_ACK, retry_wait_time_seconds=0.1, error_keyword='error', alarm_keyword='a...
<|body_start_0|> serial_port = await AsyncSerial.create(port=port, baud_rate=TC_BAUDRATE, timeout=DEFAULT_TC_TIMEOUT, loop=loop, reset_buffer_before_write=False) connection_temp = SerialConnection(serial=serial_port, port=port, name=port, ack=TC_GEN2_SERIAL_ACK, retry_wait_time_seconds=0.1, error_keywor...
ThermocyclerDriverFactory
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThermocyclerDriverFactory: async def create(port: str, loop: Optional[asyncio.AbstractEventLoop]) -> ThermocyclerDriver: """Create a thermocycler driver. Args: port: port or url of thermocycler loop: optional event loop Returns: driver""" <|body_0|> async def is_gen2_thermoc...
stack_v2_sparse_classes_36k_train_010868
13,100
permissive
[ { "docstring": "Create a thermocycler driver. Args: port: port or url of thermocycler loop: optional event loop Returns: driver", "name": "create", "signature": "async def create(port: str, loop: Optional[asyncio.AbstractEventLoop]) -> ThermocyclerDriver" }, { "docstring": "Send a message throug...
2
null
Implement the Python class `ThermocyclerDriverFactory` described below. Class description: Implement the ThermocyclerDriverFactory class. Method signatures and docstrings: - async def create(port: str, loop: Optional[asyncio.AbstractEventLoop]) -> ThermocyclerDriver: Create a thermocycler driver. Args: port: port or ...
Implement the Python class `ThermocyclerDriverFactory` described below. Class description: Implement the ThermocyclerDriverFactory class. Method signatures and docstrings: - async def create(port: str, loop: Optional[asyncio.AbstractEventLoop]) -> ThermocyclerDriver: Create a thermocycler driver. Args: port: port or ...
026b523c8c9e5d45910c490efb89194d72595be9
<|skeleton|> class ThermocyclerDriverFactory: async def create(port: str, loop: Optional[asyncio.AbstractEventLoop]) -> ThermocyclerDriver: """Create a thermocycler driver. Args: port: port or url of thermocycler loop: optional event loop Returns: driver""" <|body_0|> async def is_gen2_thermoc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThermocyclerDriverFactory: async def create(port: str, loop: Optional[asyncio.AbstractEventLoop]) -> ThermocyclerDriver: """Create a thermocycler driver. Args: port: port or url of thermocycler loop: optional event loop Returns: driver""" serial_port = await AsyncSerial.create(port=port, baud_...
the_stack_v2_python_sparse
api/src/opentrons/drivers/thermocycler/driver.py
Opentrons/opentrons
train
326
5bc4305db93fbe946c1256c5349b1b73e9954020
[ "day = datetime.timedelta(days=1)\nfor workweek in range(workweeks):\n days = tuple((start + (n + 7 * workweek) * day for n in range(7)))\n hours = tuple((timecard[today].hours for today in days))\n yield self._overtime(hours=hours)\nreturn", "day = datetime.timedelta(days=1)\nfor week in range(workweeks...
<|body_start_0|> day = datetime.timedelta(days=1) for workweek in range(workweeks): days = tuple((start + (n + 7 * workweek) * day for n in range(7))) hours = tuple((timecard[today].hours for today in days)) yield self._overtime(hours=hours) return <|end_body_...
Encapsulation of calculators compliant with California law
California
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class California: """Encapsulation of calculators compliant with California law""" def overtime(self, start, workweeks, timecard): """Classify the hours worked by an employee a given an employee's {timecard}. This calculator assumes that the work week starts on {start}, a {datetime.date} o...
stack_v2_sparse_classes_36k_train_010869
7,691
no_license
[ { "docstring": "Classify the hours worked by an employee a given an employee's {timecard}. This calculator assumes that the work week starts on {start}, a {datetime.date} object, and will clip the calculation to {workweeks} consecutive work weeks.", "name": "overtime", "signature": "def overtime(self, s...
5
stack_v2_sparse_classes_30k_train_011790
Implement the Python class `California` described below. Class description: Encapsulation of calculators compliant with California law Method signatures and docstrings: - def overtime(self, start, workweeks, timecard): Classify the hours worked by an employee a given an employee's {timecard}. This calculator assumes ...
Implement the Python class `California` described below. Class description: Encapsulation of calculators compliant with California law Method signatures and docstrings: - def overtime(self, start, workweeks, timecard): Classify the hours worked by an employee a given an employee's {timecard}. This calculator assumes ...
5b1e846d0dcd80934c8238ab0890b2bbb5126d41
<|skeleton|> class California: """Encapsulation of calculators compliant with California law""" def overtime(self, start, workweeks, timecard): """Classify the hours worked by an employee a given an employee's {timecard}. This calculator assumes that the work week starts on {start}, a {datetime.date} o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class California: """Encapsulation of calculators compliant with California law""" def overtime(self, start, workweeks, timecard): """Classify the hours worked by an employee a given an employee's {timecard}. This calculator assumes that the work week starts on {start}, a {datetime.date} object, and wi...
the_stack_v2_python_sparse
praxis/compliance/us/California.py
Orthologue/praxis
train
0
916150bf5326ec2632b7f2617308ef38fb5d272e
[ "total_sum = sum(arr)\nexpected_sum = (len(arr) + 1) * (len(arr) + 2) // 2\nreturn expected_sum - total_sum", "i, j = (0, len(arr) - 1)\nexpected_sum = arr[i] + arr[j]\nwhile i < j:\n i += 1\n j -= 1\n actual_sum = arr[i] + arr[j]\n if expected_sum > actual_sum:\n return arr[j] + 1\n elif ex...
<|body_start_0|> total_sum = sum(arr) expected_sum = (len(arr) + 1) * (len(arr) + 2) // 2 return expected_sum - total_sum <|end_body_0|> <|body_start_1|> i, j = (0, len(arr) - 1) expected_sum = arr[i] + arr[j] while i < j: i += 1 j -= 1 ...
MissingNumber
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MissingNumber: def get_missing_int_in_sequence(arr: []): """This is a linear solution and it will traverse the array entirely :param arr: Sequence from 1 to N in an array of size N - 1. ARRAY DOES NOT HAVE TO BE SORTED :return: The missing number""" <|body_0|> def get_missin...
stack_v2_sparse_classes_36k_train_010870
1,170
no_license
[ { "docstring": "This is a linear solution and it will traverse the array entirely :param arr: Sequence from 1 to N in an array of size N - 1. ARRAY DOES NOT HAVE TO BE SORTED :return: The missing number", "name": "get_missing_int_in_sequence", "signature": "def get_missing_int_in_sequence(arr: [])" },...
2
stack_v2_sparse_classes_30k_train_002836
Implement the Python class `MissingNumber` described below. Class description: Implement the MissingNumber class. Method signatures and docstrings: - def get_missing_int_in_sequence(arr: []): This is a linear solution and it will traverse the array entirely :param arr: Sequence from 1 to N in an array of size N - 1. ...
Implement the Python class `MissingNumber` described below. Class description: Implement the MissingNumber class. Method signatures and docstrings: - def get_missing_int_in_sequence(arr: []): This is a linear solution and it will traverse the array entirely :param arr: Sequence from 1 to N in an array of size N - 1. ...
638a1312a66805fefb2a1e1dd7b4968d2c957564
<|skeleton|> class MissingNumber: def get_missing_int_in_sequence(arr: []): """This is a linear solution and it will traverse the array entirely :param arr: Sequence from 1 to N in an array of size N - 1. ARRAY DOES NOT HAVE TO BE SORTED :return: The missing number""" <|body_0|> def get_missin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MissingNumber: def get_missing_int_in_sequence(arr: []): """This is a linear solution and it will traverse the array entirely :param arr: Sequence from 1 to N in an array of size N - 1. ARRAY DOES NOT HAVE TO BE SORTED :return: The missing number""" total_sum = sum(arr) expected_sum = ...
the_stack_v2_python_sparse
missing_number.py
wotann07/leetcode_py
train
0
f9faf8d9e35ba63d6993c46c1abaf4a0e42504a7
[ "Parametre.__init__(self, 'lever', 'weigh')\nself.aide_courte = \"lève l'ancre présente\"\nself.aide_longue = \"Cette commande lève l'ancre présente dans la salle où vous vous trouvez. Pour certaines ancres plus lourdes, vous aurez besoin de faire cette manoeuvre à plusieurs. Les autres pourront peser sur le cabest...
<|body_start_0|> Parametre.__init__(self, 'lever', 'weigh') self.aide_courte = "lève l'ancre présente" self.aide_longue = "Cette commande lève l'ancre présente dans la salle où vous vous trouvez. Pour certaines ancres plus lourdes, vous aurez besoin de faire cette manoeuvre à plusieurs. Les autr...
Commande 'ancre lever'.
PrmLever
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmLever: """Commande 'ancre lever'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|> <|body_start_0|> Parametre.__ini...
stack_v2_sparse_classes_36k_train_010871
3,946
permissive
[ { "docstring": "Constructeur du paramètre", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Interprétation du paramètre", "name": "interpreter", "signature": "def interpreter(self, personnage, dic_masques)" } ]
2
null
Implement the Python class `PrmLever` described below. Class description: Commande 'ancre lever'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre
Implement the Python class `PrmLever` described below. Class description: Commande 'ancre lever'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre <|skeleton|> class PrmLever: """Commande 'ancre lever'....
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmLever: """Commande 'ancre lever'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrmLever: """Commande 'ancre lever'.""" def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, 'lever', 'weigh') self.aide_courte = "lève l'ancre présente" self.aide_longue = "Cette commande lève l'ancre présente dans la salle où vous vous trouvez. Po...
the_stack_v2_python_sparse
src/secondaires/navigation/commandes/ancre/lever.py
vincent-lg/tsunami
train
5
967fa7d5a018c7ef5fda86e319dece85d75847a0
[ "self.label = label\nself.action = action\nself.name = name\nself.attributes = attributes", "if not self.action:\n if self.attributes:\n return LI(A(self.label, _href='#', _onclick='javascript:void(0);return false;'), elements, **dict(self.attributes))\n else:\n return LI(A(self.label, _href='...
<|body_start_0|> self.label = label self.action = action self.name = name self.attributes = attributes <|end_body_0|> <|body_start_1|> if not self.action: if self.attributes: return LI(A(self.label, _href='#', _onclick='javascript:void(0);return false...
Menu item
MenuItem
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MenuItem: """Menu item""" def __init__(self, label, action, name='', **attributes): """Item""" <|body_0|> def render(self, elements=''): """Render""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.label = label self.action = action ...
stack_v2_sparse_classes_36k_train_010872
5,102
permissive
[ { "docstring": "Item", "name": "__init__", "signature": "def __init__(self, label, action, name='', **attributes)" }, { "docstring": "Render", "name": "render", "signature": "def render(self, elements='')" } ]
2
stack_v2_sparse_classes_30k_train_009333
Implement the Python class `MenuItem` described below. Class description: Menu item Method signatures and docstrings: - def __init__(self, label, action, name='', **attributes): Item - def render(self, elements=''): Render
Implement the Python class `MenuItem` described below. Class description: Menu item Method signatures and docstrings: - def __init__(self, label, action, name='', **attributes): Item - def render(self, elements=''): Render <|skeleton|> class MenuItem: """Menu item""" def __init__(self, label, action, name='...
11e49db4f8e057d6649dab423e9ead136ffb1df5
<|skeleton|> class MenuItem: """Menu item""" def __init__(self, label, action, name='', **attributes): """Item""" <|body_0|> def render(self, elements=''): """Render""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MenuItem: """Menu item""" def __init__(self, label, action, name='', **attributes): """Item""" self.label = label self.action = action self.name = name self.attributes = attributes def render(self, elements=''): """Render""" if not self.action:...
the_stack_v2_python_sparse
modules/plugins/navigation.py
mycguo/instantpress
train
0
d48d253f2f77ce13b0ae7a988808232d4634e418
[ "args = parse_options()\nplan = args.plan\nblast_cache = args.blast_cache\nself.store = Store.get_instance()\nself.store.initialize(plan, use_cache=False)\ntracks = self.get_unprocessed_tracks(MUSIC_TRACKS, blast_cache)\nself.generate_dnz_files(tracks)", "logging.info('Number of tracks working on: %d', len(tracks...
<|body_start_0|> args = parse_options() plan = args.plan blast_cache = args.blast_cache self.store = Store.get_instance() self.store.initialize(plan, use_cache=False) tracks = self.get_unprocessed_tracks(MUSIC_TRACKS, blast_cache) self.generate_dnz_files(tracks) <...
Generates precached dnz files. A dnz file contains the extracted features and track segmentations for a an audio clip. The generated features and segmentations are specified in plans.
CacheTracks
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CacheTracks: """Generates precached dnz files. A dnz file contains the extracted features and track segmentations for a an audio clip. The generated features and segmentations are specified in plans.""" def __init__(self): """Initialize class""" <|body_0|> def generate_d...
stack_v2_sparse_classes_36k_train_010873
3,287
no_license
[ { "docstring": "Initialize class", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Iterates on tracks while generating the dnz files.", "name": "generate_dnz_files", "signature": "def generate_dnz_files(self, tracks)" }, { "docstring": "Determines what tr...
3
stack_v2_sparse_classes_30k_train_000058
Implement the Python class `CacheTracks` described below. Class description: Generates precached dnz files. A dnz file contains the extracted features and track segmentations for a an audio clip. The generated features and segmentations are specified in plans. Method signatures and docstrings: - def __init__(self): I...
Implement the Python class `CacheTracks` described below. Class description: Generates precached dnz files. A dnz file contains the extracted features and track segmentations for a an audio clip. The generated features and segmentations are specified in plans. Method signatures and docstrings: - def __init__(self): I...
01d06f780db511864b5f9272c7a37146aff54981
<|skeleton|> class CacheTracks: """Generates precached dnz files. A dnz file contains the extracted features and track segmentations for a an audio clip. The generated features and segmentations are specified in plans.""" def __init__(self): """Initialize class""" <|body_0|> def generate_d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CacheTracks: """Generates precached dnz files. A dnz file contains the extracted features and track segmentations for a an audio clip. The generated features and segmentations are specified in plans.""" def __init__(self): """Initialize class""" args = parse_options() plan = args....
the_stack_v2_python_sparse
whirling/run_cache_tracks.py
nate-h/Whirling
train
0
3b4ae1171eb34c1c4be575c33e6a218faa5f9be1
[ "md5_obj = hashlib.md5()\nmd5_obj.update(text.encode('utf-8'))\nreturn md5_obj.hexdigest()", "md5_obj = hashlib.md5()\ntry:\n with open(file, 'rb') as f:\n for data in f:\n md5_obj.update(data)\n return md5_obj.hexdigest()\nexcept FileNotFoundError as e:\n print(e)\n return False...
<|body_start_0|> md5_obj = hashlib.md5() md5_obj.update(text.encode('utf-8')) return md5_obj.hexdigest() <|end_body_0|> <|body_start_1|> md5_obj = hashlib.md5() try: with open(file, 'rb') as f: for data in f: md5_obj.update(data) ...
获取传入对象的md5值
GetMD5
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetMD5: """获取传入对象的md5值""" def get_str_md5(text): """检测md5 :param text: 用户明文 :return: md5""" <|body_0|> def get_file_md5(file): """计算文件的md5 :param file: 文件 :return md5""" <|body_1|> <|end_skeleton|> <|body_start_0|> md5_obj = hashlib.md5() ...
stack_v2_sparse_classes_36k_train_010874
912
no_license
[ { "docstring": "检测md5 :param text: 用户明文 :return: md5", "name": "get_str_md5", "signature": "def get_str_md5(text)" }, { "docstring": "计算文件的md5 :param file: 文件 :return md5", "name": "get_file_md5", "signature": "def get_file_md5(file)" } ]
2
null
Implement the Python class `GetMD5` described below. Class description: 获取传入对象的md5值 Method signatures and docstrings: - def get_str_md5(text): 检测md5 :param text: 用户明文 :return: md5 - def get_file_md5(file): 计算文件的md5 :param file: 文件 :return md5
Implement the Python class `GetMD5` described below. Class description: 获取传入对象的md5值 Method signatures and docstrings: - def get_str_md5(text): 检测md5 :param text: 用户明文 :return: md5 - def get_file_md5(file): 计算文件的md5 :param file: 文件 :return md5 <|skeleton|> class GetMD5: """获取传入对象的md5值""" def get_str_md5(text...
7f984fbfcb7152a055d4bc67ca0a7d64a52ce125
<|skeleton|> class GetMD5: """获取传入对象的md5值""" def get_str_md5(text): """检测md5 :param text: 用户明文 :return: md5""" <|body_0|> def get_file_md5(file): """计算文件的md5 :param file: 文件 :return md5""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetMD5: """获取传入对象的md5值""" def get_str_md5(text): """检测md5 :param text: 用户明文 :return: md5""" md5_obj = hashlib.md5() md5_obj.update(text.encode('utf-8')) return md5_obj.hexdigest() def get_file_md5(file): """计算文件的md5 :param file: 文件 :return md5""" md5_o...
the_stack_v2_python_sparse
luffycity-s8/第三模块_面向对象_网络编程基础/网络编程基础/作业_FTP文件服务器/FTPProject/server/modules/get_md5.py
PAYNE1Z/python-learn
train
2
ab557a96b07a16843ce01d55c38a14c2c13d16d9
[ "self.key = key\nself.value = value\nself.left = self.right = None", "if key < self.key:\n if self.left:\n self.left.insert(key, value)\n else:\n self.left = Tree(key, value)\nelif key > self.key:\n if self.right:\n self.right.insert(key, value)\n else:\n self.right = Tree(...
<|body_start_0|> self.key = key self.value = value self.left = self.right = None <|end_body_0|> <|body_start_1|> if key < self.key: if self.left: self.left.insert(key, value) else: self.left = Tree(key, value) elif key > se...
Tree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tree: def __init__(self, key, value=None): """Create a new Tree object with empty L & R subtrees.""" <|body_0|> def insert(self, key, value=None): """Insert a new element into the tree in th ecorrect position.""" <|body_1|> def walk(self): """Gen...
stack_v2_sparse_classes_36k_train_010875
2,224
no_license
[ { "docstring": "Create a new Tree object with empty L & R subtrees.", "name": "__init__", "signature": "def __init__(self, key, value=None)" }, { "docstring": "Insert a new element into the tree in th ecorrect position.", "name": "insert", "signature": "def insert(self, key, value=None)"...
5
stack_v2_sparse_classes_30k_test_000219
Implement the Python class `Tree` described below. Class description: Implement the Tree class. Method signatures and docstrings: - def __init__(self, key, value=None): Create a new Tree object with empty L & R subtrees. - def insert(self, key, value=None): Insert a new element into the tree in th ecorrect position. ...
Implement the Python class `Tree` described below. Class description: Implement the Tree class. Method signatures and docstrings: - def __init__(self, key, value=None): Create a new Tree object with empty L & R subtrees. - def insert(self, key, value=None): Insert a new element into the tree in th ecorrect position. ...
eff582478058db318e1b9352ce26c5afa8f21231
<|skeleton|> class Tree: def __init__(self, key, value=None): """Create a new Tree object with empty L & R subtrees.""" <|body_0|> def insert(self, key, value=None): """Insert a new element into the tree in th ecorrect position.""" <|body_1|> def walk(self): """Gen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tree: def __init__(self, key, value=None): """Create a new Tree object with empty L & R subtrees.""" self.key = key self.value = value self.left = self.right = None def insert(self, key, value=None): """Insert a new element into the tree in th ecorrect position."""...
the_stack_v2_python_sparse
python/Python4_Homework03/src/tree.py
joelgarzatx/portfolio
train
0
debeaa27111a6225ad88ba7906fb1d229c37b75d
[ "super(ContextWebInformation, self).__init__()\nself.FormDigestValue = form_digest_value\nself.FormDigestTimeoutSeconds = form_digest_timeout_secs\nself.LibraryVersion = None\nself.SiteFullUrl = None\nself.SupportedSchemaVersions = None\nself.WebFullUrl = None\nself._valid_from = time.time()", "if self.FormDigest...
<|body_start_0|> super(ContextWebInformation, self).__init__() self.FormDigestValue = form_digest_value self.FormDigestTimeoutSeconds = form_digest_timeout_secs self.LibraryVersion = None self.SiteFullUrl = None self.SupportedSchemaVersions = None self.WebFullUrl ...
Specifies metadata about a site.
ContextWebInformation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContextWebInformation: """Specifies metadata about a site.""" def __init__(self, form_digest_value=None, form_digest_timeout_secs=None): """:param str form_digest_value: An object that is inserted into a page and is used by a protocol server to validate client requests. The validatio...
stack_v2_sparse_classes_36k_train_010876
1,284
permissive
[ { "docstring": ":param str form_digest_value: An object that is inserted into a page and is used by a protocol server to validate client requests. The validation is specific to a user, site, and time period. :param int form_digest_timeout_secs: Specifies the amount of time in seconds before security validation ...
2
null
Implement the Python class `ContextWebInformation` described below. Class description: Specifies metadata about a site. Method signatures and docstrings: - def __init__(self, form_digest_value=None, form_digest_timeout_secs=None): :param str form_digest_value: An object that is inserted into a page and is used by a p...
Implement the Python class `ContextWebInformation` described below. Class description: Specifies metadata about a site. Method signatures and docstrings: - def __init__(self, form_digest_value=None, form_digest_timeout_secs=None): :param str form_digest_value: An object that is inserted into a page and is used by a p...
cbd245d1af8d69e013c469cfc2a9851f51c91417
<|skeleton|> class ContextWebInformation: """Specifies metadata about a site.""" def __init__(self, form_digest_value=None, form_digest_timeout_secs=None): """:param str form_digest_value: An object that is inserted into a page and is used by a protocol server to validate client requests. The validatio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ContextWebInformation: """Specifies metadata about a site.""" def __init__(self, form_digest_value=None, form_digest_timeout_secs=None): """:param str form_digest_value: An object that is inserted into a page and is used by a protocol server to validate client requests. The validation is specific...
the_stack_v2_python_sparse
office365/sharepoint/webs/context_web_information.py
vgrem/Office365-REST-Python-Client
train
1,006
d1f7da1c864d20309a46c3c507237f868be9a578
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
A set of methods for managing ClickHouse Backup resources.
BackupServiceServicer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BackupServiceServicer: """A set of methods for managing ClickHouse Backup resources.""" def Get(self, request, context): """Returns the specified ClickHouse Backup resource. To get the list of available ClickHouse Backup resources, make a [List] request.""" <|body_0|> de...
stack_v2_sparse_classes_36k_train_010877
5,017
permissive
[ { "docstring": "Returns the specified ClickHouse Backup resource. To get the list of available ClickHouse Backup resources, make a [List] request.", "name": "Get", "signature": "def Get(self, request, context)" }, { "docstring": "Retrieves the list of Backup resources available for the specified...
2
stack_v2_sparse_classes_30k_train_018857
Implement the Python class `BackupServiceServicer` described below. Class description: A set of methods for managing ClickHouse Backup resources. Method signatures and docstrings: - def Get(self, request, context): Returns the specified ClickHouse Backup resource. To get the list of available ClickHouse Backup resour...
Implement the Python class `BackupServiceServicer` described below. Class description: A set of methods for managing ClickHouse Backup resources. Method signatures and docstrings: - def Get(self, request, context): Returns the specified ClickHouse Backup resource. To get the list of available ClickHouse Backup resour...
b906a014dd893e2697864e1e48e814a8d9fbc48c
<|skeleton|> class BackupServiceServicer: """A set of methods for managing ClickHouse Backup resources.""" def Get(self, request, context): """Returns the specified ClickHouse Backup resource. To get the list of available ClickHouse Backup resources, make a [List] request.""" <|body_0|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BackupServiceServicer: """A set of methods for managing ClickHouse Backup resources.""" def Get(self, request, context): """Returns the specified ClickHouse Backup resource. To get the list of available ClickHouse Backup resources, make a [List] request.""" context.set_code(grpc.StatusCod...
the_stack_v2_python_sparse
yandex/cloud/mdb/clickhouse/v1/backup_service_pb2_grpc.py
yandex-cloud/python-sdk
train
63
2c519474c2f910053491c3f70bd195e2cafaf20f
[ "visited = {}\npos = 0\nwhile head is not None:\n if head in visited:\n return head\n visited[head] = pos\n pos += 1\n head = head.next\nreturn None", "fast = slow = head\nwhile fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next.next\n if fast == slow:\n b...
<|body_start_0|> visited = {} pos = 0 while head is not None: if head in visited: return head visited[head] = pos pos += 1 head = head.next return None <|end_body_0|> <|body_start_1|> fast = slow = head whil...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def naive_detectCycle(self, head): """:type head: ListNode :rtype: ListNode O(n) space complexity same as Linked List Cycle I solution""" <|body_0|> def detectCycle(self, head): """:type head: ListNode :rtype: ListNode reference: https://leetcode.com/proble...
stack_v2_sparse_classes_36k_train_010878
1,204
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode O(n) space complexity same as Linked List Cycle I solution", "name": "naive_detectCycle", "signature": "def naive_detectCycle(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode reference: https://leetcode.com/problems/linke...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def naive_detectCycle(self, head): :type head: ListNode :rtype: ListNode O(n) space complexity same as Linked List Cycle I solution - def detectCycle(self, head): :type head: Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def naive_detectCycle(self, head): :type head: ListNode :rtype: ListNode O(n) space complexity same as Linked List Cycle I solution - def detectCycle(self, head): :type head: Lis...
9746205998338fb4d7fd51300a21149c4181fc8f
<|skeleton|> class Solution: def naive_detectCycle(self, head): """:type head: ListNode :rtype: ListNode O(n) space complexity same as Linked List Cycle I solution""" <|body_0|> def detectCycle(self, head): """:type head: ListNode :rtype: ListNode reference: https://leetcode.com/proble...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def naive_detectCycle(self, head): """:type head: ListNode :rtype: ListNode O(n) space complexity same as Linked List Cycle I solution""" visited = {} pos = 0 while head is not None: if head in visited: return head visited[head]...
the_stack_v2_python_sparse
leetcode/linkedList/5_linked_list_cycle2.py
RuizhenMai/academic-blog
train
0
c515a428bc1ef189652f09797d097e2c0c90cae1
[ "auth_org = self.obtain_auth_organization()\nargs = request.args\nq = DatabaseSessionManager.get_session().query(AlgorithmPort)\nif 'result_id' in args:\n q = q.filter(AlgorithmPort.result_id == args['result_id'])\nif 'task_id' in args:\n q = q.join(Result).filter(Result.task_id == args['task_id'])\nif 'run_i...
<|body_start_0|> auth_org = self.obtain_auth_organization() args = request.args q = DatabaseSessionManager.get_session().query(AlgorithmPort) if 'result_id' in args: q = q.filter(AlgorithmPort.result_id == args['result_id']) if 'task_id' in args: q = q.joi...
Ports
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ports: def get(self): """Returns a list of ports --- description: >- Returns a list of all ports only if the node, user or container have the proper authorization to do so. ### Permission Table |Rulename|Scope|Operation|Node|Container|Description| |--|--|--|--|--|--| |Port|Global|View|❌|...
stack_v2_sparse_classes_36k_train_010879
10,984
permissive
[ { "docstring": "Returns a list of ports --- description: >- Returns a list of all ports only if the node, user or container have the proper authorization to do so. ### Permission Table |Rulename|Scope|Operation|Node|Container|Description| |--|--|--|--|--|--| |Port|Global|View|❌|❌|View any result| |Port|Organiza...
3
null
Implement the Python class `Ports` described below. Class description: Implement the Ports class. Method signatures and docstrings: - def get(self): Returns a list of ports --- description: >- Returns a list of all ports only if the node, user or container have the proper authorization to do so. ### Permission Table ...
Implement the Python class `Ports` described below. Class description: Implement the Ports class. Method signatures and docstrings: - def get(self): Returns a list of ports --- description: >- Returns a list of all ports only if the node, user or container have the proper authorization to do so. ### Permission Table ...
3326c51a56e5a6be7c67954aaf65a7d07b07ae74
<|skeleton|> class Ports: def get(self): """Returns a list of ports --- description: >- Returns a list of all ports only if the node, user or container have the proper authorization to do so. ### Permission Table |Rulename|Scope|Operation|Node|Container|Description| |--|--|--|--|--|--| |Port|Global|View|❌|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Ports: def get(self): """Returns a list of ports --- description: >- Returns a list of all ports only if the node, user or container have the proper authorization to do so. ### Permission Table |Rulename|Scope|Operation|Node|Container|Description| |--|--|--|--|--|--| |Port|Global|View|❌|❌|View any res...
the_stack_v2_python_sparse
vantage6/server/resource/port.py
IKNL/vantage6-server
train
2
0d6258b345e401a85be48827f221395fdb052aa8
[ "credentials = super().validate(attrs)\nfunc = getattr(self, credentials.get('way'))\nfunc(**credentials)\nreturn attrs", "try:\n User.objects.get(email=kwargs.pop('email'))\nexcept User.DoesNotExist:\n raise serializers.ValidationError('邮箱不存在')", "try:\n Consumer.consumer_.get(phone=kwargs.pop('phone'...
<|body_start_0|> credentials = super().validate(attrs) func = getattr(self, credentials.get('way')) func(**credentials) return attrs <|end_body_0|> <|body_start_1|> try: User.objects.get(email=kwargs.pop('email')) except User.DoesNotExist: raise s...
找回密码序列化器
RetrieveCodeSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RetrieveCodeSerializer: """找回密码序列化器""" def validate(self, attrs): """在基类验证函数基础在进一步验证""" <|body_0|> def email(self, **kwargs): """验证邮箱""" <|body_1|> def phone(self, **kwargs): """验证手机""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_010880
2,670
permissive
[ { "docstring": "在基类验证函数基础在进一步验证", "name": "validate", "signature": "def validate(self, attrs)" }, { "docstring": "验证邮箱", "name": "email", "signature": "def email(self, **kwargs)" }, { "docstring": "验证手机", "name": "phone", "signature": "def phone(self, **kwargs)" } ]
3
null
Implement the Python class `RetrieveCodeSerializer` described below. Class description: 找回密码序列化器 Method signatures and docstrings: - def validate(self, attrs): 在基类验证函数基础在进一步验证 - def email(self, **kwargs): 验证邮箱 - def phone(self, **kwargs): 验证手机
Implement the Python class `RetrieveCodeSerializer` described below. Class description: 找回密码序列化器 Method signatures and docstrings: - def validate(self, attrs): 在基类验证函数基础在进一步验证 - def email(self, **kwargs): 验证邮箱 - def phone(self, **kwargs): 验证手机 <|skeleton|> class RetrieveCodeSerializer: """找回密码序列化器""" def va...
13cb59130d15e782f78bc5148409bef0f1c516e0
<|skeleton|> class RetrieveCodeSerializer: """找回密码序列化器""" def validate(self, attrs): """在基类验证函数基础在进一步验证""" <|body_0|> def email(self, **kwargs): """验证邮箱""" <|body_1|> def phone(self, **kwargs): """验证手机""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RetrieveCodeSerializer: """找回密码序列化器""" def validate(self, attrs): """在基类验证函数基础在进一步验证""" credentials = super().validate(attrs) func = getattr(self, credentials.get('way')) func(**credentials) return attrs def email(self, **kwargs): """验证邮箱""" tr...
the_stack_v2_python_sparse
user_app/serializers/verification_serializers.py
lmyfzx/Django-Mall
train
0
d156ae6ab06ae81eb473288ceb2de35008fe3310
[ "if not grid or not grid[0]:\n return 0\nm, n = (len(grid), len(grid[0]))\nelapsed = [[float('inf')] * n for _ in range(m)]\n\ndef bfs(i, j, s):\n visited = set()\n queue = deque([(s, i, j)])\n while queue:\n s, i, j = queue.popleft()\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n ...
<|body_start_0|> if not grid or not grid[0]: return 0 m, n = (len(grid), len(grid[0])) elapsed = [[float('inf')] * n for _ in range(m)] def bfs(i, j, s): visited = set() queue = deque([(s, i, j)]) while queue: s, i, j = que...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: """Time complexity: O(n^2) Space complexity: O(n^2)""" <|body_0|> def orangesRotting(self, grid: List[List[int]]) -> int: """Time complexity: O(n^2) Space complexity: O(n^2)""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_010881
3,758
no_license
[ { "docstring": "Time complexity: O(n^2) Space complexity: O(n^2)", "name": "orangesRotting", "signature": "def orangesRotting(self, grid: List[List[int]]) -> int" }, { "docstring": "Time complexity: O(n^2) Space complexity: O(n^2)", "name": "orangesRotting", "signature": "def orangesRott...
2
stack_v2_sparse_classes_30k_train_000735
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def orangesRotting(self, grid: List[List[int]]) -> int: Time complexity: O(n^2) Space complexity: O(n^2) - def orangesRotting(self, grid: List[List[int]]) -> int: Time complexity...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def orangesRotting(self, grid: List[List[int]]) -> int: Time complexity: O(n^2) Space complexity: O(n^2) - def orangesRotting(self, grid: List[List[int]]) -> int: Time complexity...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: """Time complexity: O(n^2) Space complexity: O(n^2)""" <|body_0|> def orangesRotting(self, grid: List[List[int]]) -> int: """Time complexity: O(n^2) Space complexity: O(n^2)""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: """Time complexity: O(n^2) Space complexity: O(n^2)""" if not grid or not grid[0]: return 0 m, n = (len(grid), len(grid[0])) elapsed = [[float('inf')] * n for _ in range(m)] def bfs(i, j, s):...
the_stack_v2_python_sparse
leetcode/solved/1036_Rotting_Oranges/solution.py
sungminoh/algorithms
train
0
42bf79fc2230327592b5fcded5b3b31d27cd5295
[ "if isinstance(key, int):\n return CGAExtension(key)\nif key not in CGAExtension._member_map_:\n return extend_enum(CGAExtension, key, default)\nreturn CGAExtension[key]", "if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 0 <=...
<|body_start_0|> if isinstance(key, int): return CGAExtension(key) if key not in CGAExtension._member_map_: return extend_enum(CGAExtension, key, default) return CGAExtension[key] <|end_body_0|> <|body_start_1|> if not (isinstance(value, int) and 0 <= value <= 65...
[CGAExtension] CGA Extension Type Values
CGAExtension
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CGAExtension: """[CGAExtension] CGA Extension Type Values""" def get(key: 'int | str', default: 'int'=-1) -> 'CGAExtension': """Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""" <|body_0|> def _mi...
stack_v2_sparse_classes_36k_train_010882
2,041
permissive
[ { "docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:", "name": "get", "signature": "def get(key: 'int | str', default: 'int'=-1) -> 'CGAExtension'" }, { "docstring": "Lookup function used when value is not found...
2
null
Implement the Python class `CGAExtension` described below. Class description: [CGAExtension] CGA Extension Type Values Method signatures and docstrings: - def get(key: 'int | str', default: 'int'=-1) -> 'CGAExtension': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not...
Implement the Python class `CGAExtension` described below. Class description: [CGAExtension] CGA Extension Type Values Method signatures and docstrings: - def get(key: 'int | str', default: 'int'=-1) -> 'CGAExtension': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not...
a6fe49ec58f09e105bec5a00fb66d9b3f22730d9
<|skeleton|> class CGAExtension: """[CGAExtension] CGA Extension Type Values""" def get(key: 'int | str', default: 'int'=-1) -> 'CGAExtension': """Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""" <|body_0|> def _mi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CGAExtension: """[CGAExtension] CGA Extension Type Values""" def get(key: 'int | str', default: 'int'=-1) -> 'CGAExtension': """Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""" if isinstance(key, int): ...
the_stack_v2_python_sparse
pcapkit/const/mh/cga_extension.py
JarryShaw/PyPCAPKit
train
204
5159c412f7c30d9092558bdee9c06cbfcf490bf0
[ "self.file = file\nself.skip = skip\nself.size = size\nself.dtype = dtype\nself.scale = scale\nself.maxsize = maxsize", "f = FTFile(self.file, scale=self.scale, dtype=self.dtype)\nif self.skip != 0:\n f.skip(self.skip)\nif self.size is not None and self.size < f.size:\n if self.size < 0:\n f.size += ...
<|body_start_0|> self.file = file self.skip = skip self.size = size self.dtype = dtype self.scale = scale self.maxsize = maxsize <|end_body_0|> <|body_start_1|> f = FTFile(self.file, scale=self.scale, dtype=self.dtype) if self.skip != 0: f.ski...
FTSource
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FTSource: def __init__(self, file, skip=0, size=None, maxsize=None, dtype=None, scale=1): """Create a data source from a possible subset of a .ft file. Parameters: `file` -- (string) the filename `skip` -- (int, optional) amount of examples to skip from the start of the file. If negative...
stack_v2_sparse_classes_36k_train_010883
9,679
permissive
[ { "docstring": "Create a data source from a possible subset of a .ft file. Parameters: `file` -- (string) the filename `skip` -- (int, optional) amount of examples to skip from the start of the file. If negative, skips filesize - skip. `size` -- (int, optional) truncates number of examples read (after skipping)...
2
stack_v2_sparse_classes_30k_test_000958
Implement the Python class `FTSource` described below. Class description: Implement the FTSource class. Method signatures and docstrings: - def __init__(self, file, skip=0, size=None, maxsize=None, dtype=None, scale=1): Create a data source from a possible subset of a .ft file. Parameters: `file` -- (string) the file...
Implement the Python class `FTSource` described below. Class description: Implement the FTSource class. Method signatures and docstrings: - def __init__(self, file, skip=0, size=None, maxsize=None, dtype=None, scale=1): Create a data source from a possible subset of a .ft file. Parameters: `file` -- (string) the file...
7881458caaf2f5ab82b130ee50cb933cf12f6de7
<|skeleton|> class FTSource: def __init__(self, file, skip=0, size=None, maxsize=None, dtype=None, scale=1): """Create a data source from a possible subset of a .ft file. Parameters: `file` -- (string) the filename `skip` -- (int, optional) amount of examples to skip from the start of the file. If negative...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FTSource: def __init__(self, file, skip=0, size=None, maxsize=None, dtype=None, scale=1): """Create a data source from a possible subset of a .ft file. Parameters: `file` -- (string) the filename `skip` -- (int, optional) amount of examples to skip from the start of the file. If negative, skips filesi...
the_stack_v2_python_sparse
datasets/ift6266/datasets/ftfile.py
sauravbiswasiupr/image_transformations
train
0
b62173335183be65b5f41cc1779a5b84b3e2cbfb
[ "super(DQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=...
<|body_start_0|> super(DQN, self).__init__() obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape)) if head_hidden_size is None: head_hidden_size = encoder_hidden_size_list[-1] if isinstance(obs_shape, int) or len(obs_shape) == 1: self.encoder = FCE...
DQN
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DQN: def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optio...
stack_v2_sparse_classes_36k_train_010884
30,380
permissive
[ { "docstring": "Overview: Init the DQN (encoder + head) Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation space shape, such as 8 or [4, 84, 84]. - action_shape (:obj:`Union[int, SequenceType]`): Action space shape, such as 6 or [2, 3, 3]. - encoder_hidden_...
2
stack_v2_sparse_classes_30k_val_000077
Implement the Python class `DQN` described below. Class description: Implement the DQN class. Method signatures and docstrings: - def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size:...
Implement the Python class `DQN` described below. Class description: Implement the DQN class. Method signatures and docstrings: - def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size:...
eb483fa6e46602d58c8e7d2ca1e566adca28e703
<|skeleton|> class DQN: def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DQN: def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None)...
the_stack_v2_python_sparse
ding/model/template/q_learning.py
shengxuesun/DI-engine
train
1
9fc574cd2bcd0ed77d40f2ef591d673fd1b7b331
[ "tot = 0.0\nprop_val = self.property_id.ground_rent or 0.0\nfor pro_record in self:\n if pro_record.multi_prop:\n for prope_ids in pro_record.prop_ids:\n tot += prope_ids.ground\n pro_record.rent = tot + prop_val\n else:\n pro_record.rent = prop_val", "res = super(AccountAnal...
<|body_start_0|> tot = 0.0 prop_val = self.property_id.ground_rent or 0.0 for pro_record in self: if pro_record.multi_prop: for prope_ids in pro_record.prop_ids: tot += prope_ids.ground pro_record.rent = tot + prop_val e...
AccountAnalyticAccount
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountAnalyticAccount: def _total_prop_rent(self): """This method calculate total rent of all the selected property. @param self: The object pointer""" <|body_0|> def create(self, vals): """This Method is used to overrides orm create method, to change state and tena...
stack_v2_sparse_classes_36k_train_010885
5,593
no_license
[ { "docstring": "This method calculate total rent of all the selected property. @param self: The object pointer", "name": "_total_prop_rent", "signature": "def _total_prop_rent(self)" }, { "docstring": "This Method is used to overrides orm create method, to change state and tenant of related prop...
5
stack_v2_sparse_classes_30k_train_000354
Implement the Python class `AccountAnalyticAccount` described below. Class description: Implement the AccountAnalyticAccount class. Method signatures and docstrings: - def _total_prop_rent(self): This method calculate total rent of all the selected property. @param self: The object pointer - def create(self, vals): T...
Implement the Python class `AccountAnalyticAccount` described below. Class description: Implement the AccountAnalyticAccount class. Method signatures and docstrings: - def _total_prop_rent(self): This method calculate total rent of all the selected property. @param self: The object pointer - def create(self, vals): T...
163136f382faa8607db8fb6cda42a5ba07c4076b
<|skeleton|> class AccountAnalyticAccount: def _total_prop_rent(self): """This method calculate total rent of all the selected property. @param self: The object pointer""" <|body_0|> def create(self, vals): """This Method is used to overrides orm create method, to change state and tena...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountAnalyticAccount: def _total_prop_rent(self): """This method calculate total rent of all the selected property. @param self: The object pointer""" tot = 0.0 prop_val = self.property_id.ground_rent or 0.0 for pro_record in self: if pro_record.multi_prop: ...
the_stack_v2_python_sparse
multiple_property_rent_ee/models/multiple_property_rent.py
maarejsys/Roya
train
0
57826a9cc561ed5faa2e2148c12393c31903e184
[ "real_k = k % len(nums)\ntarget = nums[-real_k:] + nums[:-real_k]\nnums[:] = target", "real_k = k % len(nums)\ni = 0\nwhile i != real_k:\n nums.insert(0, nums.pop())\n i += 1" ]
<|body_start_0|> real_k = k % len(nums) target = nums[-real_k:] + nums[:-real_k] nums[:] = target <|end_body_0|> <|body_start_1|> real_k = k % len(nums) i = 0 while i != real_k: nums.insert(0, nums.pop()) i += 1 <|end_body_1|>
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate_pop(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modif...
stack_v2_sparse_classes_36k_train_010886
1,443
permissive
[ { "docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.", "name": "rotate", "signature": "def rotate(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. - def rotate_pop(self, nums, k): :type nums: List...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. - def rotate_pop(self, nums, k): :type nums: List...
143422321cbc3715ca08f6c3af8f960a55887ced
<|skeleton|> class Solution: def rotate(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate_pop(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modif...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotate(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.""" real_k = k % len(nums) target = nums[-real_k:] + nums[:-real_k] nums[:] = target def rotate_pop(self, nums, k): """:type...
the_stack_v2_python_sparse
LeetCode/LC189_rotate_array.py
jxie0755/Learning_Python
train
0
971b033fc41126b850d323387751a1624d6e78e1
[ "app.config.setdefault('SQLALCHEMY_DATABASE_URI', app.config.get('CLASSIC_DATABASE_URI', 'sqlite://'))\napp.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False)\nsuper(ClassicSQLAlchemy, self).init_app(app)", "super(ClassicSQLAlchemy, self).apply_pool_defaults(app, options)\nif app.config['SQLALCHEMY_DATABA...
<|body_start_0|> app.config.setdefault('SQLALCHEMY_DATABASE_URI', app.config.get('CLASSIC_DATABASE_URI', 'sqlite://')) app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False) super(ClassicSQLAlchemy, self).init_app(app) <|end_body_0|> <|body_start_1|> super(ClassicSQLAlchemy, sel...
SQLAlchemy integration for the classic database.
ClassicSQLAlchemy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassicSQLAlchemy: """SQLAlchemy integration for the classic database.""" def init_app(self, app: Flask) -> None: """Set default configuration.""" <|body_0|> def apply_pool_defaults(self, app: Flask, options: Any) -> None: """Set options for create_engine().""" ...
stack_v2_sparse_classes_36k_train_010887
3,561
permissive
[ { "docstring": "Set default configuration.", "name": "init_app", "signature": "def init_app(self, app: Flask) -> None" }, { "docstring": "Set options for create_engine().", "name": "apply_pool_defaults", "signature": "def apply_pool_defaults(self, app: Flask, options: Any) -> None" } ]
2
stack_v2_sparse_classes_30k_train_005193
Implement the Python class `ClassicSQLAlchemy` described below. Class description: SQLAlchemy integration for the classic database. Method signatures and docstrings: - def init_app(self, app: Flask) -> None: Set default configuration. - def apply_pool_defaults(self, app: Flask, options: Any) -> None: Set options for ...
Implement the Python class `ClassicSQLAlchemy` described below. Class description: SQLAlchemy integration for the classic database. Method signatures and docstrings: - def init_app(self, app: Flask) -> None: Set default configuration. - def apply_pool_defaults(self, app: Flask, options: Any) -> None: Set options for ...
6077ce4e0685d67ce7010800083a898857158112
<|skeleton|> class ClassicSQLAlchemy: """SQLAlchemy integration for the classic database.""" def init_app(self, app: Flask) -> None: """Set default configuration.""" <|body_0|> def apply_pool_defaults(self, app: Flask, options: Any) -> None: """Set options for create_engine().""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassicSQLAlchemy: """SQLAlchemy integration for the classic database.""" def init_app(self, app: Flask) -> None: """Set default configuration.""" app.config.setdefault('SQLALCHEMY_DATABASE_URI', app.config.get('CLASSIC_DATABASE_URI', 'sqlite://')) app.config.setdefault('SQLALCHEM...
the_stack_v2_python_sparse
core/arxiv/submission/services/classic/util.py
arXiv/arxiv-submission-core
train
14
a34688e0aee1b7a00f6b9df4d8b5151ef9f3009c
[ "usr = kwargs.pop('usr') if 'usr' in kwargs.keys() else None\nsuper(EnterSingleMatchResultForm, self).__init__(*args, **kwargs)\nqueryset = PlayerProfile.get_players().exclude(id=usr.id) if usr else PlayerProfile.get_players()\nself.fields.insert(0, 'opponent', forms.ModelChoiceField(queryset=queryset))", "sets =...
<|body_start_0|> usr = kwargs.pop('usr') if 'usr' in kwargs.keys() else None super(EnterSingleMatchResultForm, self).__init__(*args, **kwargs) queryset = PlayerProfile.get_players().exclude(id=usr.id) if usr else PlayerProfile.get_players() self.fields.insert(0, 'opponent', forms.ModelCh...
A form to enter the result of a singles match.-
EnterSingleMatchResultForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnterSingleMatchResultForm: """A form to enter the result of a singles match.-""" def __init__(self, *args, **kwargs): """Custom constructor to create an opponent list, excluding user currently logged-in.-""" <|body_0|> def clean(self): """Makes sure the score en...
stack_v2_sparse_classes_36k_train_010888
2,250
no_license
[ { "docstring": "Custom constructor to create an opponent list, excluding user currently logged-in.-", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Makes sure the score entered fits the match type.-", "name": "clean", "signature": "def clean(se...
2
stack_v2_sparse_classes_30k_train_009698
Implement the Python class `EnterSingleMatchResultForm` described below. Class description: A form to enter the result of a singles match.- Method signatures and docstrings: - def __init__(self, *args, **kwargs): Custom constructor to create an opponent list, excluding user currently logged-in.- - def clean(self): Ma...
Implement the Python class `EnterSingleMatchResultForm` described below. Class description: A form to enter the result of a singles match.- Method signatures and docstrings: - def __init__(self, *args, **kwargs): Custom constructor to create an opponent list, excluding user currently logged-in.- - def clean(self): Ma...
4d26e2cf1557d49a91d76dad196b89f9d933a012
<|skeleton|> class EnterSingleMatchResultForm: """A form to enter the result of a singles match.-""" def __init__(self, *args, **kwargs): """Custom constructor to create an opponent list, excluding user currently logged-in.-""" <|body_0|> def clean(self): """Makes sure the score en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnterSingleMatchResultForm: """A form to enter the result of a singles match.-""" def __init__(self, *args, **kwargs): """Custom constructor to create an opponent list, excluding user currently logged-in.-""" usr = kwargs.pop('usr') if 'usr' in kwargs.keys() else None super(EnterS...
the_stack_v2_python_sparse
ranking/forms.py
lichinka/ht
train
0
b4fda558822cc419a4d413835f130c796d1e9bbb
[ "fy_range = [str(i) for i in range(2001, FiscalDateTime.today().year + 1)]\nlast_fy = str(SubmissionAttributes.latest_available_fy()) or str(FiscalDateTime.today().year)\nrequest_settings = [{'key': 'sort', 'name': 'sort', 'type': 'object', 'optional': True, 'object_keys': {'field': {'type': 'enum', 'enum_values': ...
<|body_start_0|> fy_range = [str(i) for i in range(2001, FiscalDateTime.today().year + 1)] last_fy = str(SubmissionAttributes.latest_available_fy()) or str(FiscalDateTime.today().year) request_settings = [{'key': 'sort', 'name': 'sort', 'type': 'object', 'optional': True, 'object_keys': {'field'...
This route sends a request to the backend to retrieve a list of federal accounts.
FederalAccountsViewSet
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FederalAccountsViewSet: """This route sends a request to the backend to retrieve a list of federal accounts.""" def _parse_and_validate_request(self, request_dict): """Validate the Request object includes the required fields""" <|body_0|> def post(self, request, format=N...
stack_v2_sparse_classes_36k_train_010889
32,271
permissive
[ { "docstring": "Validate the Request object includes the required fields", "name": "_parse_and_validate_request", "signature": "def _parse_and_validate_request(self, request_dict)" }, { "docstring": "Return all high-level Federal Account information", "name": "post", "signature": "def po...
2
stack_v2_sparse_classes_30k_train_003766
Implement the Python class `FederalAccountsViewSet` described below. Class description: This route sends a request to the backend to retrieve a list of federal accounts. Method signatures and docstrings: - def _parse_and_validate_request(self, request_dict): Validate the Request object includes the required fields - ...
Implement the Python class `FederalAccountsViewSet` described below. Class description: This route sends a request to the backend to retrieve a list of federal accounts. Method signatures and docstrings: - def _parse_and_validate_request(self, request_dict): Validate the Request object includes the required fields - ...
38f920438697930ae3ac57bbcaae9034877d8fb7
<|skeleton|> class FederalAccountsViewSet: """This route sends a request to the backend to retrieve a list of federal accounts.""" def _parse_and_validate_request(self, request_dict): """Validate the Request object includes the required fields""" <|body_0|> def post(self, request, format=N...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FederalAccountsViewSet: """This route sends a request to the backend to retrieve a list of federal accounts.""" def _parse_and_validate_request(self, request_dict): """Validate the Request object includes the required fields""" fy_range = [str(i) for i in range(2001, FiscalDateTime.today(...
the_stack_v2_python_sparse
usaspending_api/accounts/views/federal_accounts_v2.py
fedspendingtransparency/usaspending-api
train
276
772d74272b5022a2931e54909e8f35b161b241d6
[ "assert len(population) > 0\nself._data = list()\nself._index = dict()\nself._total = float(sum(population.values()))\noffset = 0\nfor value in population:\n weight = population[value]\n if weight < 0:\n raise ValueError('weights must be >= 0')\n self._index[value] = len(self._data)\n self._data....
<|body_start_0|> assert len(population) > 0 self._data = list() self._index = dict() self._total = float(sum(population.values())) offset = 0 for value in population: weight = population[value] if weight < 0: raise ValueError('weigh...
Returns random elements with a probability proportional to the frequency distribution of each element in the population in O(log(N)) time. Uses N space but weight updates are proportional to O(N) time.
ArrayGenerator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArrayGenerator: """Returns random elements with a probability proportional to the frequency distribution of each element in the population in O(log(N)) time. Uses N space but weight updates are proportional to O(N) time.""" def __init__(self, population): """:type population: Dict[T,...
stack_v2_sparse_classes_36k_train_010890
4,393
permissive
[ { "docstring": ":type population: Dict[T, double]", "name": "__init__", "signature": "def __init__(self, population)" }, { "docstring": "Returns an element from the original population with probability proportional to its relative frequency. O(log(N)) time. :rtype: T", "name": "random", ...
3
stack_v2_sparse_classes_30k_train_009486
Implement the Python class `ArrayGenerator` described below. Class description: Returns random elements with a probability proportional to the frequency distribution of each element in the population in O(log(N)) time. Uses N space but weight updates are proportional to O(N) time. Method signatures and docstrings: - ...
Implement the Python class `ArrayGenerator` described below. Class description: Returns random elements with a probability proportional to the frequency distribution of each element in the population in O(log(N)) time. Uses N space but weight updates are proportional to O(N) time. Method signatures and docstrings: - ...
0e46cbaa3f2826b6ff9d4ebd150b5e2330e66859
<|skeleton|> class ArrayGenerator: """Returns random elements with a probability proportional to the frequency distribution of each element in the population in O(log(N)) time. Uses N space but weight updates are proportional to O(N) time.""" def __init__(self, population): """:type population: Dict[T,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArrayGenerator: """Returns random elements with a probability proportional to the frequency distribution of each element in the population in O(log(N)) time. Uses N space but weight updates are proportional to O(N) time.""" def __init__(self, population): """:type population: Dict[T, double]""" ...
the_stack_v2_python_sparse
geeks-for-geeks/mathematics/weighted-random-generator/generators.py
i7sharath/algorithms-1
train
0
691c146a0e2ec2407c4c43190e3b0a7182e530da
[ "bit = 0\ntitle = []\nwhile n > 0:\n n = n - 26 ** bit\n remain = n % 26 ** (bit + 1)\n title.append(str(chr(remain // 26 ** bit + 65)))\n n = n - remain\n bit += 1\nreturn ''.join(reversed(title))", "length = len(s)\nnum = 0\nfor i in range(length):\n num += (ord(s[length - i - 1]) - 64) * 26 *...
<|body_start_0|> bit = 0 title = [] while n > 0: n = n - 26 ** bit remain = n % 26 ** (bit + 1) title.append(str(chr(remain // 26 ** bit + 65))) n = n - remain bit += 1 return ''.join(reversed(title)) <|end_body_0|> <|body_star...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def convertToTitle(self, n): """:type n: int :rtype: str""" <|body_0|> def titleToNumber(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> bit = 0 title = [] while n > 0: n = ...
stack_v2_sparse_classes_36k_train_010891
705
no_license
[ { "docstring": ":type n: int :rtype: str", "name": "convertToTitle", "signature": "def convertToTitle(self, n)" }, { "docstring": ":type s: str :rtype: int", "name": "titleToNumber", "signature": "def titleToNumber(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def convertToTitle(self, n): :type n: int :rtype: str - def titleToNumber(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def convertToTitle(self, n): :type n: int :rtype: str - def titleToNumber(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def convertToTitle(self, n): ...
0584b86642dff667f5bf6b7acfbbce86a41a55b6
<|skeleton|> class Solution: def convertToTitle(self, n): """:type n: int :rtype: str""" <|body_0|> def titleToNumber(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def convertToTitle(self, n): """:type n: int :rtype: str""" bit = 0 title = [] while n > 0: n = n - 26 ** bit remain = n % 26 ** (bit + 1) title.append(str(chr(remain // 26 ** bit + 65))) n = n - remain bit +...
the_stack_v2_python_sparse
python_solution/161_170/ExcelSheetColumnTitle.py
CescWang1991/LeetCode-Python
train
1
00ab07a35f527a9d368e13d8eca64a87ce80570a
[ "self.device = device_claim(device)\nself.resources_path = resources_path\nself.model_type = model_type\nself.model_name = model_name\nself.scheduler_type = scheduler_type\nself.prompt = prompt\nself.auth_token = auth_token\nself.load_model()", "try:\n model_class = MODEL_TYPES[self.model_type]\nexcept KeyErro...
<|body_start_0|> self.device = device_claim(device) self.resources_path = resources_path self.model_type = model_type self.model_name = model_name self.scheduler_type = scheduler_type self.prompt = prompt self.auth_token = auth_token self.load_model() <|en...
Implementation of a generator.
Generator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: """Implementation of a generator.""" def __init__(self, resources_path: str, model_type: str, model_name: str, scheduler_type: str, auth_token: bool=True, prompt: Optional[Union[str, Dict[str, Any]]]=None, device: Optional[Union[torch.device, str]]=None): """A Diffusers ge...
stack_v2_sparse_classes_36k_train_010892
5,391
permissive
[ { "docstring": "A Diffusers generation algorithm. Args: resources_path: path to the cache. model_type: type of the model. model_name: name of the model weights/version. scheduler_type: type of the schedule. auth_token: authentication token for private models. prompt: target for conditional generation. device: d...
3
stack_v2_sparse_classes_30k_train_001901
Implement the Python class `Generator` described below. Class description: Implementation of a generator. Method signatures and docstrings: - def __init__(self, resources_path: str, model_type: str, model_name: str, scheduler_type: str, auth_token: bool=True, prompt: Optional[Union[str, Dict[str, Any]]]=None, device:...
Implement the Python class `Generator` described below. Class description: Implementation of a generator. Method signatures and docstrings: - def __init__(self, resources_path: str, model_type: str, model_name: str, scheduler_type: str, auth_token: bool=True, prompt: Optional[Union[str, Dict[str, Any]]]=None, device:...
0b69b7d5b261f2f9af3984793c1295b9b80cd01a
<|skeleton|> class Generator: """Implementation of a generator.""" def __init__(self, resources_path: str, model_type: str, model_name: str, scheduler_type: str, auth_token: bool=True, prompt: Optional[Union[str, Dict[str, Any]]]=None, device: Optional[Union[torch.device, str]]=None): """A Diffusers ge...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: """Implementation of a generator.""" def __init__(self, resources_path: str, model_type: str, model_name: str, scheduler_type: str, auth_token: bool=True, prompt: Optional[Union[str, Dict[str, Any]]]=None, device: Optional[Union[torch.device, str]]=None): """A Diffusers generation algo...
the_stack_v2_python_sparse
src/gt4sd/algorithms/generation/diffusion/implementation.py
GT4SD/gt4sd-core
train
239
d0ea87c9c30a5f1d183d4fb95e618a2e684300c7
[ "reasoner = GdlChainingReasoner.create(model)\nsentencesByForm = reasoner.getConstantSentences()\naddSentencesTrueByRulesDifferentially(sentencesByForm, model, reasoner)\nreturn ImmutableConstantChecker.create(model, Multimaps.filterKeys(sentencesByForm.getSentences(), Predicates.in_(model.getConstantSentenceForms(...
<|body_start_0|> reasoner = GdlChainingReasoner.create(model) sentencesByForm = reasoner.getConstantSentences() addSentencesTrueByRulesDifferentially(sentencesByForm, model, reasoner) return ImmutableConstantChecker.create(model, Multimaps.filterKeys(sentencesByForm.getSentences(), Predi...
generated source for class ConstantCheckerFactory
ConstantCheckerFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConstantCheckerFactory: """generated source for class ConstantCheckerFactory""" def createWithForwardChaining(cls, model): """generated source for method createWithForwardChaining""" <|body_0|> def addSentencesTrueByRulesDifferentially(cls, sentencesByForm, domainModel, ...
stack_v2_sparse_classes_36k_train_010893
5,719
permissive
[ { "docstring": "generated source for method createWithForwardChaining", "name": "createWithForwardChaining", "signature": "def createWithForwardChaining(cls, model)" }, { "docstring": "generated source for method addSentencesTrueByRulesDifferentially", "name": "addSentencesTrueByRulesDiffere...
5
null
Implement the Python class `ConstantCheckerFactory` described below. Class description: generated source for class ConstantCheckerFactory Method signatures and docstrings: - def createWithForwardChaining(cls, model): generated source for method createWithForwardChaining - def addSentencesTrueByRulesDifferentially(cls...
Implement the Python class `ConstantCheckerFactory` described below. Class description: generated source for class ConstantCheckerFactory Method signatures and docstrings: - def createWithForwardChaining(cls, model): generated source for method createWithForwardChaining - def addSentencesTrueByRulesDifferentially(cls...
4e6e6e876c3a4294cd711647051da2d9c1836b60
<|skeleton|> class ConstantCheckerFactory: """generated source for class ConstantCheckerFactory""" def createWithForwardChaining(cls, model): """generated source for method createWithForwardChaining""" <|body_0|> def addSentencesTrueByRulesDifferentially(cls, sentencesByForm, domainModel, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConstantCheckerFactory: """generated source for class ConstantCheckerFactory""" def createWithForwardChaining(cls, model): """generated source for method createWithForwardChaining""" reasoner = GdlChainingReasoner.create(model) sentencesByForm = reasoner.getConstantSentences() ...
the_stack_v2_python_sparse
ggpy/cruft/autocode/ConstantCheckerFactory.py
hobson/ggpy
train
1
4bd765bef7cdfedf4bc21fead1433035f0f114ae
[ "n = len(nums)\nk = k % n\nnums[:] = nums[n - k:] + nums[:n - k]", "d = deque(nums)\nd.rotate(k)\nnums[:] = list(d)" ]
<|body_start_0|> n = len(nums) k = k % n nums[:] = nums[n - k:] + nums[:n - k] <|end_body_0|> <|body_start_1|> d = deque(nums) d.rotate(k) nums[:] = list(d) <|end_body_1|>
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, nums: List[int], k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate2(self, nums: List[int], k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> <|e...
stack_v2_sparse_classes_36k_train_010894
653
no_license
[ { "docstring": "Do not return anything, modify nums in-place instead.", "name": "rotate", "signature": "def rotate(self, nums: List[int], k: int) -> None" }, { "docstring": "Do not return anything, modify nums in-place instead.", "name": "rotate2", "signature": "def rotate2(self, nums: L...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead. - def rotate2(self, nums: List[int], k: int) -> None: Do not return anyth...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead. - def rotate2(self, nums: List[int], k: int) -> None: Do not return anyth...
07b652843da19f0d5beffe8a861071f7b599779b
<|skeleton|> class Solution: def rotate(self, nums: List[int], k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate2(self, nums: List[int], k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> <|e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotate(self, nums: List[int], k: int) -> None: """Do not return anything, modify nums in-place instead.""" n = len(nums) k = k % n nums[:] = nums[n - k:] + nums[:n - k] def rotate2(self, nums: List[int], k: int) -> None: """Do not return anything, mod...
the_stack_v2_python_sparse
coding_challenges/arrays/rotate_array.py
Harishkumar18/data_structures
train
1
9a29e20784fc11b0406c70e2b9f8072e177a099a
[ "Validation.string(config_file, 'The configuration file name must be a string')\nValidation.file_exist(config_file, 'The provided configuration file does not exist')\nself.config = ConfigParser.ConfigParser()\nself.config.read(config_file)\nfor section in sections:\n setattr(self, section, ConfigurationFile._con...
<|body_start_0|> Validation.string(config_file, 'The configuration file name must be a string') Validation.file_exist(config_file, 'The provided configuration file does not exist') self.config = ConfigParser.ConfigParser() self.config.read(config_file) for section in sections: ...
Used to extract data from the configuration file
ConfigurationFile
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigurationFile: """Used to extract data from the configuration file""" def __init__(self, sections, config_file='conf.cfg'): """Reads configuration file sections :param sections: list of strings representing the sections to be loaded :param config_file: name of the configuration f...
stack_v2_sparse_classes_36k_train_010895
17,407
permissive
[ { "docstring": "Reads configuration file sections :param sections: list of strings representing the sections to be loaded :param config_file: name of the configuration file (string) :return: None", "name": "__init__", "signature": "def __init__(self, sections, config_file='conf.cfg')" }, { "docs...
4
stack_v2_sparse_classes_30k_train_012003
Implement the Python class `ConfigurationFile` described below. Class description: Used to extract data from the configuration file Method signatures and docstrings: - def __init__(self, sections, config_file='conf.cfg'): Reads configuration file sections :param sections: list of strings representing the sections to ...
Implement the Python class `ConfigurationFile` described below. Class description: Used to extract data from the configuration file Method signatures and docstrings: - def __init__(self, sections, config_file='conf.cfg'): Reads configuration file sections :param sections: list of strings representing the sections to ...
3015df47b04923a4acafc56a2f372fd13b2cdf4e
<|skeleton|> class ConfigurationFile: """Used to extract data from the configuration file""" def __init__(self, sections, config_file='conf.cfg'): """Reads configuration file sections :param sections: list of strings representing the sections to be loaded :param config_file: name of the configuration f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigurationFile: """Used to extract data from the configuration file""" def __init__(self, sections, config_file='conf.cfg'): """Reads configuration file sections :param sections: list of strings representing the sections to be loaded :param config_file: name of the configuration file (string) ...
the_stack_v2_python_sparse
analytics_engine/utilities/misc.py
mF2C/analytics_engine
train
0
5e6876098f4556deac902dc7091f05d57eb56c74
[ "if data is None:\n if n <= 0:\n raise ValueError('n must be a positive value')\n elif p >= 1 or p <= 0:\n raise ValueError('p must be greater than 0 and less than 1')\n else:\n self.n = int(n)\n self.p = float(p)\nelif type(data) is not list:\n raise TypeError('data must be ...
<|body_start_0|> if data is None: if n <= 0: raise ValueError('n must be a positive value') elif p >= 1 or p <= 0: raise ValueError('p must be greater than 0 and less than 1') else: self.n = int(n) self.p = float...
Binomial class. It defines binomial distribution.
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """Binomial class. It defines binomial distribution.""" def __init__(self, data=None, n=1, p=0.5): """Initializes the data.""" <|body_0|> def pmf(self, k): """Calculates the value of the PMF.""" <|body_1|> def cdf(self, k): """Calcu...
stack_v2_sparse_classes_36k_train_010896
2,015
no_license
[ { "docstring": "Initializes the data.", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5)" }, { "docstring": "Calculates the value of the PMF.", "name": "pmf", "signature": "def pmf(self, k)" }, { "docstring": "Calculates the value of the CDF.", "nam...
3
stack_v2_sparse_classes_30k_train_020853
Implement the Python class `Binomial` described below. Class description: Binomial class. It defines binomial distribution. Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Initializes the data. - def pmf(self, k): Calculates the value of the PMF. - def cdf(self, k): Calculates the value...
Implement the Python class `Binomial` described below. Class description: Binomial class. It defines binomial distribution. Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Initializes the data. - def pmf(self, k): Calculates the value of the PMF. - def cdf(self, k): Calculates the value...
131be8fcf61aafb5a4ddc0b3853ba625560eb786
<|skeleton|> class Binomial: """Binomial class. It defines binomial distribution.""" def __init__(self, data=None, n=1, p=0.5): """Initializes the data.""" <|body_0|> def pmf(self, k): """Calculates the value of the PMF.""" <|body_1|> def cdf(self, k): """Calcu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Binomial: """Binomial class. It defines binomial distribution.""" def __init__(self, data=None, n=1, p=0.5): """Initializes the data.""" if data is None: if n <= 0: raise ValueError('n must be a positive value') elif p >= 1 or p <= 0: ...
the_stack_v2_python_sparse
math/0x03-probability/binomial.py
zahraaassaad/holbertonschool-machine_learning
train
1
c6ab01ab5c293127d2388c11a1ffc8cdae404dee
[ "qs = Friendship.objects.select_related('from_user', 'to_user').filter(to_user=user).all()\nfriends = [u.from_user for u in qs]\nreturn friends", "if from_user == to_user:\n raise ValidationError('Users cannot be friends with themselves')\nif self.are_friends(from_user, to_user):\n raise AlreadyFriendsError...
<|body_start_0|> qs = Friendship.objects.select_related('from_user', 'to_user').filter(to_user=user).all() friends = [u.from_user for u in qs] return friends <|end_body_0|> <|body_start_1|> if from_user == to_user: raise ValidationError('Users cannot be friends with themselv...
Friendship manager
FriendshipManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FriendshipManager: """Friendship manager""" def friends(self, user): """Return a list of all friends""" <|body_0|> def add_friend(self, from_user, to_user, message=None): """Create a friendship request""" <|body_1|> def remove_friend(self, from_user,...
stack_v2_sparse_classes_36k_train_010897
5,408
no_license
[ { "docstring": "Return a list of all friends", "name": "friends", "signature": "def friends(self, user)" }, { "docstring": "Create a friendship request", "name": "add_friend", "signature": "def add_friend(self, from_user, to_user, message=None)" }, { "docstring": "Destroy a frien...
4
stack_v2_sparse_classes_30k_train_016607
Implement the Python class `FriendshipManager` described below. Class description: Friendship manager Method signatures and docstrings: - def friends(self, user): Return a list of all friends - def add_friend(self, from_user, to_user, message=None): Create a friendship request - def remove_friend(self, from_user, to_...
Implement the Python class `FriendshipManager` described below. Class description: Friendship manager Method signatures and docstrings: - def friends(self, user): Return a list of all friends - def add_friend(self, from_user, to_user, message=None): Create a friendship request - def remove_friend(self, from_user, to_...
371730ba887d41b47d9a7cff1d8ba37d1f96fc94
<|skeleton|> class FriendshipManager: """Friendship manager""" def friends(self, user): """Return a list of all friends""" <|body_0|> def add_friend(self, from_user, to_user, message=None): """Create a friendship request""" <|body_1|> def remove_friend(self, from_user,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FriendshipManager: """Friendship manager""" def friends(self, user): """Return a list of all friends""" qs = Friendship.objects.select_related('from_user', 'to_user').filter(to_user=user).all() friends = [u.from_user for u in qs] return friends def add_friend(self, fr...
the_stack_v2_python_sparse
web/project/friendship/models.py
kochnev/Speak-n-Time
train
0
b37bff891c17bee161d4195e609a3493fe9c26d2
[ "n = len(nums)\nINT_MAX = 10 ** 6 + 1\nleftMax = [-1] * n\nleftMax[0] = nums[0]\nrightMin = [INT_MAX] * n\nrightMin[-1] = nums[-1]\nfor i in range(1, n):\n leftMax[i] = max(leftMax[i - 1], nums[i])\nfor i in range(n - 2, -1, -1):\n rightMin[i] = min(rightMin[i + 1], nums[i])\nfor i in range(n - 1):\n if le...
<|body_start_0|> n = len(nums) INT_MAX = 10 ** 6 + 1 leftMax = [-1] * n leftMax[0] = nums[0] rightMin = [INT_MAX] * n rightMin[-1] = nums[-1] for i in range(1, n): leftMax[i] = max(leftMax[i - 1], nums[i]) for i in range(n - 2, -1, -1): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def partitionDisjoint(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def partitionDisjointFast(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) INT_MAX...
stack_v2_sparse_classes_36k_train_010898
2,177
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "partitionDisjoint", "signature": "def partitionDisjoint(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "partitionDisjointFast", "signature": "def partitionDisjointFast(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_001678
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def partitionDisjoint(self, nums): :type nums: List[int] :rtype: int - def partitionDisjointFast(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def partitionDisjoint(self, nums): :type nums: List[int] :rtype: int - def partitionDisjointFast(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: ...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def partitionDisjoint(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def partitionDisjointFast(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def partitionDisjoint(self, nums): """:type nums: List[int] :rtype: int""" n = len(nums) INT_MAX = 10 ** 6 + 1 leftMax = [-1] * n leftMax[0] = nums[0] rightMin = [INT_MAX] * n rightMin[-1] = nums[-1] for i in range(1, n): le...
the_stack_v2_python_sparse
P/PartitionArrayintoDisjointIntervals.py
bssrdf/pyleet
train
2
143d070a140238ed9f332673146446f49427ea30
[ "time_series_statistics = self.time_series_statistics\nif isinstance(time_series_statistics, TimeSeriesStatistics):\n time_series_statistics = [time_series_statistics]\nreturn sum((statistics.n_total_points for statistics in time_series_statistics))", "time_series_statistics = self.time_series_statistics\nif i...
<|body_start_0|> time_series_statistics = self.time_series_statistics if isinstance(time_series_statistics, TimeSeriesStatistics): time_series_statistics = [time_series_statistics] return sum((statistics.n_total_points for statistics in time_series_statistics)) <|end_body_0|> <|body...
An abstract base class for protocols which will subsample a set of data, yielding only equilibrated, uncorrelated data.
BaseDecorrelateProtocol
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseDecorrelateProtocol: """An abstract base class for protocols which will subsample a set of data, yielding only equilibrated, uncorrelated data.""" def _n_expected(self) -> int: """Returns the expected number of samples to decorrelate.""" <|body_0|> def _uncorrelated_...
stack_v2_sparse_classes_36k_train_010899
30,028
permissive
[ { "docstring": "Returns the expected number of samples to decorrelate.", "name": "_n_expected", "signature": "def _n_expected(self) -> int" }, { "docstring": "Returns the indices of the time series being decorrelated to retain.", "name": "_uncorrelated_indices", "signature": "def _uncorr...
2
null
Implement the Python class `BaseDecorrelateProtocol` described below. Class description: An abstract base class for protocols which will subsample a set of data, yielding only equilibrated, uncorrelated data. Method signatures and docstrings: - def _n_expected(self) -> int: Returns the expected number of samples to d...
Implement the Python class `BaseDecorrelateProtocol` described below. Class description: An abstract base class for protocols which will subsample a set of data, yielding only equilibrated, uncorrelated data. Method signatures and docstrings: - def _n_expected(self) -> int: Returns the expected number of samples to d...
2fd51633dbc0b7e001093ae81fd7e3d56f18d70f
<|skeleton|> class BaseDecorrelateProtocol: """An abstract base class for protocols which will subsample a set of data, yielding only equilibrated, uncorrelated data.""" def _n_expected(self) -> int: """Returns the expected number of samples to decorrelate.""" <|body_0|> def _uncorrelated_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseDecorrelateProtocol: """An abstract base class for protocols which will subsample a set of data, yielding only equilibrated, uncorrelated data.""" def _n_expected(self) -> int: """Returns the expected number of samples to decorrelate.""" time_series_statistics = self.time_series_stati...
the_stack_v2_python_sparse
openff/evaluator/protocols/analysis.py
openforcefield/openff-evaluator
train
28