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
248b4261ea8199e77a5478eafe17e8e2521894c4
[ "self._modules = args\nself._base_module = kwargs.get('base_module', 'galileo')\nif not self._modules:\n self._modules = [self._base_module]", "for module in self._modules:\n m = sys.modules[module]\n setattr(m, func.__name__, func)\nreturn func", "for module in self._modules:\n m = sys.modules[modu...
<|body_start_0|> self._modules = args self._base_module = kwargs.get('base_module', 'galileo') if not self._modules: self._modules = [self._base_module] <|end_body_0|> <|body_start_1|> for module in self._modules: m = sys.modules[module] setattr(m, fu...
\\brief Export galileo APIs
export
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class export: """\\brief Export galileo APIs""" def __init__(self, *args, **kwargs): """\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module Default is `galileo`.""" <|body_0|> def __cal...
stack_v2_sparse_classes_36k_train_016400
2,131
permissive
[ { "docstring": "\\\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\\\param **kwargs base_module Default is `galileo`.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "\\\\brief export c...
4
stack_v2_sparse_classes_30k_train_015352
Implement the Python class `export` described below. Class description: \\brief Export galileo APIs Method signatures and docstrings: - def __init__(self, *args, **kwargs): \\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module D...
Implement the Python class `export` described below. Class description: \\brief Export galileo APIs Method signatures and docstrings: - def __init__(self, *args, **kwargs): \\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module D...
48099ec3f0331196c6812208ceb080ba618a588b
<|skeleton|> class export: """\\brief Export galileo APIs""" def __init__(self, *args, **kwargs): """\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module Default is `galileo`.""" <|body_0|> def __cal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class export: """\\brief Export galileo APIs""" def __init__(self, *args, **kwargs): """\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module Default is `galileo`.""" self._modules = args self._bas...
the_stack_v2_python_sparse
galileo/platform/export.py
2012fang1/galileo
train
0
df1f7ec18c67941dd46beb4812c532d7686e3bf0
[ "super(SkyDriveOldLogParser, self).__init__()\nself._last_date_time = None\nself._last_event_data = None\nself.offset = 0", "time_elements_tuple = self._GetValueFromStructure(structure, 'date_time')\nmonth, day_of_month, year, hours, minutes, seconds, milliseconds = time_elements_tuple\ntime_elements_tuple = (yea...
<|body_start_0|> super(SkyDriveOldLogParser, self).__init__() self._last_date_time = None self._last_event_data = None self.offset = 0 <|end_body_0|> <|body_start_1|> time_elements_tuple = self._GetValueFromStructure(structure, 'date_time') month, day_of_month, year, hou...
Parse SkyDrive old log files.
SkyDriveOldLogParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SkyDriveOldLogParser: """Parse SkyDrive old log files.""" def __init__(self): """Initializes a parser.""" <|body_0|> def _ParseLogline(self, parser_mediator, structure): """Parse a logline and store appropriate attributes. Args: parser_mediator (ParserMediator): ...
stack_v2_sparse_classes_36k_train_016401
16,775
permissive
[ { "docstring": "Initializes a parser.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Parse a logline and store appropriate attributes. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. struct...
5
null
Implement the Python class `SkyDriveOldLogParser` described below. Class description: Parse SkyDrive old log files. Method signatures and docstrings: - def __init__(self): Initializes a parser. - def _ParseLogline(self, parser_mediator, structure): Parse a logline and store appropriate attributes. Args: parser_mediat...
Implement the Python class `SkyDriveOldLogParser` described below. Class description: Parse SkyDrive old log files. Method signatures and docstrings: - def __init__(self): Initializes a parser. - def _ParseLogline(self, parser_mediator, structure): Parse a logline and store appropriate attributes. Args: parser_mediat...
c69b2952b608cfce47ff8fd0d1409d856be35cb1
<|skeleton|> class SkyDriveOldLogParser: """Parse SkyDrive old log files.""" def __init__(self): """Initializes a parser.""" <|body_0|> def _ParseLogline(self, parser_mediator, structure): """Parse a logline and store appropriate attributes. Args: parser_mediator (ParserMediator): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SkyDriveOldLogParser: """Parse SkyDrive old log files.""" def __init__(self): """Initializes a parser.""" super(SkyDriveOldLogParser, self).__init__() self._last_date_time = None self._last_event_data = None self.offset = 0 def _ParseLogline(self, parser_media...
the_stack_v2_python_sparse
plaso/parsers/skydrivelog.py
cyb3rfox/plaso
train
3
a9f2ddf7bcf9f7dc674a5f70abfdbd1730a5438f
[ "if not parent:\n raise ValueError('Missing parent value.')\nsuper(VShadowPathSpec, self).__init__(parent=parent, **kwargs)\nself.location = location\nself.store_index = store_index", "string_parts = []\nif self.location is not None:\n string_parts.append(f'location: {self.location:s}')\nif self.store_index...
<|body_start_0|> if not parent: raise ValueError('Missing parent value.') super(VShadowPathSpec, self).__init__(parent=parent, **kwargs) self.location = location self.store_index = store_index <|end_body_0|> <|body_start_1|> string_parts = [] if self.location...
Volume Shadow Snapshots (VSS) path specification. Attributes: location (str): location. store_index (int): store index.
VShadowPathSpec
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VShadowPathSpec: """Volume Shadow Snapshots (VSS) path specification. Attributes: location (str): location. store_index (int): store index.""" def __init__(self, location=None, parent=None, store_index=None, **kwargs): """Initializes a path specification. Note that the VSS path speci...
stack_v2_sparse_classes_36k_train_016402
1,499
permissive
[ { "docstring": "Initializes a path specification. Note that the VSS path specification must have a parent. Args: location (Optional[str]): location. parent (Optional[PathSpec]): parent path specification. store_index (Optional[int]): store index. Raises: ValueError: when parent is not set.", "name": "__init...
2
null
Implement the Python class `VShadowPathSpec` described below. Class description: Volume Shadow Snapshots (VSS) path specification. Attributes: location (str): location. store_index (int): store index. Method signatures and docstrings: - def __init__(self, location=None, parent=None, store_index=None, **kwargs): Initi...
Implement the Python class `VShadowPathSpec` described below. Class description: Volume Shadow Snapshots (VSS) path specification. Attributes: location (str): location. store_index (int): store index. Method signatures and docstrings: - def __init__(self, location=None, parent=None, store_index=None, **kwargs): Initi...
28756d910e951a22c5f0b2bcf5184f055a19d544
<|skeleton|> class VShadowPathSpec: """Volume Shadow Snapshots (VSS) path specification. Attributes: location (str): location. store_index (int): store index.""" def __init__(self, location=None, parent=None, store_index=None, **kwargs): """Initializes a path specification. Note that the VSS path speci...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VShadowPathSpec: """Volume Shadow Snapshots (VSS) path specification. Attributes: location (str): location. store_index (int): store index.""" def __init__(self, location=None, parent=None, store_index=None, **kwargs): """Initializes a path specification. Note that the VSS path specification must...
the_stack_v2_python_sparse
dfvfs/path/vshadow_path_spec.py
log2timeline/dfvfs
train
197
2b5ae912190d192c9800f906ef4ce1e338138b5b
[ "if value is self.field.missing_value:\n return []\nterms = self.widget.updateTerms()\ntry:\n return [terms.getTerm(value).token]\nexcept LookupError:\n return []", "widget = self.widget\nif not len(value) or value[0] == widget.noValueToken:\n return self.field.missing_value\nwidget.updateTerms()\nret...
<|body_start_0|> if value is self.field.missing_value: return [] terms = self.widget.updateTerms() try: return [terms.getTerm(value).token] except LookupError: return [] <|end_body_0|> <|body_start_1|> widget = self.widget if not len(v...
Basic data converter for ISequenceWidget.
SequenceDataConverter
[ "ZPL-2.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SequenceDataConverter: """Basic data converter for ISequenceWidget.""" def toWidgetValue(self, value): """Convert from Python bool to HTML representation.""" <|body_0|> def toFieldValue(self, value): """See interfaces.IDataConverter""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k_train_016403
15,934
permissive
[ { "docstring": "Convert from Python bool to HTML representation.", "name": "toWidgetValue", "signature": "def toWidgetValue(self, value)" }, { "docstring": "See interfaces.IDataConverter", "name": "toFieldValue", "signature": "def toFieldValue(self, value)" } ]
2
stack_v2_sparse_classes_30k_train_001816
Implement the Python class `SequenceDataConverter` described below. Class description: Basic data converter for ISequenceWidget. Method signatures and docstrings: - def toWidgetValue(self, value): Convert from Python bool to HTML representation. - def toFieldValue(self, value): See interfaces.IDataConverter
Implement the Python class `SequenceDataConverter` described below. Class description: Basic data converter for ISequenceWidget. Method signatures and docstrings: - def toWidgetValue(self, value): Convert from Python bool to HTML representation. - def toFieldValue(self, value): See interfaces.IDataConverter <|skelet...
aa47e9b109ad2d7de600fc1d4ea7359d8144f356
<|skeleton|> class SequenceDataConverter: """Basic data converter for ISequenceWidget.""" def toWidgetValue(self, value): """Convert from Python bool to HTML representation.""" <|body_0|> def toFieldValue(self, value): """See interfaces.IDataConverter""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SequenceDataConverter: """Basic data converter for ISequenceWidget.""" def toWidgetValue(self, value): """Convert from Python bool to HTML representation.""" if value is self.field.missing_value: return [] terms = self.widget.updateTerms() try: retu...
the_stack_v2_python_sparse
src/z3c/form/converter.py
zopefoundation/z3c.form
train
6
03d7ef71403e445c77fc720711810bb338f93751
[ "self.mask = np.copy(mask)\nself.masked_vol = np.copy(vol)\nself.masked_vol[self.mask == 0] = 0", "min_intensity = np.float64(np.min(self.masked_vol[self.masked_vol != 0]))\nmax_intensity = np.max(self.masked_vol)\nw1 = np.copy(self.masked_vol)\nw1 = (w1 - min_intensity) / (max_intensity - min_intensity)\nw1[w1 <...
<|body_start_0|> self.mask = np.copy(mask) self.masked_vol = np.copy(vol) self.masked_vol[self.mask == 0] = 0 <|end_body_0|> <|body_start_1|> min_intensity = np.float64(np.min(self.masked_vol[self.masked_vol != 0])) max_intensity = np.max(self.masked_vol) w1 = np.copy(se...
vertices
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class vertices: def __init__(self, mask, vol): """Constructor""" <|body_0|> def compute_w1(self): """Compute W1 for vertex weight computation""" <|body_1|> def compute_w2(self): """Compute W2 for vertex weight computation; Distance from boundaries.""" ...
stack_v2_sparse_classes_36k_train_016404
8,906
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, mask, vol)" }, { "docstring": "Compute W1 for vertex weight computation", "name": "compute_w1", "signature": "def compute_w1(self)" }, { "docstring": "Compute W2 for vertex weight computation; Dist...
5
stack_v2_sparse_classes_30k_val_000546
Implement the Python class `vertices` described below. Class description: Implement the vertices class. Method signatures and docstrings: - def __init__(self, mask, vol): Constructor - def compute_w1(self): Compute W1 for vertex weight computation - def compute_w2(self): Compute W2 for vertex weight computation; Dist...
Implement the Python class `vertices` described below. Class description: Implement the vertices class. Method signatures and docstrings: - def __init__(self, mask, vol): Constructor - def compute_w1(self): Compute W1 for vertex weight computation - def compute_w2(self): Compute W2 for vertex weight computation; Dist...
f966200d09d03a75ff9f56ab5c08b03b7bc3aadb
<|skeleton|> class vertices: def __init__(self, mask, vol): """Constructor""" <|body_0|> def compute_w1(self): """Compute W1 for vertex weight computation""" <|body_1|> def compute_w2(self): """Compute W2 for vertex weight computation; Distance from boundaries.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class vertices: def __init__(self, mask, vol): """Constructor""" self.mask = np.copy(mask) self.masked_vol = np.copy(vol) self.masked_vol[self.mask == 0] = 0 def compute_w1(self): """Compute W1 for vertex weight computation""" min_intensity = np.float64(np.min(se...
the_stack_v2_python_sparse
src/jupyter/kkarbasi/cobalt_tractography/cobalt_tractography/tractography.py
neurodata-cobalt/cobalt
train
0
d349de07b292bdeab635290cd1dfcd044933b896
[ "res = 0\nfor i in range(len(nums)):\n res = max(res, nums[i] + self.rob(nums[i + 2:]))\nreturn res", "if not nums:\n return 0\np_0 = nums[0]\nif len(nums) == 1:\n return p_0\np_1 = max(p_0, nums[1])\nfor i in range(2, len(nums)):\n p_2 = max(p_1, p_0 + nums[i])\n p_0 = p_1\n p_1 = p_2\nreturn p...
<|body_start_0|> res = 0 for i in range(len(nums)): res = max(res, nums[i] + self.rob(nums[i + 2:])) return res <|end_body_0|> <|body_start_1|> if not nums: return 0 p_0 = nums[0] if len(nums) == 1: return p_0 p_1 = max(p_0, nu...
Solution
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """Brute Force (Time Limit Exceeded)""" <|body_0|> def rob2(self, nums): """DP""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = 0 for i in range(len(nums)): res = max(res, nums[i] + self.rob(nu...
stack_v2_sparse_classes_36k_train_016405
1,489
permissive
[ { "docstring": "Brute Force (Time Limit Exceeded)", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": "DP", "name": "rob2", "signature": "def rob2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_002289
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): Brute Force (Time Limit Exceeded) - def rob2(self, nums): DP
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): Brute Force (Time Limit Exceeded) - def rob2(self, nums): DP <|skeleton|> class Solution: def rob(self, nums): """Brute Force (Time Limit Excee...
49a0b03c55d8a702785888d473ef96539265ce9c
<|skeleton|> class Solution: def rob(self, nums): """Brute Force (Time Limit Exceeded)""" <|body_0|> def rob2(self, nums): """DP""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rob(self, nums): """Brute Force (Time Limit Exceeded)""" res = 0 for i in range(len(nums)): res = max(res, nums[i] + self.rob(nums[i + 2:])) return res def rob2(self, nums): """DP""" if not nums: return 0 p_0 = ...
the_stack_v2_python_sparse
leetcode/0198_house_robber.py
chaosWsF/Python-Practice
train
1
3d3769dfb66f03a6652f6e4821e07e02986e2c9c
[ "active_users_by_email = UserModel._default_manager.filter(**{'%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True})\nactive_users_by_username = UserModel._default_manager.filter(**{'username__iexact': username, 'is_active': True})\nusers = []\nfor u in active_users_by_email:\n if u.has_usab...
<|body_start_0|> active_users_by_email = UserModel._default_manager.filter(**{'%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True}) active_users_by_username = UserModel._default_manager.filter(**{'username__iexact': username, 'is_active': True}) users = [] for u in ...
UsernameAwarePasswordResetForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UsernameAwarePasswordResetForm: def get_users(self, email=None, username=None): """Given an email or username, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable pass...
stack_v2_sparse_classes_36k_train_016406
11,141
no_license
[ { "docstring": "Given an email or username, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password.", "name": "get_users", "signature": "def get_u...
2
stack_v2_sparse_classes_30k_train_014422
Implement the Python class `UsernameAwarePasswordResetForm` described below. Class description: Implement the UsernameAwarePasswordResetForm class. Method signatures and docstrings: - def get_users(self, email=None, username=None): Given an email or username, return matching user(s) who should receive a reset. This a...
Implement the Python class `UsernameAwarePasswordResetForm` described below. Class description: Implement the UsernameAwarePasswordResetForm class. Method signatures and docstrings: - def get_users(self, email=None, username=None): Given an email or username, return matching user(s) who should receive a reset. This a...
0a90553a04a947175a74dd11fb2eb9dc72385a12
<|skeleton|> class UsernameAwarePasswordResetForm: def get_users(self, email=None, username=None): """Given an email or username, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable pass...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UsernameAwarePasswordResetForm: def get_users(self, email=None, username=None): """Given an email or username, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from res...
the_stack_v2_python_sparse
fanart/forms.py
bctiemann/tlkfaa
train
1
c740e18d709baa471bc0f12144c76089953feeac
[ "json = self.json_parse(value)\nif json and json['source'] == self._YOUTUBE_MILESTONE_SOURCE:\n data = transforms.loads(json['data'])\n video_identifier = (data['video_id'], data['instance_id'])\n playhead_position = data['position']\n if playhead_position <= _POS_LIMIT_SECONDS and playhead_position != ...
<|body_start_0|> json = self.json_parse(value) if json and json['source'] == self._YOUTUBE_MILESTONE_SOURCE: data = transforms.loads(json['data']) video_identifier = (data['video_id'], data['instance_id']) playhead_position = data['position'] if playhead_p...
Generates time histogram of user video engagement. Input file: EventEntity JSON file. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who triggered the event. The event 'data' is a JSON object and its format and content depends on t...
YoutubeHistogramGenerator
[ "Apache-2.0", "CC-BY-3.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YoutubeHistogramGenerator: """Generates time histogram of user video engagement. Input file: EventEntity JSON file. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who triggered the event. The event 'data' is ...
stack_v2_sparse_classes_36k_train_016407
20,093
permissive
[ { "docstring": "Filters out YouTube video data from EventEntity JSON file. Args: unused_key: int. line number of each EventEntity in file. value: str. instance of EventEntity extracted from file. Yields: A tuple of (video_identifier, time_position) to be passed into reduce function. Video_identifier is a tuple ...
2
stack_v2_sparse_classes_30k_train_005712
Implement the Python class `YoutubeHistogramGenerator` described below. Class description: Generates time histogram of user video engagement. Input file: EventEntity JSON file. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who tr...
Implement the Python class `YoutubeHistogramGenerator` described below. Class description: Generates time histogram of user video engagement. Input file: EventEntity JSON file. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who tr...
64f5ea13a8d85b9ef057dddae888a427b1396df6
<|skeleton|> class YoutubeHistogramGenerator: """Generates time histogram of user video engagement. Input file: EventEntity JSON file. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who triggered the event. The event 'data' is ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class YoutubeHistogramGenerator: """Generates time histogram of user video engagement. Input file: EventEntity JSON file. Each event has a 'source' that defines a place in a code where the event was recorded. Each event has a 'user_id' to represent an actor who triggered the event. The event 'data' is a JSON object...
the_stack_v2_python_sparse
coursebuilder/tools/etl/mapreduce_examples.py
ram8647/gcb-clone-v111
train
1
531c95b2f38de3a513426138e108d8c38222fa57
[ "sql = '\\n SELECT \\n mobile,\\n `name`,\\n driver_id,\\n city \\n FROM \\n db_cdm.zd_new_driver_message'\nread_data = self.select_all(sql)\nreturn pd.DataFrame(read_data)", "sql = \"\\n SELECT\\n ucf.driver_id,\\n ubi.`name` driver_na...
<|body_start_0|> sql = '\n SELECT \n mobile,\n `name`,\n driver_id,\n city \n FROM \n db_cdm.zd_new_driver_message' read_data = self.select_all(sql) return pd.DataFrame(read_data) <|end_body_0|> <|body_start_1|> sql = "\n SELECT\n ...
PickLabelDao
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PickLabelDao: def select_new_driver(self): """查询新司机信息 :return:""" <|body_0|> def select_user_common_flow(self): """查询司机常运流向列表 :return:""" <|body_1|> def select_user_common_kind(self, values): """查询司机常运品种列表 :return:""" <|body_2|> def ...
stack_v2_sparse_classes_36k_train_016408
3,525
no_license
[ { "docstring": "查询新司机信息 :return:", "name": "select_new_driver", "signature": "def select_new_driver(self)" }, { "docstring": "查询司机常运流向列表 :return:", "name": "select_user_common_flow", "signature": "def select_user_common_flow(self)" }, { "docstring": "查询司机常运品种列表 :return:", "na...
4
null
Implement the Python class `PickLabelDao` described below. Class description: Implement the PickLabelDao class. Method signatures and docstrings: - def select_new_driver(self): 查询新司机信息 :return: - def select_user_common_flow(self): 查询司机常运流向列表 :return: - def select_user_common_kind(self, values): 查询司机常运品种列表 :return: - ...
Implement the Python class `PickLabelDao` described below. Class description: Implement the PickLabelDao class. Method signatures and docstrings: - def select_new_driver(self): 查询新司机信息 :return: - def select_user_common_flow(self): 查询司机常运流向列表 :return: - def select_user_common_kind(self, values): 查询司机常运品种列表 :return: - ...
5fb62820fa697ffc45931c4c19a9b0775feb1fc5
<|skeleton|> class PickLabelDao: def select_new_driver(self): """查询新司机信息 :return:""" <|body_0|> def select_user_common_flow(self): """查询司机常运流向列表 :return:""" <|body_1|> def select_user_common_kind(self, values): """查询司机常运品种列表 :return:""" <|body_2|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PickLabelDao: def select_new_driver(self): """查询新司机信息 :return:""" sql = '\n SELECT \n mobile,\n `name`,\n driver_id,\n city \n FROM \n db_cdm.zd_new_driver_message' read_data = self.select_all(sql) return pd.DataFrame(read_data) ...
the_stack_v2_python_sparse
app/main/steel_factory/dao/pick_propelling_label_dao.py
9Echo/gc-goods-allocation
train
0
afaa7a4364047103fd1bd9444f12f304e1210ccc
[ "super(AttentionalFactorizationMachineModel, self).__init__()\nself.afm = AFMLayer(embed_size, num_fields, attn_size, dropout_p)\nself.bias = nn.Parameter(torch.zeros(1))\nnn.init.uniform_(self.bias.data)", "linear_out = feat_inputs.sum(dim=1)\nafm_out, _ = self.afm(emb_inputs)\nafm_out = afm_out.sum(dim=2)\noutp...
<|body_start_0|> super(AttentionalFactorizationMachineModel, self).__init__() self.afm = AFMLayer(embed_size, num_fields, attn_size, dropout_p) self.bias = nn.Parameter(torch.zeros(1)) nn.init.uniform_(self.bias.data) <|end_body_0|> <|body_start_1|> linear_out = feat_inputs.sum(...
AttentionalFactorizationMachineModel is a model of attentional factorization machine, which calculate prediction by summing up bias, linear terms and attentional factorization machine values. :Reference: #. `Jun Xiao et al, 2017. Attentional Factorization Machines: Learning the Weight of Feature Interactions via Attent...
AttentionalFactorizationMachineModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentionalFactorizationMachineModel: """AttentionalFactorizationMachineModel is a model of attentional factorization machine, which calculate prediction by summing up bias, linear terms and attentional factorization machine values. :Reference: #. `Jun Xiao et al, 2017. Attentional Factorization ...
stack_v2_sparse_classes_36k_train_016409
2,613
permissive
[ { "docstring": "initialize Attention Factorization Machine Model Args: embed_size (int): embedding size num_fields (int): number of fields in input attn_size (int): attention layer size dropout_p (float, optional): dropout probability after AFM layer. Defaults to 0.0.", "name": "__init__", "signature": ...
2
stack_v2_sparse_classes_30k_train_000088
Implement the Python class `AttentionalFactorizationMachineModel` described below. Class description: AttentionalFactorizationMachineModel is a model of attentional factorization machine, which calculate prediction by summing up bias, linear terms and attentional factorization machine values. :Reference: #. `Jun Xiao ...
Implement the Python class `AttentionalFactorizationMachineModel` described below. Class description: AttentionalFactorizationMachineModel is a model of attentional factorization machine, which calculate prediction by summing up bias, linear terms and attentional factorization machine values. :Reference: #. `Jun Xiao ...
8b4cdbd5ed126a86da3bd9ef1665a6985dedc07c
<|skeleton|> class AttentionalFactorizationMachineModel: """AttentionalFactorizationMachineModel is a model of attentional factorization machine, which calculate prediction by summing up bias, linear terms and attentional factorization machine values. :Reference: #. `Jun Xiao et al, 2017. Attentional Factorization ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttentionalFactorizationMachineModel: """AttentionalFactorizationMachineModel is a model of attentional factorization machine, which calculate prediction by summing up bias, linear terms and attentional factorization machine values. :Reference: #. `Jun Xiao et al, 2017. Attentional Factorization Machines: Lea...
the_stack_v2_python_sparse
torecsys/models/ctr/attentional_factorization_machine.py
codeants2012/torecsys
train
0
cd540ad9e95d9409ff4beb53c26767868f3927d4
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn InternalDomainFederation()", "from .federated_idp_mfa_behavior import FederatedIdpMfaBehavior\nfrom .prompt_login_behavior import PromptLoginBehavior\nfrom .saml_or_ws_fed_provider import SamlOrWsFedProvider\nfrom .signing_certificate_...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return InternalDomainFederation() <|end_body_0|> <|body_start_1|> from .federated_idp_mfa_behavior import FederatedIdpMfaBehavior from .prompt_login_behavior import PromptLoginBehavior ...
InternalDomainFederation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InternalDomainFederation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InternalDomainFederation: """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 cre...
stack_v2_sparse_classes_36k_train_016410
6,466
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: InternalDomainFederation", "name": "create_from_discriminator_value", "signature": "def create_from_discrimi...
3
stack_v2_sparse_classes_30k_train_014378
Implement the Python class `InternalDomainFederation` described below. Class description: Implement the InternalDomainFederation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InternalDomainFederation: Creates a new instance of the appropriate c...
Implement the Python class `InternalDomainFederation` described below. Class description: Implement the InternalDomainFederation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InternalDomainFederation: Creates a new instance of the appropriate c...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class InternalDomainFederation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InternalDomainFederation: """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 cre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InternalDomainFederation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InternalDomainFederation: """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...
the_stack_v2_python_sparse
msgraph/generated/models/internal_domain_federation.py
microsoftgraph/msgraph-sdk-python
train
135
15c87d4742a17bab9f19927567f9cab6a21d1a45
[ "header = {'typ': 'JWT', 'alg': 'HS256'}\nheader = json.dumps(header, separators=(',', ':')).encode('utf-8')\nheader = base64.urlsafe_b64encode(header).replace(b'=', b'')\np = json.dumps(data, separators=(',', ':')).encode('utf-8')\np = base64.urlsafe_b64encode(p).replace(b'=', b'')\nsecret_key = properties.get('se...
<|body_start_0|> header = {'typ': 'JWT', 'alg': 'HS256'} header = json.dumps(header, separators=(',', ':')).encode('utf-8') header = base64.urlsafe_b64encode(header).replace(b'=', b'') p = json.dumps(data, separators=(',', ':')).encode('utf-8') p = base64.urlsafe_b64encode(p).rep...
JWT
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JWT: def encode(data): """JWT签名 :param data: :return:""" <|body_0|> def verify(access_token): """JWT验签 :param access_token: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> header = {'typ': 'JWT', 'alg': 'HS256'} header = json.dumps(...
stack_v2_sparse_classes_36k_train_016411
2,016
no_license
[ { "docstring": "JWT签名 :param data: :return:", "name": "encode", "signature": "def encode(data)" }, { "docstring": "JWT验签 :param access_token: :return:", "name": "verify", "signature": "def verify(access_token)" } ]
2
stack_v2_sparse_classes_30k_train_020873
Implement the Python class `JWT` described below. Class description: Implement the JWT class. Method signatures and docstrings: - def encode(data): JWT签名 :param data: :return: - def verify(access_token): JWT验签 :param access_token: :return:
Implement the Python class `JWT` described below. Class description: Implement the JWT class. Method signatures and docstrings: - def encode(data): JWT签名 :param data: :return: - def verify(access_token): JWT验签 :param access_token: :return: <|skeleton|> class JWT: def encode(data): """JWT签名 :param data: ...
6156ba7e3b87552b80fe20b886fa476d8fc4a277
<|skeleton|> class JWT: def encode(data): """JWT签名 :param data: :return:""" <|body_0|> def verify(access_token): """JWT验签 :param access_token: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JWT: def encode(data): """JWT签名 :param data: :return:""" header = {'typ': 'JWT', 'alg': 'HS256'} header = json.dumps(header, separators=(',', ':')).encode('utf-8') header = base64.urlsafe_b64encode(header).replace(b'=', b'') p = json.dumps(data, separators=(',', ':')).e...
the_stack_v2_python_sparse
tools/jwt.py
Duo-Shou-Store/DSSP
train
0
80b5951479a69718770006f817275fc7c576e8f3
[ "super(LinearRegression, self).setUp()\ndataset = self.get_file('linear_regression_gen.csv')\nschema = [('c1', float), ('c2', float), ('c3', float), ('c4', float), ('label', float)]\nself.frame = self.context.frame.import_csv(dataset, schema=schema)", "model = self.context.models.regression.linear_regression.trai...
<|body_start_0|> super(LinearRegression, self).setUp() dataset = self.get_file('linear_regression_gen.csv') schema = [('c1', float), ('c2', float), ('c3', float), ('c4', float), ('label', float)] self.frame = self.context.frame.import_csv(dataset, schema=schema) <|end_body_0|> <|body_st...
LinearRegression
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearRegression: def setUp(self): """Build test frame""" <|body_0|> def test_model_scoring(self): """Test publishing a linear regression model""" <|body_1|> def test_revise_model(self): """Tests revise api in scoring engine""" <|body_2|>...
stack_v2_sparse_classes_36k_train_016412
3,490
permissive
[ { "docstring": "Build test frame", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test publishing a linear regression model", "name": "test_model_scoring", "signature": "def test_model_scoring(self)" }, { "docstring": "Tests revise api in scoring engine", ...
3
stack_v2_sparse_classes_30k_train_005913
Implement the Python class `LinearRegression` described below. Class description: Implement the LinearRegression class. Method signatures and docstrings: - def setUp(self): Build test frame - def test_model_scoring(self): Test publishing a linear regression model - def test_revise_model(self): Tests revise api in sco...
Implement the Python class `LinearRegression` described below. Class description: Implement the LinearRegression class. Method signatures and docstrings: - def setUp(self): Build test frame - def test_model_scoring(self): Test publishing a linear regression model - def test_revise_model(self): Tests revise api in sco...
5548fc925b5c278263cbdebbd9e8c7593320c2f4
<|skeleton|> class LinearRegression: def setUp(self): """Build test frame""" <|body_0|> def test_model_scoring(self): """Test publishing a linear regression model""" <|body_1|> def test_revise_model(self): """Tests revise api in scoring engine""" <|body_2|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearRegression: def setUp(self): """Build test frame""" super(LinearRegression, self).setUp() dataset = self.get_file('linear_regression_gen.csv') schema = [('c1', float), ('c2', float), ('c3', float), ('c4', float), ('label', float)] self.frame = self.context.frame.i...
the_stack_v2_python_sparse
regression-tests/sparktkregtests/testcases/scoretests/linear_regression_test.py
trustedanalytics/spark-tk
train
35
c1aaac53a18741be14da9eb53da728d7fdb56858
[ "self.n = n = model.n\ncounts = model.counts\nself.probs = probs = dict()\nself.sorted_probs = sorted_probs = dict()\nfor tokens in counts.keys():\n if len(tokens) == n:\n token = tokens[n - 1]\n prev_tokens = tokens[:-1]\n probability = model.cond_prob(token, list(prev_tokens))\n if ...
<|body_start_0|> self.n = n = model.n counts = model.counts self.probs = probs = dict() self.sorted_probs = sorted_probs = dict() for tokens in counts.keys(): if len(tokens) == n: token = tokens[n - 1] prev_tokens = tokens[:-1] ...
NGramGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NGramGenerator: def __init__(self, model): """model -- n-gram model.""" <|body_0|> def generate_token(self, prev_tokens=None): """Randomly generate a token, given prev_tokens. prev_tokens -- the previous n-1 tokens (optional only if n = 1).""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_016413
27,345
no_license
[ { "docstring": "model -- n-gram model.", "name": "__init__", "signature": "def __init__(self, model)" }, { "docstring": "Randomly generate a token, given prev_tokens. prev_tokens -- the previous n-1 tokens (optional only if n = 1).", "name": "generate_token", "signature": "def generate_t...
3
stack_v2_sparse_classes_30k_val_000891
Implement the Python class `NGramGenerator` described below. Class description: Implement the NGramGenerator class. Method signatures and docstrings: - def __init__(self, model): model -- n-gram model. - def generate_token(self, prev_tokens=None): Randomly generate a token, given prev_tokens. prev_tokens -- the previ...
Implement the Python class `NGramGenerator` described below. Class description: Implement the NGramGenerator class. Method signatures and docstrings: - def __init__(self, model): model -- n-gram model. - def generate_token(self, prev_tokens=None): Randomly generate a token, given prev_tokens. prev_tokens -- the previ...
540cbea09b8e0d609e423c2d8dad192cd3a8e00c
<|skeleton|> class NGramGenerator: def __init__(self, model): """model -- n-gram model.""" <|body_0|> def generate_token(self, prev_tokens=None): """Randomly generate a token, given prev_tokens. prev_tokens -- the previous n-1 tokens (optional only if n = 1).""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NGramGenerator: def __init__(self, model): """model -- n-gram model.""" self.n = n = model.n counts = model.counts self.probs = probs = dict() self.sorted_probs = sorted_probs = dict() for tokens in counts.keys(): if len(tokens) == n: ...
the_stack_v2_python_sparse
languagemodeling/ngram.py
famaf/PLN_2017
train
0
ecdf7c4683818cf2095a56ccbe027b9dc2c37b9a
[ "super(Discriminator, self).__init__()\nself.first_conv_layer = ConvolutionDown(in_channels=7, out_channels=32, kernel_size=3)\nself.second_conv_layer = ConvolutionDown(in_channels=32, out_channels=64, kernel_size=3)\nself.third_conv_layer = ConvolutionDown(in_channels=64, out_channels=128, kernel_size=3)\nself.fou...
<|body_start_0|> super(Discriminator, self).__init__() self.first_conv_layer = ConvolutionDown(in_channels=7, out_channels=32, kernel_size=3) self.second_conv_layer = ConvolutionDown(in_channels=32, out_channels=64, kernel_size=3) self.third_conv_layer = ConvolutionDown(in_channels=64, o...
Discriminator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Discriminator: def __init__(self): """In the constructor we instantiate our custom modules and assign them as member variables.""" <|body_0|> def forward(self, x): """In the forward function we accept a Variable of input data and we must return a Variable of output d...
stack_v2_sparse_classes_36k_train_016414
2,339
no_license
[ { "docstring": "In the constructor we instantiate our custom modules and assign them as member variables.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "In the forward function we accept a Variable of input data and we must return a Variable of output data. We can use...
2
null
Implement the Python class `Discriminator` described below. Class description: Implement the Discriminator class. Method signatures and docstrings: - def __init__(self): In the constructor we instantiate our custom modules and assign them as member variables. - def forward(self, x): In the forward function we accept ...
Implement the Python class `Discriminator` described below. Class description: Implement the Discriminator class. Method signatures and docstrings: - def __init__(self): In the constructor we instantiate our custom modules and assign them as member variables. - def forward(self, x): In the forward function we accept ...
0adf5a0a5d4c2e4de41faac6fcc75700104c2b53
<|skeleton|> class Discriminator: def __init__(self): """In the constructor we instantiate our custom modules and assign them as member variables.""" <|body_0|> def forward(self, x): """In the forward function we accept a Variable of input data and we must return a Variable of output d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Discriminator: def __init__(self): """In the constructor we instantiate our custom modules and assign them as member variables.""" super(Discriminator, self).__init__() self.first_conv_layer = ConvolutionDown(in_channels=7, out_channels=32, kernel_size=3) self.second_conv_layer...
the_stack_v2_python_sparse
PyTorch-practice/video_gans_cnn/discriminator.py
TheIllusion/TheIllusionsLibraries
train
1
879dfd80e872d307995bd365202b96fcf2d9affd
[ "data = jsonld.read_yaml(path)\nself = DatasetSchemaV3(client=client, commit=commit).load(data)\nself.__reference__ = path\nreturn self", "from renku.core.management import LocalClient\ndata = DatasetSchemaV3().dump(self)\npath = path or self.__reference__ or os.path.join(self.path, LocalClient.METADATA)\njsonld....
<|body_start_0|> data = jsonld.read_yaml(path) self = DatasetSchemaV3(client=client, commit=commit).load(data) self.__reference__ = path return self <|end_body_0|> <|body_start_1|> from renku.core.management import LocalClient data = DatasetSchemaV3().dump(self) ...
Dataset migration model.
Dataset
[ "Apache-2.0", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """Dataset migration model.""" def from_yaml(cls, path, client=None, commit=None): """Read content from YAML file.""" <|body_0|> def to_yaml(self, path=None): """Write content to a YAML file.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_016415
9,656
permissive
[ { "docstring": "Read content from YAML file.", "name": "from_yaml", "signature": "def from_yaml(cls, path, client=None, commit=None)" }, { "docstring": "Write content to a YAML file.", "name": "to_yaml", "signature": "def to_yaml(self, path=None)" } ]
2
stack_v2_sparse_classes_30k_train_008319
Implement the Python class `Dataset` described below. Class description: Dataset migration model. Method signatures and docstrings: - def from_yaml(cls, path, client=None, commit=None): Read content from YAML file. - def to_yaml(self, path=None): Write content to a YAML file.
Implement the Python class `Dataset` described below. Class description: Dataset migration model. Method signatures and docstrings: - def from_yaml(cls, path, client=None, commit=None): Read content from YAML file. - def to_yaml(self, path=None): Write content to a YAML file. <|skeleton|> class Dataset: """Datas...
88504c2ebe2f5b052f25f073957fd4a2e1f79d11
<|skeleton|> class Dataset: """Dataset migration model.""" def from_yaml(cls, path, client=None, commit=None): """Read content from YAML file.""" <|body_0|> def to_yaml(self, path=None): """Write content to a YAML file.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dataset: """Dataset migration model.""" def from_yaml(cls, path, client=None, commit=None): """Read content from YAML file.""" data = jsonld.read_yaml(path) self = DatasetSchemaV3(client=client, commit=commit).load(data) self.__reference__ = path return self d...
the_stack_v2_python_sparse
renku/core/management/migrations/models/v3.py
ltalirz/renku-python
train
0
dc3bc04babbd05cc7879e90a99281c58e54fba3d
[ "if id is None:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\nelif id <= 0:\n raise ValueError('id must be positive integer')\nelse:\n self.id = id\n Base.__nb_objects += 1", "if list_dictionaries is None or list_dictionaries is []:\n return '[]'\nreturn json.dumps(list_dictionaries)",...
<|body_start_0|> if id is None: Base.__nb_objects += 1 self.id = Base.__nb_objects elif id <= 0: raise ValueError('id must be positive integer') else: self.id = id Base.__nb_objects += 1 <|end_body_0|> <|body_start_1|> if list_...
This class will be the base of all other classes in project
Base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Base: """This class will be the base of all other classes in project""" def __init__(self, id=None): """Assign obj id""" <|body_0|> def to_json_string(list_dictionaries): """json string rep of for instances of dicts""" <|body_1|> def save_to_file(cls...
stack_v2_sparse_classes_36k_train_016416
2,141
no_license
[ { "docstring": "Assign obj id", "name": "__init__", "signature": "def __init__(self, id=None)" }, { "docstring": "json string rep of for instances of dicts", "name": "to_json_string", "signature": "def to_json_string(list_dictionaries)" }, { "docstring": "writes the JSON string r...
6
stack_v2_sparse_classes_30k_val_000048
Implement the Python class `Base` described below. Class description: This class will be the base of all other classes in project Method signatures and docstrings: - def __init__(self, id=None): Assign obj id - def to_json_string(list_dictionaries): json string rep of for instances of dicts - def save_to_file(cls, li...
Implement the Python class `Base` described below. Class description: This class will be the base of all other classes in project Method signatures and docstrings: - def __init__(self, id=None): Assign obj id - def to_json_string(list_dictionaries): json string rep of for instances of dicts - def save_to_file(cls, li...
75bedbbd249be2536da5a77f6337b14c8363f1b8
<|skeleton|> class Base: """This class will be the base of all other classes in project""" def __init__(self, id=None): """Assign obj id""" <|body_0|> def to_json_string(list_dictionaries): """json string rep of for instances of dicts""" <|body_1|> def save_to_file(cls...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Base: """This class will be the base of all other classes in project""" def __init__(self, id=None): """Assign obj id""" if id is None: Base.__nb_objects += 1 self.id = Base.__nb_objects elif id <= 0: raise ValueError('id must be positive intege...
the_stack_v2_python_sparse
0x0C-python-almost_a_circle/models/base.py
Sainterman/holbertonschool-higher_level_programming
train
0
d38d707802ba785f70aaa93d9464269f3627902d
[ "product = Product.objects.create(name='earings', description='very beautiful', price=200, quantity=20)\nphoto = ProductPhoto.objects.create(photo_url='photo a', product=product)\nproduct_id = product.id\nbasket_id = Basket.objects.create().id\nresponse = self.client.post(path=f'/api/v1/baskets/{basket_id}/items/',...
<|body_start_0|> product = Product.objects.create(name='earings', description='very beautiful', price=200, quantity=20) photo = ProductPhoto.objects.create(photo_url='photo a', product=product) product_id = product.id basket_id = Basket.objects.create().id response = self.client....
BasketItemsTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasketItemsTest: def test_return_item_info(self): """tests that the endpoint returns a dictionary with all the relevant information for the item.""" <|body_0|> def test_item_can_be_added_only_once(self): """tests that the endpoint adds the item to the basket only one...
stack_v2_sparse_classes_36k_train_016417
7,771
no_license
[ { "docstring": "tests that the endpoint returns a dictionary with all the relevant information for the item.", "name": "test_return_item_info", "signature": "def test_return_item_info(self)" }, { "docstring": "tests that the endpoint adds the item to the basket only one time.", "name": "test...
5
null
Implement the Python class `BasketItemsTest` described below. Class description: Implement the BasketItemsTest class. Method signatures and docstrings: - def test_return_item_info(self): tests that the endpoint returns a dictionary with all the relevant information for the item. - def test_item_can_be_added_only_once...
Implement the Python class `BasketItemsTest` described below. Class description: Implement the BasketItemsTest class. Method signatures and docstrings: - def test_return_item_info(self): tests that the endpoint returns a dictionary with all the relevant information for the item. - def test_item_can_be_added_only_once...
d84bdedc9ed011dc009cd1b6d42eed1925ccc977
<|skeleton|> class BasketItemsTest: def test_return_item_info(self): """tests that the endpoint returns a dictionary with all the relevant information for the item.""" <|body_0|> def test_item_can_be_added_only_once(self): """tests that the endpoint adds the item to the basket only one...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BasketItemsTest: def test_return_item_info(self): """tests that the endpoint returns a dictionary with all the relevant information for the item.""" product = Product.objects.create(name='earings', description='very beautiful', price=200, quantity=20) photo = ProductPhoto.objects.creat...
the_stack_v2_python_sparse
backend/basket/tests.py
Code-Institute-Submissions/vintage-earrings
train
0
80e130debf343b1ea7769e77323115739ddc4391
[ "if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.T = dict()\nfor source in self.graph.iternodes():\n self.T[source] = dict()\n for target in self.graph.iternodes():\n self.T[source][target] = False\n self.T[source][source] = True", "for step...
<|body_start_0|> if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.T = dict() for source in self.graph.iternodes(): self.T[source] = dict() for target in self.graph.iternodes(): self.T[sou...
Based on the matrix multiplication, O(V**2 E) time.
TransitiveClosureSimple
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransitiveClosureSimple: """Based on the matrix multiplication, O(V**2 E) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_016418
3,816
permissive
[ { "docstring": "The algorithm initialization, O(V**2) time.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_000640
Implement the Python class `TransitiveClosureSimple` described below. Class description: Based on the matrix multiplication, O(V**2 E) time. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization, O(V**2) time. - def run(self): Executable pseudocode.
Implement the Python class `TransitiveClosureSimple` described below. Class description: Based on the matrix multiplication, O(V**2 E) time. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization, O(V**2) time. - def run(self): Executable pseudocode. <|skeleton|> class Transitive...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class TransitiveClosureSimple: """Based on the matrix multiplication, O(V**2 E) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransitiveClosureSimple: """Based on the matrix multiplication, O(V**2 E) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.T =...
the_stack_v2_python_sparse
graphtheory/algorithms/closure.py
kgashok/graphs-dict
train
0
7bd72cf3778d6311e0102715cdddfbd6c8bd130f
[ "self._flag_n = False\nself.__cached__.clear()\nBUFID = info.bufid\nFO = info.fo\nIHL = info.ihl\nMF = info.mf\nTL = info.tl\nif not FO and (not MF):\n if BUFID in self._buffer:\n self._dtgram.extend(self.submit(self._buffer.pop(BUFID), bufid=BUFID))\n return\nif BUFID not in self._buffer:\n sel...
<|body_start_0|> self._flag_n = False self.__cached__.clear() BUFID = info.bufid FO = info.fo IHL = info.ihl MF = info.mf TL = info.tl if not FO and (not MF): if BUFID in self._buffer: self._dtgram.extend(self.submit(self._buffe...
Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class for the protocol-aware reassembl...
IP
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IP: """Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class fo...
stack_v2_sparse_classes_36k_train_016419
6,372
permissive
[ { "docstring": "Reassembly procedure. Arguments: info: info dict of packets to be reassembled", "name": "reassembly", "signature": "def reassembly(self, info: 'Packet[AT]') -> 'None'" }, { "docstring": "Submit reassembled payload. Arguments: buf: buffer dict of reassembled packets bufid: buffer ...
2
null
Implement the Python class `IP` described below. Class description: Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated direc...
Implement the Python class `IP` described below. Class description: Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated direc...
a6fe49ec58f09e105bec5a00fb66d9b3f22730d9
<|skeleton|> class IP: """Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class fo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IP: """Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class for the protoco...
the_stack_v2_python_sparse
pcapkit/foundation/reassembly/ip.py
JarryShaw/PyPCAPKit
train
204
fbb4838432e3b26b59c11c186a608911a5b9c8a1
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Trending()", "from .entity import Entity\nfrom .resource_reference import ResourceReference\nfrom .resource_visualization import ResourceVisualization\nfrom .entity import Entity\nfrom .resource_reference import ResourceReference\nfrom...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return Trending() <|end_body_0|> <|body_start_1|> from .entity import Entity from .resource_reference import ResourceReference from .resource_visualization import ResourceVisualization ...
Trending
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trending: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Trending: """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: Trending...
stack_v2_sparse_classes_36k_train_016420
3,591
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: Trending", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(pars...
3
null
Implement the Python class `Trending` described below. Class description: Implement the Trending class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Trending: Creates a new instance of the appropriate class based on discriminator value Args: parse_no...
Implement the Python class `Trending` described below. Class description: Implement the Trending class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Trending: Creates a new instance of the appropriate class based on discriminator value Args: parse_no...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Trending: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Trending: """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: Trending...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trending: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Trending: """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: Trending""" if...
the_stack_v2_python_sparse
msgraph/generated/models/trending.py
microsoftgraph/msgraph-sdk-python
train
135
8f5a313b35770f6ebb2c1c0045db312e8147b070
[ "if site_admin_email is None and reject_instructions is None:\n raise ValueError('Either reject_instructions or site_admin_email must be provided.')\nself.privacy_policy_url = privacy_policy_url\nself.terms_of_service_url = terms_of_service_url\nself.site_admin_email = site_admin_email\nself.reject_instructions ...
<|body_start_0|> if site_admin_email is None and reject_instructions is None: raise ValueError('Either reject_instructions or site_admin_email must be provided.') self.privacy_policy_url = privacy_policy_url self.terms_of_service_url = terms_of_service_url self.site_admin_ema...
A consent requirement for asking users to acknowledge policies.
PolicyConsentRequirement
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PolicyConsentRequirement: """A consent requirement for asking users to acknowledge policies.""" def __init__(self, privacy_policy_url, terms_of_service_url, site_admin_email=None, reject_instructions=None): """Initialize the consent requirement. Args: privacy_policy_url (unicode): Th...
stack_v2_sparse_classes_36k_train_016421
5,387
no_license
[ { "docstring": "Initialize the consent requirement. Args: privacy_policy_url (unicode): The URL to the privacy policy, if applicable. terms_of_service (unicode): The URL to the terms of service, if applicable. site_admin_email (unicode, optional): The e-mail address of the site admin. This is only used if ``rej...
4
stack_v2_sparse_classes_30k_train_018712
Implement the Python class `PolicyConsentRequirement` described below. Class description: A consent requirement for asking users to acknowledge policies. Method signatures and docstrings: - def __init__(self, privacy_policy_url, terms_of_service_url, site_admin_email=None, reject_instructions=None): Initialize the co...
Implement the Python class `PolicyConsentRequirement` described below. Class description: A consent requirement for asking users to acknowledge policies. Method signatures and docstrings: - def __init__(self, privacy_policy_url, terms_of_service_url, site_admin_email=None, reject_instructions=None): Initialize the co...
99ea69d80a3a393b0da4da3152ef26e808dd8487
<|skeleton|> class PolicyConsentRequirement: """A consent requirement for asking users to acknowledge policies.""" def __init__(self, privacy_policy_url, terms_of_service_url, site_admin_email=None, reject_instructions=None): """Initialize the consent requirement. Args: privacy_policy_url (unicode): Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PolicyConsentRequirement: """A consent requirement for asking users to acknowledge policies.""" def __init__(self, privacy_policy_url, terms_of_service_url, site_admin_email=None, reject_instructions=None): """Initialize the consent requirement. Args: privacy_policy_url (unicode): The URL to the ...
the_stack_v2_python_sparse
djblets/privacy/consent/common.py
chipx86/djblets
train
2
8b66b5892f8d31c0a5405b9f2066fb0627f91ee8
[ "self.dev = dev\nself.metadata = metadata\nself.fs_type = get_filesystem_type(fs_stream)\nif self.fs_type == 'NTFS':\n self.fs = NTFSMftSlack(dev, fs_stream)\n self.fs.domirr = domirr\n self.metadata.set_module('ntfs-mft-slack')\nelse:\n raise NotImplementedError()", "LOGGER.info('Write')\nif filename...
<|body_start_0|> self.dev = dev self.metadata = metadata self.fs_type = get_filesystem_type(fs_stream) if self.fs_type == 'NTFS': self.fs = NTFSMftSlack(dev, fs_stream) self.fs.domirr = domirr self.metadata.set_module('ntfs-mft-slack') else: ...
This class wrapps the mft slack implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> ms = MftSlack(f) >>> m = Metadata("MftSlack") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to write something from stdin into slack with offset: >>> fs.write(sys.stdin.buffer, m, 36) to re...
MftSlack
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MftSlack: """This class wrapps the mft slack implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> ms = MftSlack(f) >>> m = Metadata("MftSlack") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to write something from stdin into slack with offset: >>> fs....
stack_v2_sparse_classes_36k_train_016422
4,776
permissive
[ { "docstring": ":param fs_stream: Stream of filesystem :param metadata: Metadata object :param dev: device to use :param domirr: write copy of data to $MFTMirr", "name": "__init__", "signature": "def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None, domirr=False)" }, { "...
6
null
Implement the Python class `MftSlack` described below. Class description: This class wrapps the mft slack implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> ms = MftSlack(f) >>> m = Metadata("MftSlack") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to write something fro...
Implement the Python class `MftSlack` described below. Class description: This class wrapps the mft slack implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> ms = MftSlack(f) >>> m = Metadata("MftSlack") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to write something fro...
b602e90ddecb8e469a28e092da3ca7fec514e3dc
<|skeleton|> class MftSlack: """This class wrapps the mft slack implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> ms = MftSlack(f) >>> m = Metadata("MftSlack") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to write something from stdin into slack with offset: >>> fs....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MftSlack: """This class wrapps the mft slack implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> ms = MftSlack(f) >>> m = Metadata("MftSlack") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to write something from stdin into slack with offset: >>> fs.write(sys.std...
the_stack_v2_python_sparse
src/wrapper/mft_slack.py
VanirLab/weever
train
3
14ffef7b8d46d353529df670c2c4fa0c97c348bb
[ "seo = SiteSeo.objects.get(choices='Password Reset')\ntemplate_name = 'registration/password_reset_form.html'\nreset_form = PasswordResetForm()\ncontext = {'reset_form': reset_form, 'seo': seo}\nreturn render(request, template_name, context)", "template_name = 'registration/password_reset_form.html'\nseo = SiteSe...
<|body_start_0|> seo = SiteSeo.objects.get(choices='Password Reset') template_name = 'registration/password_reset_form.html' reset_form = PasswordResetForm() context = {'reset_form': reset_form, 'seo': seo} return render(request, template_name, context) <|end_body_0|> <|body_sta...
PasswordResetView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordResetView: def get(self, request): """get method to display the password reset form""" <|body_0|> def post(self, request): """post method to receive the email id entered by the customer, create token,id to send the password reset link to entered email""" ...
stack_v2_sparse_classes_36k_train_016423
36,770
permissive
[ { "docstring": "get method to display the password reset form", "name": "get", "signature": "def get(self, request)" }, { "docstring": "post method to receive the email id entered by the customer, create token,id to send the password reset link to entered email", "name": "post", "signatu...
2
stack_v2_sparse_classes_30k_train_016911
Implement the Python class `PasswordResetView` described below. Class description: Implement the PasswordResetView class. Method signatures and docstrings: - def get(self, request): get method to display the password reset form - def post(self, request): post method to receive the email id entered by the customer, cr...
Implement the Python class `PasswordResetView` described below. Class description: Implement the PasswordResetView class. Method signatures and docstrings: - def get(self, request): get method to display the password reset form - def post(self, request): post method to receive the email id entered by the customer, cr...
ab828ca95571c6dffef2b2392522e6a4160a2304
<|skeleton|> class PasswordResetView: def get(self, request): """get method to display the password reset form""" <|body_0|> def post(self, request): """post method to receive the email id entered by the customer, create token,id to send the password reset link to entered email""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PasswordResetView: def get(self, request): """get method to display the password reset form""" seo = SiteSeo.objects.get(choices='Password Reset') template_name = 'registration/password_reset_form.html' reset_form = PasswordResetForm() context = {'reset_form': reset_for...
the_stack_v2_python_sparse
login/views.py
Quanscendence/braynai
train
0
f55f034d334cfd5b2e18df4c9f7146f6f08939c0
[ "if rng is None:\n rng = numpy.random.RandomState(1234)\nUpwardModel.__init__(self, nDim, nRela, rng)\nself.nDim, self.nRela = (nDim, nRela)\nself.U = initU(nDim, nRela, rng)\nself.b = numpy.zeros((nRela,))\nself.USqSum = {}\nfor nrela in range(nRela):\n self.USqSum[nrela] = numpy.ones(self.U[nrela].shape)\ns...
<|body_start_0|> if rng is None: rng = numpy.random.RandomState(1234) UpwardModel.__init__(self, nDim, nRela, rng) self.nDim, self.nRela = (nDim, nRela) self.U = initU(nDim, nRela, rng) self.b = numpy.zeros((nRela,)) self.USqSum = {} for nrela in range...
UpwardModelMV
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpwardModelMV: def __init__(self, nDim, nRela, rng=None): """Initialize the basic model, which is the standard RNN based semantic composition model :type nDim: int :param nDim: latent units :type nRela: int :param nRela: number of discourse relations""" <|body_0|> def combin...
stack_v2_sparse_classes_36k_train_016424
4,123
no_license
[ { "docstring": "Initialize the basic model, which is the standard RNN based semantic composition model :type nDim: int :param nDim: latent units :type nRela: int :param nRela: number of discourse relations", "name": "__init__", "signature": "def __init__(self, nDim, nRela, rng=None)" }, { "docst...
3
stack_v2_sparse_classes_30k_train_016157
Implement the Python class `UpwardModelMV` described below. Class description: Implement the UpwardModelMV class. Method signatures and docstrings: - def __init__(self, nDim, nRela, rng=None): Initialize the basic model, which is the standard RNN based semantic composition model :type nDim: int :param nDim: latent un...
Implement the Python class `UpwardModelMV` described below. Class description: Implement the UpwardModelMV class. Method signatures and docstrings: - def __init__(self, nDim, nRela, rng=None): Initialize the basic model, which is the standard RNN based semantic composition model :type nDim: int :param nDim: latent un...
b4703ef7af94034bb336d596c2914b51d82c4e4b
<|skeleton|> class UpwardModelMV: def __init__(self, nDim, nRela, rng=None): """Initialize the basic model, which is the standard RNN based semantic composition model :type nDim: int :param nDim: latent units :type nRela: int :param nRela: number of discourse relations""" <|body_0|> def combin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpwardModelMV: def __init__(self, nDim, nRela, rng=None): """Initialize the basic model, which is the standard RNN based semantic composition model :type nDim: int :param nDim: latent units :type nRela: int :param nRela: number of discourse relations""" if rng is None: rng = numpy....
the_stack_v2_python_sparse
UpwardModel/upwardmodelmv.py
qileio/updown
train
0
43e5e226a83acc990de5062936b4ecee34d405e1
[ "url = f'https://graph.microsoft.com/v1.0/users/{user_oid}/getMemberObjects'\nheaders = {'Authorization': f'Bearer {graph_api_access_token}'}\ndata = {'securityEnabledOnly': False}\nresponse = requests.post(url, json=data, headers=headers)\nresponse.raise_for_status()\ngroups = response.json()['value']\ntry:\n f...
<|body_start_0|> url = f'https://graph.microsoft.com/v1.0/users/{user_oid}/getMemberObjects' headers = {'Authorization': f'Bearer {graph_api_access_token}'} data = {'securityEnabledOnly': False} response = requests.post(url, json=data, headers=headers) response.raise_for_status()...
HelsinkiAdfsAuthCodeBackend
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HelsinkiAdfsAuthCodeBackend: def get_member_objects_from_graph_api(self, user_oid: str, graph_api_access_token: str): """Fetches user groups from MS Graph API, validates the group names and adds "adfs-" prefix for them. :returns A list of group names""" <|body_0|> def update...
stack_v2_sparse_classes_36k_train_016425
6,014
permissive
[ { "docstring": "Fetches user groups from MS Graph API, validates the group names and adds \"adfs-\" prefix for them. :returns A list of group names", "name": "get_member_objects_from_graph_api", "signature": "def get_member_objects_from_graph_api(self, user_oid: str, graph_api_access_token: str)" }, ...
4
stack_v2_sparse_classes_30k_train_015172
Implement the Python class `HelsinkiAdfsAuthCodeBackend` described below. Class description: Implement the HelsinkiAdfsAuthCodeBackend class. Method signatures and docstrings: - def get_member_objects_from_graph_api(self, user_oid: str, graph_api_access_token: str): Fetches user groups from MS Graph API, validates th...
Implement the Python class `HelsinkiAdfsAuthCodeBackend` described below. Class description: Implement the HelsinkiAdfsAuthCodeBackend class. Method signatures and docstrings: - def get_member_objects_from_graph_api(self, user_oid: str, graph_api_access_token: str): Fetches user groups from MS Graph API, validates th...
90f477f31f7ffb4a9c2a13fb7fa55908303cccce
<|skeleton|> class HelsinkiAdfsAuthCodeBackend: def get_member_objects_from_graph_api(self, user_oid: str, graph_api_access_token: str): """Fetches user groups from MS Graph API, validates the group names and adds "adfs-" prefix for them. :returns A list of group names""" <|body_0|> def update...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HelsinkiAdfsAuthCodeBackend: def get_member_objects_from_graph_api(self, user_oid: str, graph_api_access_token: str): """Fetches user groups from MS Graph API, validates the group names and adds "adfs-" prefix for them. :returns A list of group names""" url = f'https://graph.microsoft.com/v1.0...
the_stack_v2_python_sparse
backend/shared/shared/azure_adfs/auth.py
jannetasa/yjdh
train
0
12033b48fdd9011707e972f6aedc5bc3fbcdb7d2
[ "user = get_object_or_404(DashUser, uuid=request.data['userID'])\nscenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])\nuser_scenario = UserScenario.objects.filter(userID=user, scenarioID=scenario)\nif user_scenario:\n msg = scenario.name + ' scenario is already subscribed'\n return Respons...
<|body_start_0|> user = get_object_or_404(DashUser, uuid=request.data['userID']) scenario = get_object_or_404(Scenario, uuid=request.data['scenarioID']) user_scenario = UserScenario.objects.filter(userID=user, scenarioID=scenario) if user_scenario: msg = scenario.name + ' sce...
SubscribeScenario
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubscribeScenario: def post(self, request): """To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }""" <|body_0|> def delete(self, request): """To unsubscribe existing scenario of the user # Format { "uuid": "<USERSCENARIO...
stack_v2_sparse_classes_36k_train_016426
16,902
no_license
[ { "docstring": "To subscribe a new scenario # Format { \"userID\": \"<USER UUID>\", \"scenarioID\": \"<SCENARIO UUID>\" }", "name": "post", "signature": "def post(self, request)" }, { "docstring": "To unsubscribe existing scenario of the user # Format { \"uuid\": \"<USERSCENARIO UUID>\" }", ...
2
stack_v2_sparse_classes_30k_test_000542
Implement the Python class `SubscribeScenario` described below. Class description: Implement the SubscribeScenario class. Method signatures and docstrings: - def post(self, request): To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" } - def delete(self, request): To unsub...
Implement the Python class `SubscribeScenario` described below. Class description: Implement the SubscribeScenario class. Method signatures and docstrings: - def post(self, request): To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" } - def delete(self, request): To unsub...
9cb5303df8c54f1d26e72557680c35aa4d0b74d0
<|skeleton|> class SubscribeScenario: def post(self, request): """To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }""" <|body_0|> def delete(self, request): """To unsubscribe existing scenario of the user # Format { "uuid": "<USERSCENARIO...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubscribeScenario: def post(self, request): """To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }""" user = get_object_or_404(DashUser, uuid=request.data['userID']) scenario = get_object_or_404(Scenario, uuid=request.data['scenarioID']) ...
the_stack_v2_python_sparse
apps/apis/views.py
guyandtheworld/news-serve-api
train
2
a6af09a5c1317191a7c65188261706f32c29a367
[ "deq1 = collections.deque()\ndeq2 = collections.deque()\nfor i in range(len(start)):\n a, b = (start[i], end[i])\n if a != 'X':\n deq1.append((a, i))\n if b != 'X':\n deq2.append((b, i))\n while deq1 and deq2:\n if deq1[0][0] != deq2[0][0]:\n return False\n elif de...
<|body_start_0|> deq1 = collections.deque() deq2 = collections.deque() for i in range(len(start)): a, b = (start[i], end[i]) if a != 'X': deq1.append((a, i)) if b != 'X': deq2.append((b, i)) while deq1 and deq2: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canTransform(self, start: str, end: str) -> bool: """Intuition: we can ignore all "X" and only check for "L" & "R". 1. The order of "L", "R" in start, end should be the same. 2. For "L", the index in start should be no less than that of end. For "R", the index in start shou...
stack_v2_sparse_classes_36k_train_016427
2,729
no_license
[ { "docstring": "Intuition: we can ignore all \"X\" and only check for \"L\" & \"R\". 1. The order of \"L\", \"R\" in start, end should be the same. 2. For \"L\", the index in start should be no less than that of end. For \"R\", the index in start should be no more than that of start. time/space O(N)", "name...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canTransform(self, start: str, end: str) -> bool: Intuition: we can ignore all "X" and only check for "L" & "R". 1. The order of "L", "R" in start, end should be the same. 2....
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canTransform(self, start: str, end: str) -> bool: Intuition: we can ignore all "X" and only check for "L" & "R". 1. The order of "L", "R" in start, end should be the same. 2....
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Solution: def canTransform(self, start: str, end: str) -> bool: """Intuition: we can ignore all "X" and only check for "L" & "R". 1. The order of "L", "R" in start, end should be the same. 2. For "L", the index in start should be no less than that of end. For "R", the index in start shou...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canTransform(self, start: str, end: str) -> bool: """Intuition: we can ignore all "X" and only check for "L" & "R". 1. The order of "L", "R" in start, end should be the same. 2. For "L", the index in start should be no less than that of end. For "R", the index in start should be no more ...
the_stack_v2_python_sparse
Leetcode 0777. Swap Adjacent in LR String.py
Chaoran-sjsu/leetcode
train
0
b2a45618b02c9babe1661231eefdf1d309e6fe6d
[ "assert isinstance(response, scrapy.http.response.html.HtmlResponse)\ncurboard = response.selector.xpath('//div[contains(@class, \"titleBar\")]/h1/text()').extract()\nlast_page = MAX_PAGE[curboard[0].lower()]\n'try:\\n last_page = int(response.selector.xpath(\\'//nav/a[@class=\"PageNavNext\"]/following::...
<|body_start_0|> assert isinstance(response, scrapy.http.response.html.HtmlResponse) curboard = response.selector.xpath('//div[contains(@class, "titleBar")]/h1/text()').extract() last_page = MAX_PAGE[curboard[0].lower()] 'try:\n last_page = int(response.selector.xpath(\'//nav/...
scrape reports from angling addicts forum
worldseafishingAfloatSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class worldseafishingAfloatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...""" <|body_0|> def crawl_board_threads(sel...
stack_v2_sparse_classes_36k_train_016428
9,045
no_license
[ { "docstring": "generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "crawl", "name": "crawl_board_threads", "signature": "def crawl_board_t...
3
stack_v2_sparse_classes_30k_train_018107
Implement the Python class `worldseafishingAfloatSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ....
Implement the Python class `worldseafishingAfloatSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ....
9123aa6baf538b662143b9098d963d55165e8409
<|skeleton|> class worldseafishingAfloatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...""" <|body_0|> def crawl_board_threads(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class worldseafishingAfloatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...""" assert isinstance(response, scrapy.http.response.html.Ht...
the_stack_v2_python_sparse
imgscrape/spiders/worldseafishing_reports.py
gmonkman/python
train
0
ed94486254899116b94770c0259e0fb6dc50c06d
[ "data_list = []\nresults = self.query.all()\nformatter = date.getLocaleFormatter(self.request, 'date', 'long')\nfor result in results:\n data = {}\n data['qid'] = 'i-' + str(result.parliamentary_item_id)\n if type(result) == domain.AgendaItem:\n g = u' ' + result.group.type + u' ' + result.group.sho...
<|body_start_0|> data_list = [] results = self.query.all() formatter = date.getLocaleFormatter(self.request, 'date', 'long') for result in results: data = {} data['qid'] = 'i-' + str(result.parliamentary_item_id) if type(result) == domain.AgendaItem: ...
Group parliamentary items per stage e.g. action required, in progress, answered/debated, "dead" (withdrawn, elapsed, inadmissible, dropped).
OwnedItemsInStageViewlet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OwnedItemsInStageViewlet: """Group parliamentary items per stage e.g. action required, in progress, answered/debated, "dead" (withdrawn, elapsed, inadmissible, dropped).""" def _setData(self): """Return the data of the query.""" <|body_0|> def update(self): """Re...
stack_v2_sparse_classes_36k_train_016429
27,657
no_license
[ { "docstring": "Return the data of the query.", "name": "_setData", "signature": "def _setData(self)" }, { "docstring": "Refresh the query.", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_test_000903
Implement the Python class `OwnedItemsInStageViewlet` described below. Class description: Group parliamentary items per stage e.g. action required, in progress, answered/debated, "dead" (withdrawn, elapsed, inadmissible, dropped). Method signatures and docstrings: - def _setData(self): Return the data of the query. -...
Implement the Python class `OwnedItemsInStageViewlet` described below. Class description: Group parliamentary items per stage e.g. action required, in progress, answered/debated, "dead" (withdrawn, elapsed, inadmissible, dropped). Method signatures and docstrings: - def _setData(self): Return the data of the query. -...
5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d
<|skeleton|> class OwnedItemsInStageViewlet: """Group parliamentary items per stage e.g. action required, in progress, answered/debated, "dead" (withdrawn, elapsed, inadmissible, dropped).""" def _setData(self): """Return the data of the query.""" <|body_0|> def update(self): """Re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OwnedItemsInStageViewlet: """Group parliamentary items per stage e.g. action required, in progress, answered/debated, "dead" (withdrawn, elapsed, inadmissible, dropped).""" def _setData(self): """Return the data of the query.""" data_list = [] results = self.query.all() fo...
the_stack_v2_python_sparse
bungeni.main/branches/mr/bungeni/ui/viewlets/workspace.py
malangalanga/bungeni-portal
train
0
818de0542b7448a1b819c641c5203ddd5bfd35a2
[ "if len(temp_result) == n:\n result.append(temp_result.copy())\nelse:\n for num in range(1, n + 1):\n if num in temp_result:\n continue\n temp_result.append(num)\n self.genPermutation(result, n, temp_result)\n temp_result.pop()\nreturn result", "ordered_permutations = ...
<|body_start_0|> if len(temp_result) == n: result.append(temp_result.copy()) else: for num in range(1, n + 1): if num in temp_result: continue temp_result.append(num) self.genPermutation(result, n, temp_result) ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def genPermutation(self, result, n, temp_result): """time limit exceeded!!!!""" <|body_0|> def getPermutation(self, n, k): """:type n: int :type k: int :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(temp_result) == n: ...
stack_v2_sparse_classes_36k_train_016430
1,399
permissive
[ { "docstring": "time limit exceeded!!!!", "name": "genPermutation", "signature": "def genPermutation(self, result, n, temp_result)" }, { "docstring": ":type n: int :type k: int :rtype: str", "name": "getPermutation", "signature": "def getPermutation(self, n, k)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def genPermutation(self, result, n, temp_result): time limit exceeded!!!! - def getPermutation(self, n, k): :type n: int :type k: int :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def genPermutation(self, result, n, temp_result): time limit exceeded!!!! - def getPermutation(self, n, k): :type n: int :type k: int :rtype: str <|skeleton|> class Solution: ...
1ed22267156fb968671731c2e983b0e65f670750
<|skeleton|> class Solution: def genPermutation(self, result, n, temp_result): """time limit exceeded!!!!""" <|body_0|> def getPermutation(self, n, k): """:type n: int :type k: int :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def genPermutation(self, result, n, temp_result): """time limit exceeded!!!!""" if len(temp_result) == n: result.append(temp_result.copy()) else: for num in range(1, n + 1): if num in temp_result: continue ...
the_stack_v2_python_sparse
leetcode/60.py
pingrunhuang/CodeChallenge
train
0
e206688cd0b613637d148461689d31f87a5e44dc
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsMalwareSeverityCount()", "from .windows_malware_severity import WindowsMalwareSeverity\nfrom .windows_malware_severity import WindowsMalwareSeverity\nfields: Dict[str, Callable[[Any], None]] = {'distinctMalwareCount': lambda n: ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return WindowsMalwareSeverityCount() <|end_body_0|> <|body_start_1|> from .windows_malware_severity import WindowsMalwareSeverity from .windows_malware_severity import WindowsMalwareSeverity ...
Windows Malware Severity Count Summary
WindowsMalwareSeverityCount
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowsMalwareSeverityCount: """Windows Malware Severity Count Summary""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareSeverityCount: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pa...
stack_v2_sparse_classes_36k_train_016431
3,844
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: WindowsMalwareSeverityCount", "name": "create_from_discriminator_value", "signature": "def create_from_discr...
3
null
Implement the Python class `WindowsMalwareSeverityCount` described below. Class description: Windows Malware Severity Count Summary Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareSeverityCount: Creates a new instance of the appropriate cl...
Implement the Python class `WindowsMalwareSeverityCount` described below. Class description: Windows Malware Severity Count Summary Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareSeverityCount: Creates a new instance of the appropriate cl...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class WindowsMalwareSeverityCount: """Windows Malware Severity Count Summary""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareSeverityCount: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WindowsMalwareSeverityCount: """Windows Malware Severity Count Summary""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareSeverityCount: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to u...
the_stack_v2_python_sparse
msgraph/generated/models/windows_malware_severity_count.py
microsoftgraph/msgraph-sdk-python
train
135
a70f58e352d3e052b4ce5c1066e27e8ccd298312
[ "retcode = 201\npost = TaxonomyPost(self.get_connection())\ntaxa = post.post(taxonomy)\nreturn (taxa, retcode)", "retcode = 200\nlog_items = None\nget = History(self.get_connection())\ntry:\n log_items = get.get(record_type, record_id, action_types)\nexcept MissingKeyException as dme:\n logging.getLogger(__...
<|body_start_0|> retcode = 201 post = TaxonomyPost(self.get_connection()) taxa = post.post(taxonomy) return (taxa, retcode) <|end_body_0|> <|body_start_1|> retcode = 200 log_items = None get = History(self.get_connection()) try: log_items = ge...
MetadataController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetadataController: def create_taxonomy(self, taxonomy, studies=None, user=None, auths=None): """create_taxonomy Create a Taxonomy :param taxonomy: :type taxonomy: dict | bytes :rtype: Taxonomy""" <|body_0|> def download_history(self, record_type, record_id, action_types=Non...
stack_v2_sparse_classes_36k_train_016432
3,641
no_license
[ { "docstring": "create_taxonomy Create a Taxonomy :param taxonomy: :type taxonomy: dict | bytes :rtype: Taxonomy", "name": "create_taxonomy", "signature": "def create_taxonomy(self, taxonomy, studies=None, user=None, auths=None)" }, { "docstring": "fetches the history of a record # noqa: E501 :p...
6
stack_v2_sparse_classes_30k_train_006658
Implement the Python class `MetadataController` described below. Class description: Implement the MetadataController class. Method signatures and docstrings: - def create_taxonomy(self, taxonomy, studies=None, user=None, auths=None): create_taxonomy Create a Taxonomy :param taxonomy: :type taxonomy: dict | bytes :rty...
Implement the Python class `MetadataController` described below. Class description: Implement the MetadataController class. Method signatures and docstrings: - def create_taxonomy(self, taxonomy, studies=None, user=None, auths=None): create_taxonomy Create a Taxonomy :param taxonomy: :type taxonomy: dict | bytes :rty...
69884943f6e0afa2d371e78b02ab7ce3542e32c4
<|skeleton|> class MetadataController: def create_taxonomy(self, taxonomy, studies=None, user=None, auths=None): """create_taxonomy Create a Taxonomy :param taxonomy: :type taxonomy: dict | bytes :rtype: Taxonomy""" <|body_0|> def download_history(self, record_type, record_id, action_types=Non...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetadataController: def create_taxonomy(self, taxonomy, studies=None, user=None, auths=None): """create_taxonomy Create a Taxonomy :param taxonomy: :type taxonomy: dict | bytes :rtype: Taxonomy""" retcode = 201 post = TaxonomyPost(self.get_connection()) taxa = post.post(taxonom...
the_stack_v2_python_sparse
server/backbone_server/controllers/metadata_controller.py
malariagen/sims-backbone
train
1
2e94d2f2d4931cbdecd564c290af1f08df494eed
[ "params = super().get_default_params()\nparams['optimizer'] = 'adam'\nparams['input_shapes'] = [(None, 900), (None, 900)]\nparams.add(engine.Param('w_initializer', 'glorot_normal'))\nparams.add(engine.Param('b_initializer', 'zeros'))\nparams.add(engine.Param('dim_fan_out', 128))\nparams.add(engine.Param('dim_hidden...
<|body_start_0|> params = super().get_default_params() params['optimizer'] = 'adam' params['input_shapes'] = [(None, 900), (None, 900)] params.add(engine.Param('w_initializer', 'glorot_normal')) params.add(engine.Param('b_initializer', 'zeros')) params.add(engine.Param('d...
CDSSM Model implementation. A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. Examples: >>> model = CDSSMModel() >>> model.guess_and_fill_missing_params() >>> model.build()
CDSSMModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CDSSMModel: """CDSSM Model implementation. A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. Examples: >>> model = CDSSMModel() >>> model.guess_and_fill_missing_params() >>>...
stack_v2_sparse_classes_36k_train_016433
3,995
permissive
[ { "docstring": ":return: model default parameters.", "name": "get_default_params", "signature": "def get_default_params(cls) -> engine.ParamTable" }, { "docstring": "Apply conv and maxpooling operation towards to each tri-letter. The input shape is `num_word_ngrams`*(`contextual_window`* `dim_tr...
3
stack_v2_sparse_classes_30k_train_008012
Implement the Python class `CDSSMModel` described below. Class description: CDSSM Model implementation. A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. Examples: >>> model = CDSSMModel() >>> mo...
Implement the Python class `CDSSMModel` described below. Class description: CDSSM Model implementation. A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. Examples: >>> model = CDSSMModel() >>> mo...
e49d619a52b2e96b6f0e8e76164d76f623210198
<|skeleton|> class CDSSMModel: """CDSSM Model implementation. A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. Examples: >>> model = CDSSMModel() >>> model.guess_and_fill_missing_params() >>>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CDSSMModel: """CDSSM Model implementation. A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. Examples: >>> model = CDSSMModel() >>> model.guess_and_fill_missing_params() >>> model.build(...
the_stack_v2_python_sparse
matchzoo/models/cdssm_model.py
JacobPolloreno/MatchZoo
train
0
a77270dbcc8b177b11735b92e0c953ca640d7e77
[ "self.n_elements = n_elements\nself.x_axis = x_axis\nself.unique_locations = set()\nself._sample_rate = sample_rate\nself.appends = []", "if start is None and end is None:\n start = 'Start'\n if isinstance(pulse, list):\n if isinstance(pulse[0], list):\n og_start, end = self.append(pulse[0...
<|body_start_0|> self.n_elements = n_elements self.x_axis = x_axis self.unique_locations = set() self._sample_rate = sample_rate self.appends = [] <|end_body_0|> <|body_start_1|> if start is None and end is None: start = 'Start' if isinstance(puls...
SequenceWrapper
[ "BSD-3-Clause-LBNL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SequenceWrapper: def __init__(self, n_elements, x_axis=None, sample_rate=None): """This is a wrapper around a standard Sequence. It records the absolute minimum in order to rebuild a full sequence. It is almost a direct replacement for the Sequence object. The primary change is that the ...
stack_v2_sparse_classes_36k_train_016434
5,553
permissive
[ { "docstring": "This is a wrapper around a standard Sequence. It records the absolute minimum in order to rebuild a full sequence. It is almost a direct replacement for the Sequence object. The primary change is that the pulses which are appended should be the keys in the pulse dictionary which is specified dur...
3
null
Implement the Python class `SequenceWrapper` described below. Class description: Implement the SequenceWrapper class. Method signatures and docstrings: - def __init__(self, n_elements, x_axis=None, sample_rate=None): This is a wrapper around a standard Sequence. It records the absolute minimum in order to rebuild a f...
Implement the Python class `SequenceWrapper` described below. Class description: Implement the SequenceWrapper class. Method signatures and docstrings: - def __init__(self, n_elements, x_axis=None, sample_rate=None): This is a wrapper around a standard Sequence. It records the absolute minimum in order to rebuild a f...
ea2ecae8fb3315ec220a165b39f4003b4fb12c0b
<|skeleton|> class SequenceWrapper: def __init__(self, n_elements, x_axis=None, sample_rate=None): """This is a wrapper around a standard Sequence. It records the absolute minimum in order to rebuild a full sequence. It is almost a direct replacement for the Sequence object. The primary change is that the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SequenceWrapper: def __init__(self, n_elements, x_axis=None, sample_rate=None): """This is a wrapper around a standard Sequence. It records the absolute minimum in order to rebuild a full sequence. It is almost a direct replacement for the Sequence object. The primary change is that the pulses which a...
the_stack_v2_python_sparse
qtrl/qtrl/sequencer/wrapper.py
ana-tudor/openqasm_to_qtrl
train
1
c7bdd9a54bc9288d40edad0da10c9efe01dea791
[ "fields = super(RelationSerializer, self).get_fields()\nif self.request.method == 'GET':\n fields['type'] = serializers.CharField(source='type.name')\nelse:\n fields['type'] = serializers.PrimaryKeyRelatedField(queryset=RelationType.objects.all())\nreturn fields", "entities = validated_data.pop('positioninr...
<|body_start_0|> fields = super(RelationSerializer, self).get_fields() if self.request.method == 'GET': fields['type'] = serializers.CharField(source='type.name') else: fields['type'] = serializers.PrimaryKeyRelatedField(queryset=RelationType.objects.all()) return...
Serializer for Relation objects.
RelationSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelationSerializer: """Serializer for Relation objects.""" def get_fields(self): """Dynamically adapt fields based on the current request.""" <|body_0|> def create(self, validated_data): """Create ``Relation`` object and add ``Entities``.""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_016435
2,651
permissive
[ { "docstring": "Dynamically adapt fields based on the current request.", "name": "get_fields", "signature": "def get_fields(self)" }, { "docstring": "Create ``Relation`` object and add ``Entities``.", "name": "create", "signature": "def create(self, validated_data)" } ]
2
stack_v2_sparse_classes_30k_train_010652
Implement the Python class `RelationSerializer` described below. Class description: Serializer for Relation objects. Method signatures and docstrings: - def get_fields(self): Dynamically adapt fields based on the current request. - def create(self, validated_data): Create ``Relation`` object and add ``Entities``.
Implement the Python class `RelationSerializer` described below. Class description: Serializer for Relation objects. Method signatures and docstrings: - def get_fields(self): Dynamically adapt fields based on the current request. - def create(self, validated_data): Create ``Relation`` object and add ``Entities``. <|...
cf7b0d63a3cf9bd6d85ab891ded6aeb2208636c0
<|skeleton|> class RelationSerializer: """Serializer for Relation objects.""" def get_fields(self): """Dynamically adapt fields based on the current request.""" <|body_0|> def create(self, validated_data): """Create ``Relation`` object and add ``Entities``.""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelationSerializer: """Serializer for Relation objects.""" def get_fields(self): """Dynamically adapt fields based on the current request.""" fields = super(RelationSerializer, self).get_fields() if self.request.method == 'GET': fields['type'] = serializers.CharField(s...
the_stack_v2_python_sparse
resolwe/flow/serializers/relation.py
mstajdohar/resolwe
train
0
898844c574a735ddd0b2c73f92daf849c700c4e1
[ "adm = ApplikationsAdministration()\nhaendler = adm.get_einzelhaendler_by_id(id)\nadm.delete_einzelhaendler(haendler)\nreturn ('', 200)", "adm = ApplikationsAdministration()\na = Einzelhaendler.from_dict(api.payload)\nif a is not None:\n a.set_id(id)\n adm.update_einzelhaendler(a)\n return ('', 200)\nels...
<|body_start_0|> adm = ApplikationsAdministration() haendler = adm.get_einzelhaendler_by_id(id) adm.delete_einzelhaendler(haendler) return ('', 200) <|end_body_0|> <|body_start_1|> adm = ApplikationsAdministration() a = Einzelhaendler.from_dict(api.payload) if a ...
EinzelhaendlerOperations
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EinzelhaendlerOperations: def delete(self, id): """Löschen eines Einzelhändlers anhand einer id""" <|body_0|> def put(self, id): """Update eines durch eine id bestimmten Einzelhändlers""" <|body_1|> <|end_skeleton|> <|body_start_0|> adm = Applikatio...
stack_v2_sparse_classes_36k_train_016436
23,456
no_license
[ { "docstring": "Löschen eines Einzelhändlers anhand einer id", "name": "delete", "signature": "def delete(self, id)" }, { "docstring": "Update eines durch eine id bestimmten Einzelhändlers", "name": "put", "signature": "def put(self, id)" } ]
2
stack_v2_sparse_classes_30k_val_000752
Implement the Python class `EinzelhaendlerOperations` described below. Class description: Implement the EinzelhaendlerOperations class. Method signatures and docstrings: - def delete(self, id): Löschen eines Einzelhändlers anhand einer id - def put(self, id): Update eines durch eine id bestimmten Einzelhändlers
Implement the Python class `EinzelhaendlerOperations` described below. Class description: Implement the EinzelhaendlerOperations class. Method signatures and docstrings: - def delete(self, id): Löschen eines Einzelhändlers anhand einer id - def put(self, id): Update eines durch eine id bestimmten Einzelhändlers <|sk...
d4a2b196f21a5379188cb78b31c59d69f739964f
<|skeleton|> class EinzelhaendlerOperations: def delete(self, id): """Löschen eines Einzelhändlers anhand einer id""" <|body_0|> def put(self, id): """Update eines durch eine id bestimmten Einzelhändlers""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EinzelhaendlerOperations: def delete(self, id): """Löschen eines Einzelhändlers anhand einer id""" adm = ApplikationsAdministration() haendler = adm.get_einzelhaendler_by_id(id) adm.delete_einzelhaendler(haendler) return ('', 200) def put(self, id): """Upda...
the_stack_v2_python_sparse
src/main.py
SvenjaHolzinger/SoftwarePraktikum
train
0
048562c223f206e16cb9dc4a6975e2ecc5cb2012
[ "tree = []\nqueue = collections.deque([root])\nwhile queue:\n val = queue.popleft()\n if not val:\n tree.append(None)\n else:\n tree.append(str(val.val))\n queue.append(val.left)\n queue.append(val.right)\nreturn ' '.join(tree)", "data = collections.deque(data.split(' '))\nnod...
<|body_start_0|> tree = [] queue = collections.deque([root]) while queue: val = queue.popleft() if not val: tree.append(None) else: tree.append(str(val.val)) queue.append(val.left) queue.append(va...
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_016437
2,037
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_007748
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:...
c7a42753b2b16c7b9c66b8d7c2e67b683a15e27d
<|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""" tree = [] queue = collections.deque([root]) while queue: val = queue.popleft() if not val: tree.append(None) else: ...
the_stack_v2_python_sparse
hard/297.py
brandoneng000/LeetCode
train
0
0232cb2adc1232eae895e06ea96367b49961d1c5
[ "if grid is None or len(grid) == 0 or len(grid[0]) == 0:\n return 0\nresult = 0\nfor r in range(len(grid)):\n for c in range(len(grid[0])):\n if grid[r][c] == '1':\n result += 1\n self.dfs(grid, r, c)\nreturn result", "if r < 0 or c < 0 or r >= len(grid) or (c >= len(grid[0])):\...
<|body_start_0|> if grid is None or len(grid) == 0 or len(grid[0]) == 0: return 0 result = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == '1': result += 1 self.dfs(grid, r, c) ret...
DFSSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DFSSolution: def numIslands(self, grid): """Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surround...
stack_v2_sparse_classes_36k_train_016438
3,205
no_license
[ { "docstring": "Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 000...
2
null
Implement the Python class `DFSSolution` described below. Class description: Implement the DFSSolution class. Method signatures and docstrings: - def numIslands(self, grid): Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting a...
Implement the Python class `DFSSolution` described below. Class description: Implement the DFSSolution class. Method signatures and docstrings: - def numIslands(self, grid): Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting a...
08c6d27498e35f636045fed05a6f94b760ab69ca
<|skeleton|> class DFSSolution: def numIslands(self, grid): """Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surround...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DFSSolution: def numIslands(self, grid): """Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. E...
the_stack_v2_python_sparse
solutions/dfs/200.Number.of.Islands.py
ljia2/leetcode.py
train
0
95a00bf540728437bb745b9e5ca5eb3cdfbb087e
[ "super(ResNet, self).__init__()\nself.conv1 = nn.Conv2d(num_channels, 16, 3, 1, 1)\nself.norm1 = nn.BatchNorm2d(16)\nself.relu1 = nn.ReLU(inplace=True)\nself.layers1 = self._make_layer(n, 16, 16, 1)\nself.layers2 = self._make_layer(n, 32, 16, 2)\nself.layers3 = self._make_layer(n, 64, 32, 2)\nself.avgpool = nn.AvgP...
<|body_start_0|> super(ResNet, self).__init__() self.conv1 = nn.Conv2d(num_channels, 16, 3, 1, 1) self.norm1 = nn.BatchNorm2d(16) self.relu1 = nn.ReLU(inplace=True) self.layers1 = self._make_layer(n, 16, 16, 1) self.layers2 = self._make_layer(n, 32, 16, 2) self.la...
Class for a ResNet classifier.
ResNet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResNet: """Class for a ResNet classifier.""" def __init__(self, num_channels, num_classes, n=2): """Class initializer.""" <|body_0|> def _make_layer(n, num_filters, channels_in, stride): """Make a single layer.""" <|body_1|> def forward(self, x): ...
stack_v2_sparse_classes_36k_train_016439
4,467
permissive
[ { "docstring": "Class initializer.", "name": "__init__", "signature": "def __init__(self, num_channels, num_classes, n=2)" }, { "docstring": "Make a single layer.", "name": "_make_layer", "signature": "def _make_layer(n, num_filters, channels_in, stride)" }, { "docstring": "Forwa...
5
stack_v2_sparse_classes_30k_train_007742
Implement the Python class `ResNet` described below. Class description: Class for a ResNet classifier. Method signatures and docstrings: - def __init__(self, num_channels, num_classes, n=2): Class initializer. - def _make_layer(n, num_filters, channels_in, stride): Make a single layer. - def forward(self, x): Forward...
Implement the Python class `ResNet` described below. Class description: Class for a ResNet classifier. Method signatures and docstrings: - def __init__(self, num_channels, num_classes, n=2): Class initializer. - def _make_layer(n, num_filters, channels_in, stride): Make a single layer. - def forward(self, x): Forward...
fe5d1eb5ab5453be70c4be473fd3da71afe4b06c
<|skeleton|> class ResNet: """Class for a ResNet classifier.""" def __init__(self, num_channels, num_classes, n=2): """Class initializer.""" <|body_0|> def _make_layer(n, num_filters, channels_in, stride): """Make a single layer.""" <|body_1|> def forward(self, x): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResNet: """Class for a ResNet classifier.""" def __init__(self, num_channels, num_classes, n=2): """Class initializer.""" super(ResNet, self).__init__() self.conv1 = nn.Conv2d(num_channels, 16, 3, 1, 1) self.norm1 = nn.BatchNorm2d(16) self.relu1 = nn.ReLU(inplace=T...
the_stack_v2_python_sparse
src/kegnet/classifier/models/resnet.py
videoturingtest/KegNet
train
0
d2872ffd05b8c027136a2652a720b7c32cb7a4ff
[ "self.converterWindow = converterWindow\nself.inFile = inFile\nself.outLocation = outLocation\nself.outName = outName\nself.outPath = os.path.join(self.outLocation, 'latools_temp_data.csv')\ntry:\n if getattr(sys, 'frozen', False):\n infoFile = os.path.join(os.path.dirname(sys.executable), inFile)\n ...
<|body_start_0|> self.converterWindow = converterWindow self.inFile = inFile self.outLocation = outLocation self.outName = outName self.outPath = os.path.join(self.outLocation, 'latools_temp_data.csv') try: if getattr(sys, 'frozen', False): inf...
A parser that converts a text file into a csv file that can be processed by Parser_csv. Currently this is a bit more specific than the csv parser, due to a lack of example txt files to work with, but it works on general principles.
Parser_txt
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Parser_txt: """A parser that converts a text file into a csv file that can be processed by Parser_csv. Currently this is a bit more specific than the csv parser, due to a lack of example txt files to work with, but it works on general principles.""" def __init__(self, converterWindow, inFile...
stack_v2_sparse_classes_36k_train_016440
32,016
no_license
[ { "docstring": "Parameters ---------- converterWindow : ConverterWindow A reference to the window running the show, so that responses to questions can be gathered. inFile : str The filepath of the data file to process outLocation : str The directory to save the converted file to outName : str The name of the co...
6
stack_v2_sparse_classes_30k_train_017731
Implement the Python class `Parser_txt` described below. Class description: A parser that converts a text file into a csv file that can be processed by Parser_csv. Currently this is a bit more specific than the csv parser, due to a lack of example txt files to work with, but it works on general principles. Method sig...
Implement the Python class `Parser_txt` described below. Class description: A parser that converts a text file into a csv file that can be processed by Parser_csv. Currently this is a bit more specific than the csv parser, due to a lack of example txt files to work with, but it works on general principles. Method sig...
ab59d0a5655d514246fa23a1110e0279254ea5d2
<|skeleton|> class Parser_txt: """A parser that converts a text file into a csv file that can be processed by Parser_csv. Currently this is a bit more specific than the csv parser, due to a lack of example txt files to work with, but it works on general principles.""" def __init__(self, converterWindow, inFile...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Parser_txt: """A parser that converts a text file into a csv file that can be processed by Parser_csv. Currently this is a bit more specific than the csv parser, due to a lack of example txt files to work with, but it works on general principles.""" def __init__(self, converterWindow, inFile, outLocation...
the_stack_v2_python_sparse
latools_gui/templates/converterWindow.py
ch-king/latools_gui
train
0
5ca359631eab5a5205457dba67ca43f49785e9c1
[ "if not string:\n return ''\nm, M = (min(string), max(string))\nfor i, letter in enumerate(m):\n if letter != M[i]:\n return m[:i]\nreturn m", "if not string:\n return ''\nm = min(string, key=len)\nleft, right = (0, len(m))\nwhile left <= right:\n pivot = (left + right) // 2\n prefix = strin...
<|body_start_0|> if not string: return '' m, M = (min(string), max(string)) for i, letter in enumerate(m): if letter != M[i]: return m[:i] return m <|end_body_0|> <|body_start_1|> if not string: return '' m = min(string...
LongestCommonPrefix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LongestCommonPrefix: def longest_common_prefix_1(self, string: str) -> str: """Approach: Using min and max function. :param string: :return:""" <|body_0|> def longest_common_prefix_2(self, string: str) -> str: """Approach: Binary Search :param string: :return:""" ...
stack_v2_sparse_classes_36k_train_016441
1,164
no_license
[ { "docstring": "Approach: Using min and max function. :param string: :return:", "name": "longest_common_prefix_1", "signature": "def longest_common_prefix_1(self, string: str) -> str" }, { "docstring": "Approach: Binary Search :param string: :return:", "name": "longest_common_prefix_2", ...
2
stack_v2_sparse_classes_30k_train_002469
Implement the Python class `LongestCommonPrefix` described below. Class description: Implement the LongestCommonPrefix class. Method signatures and docstrings: - def longest_common_prefix_1(self, string: str) -> str: Approach: Using min and max function. :param string: :return: - def longest_common_prefix_2(self, str...
Implement the Python class `LongestCommonPrefix` described below. Class description: Implement the LongestCommonPrefix class. Method signatures and docstrings: - def longest_common_prefix_1(self, string: str) -> str: Approach: Using min and max function. :param string: :return: - def longest_common_prefix_2(self, str...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class LongestCommonPrefix: def longest_common_prefix_1(self, string: str) -> str: """Approach: Using min and max function. :param string: :return:""" <|body_0|> def longest_common_prefix_2(self, string: str) -> str: """Approach: Binary Search :param string: :return:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LongestCommonPrefix: def longest_common_prefix_1(self, string: str) -> str: """Approach: Using min and max function. :param string: :return:""" if not string: return '' m, M = (min(string), max(string)) for i, letter in enumerate(m): if letter != M[i]: ...
the_stack_v2_python_sparse
math_and_srings/longestcommonprefix.py
Shiv2157k/leet_code
train
1
cfe8803fb0d0878cc21ec74d87d8fab115e7ecf7
[ "response_mock = Response()\nresponse_mock.url = url\nif redirect_url is not None:\n response_mock.status_code = 301\n response_mock.headers['Location'] = redirect_url\nelse:\n response_mock.status_code = response_code\nreturn response_mock", "def redirect_side_effect() -> Response:\n for response in ...
<|body_start_0|> response_mock = Response() response_mock.url = url if redirect_url is not None: response_mock.status_code = 301 response_mock.headers['Location'] = redirect_url else: response_mock.status_code = response_code return response_mo...
TestBuiltInService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestBuiltInService: def get_response_mock(url: str, redirect_url: str | None=None, response_code: int | None=200) -> Response: """Create a mock requests.Response object. Args: url (str): URL to set as the `url` attribute (should be the last URL in the redirect chain). redirect_url (str |...
stack_v2_sparse_classes_36k_train_016442
12,600
permissive
[ { "docstring": "Create a mock requests.Response object. Args: url (str): URL to set as the `url` attribute (should be the last URL in the redirect chain). redirect_url (str | None, optional): URL to redirect to. Defaults to None. response_code (int | None, optional): Response code to set as the `status_code` at...
3
null
Implement the Python class `TestBuiltInService` described below. Class description: Implement the TestBuiltInService class. Method signatures and docstrings: - def get_response_mock(url: str, redirect_url: str | None=None, response_code: int | None=200) -> Response: Create a mock requests.Response object. Args: url (...
Implement the Python class `TestBuiltInService` described below. Class description: Implement the TestBuiltInService class. Method signatures and docstrings: - def get_response_mock(url: str, redirect_url: str | None=None, response_code: int | None=200) -> Response: Create a mock requests.Response object. Args: url (...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestBuiltInService: def get_response_mock(url: str, redirect_url: str | None=None, response_code: int | None=200) -> Response: """Create a mock requests.Response object. Args: url (str): URL to set as the `url` attribute (should be the last URL in the redirect chain). redirect_url (str |...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestBuiltInService: def get_response_mock(url: str, redirect_url: str | None=None, response_code: int | None=200) -> Response: """Create a mock requests.Response object. Args: url (str): URL to set as the `url` attribute (should be the last URL in the redirect chain). redirect_url (str | None, optiona...
the_stack_v2_python_sparse
Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL_test.py
demisto/content
train
1,023
f50e14b4613a5249702012a19ab22828da5c608c
[ "try:\n self.sqlite_obj = sqlite.Database('report.db')\n with open(file_name) as file:\n self.contents = yaml.load(file)\n self.root_string = [i for i in self.contents.keys()][0]\nexcept Exception as err:\n print(err)", "test_config_query = '\\n CREATE TABLE `test_configuration` (\\n...
<|body_start_0|> try: self.sqlite_obj = sqlite.Database('report.db') with open(file_name) as file: self.contents = yaml.load(file) self.root_string = [i for i in self.contents.keys()][0] except Exception as err: print(err) <|end_body_0|...
Class to represent a YAML Parser and creates database Methods: create_table: Creates sqlite db table with necessary fields. parse_file: Parses the yaml file to obtain necessary data for the test result table and updates it. update_test_config_table: Parses the yaml file to obtain necessary data fot the test config tabl...
YAMLParser
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YAMLParser: """Class to represent a YAML Parser and creates database Methods: create_table: Creates sqlite db table with necessary fields. parse_file: Parses the yaml file to obtain necessary data for the test result table and updates it. update_test_config_table: Parses the yaml file to obtain n...
stack_v2_sparse_classes_36k_train_016443
4,235
permissive
[ { "docstring": "Creates an instance for sqlite_obj and loads the contents of the yamlfile to be parsed", "name": "__init__", "signature": "def __init__(self, file_name='')" }, { "docstring": "Creates empty tables in the sqlite database from the contents of test_config_table and test_result_table...
4
stack_v2_sparse_classes_30k_train_017605
Implement the Python class `YAMLParser` described below. Class description: Class to represent a YAML Parser and creates database Methods: create_table: Creates sqlite db table with necessary fields. parse_file: Parses the yaml file to obtain necessary data for the test result table and updates it. update_test_config_...
Implement the Python class `YAMLParser` described below. Class description: Class to represent a YAML Parser and creates database Methods: create_table: Creates sqlite db table with necessary fields. parse_file: Parses the yaml file to obtain necessary data for the test result table and updates it. update_test_config_...
f98052a6e824dbefac257b4e327f3ab36e3ed5c9
<|skeleton|> class YAMLParser: """Class to represent a YAML Parser and creates database Methods: create_table: Creates sqlite db table with necessary fields. parse_file: Parses the yaml file to obtain necessary data for the test result table and updates it. update_test_config_table: Parses the yaml file to obtain n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class YAMLParser: """Class to represent a YAML Parser and creates database Methods: create_table: Creates sqlite db table with necessary fields. parse_file: Parses the yaml file to obtain necessary data for the test result table and updates it. update_test_config_table: Parses the yaml file to obtain necessary data...
the_stack_v2_python_sparse
report-tools/adaptors/sql/yaml_parser.py
lsandov1/arm-qa-tools
train
0
ea0565a332eb121e99f74c4d4b42866fa020cf01
[ "B, Nt, E = q.shape\nq = q / math.sqrt(E)\nattn = torch.bmm(q, k.transpose(-2, -1))\nif attn_mask is not None:\n attn += attn_mask\nattn = attn.softmax(-1)\noutput = torch.bmm(attn, v)\nreturn (output, attn)", "inputs = [q, k, v]\nif mask is not None:\n inputs += [mask]\nreturn g.op('mmdeploy::ScaledDotProd...
<|body_start_0|> B, Nt, E = q.shape q = q / math.sqrt(E) attn = torch.bmm(q, k.transpose(-2, -1)) if attn_mask is not None: attn += attn_mask attn = attn.softmax(-1) output = torch.bmm(attn, v) return (output, attn) <|end_body_0|> <|body_start_1|> ...
Caller of scale dot product attention.
ScaledDotProductAttentionTRT
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScaledDotProductAttentionTRT: """Caller of scale dot product attention.""" def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): """forward function.""" <|body_0|> def symbolic(g, q, k, v, mask): """Symbolic function.""" <|b...
stack_v2_sparse_classes_36k_train_016444
1,811
permissive
[ { "docstring": "forward function.", "name": "forward", "signature": "def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None)" }, { "docstring": "Symbolic function.", "name": "symbolic", "signature": "def symbolic(g, q, k, v, mask)" } ]
2
null
Implement the Python class `ScaledDotProductAttentionTRT` described below. Class description: Caller of scale dot product attention. Method signatures and docstrings: - def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): forward function. - def symbolic(g, q, k, v, mask): Symbolic fun...
Implement the Python class `ScaledDotProductAttentionTRT` described below. Class description: Caller of scale dot product attention. Method signatures and docstrings: - def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): forward function. - def symbolic(g, q, k, v, mask): Symbolic fun...
5479c8774f5b88d7ed9d399d4e305cb42cc2e73a
<|skeleton|> class ScaledDotProductAttentionTRT: """Caller of scale dot product attention.""" def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): """forward function.""" <|body_0|> def symbolic(g, q, k, v, mask): """Symbolic function.""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScaledDotProductAttentionTRT: """Caller of scale dot product attention.""" def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): """forward function.""" B, Nt, E = q.shape q = q / math.sqrt(E) attn = torch.bmm(q, k.transpose(-2, -1)) ...
the_stack_v2_python_sparse
mmdeploy/pytorch/functions/multi_head_attention_forward.py
open-mmlab/mmdeploy
train
2,164
6b00a9bf98504e604ea482a9cddc3674ce47d7cf
[ "hex_addr = _HexAddressRegexpFor(android_abi)\nself._re_stack_line = re.compile('\\\\s+(?P<frame_number>#[0-9]+)?\\\\s*' + '(?P<stack_addr>' + hex_addr + ')\\\\s+' + '(?P<stack_value>' + hex_addr + ')' + '(\\\\s+(?P<location>[^ \\\\t]+))?')\nself._re_stack_abbrev = re.compile('\\\\s+[.]+\\\\s+[.]+')\nself._memory_m...
<|body_start_0|> hex_addr = _HexAddressRegexpFor(android_abi) self._re_stack_line = re.compile('\\s+(?P<frame_number>#[0-9]+)?\\s*' + '(?P<stack_addr>' + hex_addr + ')\\s+' + '(?P<stack_value>' + hex_addr + ')' + '(\\s+(?P<location>[^ \\t]+))?') self._re_stack_abbrev = re.compile('\\s+[.]+\\s+[....
Translates stack-related lines in a tombstone or crash report.
StackTranslator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StackTranslator: """Translates stack-related lines in a tombstone or crash report.""" def __init__(self, android_abi, memory_map, apk_translator): """Initialize instance.""" <|body_0|> def _ParseLine(self, line): """Check a given input line for a relevant _re_sta...
stack_v2_sparse_classes_36k_train_016445
28,535
permissive
[ { "docstring": "Initialize instance.", "name": "__init__", "signature": "def __init__(self, android_abi, memory_map, apk_translator)" }, { "docstring": "Check a given input line for a relevant _re_stack_line match. Args: line: input tombstone line. Returns: A LineTuple instance on success, None ...
4
null
Implement the Python class `StackTranslator` described below. Class description: Translates stack-related lines in a tombstone or crash report. Method signatures and docstrings: - def __init__(self, android_abi, memory_map, apk_translator): Initialize instance. - def _ParseLine(self, line): Check a given input line f...
Implement the Python class `StackTranslator` described below. Class description: Translates stack-related lines in a tombstone or crash report. Method signatures and docstrings: - def __init__(self, android_abi, memory_map, apk_translator): Initialize instance. - def _ParseLine(self, line): Check a given input line f...
acefdaaadd3ef46f10f63d1acae2259e4024d383
<|skeleton|> class StackTranslator: """Translates stack-related lines in a tombstone or crash report.""" def __init__(self, android_abi, memory_map, apk_translator): """Initialize instance.""" <|body_0|> def _ParseLine(self, line): """Check a given input line for a relevant _re_sta...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StackTranslator: """Translates stack-related lines in a tombstone or crash report.""" def __init__(self, android_abi, memory_map, apk_translator): """Initialize instance.""" hex_addr = _HexAddressRegexpFor(android_abi) self._re_stack_line = re.compile('\\s+(?P<frame_number>#[0-9]+...
the_stack_v2_python_sparse
build/android/pylib/symbols/symbol_utils.py
youtube/cobalt
train
169
f9cfaad71e09c10311e6cc27634f3c7249b79f33
[ "self.URL_VARIABLES = {'client_id': kwargs.get('client_id'), 'client_location_id': kwargs.get('client_location_id')}\nresults = ClientLocationMeal.objects.prefetch_related('meal').prefetch_related('client_location').filter(client_location__pk=kwargs.get('client_location_id'), client_location__client__pk=kwargs.get(...
<|body_start_0|> self.URL_VARIABLES = {'client_id': kwargs.get('client_id'), 'client_location_id': kwargs.get('client_location_id')} results = ClientLocationMeal.objects.prefetch_related('meal').prefetch_related('client_location').filter(client_location__pk=kwargs.get('client_location_id'), client_locat...
Client Location Meal List API Class Example URLs: /api/v1/clients/<client_id>/locations/<client_location_id>/meals/
ClientLocationMealList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientLocationMealList: """Client Location Meal List API Class Example URLs: /api/v1/clients/<client_id>/locations/<client_location_id>/meals/""" def _handle_get(self, request, *args, **kwargs): """GET handler for Client Location Meal List :request - HTTP request from the api call :c...
stack_v2_sparse_classes_36k_train_016446
2,376
no_license
[ { "docstring": "GET handler for Client Location Meal List :request - HTTP request from the api call :client_id - The ID of the client that we want to get locations for", "name": "_handle_get", "signature": "def _handle_get(self, request, *args, **kwargs)" }, { "docstring": "POST handler for Clie...
2
null
Implement the Python class `ClientLocationMealList` described below. Class description: Client Location Meal List API Class Example URLs: /api/v1/clients/<client_id>/locations/<client_location_id>/meals/ Method signatures and docstrings: - def _handle_get(self, request, *args, **kwargs): GET handler for Client Locati...
Implement the Python class `ClientLocationMealList` described below. Class description: Client Location Meal List API Class Example URLs: /api/v1/clients/<client_id>/locations/<client_location_id>/meals/ Method signatures and docstrings: - def _handle_get(self, request, *args, **kwargs): GET handler for Client Locati...
9769e1a96730b02511d25af8828b075dff5c35b5
<|skeleton|> class ClientLocationMealList: """Client Location Meal List API Class Example URLs: /api/v1/clients/<client_id>/locations/<client_location_id>/meals/""" def _handle_get(self, request, *args, **kwargs): """GET handler for Client Location Meal List :request - HTTP request from the api call :c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClientLocationMealList: """Client Location Meal List API Class Example URLs: /api/v1/clients/<client_id>/locations/<client_location_id>/meals/""" def _handle_get(self, request, *args, **kwargs): """GET handler for Client Location Meal List :request - HTTP request from the api call :client_id - Th...
the_stack_v2_python_sparse
clients/api/client_location_meal_list.py
doubleclickdetroit/dindintonight
train
0
c69c633ed0d4cc30bc8b89190e2c5e9ed0f706b4
[ "self.rtol = rtol\nself.atol = atol\nsuper(WeightedDiGraphMatcher, self).__init__(G1, G2)", "G1_succ = self.G1.succ\nG1_pred = self.G1.pred\nG2_succ = self.G2.succ\nG2_pred = self.G2.pred\ncore_1 = self.core_1\nrtol, atol = (self.rtol, self.atol)\nfor successor in G1_succ[G1_node]:\n if successor is G1_node:\n...
<|body_start_0|> self.rtol = rtol self.atol = atol super(WeightedDiGraphMatcher, self).__init__(G1, G2) <|end_body_0|> <|body_start_1|> G1_succ = self.G1.succ G1_pred = self.G1.pred G2_succ = self.G2.succ G2_pred = self.G2.pred core_1 = self.core_1 ...
Implementation of VF2 algorithm for directed, weighted graphs.
WeightedDiGraphMatcher
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeightedDiGraphMatcher: """Implementation of VF2 algorithm for directed, weighted graphs.""" def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): """Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.DiGraph instances G1 and G2 must be weighted graphs. rtol : float, op...
stack_v2_sparse_classes_36k_train_016447
9,804
permissive
[ { "docstring": "Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.DiGraph instances G1 and G2 must be weighted graphs. rtol : float, optional The relative tolerance used to compare weights. atol : float, optional The absolute tolerance used to compare weights.", "name": "__init__", "sig...
2
null
Implement the Python class `WeightedDiGraphMatcher` described below. Class description: Implementation of VF2 algorithm for directed, weighted graphs. Method signatures and docstrings: - def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.DiGraph inst...
Implement the Python class `WeightedDiGraphMatcher` described below. Class description: Implementation of VF2 algorithm for directed, weighted graphs. Method signatures and docstrings: - def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.DiGraph inst...
de0cdb26248f6d0d8bea594124c1dd7a155d406d
<|skeleton|> class WeightedDiGraphMatcher: """Implementation of VF2 algorithm for directed, weighted graphs.""" def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): """Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.DiGraph instances G1 and G2 must be weighted graphs. rtol : float, op...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeightedDiGraphMatcher: """Implementation of VF2 algorithm for directed, weighted graphs.""" def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): """Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.DiGraph instances G1 and G2 must be weighted graphs. rtol : float, optional The re...
the_stack_v2_python_sparse
Source/lib/CrossPlatform/networkx/algorithms/isomorphism/vf2weighted.py
JaneliaSciComp/Neuroptikon
train
9
037d5658e5e85f09b18e9b0cab84902de5aed6fe
[ "super().__init__()\nself.fft_size = fft_size\nself.shift_size = shift_size\nself.win_length = win_length\nself.window = window\nself.spectral_convergence_loss = SpectralConvergenceLoss()\nself.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()", "x_mag = stft(x, self.fft_size, self.shift_size, self.win_length, sel...
<|body_start_0|> super().__init__() self.fft_size = fft_size self.shift_size = shift_size self.win_length = win_length self.window = window self.spectral_convergence_loss = SpectralConvergenceLoss() self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss() <|end_body_...
STFT loss module.
STFTLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class STFTLoss: """STFT loss module.""" def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): """Initialize STFT loss module.""" <|body_0|> def forward(self, x, y): """Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T)....
stack_v2_sparse_classes_36k_train_016448
46,210
permissive
[ { "docstring": "Initialize STFT loss module.", "name": "__init__", "signature": "def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann')" }, { "docstring": "Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtruth signal (B, T). R...
2
stack_v2_sparse_classes_30k_train_005085
Implement the Python class `STFTLoss` described below. Class description: STFT loss module. Method signatures and docstrings: - def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): Initialize STFT loss module. - def forward(self, x, y): Calculate forward propagation. Args: x (Tensor): Pre...
Implement the Python class `STFTLoss` described below. Class description: STFT loss module. Method signatures and docstrings: - def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): Initialize STFT loss module. - def forward(self, x, y): Calculate forward propagation. Args: x (Tensor): Pre...
17854a04d43c231eff66bfed9d6aa55e94a29e79
<|skeleton|> class STFTLoss: """STFT loss module.""" def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): """Initialize STFT loss module.""" <|body_0|> def forward(self, x, y): """Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T)....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class STFTLoss: """STFT loss module.""" def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): """Initialize STFT loss module.""" super().__init__() self.fft_size = fft_size self.shift_size = shift_size self.win_length = win_length self...
the_stack_v2_python_sparse
paddlespeech/t2s/modules/losses.py
anniyanvr/DeepSpeech-1
train
0
6e6d6ade4ff5207f3f27e89817678565d30012dd
[ "index_i = 0\nindex_j = 0\nloop_i = 0\nwhile loop_i < m and index_j < n:\n if nums1[index_i] <= nums2[index_j]:\n index_i += 1\n else:\n nums1.insert(index_i, nums2[index_j])\n nums1.pop()\n index_i += 1\n index_j += 1\n loop_i -= 1\n loop_i += 1\nwhile index_j < n...
<|body_start_0|> index_i = 0 index_j = 0 loop_i = 0 while loop_i < m and index_j < n: if nums1[index_i] <= nums2[index_j]: index_i += 1 else: nums1.insert(index_i, nums2[index_j]) nums1.pop() index_i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def merge(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_0|> def merge_2(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_1|> def merge_LC(self, nums1...
stack_v2_sparse_classes_36k_train_016449
3,309
no_license
[ { "docstring": "Do not return anything, modify nums1 in-place instead.", "name": "merge", "signature": "def merge(self, nums1, m, nums2, n)" }, { "docstring": "Do not return anything, modify nums1 in-place instead.", "name": "merge_2", "signature": "def merge_2(self, nums1, m, nums2, n)"...
3
stack_v2_sparse_classes_30k_train_005653
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place instead. - def merge_2(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place instead. - def merge_2(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place...
ec48cbde4356208afac226d41752daffe674be2c
<|skeleton|> class Solution: def merge(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_0|> def merge_2(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_1|> def merge_LC(self, nums1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def merge(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" index_i = 0 index_j = 0 loop_i = 0 while loop_i < m and index_j < n: if nums1[index_i] <= nums2[index_j]: index_i += 1 els...
the_stack_v2_python_sparse
Leetcode/Python/Easy/Sorting/merge_sorted_array.py
librar127/PythonDS
train
0
7ada38ce3f9e547a2bbc91c707b9c16f68211b33
[ "with patch.object(DailyIndexDocType, 'get_field_mapping') as gfm:\n field = 'field'\n gfm.return_value = {'index': {'mappings': {'syslog': {field: {'mapping': {field: {'fields': {'raw': True}}}}}}}}\n result = DailyIndexDocType.field_has_raw('field')\n self.assertTrue(gfm.called)\n self.assertTrue(r...
<|body_start_0|> with patch.object(DailyIndexDocType, 'get_field_mapping') as gfm: field = 'field' gfm.return_value = {'index': {'mappings': {'syslog': {field: {'mapping': {field: {'fields': {'raw': True}}}}}}}} result = DailyIndexDocType.field_has_raw('field') se...
Tests for the LogData model
DailyIndexDocTypeTests
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DailyIndexDocTypeTests: """Tests for the LogData model""" def test_field_has_raw_true(self): """field_has_raw returns True if mapping has a raw field.""" <|body_0|> def test_field_has_raw_false(self): """field_has_raw returns False if mapping doesn't have a raw f...
stack_v2_sparse_classes_36k_train_016450
12,045
permissive
[ { "docstring": "field_has_raw returns True if mapping has a raw field.", "name": "test_field_has_raw_true", "signature": "def test_field_has_raw_true(self)" }, { "docstring": "field_has_raw returns False if mapping doesn't have a raw field.", "name": "test_field_has_raw_false", "signatur...
4
stack_v2_sparse_classes_30k_train_017708
Implement the Python class `DailyIndexDocTypeTests` described below. Class description: Tests for the LogData model Method signatures and docstrings: - def test_field_has_raw_true(self): field_has_raw returns True if mapping has a raw field. - def test_field_has_raw_false(self): field_has_raw returns False if mapping...
Implement the Python class `DailyIndexDocTypeTests` described below. Class description: Tests for the LogData model Method signatures and docstrings: - def test_field_has_raw_true(self): field_has_raw returns True if mapping has a raw field. - def test_field_has_raw_false(self): field_has_raw returns False if mapping...
73d334a9f0df7c044c06989977a9a22dd2ff9b7a
<|skeleton|> class DailyIndexDocTypeTests: """Tests for the LogData model""" def test_field_has_raw_true(self): """field_has_raw returns True if mapping has a raw field.""" <|body_0|> def test_field_has_raw_false(self): """field_has_raw returns False if mapping doesn't have a raw f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DailyIndexDocTypeTests: """Tests for the LogData model""" def test_field_has_raw_true(self): """field_has_raw returns True if mapping has a raw field.""" with patch.object(DailyIndexDocType, 'get_field_mapping') as gfm: field = 'field' gfm.return_value = {'index': ...
the_stack_v2_python_sparse
goldstone/drfes/tests.py
bhuvan-rk/goldstone-server
train
0
df67df348f50c1e76ef37b8b857dae16d7453aa8
[ "if left == 0 and right == 0:\n self.results.append(pattern_str)\n return\nif left > 0:\n self._gen(left - 1, right, pattern_str + '(')\nif right > left and right > 0:\n self._gen(left, right - 1, pattern_str + ')')", "self.results = []\nself._gen(n, n, '')\nreturn self.results" ]
<|body_start_0|> if left == 0 and right == 0: self.results.append(pattern_str) return if left > 0: self._gen(left - 1, right, pattern_str + '(') if right > left and right > 0: self._gen(left, right - 1, pattern_str + ')') <|end_body_0|> <|body_sta...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _gen(self, left: int, right: int, pattern_str: str): """Args: left: right: pattern_str: Returns:""" <|body_0|> def generateParenthesis(self, n: int) -> List[str]: """DFS 递归 Args: n: Returns:""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_016451
1,028
no_license
[ { "docstring": "Args: left: right: pattern_str: Returns:", "name": "_gen", "signature": "def _gen(self, left: int, right: int, pattern_str: str)" }, { "docstring": "DFS 递归 Args: n: Returns:", "name": "generateParenthesis", "signature": "def generateParenthesis(self, n: int) -> List[str]"...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _gen(self, left: int, right: int, pattern_str: str): Args: left: right: pattern_str: Returns: - def generateParenthesis(self, n: int) -> List[str]: DFS 递归 Args: n: Returns:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _gen(self, left: int, right: int, pattern_str: str): Args: left: right: pattern_str: Returns: - def generateParenthesis(self, n: int) -> List[str]: DFS 递归 Args: n: Returns: ...
c0dd577481b46129d950354d567d332a4d091137
<|skeleton|> class Solution: def _gen(self, left: int, right: int, pattern_str: str): """Args: left: right: pattern_str: Returns:""" <|body_0|> def generateParenthesis(self, n: int) -> List[str]: """DFS 递归 Args: n: Returns:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _gen(self, left: int, right: int, pattern_str: str): """Args: left: right: pattern_str: Returns:""" if left == 0 and right == 0: self.results.append(pattern_str) return if left > 0: self._gen(left - 1, right, pattern_str + '(') ...
the_stack_v2_python_sparse
leetcode/22_括号生成.py
tenqaz/crazy_arithmetic
train
0
62f96a6d2ff09586914263ebfbdb2827d8ad5e38
[ "view = cls.as_view('periodic_expenses')\napp.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', defaults={'expense_id': None}, view_func=view, methods=['GET'])\napp.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', view_func=view, methods=['POST'])\napp.add_url_rule('/api/budget-periodic-e...
<|body_start_0|> view = cls.as_view('periodic_expenses') app.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', defaults={'expense_id': None}, view_func=view, methods=['GET']) app.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', view_func=view, methods=['POST']) ...
Periodic expense REST resource view
PeriodicExpensesView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PeriodicExpensesView: """Periodic expense REST resource view""" def register(cls, app: Flask): """Registers routes for this view""" <|body_0|> def get(budget_id: Optional[int], expense_id: Optional[int]): """Gets a specific periodic expense or all expenses in the...
stack_v2_sparse_classes_36k_train_016452
17,779
permissive
[ { "docstring": "Registers routes for this view", "name": "register", "signature": "def register(cls, app: Flask)" }, { "docstring": "Gets a specific periodic expense or all expenses in the specified budget", "name": "get", "signature": "def get(budget_id: Optional[int], expense_id: Optio...
5
stack_v2_sparse_classes_30k_test_001026
Implement the Python class `PeriodicExpensesView` described below. Class description: Periodic expense REST resource view Method signatures and docstrings: - def register(cls, app: Flask): Registers routes for this view - def get(budget_id: Optional[int], expense_id: Optional[int]): Gets a specific periodic expense o...
Implement the Python class `PeriodicExpensesView` described below. Class description: Periodic expense REST resource view Method signatures and docstrings: - def register(cls, app: Flask): Registers routes for this view - def get(budget_id: Optional[int], expense_id: Optional[int]): Gets a specific periodic expense o...
20d992356952542fd79aab69849a04129fa22de2
<|skeleton|> class PeriodicExpensesView: """Periodic expense REST resource view""" def register(cls, app: Flask): """Registers routes for this view""" <|body_0|> def get(budget_id: Optional[int], expense_id: Optional[int]): """Gets a specific periodic expense or all expenses in the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PeriodicExpensesView: """Periodic expense REST resource view""" def register(cls, app: Flask): """Registers routes for this view""" view = cls.as_view('periodic_expenses') app.add_url_rule('/api/budgets/<int:budget_id>/periodic-expenses', defaults={'expense_id': None}, view_func=v...
the_stack_v2_python_sparse
backend/underbudget/views/budgets.py
vimofthevine/underbudget4
train
0
831f99a16fff6da946db1b337de2ca1436969f8a
[ "self._cfg_pins = cfg_pins\nself._program_pin = program_pin\nself._done_pin = done_pin\nself._init_pin = init_pin\nif self._cfg_pins:\n self._cfg_pins.all_output()\nif self._program_pin:\n self._program_pin.high()\nif self._done_pin:\n self._done_pin.input()\nif self._init_pin:\n self._init_pin.input()\...
<|body_start_0|> self._cfg_pins = cfg_pins self._program_pin = program_pin self._done_pin = done_pin self._init_pin = init_pin if self._cfg_pins: self._cfg_pins.all_output() if self._program_pin: self._program_pin.high() if self._done_pin: ...
Abstract base class for programming ECP5 FPGAs.
ECP5Programmer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ECP5Programmer: """Abstract base class for programming ECP5 FPGAs.""" def __init__(self, cfg_pins=None, init_pin=None, program_pin=None, done_pin=None, verbose_function=None): """Captures the common fields for all ECP5 programmers. Paramters, all optional: cfg_pins -- A (potentially ...
stack_v2_sparse_classes_36k_train_016453
22,746
permissive
[ { "docstring": "Captures the common fields for all ECP5 programmers. Paramters, all optional: cfg_pins -- A (potentially virtual) port containing the three CFG pins that select the device's configuration mode. See VirtualGPIOPort for an example of a class that might be used for this. init_pin -- A GPIOPin objec...
3
null
Implement the Python class `ECP5Programmer` described below. Class description: Abstract base class for programming ECP5 FPGAs. Method signatures and docstrings: - def __init__(self, cfg_pins=None, init_pin=None, program_pin=None, done_pin=None, verbose_function=None): Captures the common fields for all ECP5 programm...
Implement the Python class `ECP5Programmer` described below. Class description: Abstract base class for programming ECP5 FPGAs. Method signatures and docstrings: - def __init__(self, cfg_pins=None, init_pin=None, program_pin=None, done_pin=None, verbose_function=None): Captures the common fields for all ECP5 programm...
2409575d28fc7c9cae44c9085c7457ddfb54f893
<|skeleton|> class ECP5Programmer: """Abstract base class for programming ECP5 FPGAs.""" def __init__(self, cfg_pins=None, init_pin=None, program_pin=None, done_pin=None, verbose_function=None): """Captures the common fields for all ECP5 programmers. Paramters, all optional: cfg_pins -- A (potentially ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ECP5Programmer: """Abstract base class for programming ECP5 FPGAs.""" def __init__(self, cfg_pins=None, init_pin=None, program_pin=None, done_pin=None, verbose_function=None): """Captures the common fields for all ECP5 programmers. Paramters, all optional: cfg_pins -- A (potentially virtual) port...
the_stack_v2_python_sparse
host/greatfet/programmers/ecp5.py
greatscottgadgets/greatfet
train
273
d929855fd46453dfb44b845cb863131983683675
[ "self.id = id\nself.title = title\nself.authentication_flows = authentication_flows\nself.links = links", "for key, value in (('id', self.id), ('title', self.title)):\n if not value:\n raise ValueError(\"'%s' is required in an Authentication For OPDS document.\" % key)\nfor key, value in [('authenticati...
<|body_start_0|> self.id = id self.title = title self.authentication_flows = authentication_flows self.links = links <|end_body_0|> <|body_start_1|> for key, value in (('id', self.id), ('title', self.title)): if not value: raise ValueError("'%s' is re...
A data structure that can become an Authentication For OPDS document.
AuthenticationForOPDSDocument
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthenticationForOPDSDocument: """A data structure that can become an Authentication For OPDS document.""" def __init__(self, id=None, title=None, authentication_flows=[], links=[]): """Initialize an Authentication For OPDS document. :param id: URL to use as the 'id' of the Authentic...
stack_v2_sparse_classes_36k_train_016454
3,847
permissive
[ { "docstring": "Initialize an Authentication For OPDS document. :param id: URL to use as the 'id' of the Authentication For OPDS document. :param title: String to use as the 'title' of the Authentication For OPDS document. :param authentication_flows: A list of `OPDSAuthenticationFlow` objects, used to construc...
2
null
Implement the Python class `AuthenticationForOPDSDocument` described below. Class description: A data structure that can become an Authentication For OPDS document. Method signatures and docstrings: - def __init__(self, id=None, title=None, authentication_flows=[], links=[]): Initialize an Authentication For OPDS doc...
Implement the Python class `AuthenticationForOPDSDocument` described below. Class description: A data structure that can become an Authentication For OPDS document. Method signatures and docstrings: - def __init__(self, id=None, title=None, authentication_flows=[], links=[]): Initialize an Authentication For OPDS doc...
662cc7e0721d0153857c8c17a37e2a6df86f8ce6
<|skeleton|> class AuthenticationForOPDSDocument: """A data structure that can become an Authentication For OPDS document.""" def __init__(self, id=None, title=None, authentication_flows=[], links=[]): """Initialize an Authentication For OPDS document. :param id: URL to use as the 'id' of the Authentic...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthenticationForOPDSDocument: """A data structure that can become an Authentication For OPDS document.""" def __init__(self, id=None, title=None, authentication_flows=[], links=[]): """Initialize an Authentication For OPDS document. :param id: URL to use as the 'id' of the Authentication For OPD...
the_stack_v2_python_sparse
core/util/authentication_for_opds.py
NYPL-Simplified/circulation
train
20
e9c4f08fb41979f14ea0af5a35afa726eb233112
[ "self.game = game\nself.nnet = nnet\nself.mcts = MCTS(game, nnet, args)\nself.playerId = playerId", "probs = self.mcts.getActionProb(board, temp=0, curPlayer=self.playerId)\nvalids = self.game.getValidMoves(board, 1, self.playerId)\naction = np.argmax(valids * probs)\nreturn action" ]
<|body_start_0|> self.game = game self.nnet = nnet self.mcts = MCTS(game, nnet, args) self.playerId = playerId <|end_body_0|> <|body_start_1|> probs = self.mcts.getActionProb(board, temp=0, curPlayer=self.playerId) valids = self.game.getValidMoves(board, 1, self.playerId...
CentaurPlayer
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CentaurPlayer: def __init__(self, game, nnet, playerId, args): """:type game: HexagonGame :type nnet: HexagonModel""" <|body_0|> def play(self, board): """xx :type board: ndarray :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.game = g...
stack_v2_sparse_classes_36k_train_016455
28,513
permissive
[ { "docstring": ":type game: HexagonGame :type nnet: HexagonModel", "name": "__init__", "signature": "def __init__(self, game, nnet, playerId, args)" }, { "docstring": "xx :type board: ndarray :return:", "name": "play", "signature": "def play(self, board)" } ]
2
stack_v2_sparse_classes_30k_train_014512
Implement the Python class `CentaurPlayer` described below. Class description: Implement the CentaurPlayer class. Method signatures and docstrings: - def __init__(self, game, nnet, playerId, args): :type game: HexagonGame :type nnet: HexagonModel - def play(self, board): xx :type board: ndarray :return:
Implement the Python class `CentaurPlayer` described below. Class description: Implement the CentaurPlayer class. Method signatures and docstrings: - def __init__(self, game, nnet, playerId, args): :type game: HexagonGame :type nnet: HexagonModel - def play(self, board): xx :type board: ndarray :return: <|skeleton|>...
cd4180bda26f92c0bde11a08aa13c825cd151a10
<|skeleton|> class CentaurPlayer: def __init__(self, game, nnet, playerId, args): """:type game: HexagonGame :type nnet: HexagonModel""" <|body_0|> def play(self, board): """xx :type board: ndarray :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CentaurPlayer: def __init__(self, game, nnet, playerId, args): """:type game: HexagonGame :type nnet: HexagonModel""" self.game = game self.nnet = nnet self.mcts = MCTS(game, nnet, args) self.playerId = playerId def play(self, board): """xx :type board: nda...
the_stack_v2_python_sparse
hexagon_alphazero.py
aliostad/hexagon-rl
train
7
76899410cc97ac4d1debfb613e384d52e2217a6f
[ "self.spy_on(TrelloCardSearchView.get, owner=TrelloCardSearchView, call_fake=lambda self, request, **kwargs: HttpResponse('{}', content_type='application/json'))\nreview_request = self.create_review_request(public=True)\nrsp = self.client.get(local_site_reverse('trello-card-search', kwargs={'review_request_id': rev...
<|body_start_0|> self.spy_on(TrelloCardSearchView.get, owner=TrelloCardSearchView, call_fake=lambda self, request, **kwargs: HttpResponse('{}', content_type='application/json')) review_request = self.create_review_request(public=True) rsp = self.client.get(local_site_reverse('trello-card-search'...
Tests for Trello.
TrelloIntegrationTests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrelloIntegrationTests: """Tests for Trello.""" def test_card_search(self): """Testing TrelloCardSearchView""" <|body_0|> def test_card_search_unpublished(self): """Testing TrelloCardSearchView with an unpublished review request""" <|body_1|> def tes...
stack_v2_sparse_classes_36k_train_016456
3,505
permissive
[ { "docstring": "Testing TrelloCardSearchView", "name": "test_card_search", "signature": "def test_card_search(self)" }, { "docstring": "Testing TrelloCardSearchView with an unpublished review request", "name": "test_card_search_unpublished", "signature": "def test_card_search_unpublished...
4
stack_v2_sparse_classes_30k_train_006498
Implement the Python class `TrelloIntegrationTests` described below. Class description: Tests for Trello. Method signatures and docstrings: - def test_card_search(self): Testing TrelloCardSearchView - def test_card_search_unpublished(self): Testing TrelloCardSearchView with an unpublished review request - def test_ca...
Implement the Python class `TrelloIntegrationTests` described below. Class description: Tests for Trello. Method signatures and docstrings: - def test_card_search(self): Testing TrelloCardSearchView - def test_card_search_unpublished(self): Testing TrelloCardSearchView with an unpublished review request - def test_ca...
52bbaecc1227764f3e9a66f03226e0013f2b0c48
<|skeleton|> class TrelloIntegrationTests: """Tests for Trello.""" def test_card_search(self): """Testing TrelloCardSearchView""" <|body_0|> def test_card_search_unpublished(self): """Testing TrelloCardSearchView with an unpublished review request""" <|body_1|> def tes...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrelloIntegrationTests: """Tests for Trello.""" def test_card_search(self): """Testing TrelloCardSearchView""" self.spy_on(TrelloCardSearchView.get, owner=TrelloCardSearchView, call_fake=lambda self, request, **kwargs: HttpResponse('{}', content_type='application/json')) review_re...
the_stack_v2_python_sparse
rbintegrations/trello/tests.py
reviewboard/rbintegrations
train
0
572c2c2259bc5aa72c2603c3b9f0be17a64a2359
[ "inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])\nfor pretrained_model_name in XLNetEncoder.available_checkpoints():\n encoder = XLNetEncoder(pretrained_model_name=pretrained_model_name)\n _ = encoder(inputs)", "inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])\nencoder = XLNetEncoder(...
<|body_start_0|> inputs = tf.placeholder(dtype=tf.int32, shape=[None, None]) for pretrained_model_name in XLNetEncoder.available_checkpoints(): encoder = XLNetEncoder(pretrained_model_name=pretrained_model_name) _ = encoder(inputs) <|end_body_0|> <|body_start_1|> inputs ...
Tests :class:`~texar.tf.modules.XLNetEncoder` class.
XLNetEncoderTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XLNetEncoderTest: """Tests :class:`~texar.tf.modules.XLNetEncoder` class.""" def test_model_loading(self): """Tests model loading functionality.""" <|body_0|> def test_hparams(self): """Tests the priority of the encoder architecture parameter.""" <|body_1...
stack_v2_sparse_classes_36k_train_016457
5,625
permissive
[ { "docstring": "Tests model loading functionality.", "name": "test_model_loading", "signature": "def test_model_loading(self)" }, { "docstring": "Tests the priority of the encoder architecture parameter.", "name": "test_hparams", "signature": "def test_hparams(self)" }, { "docstr...
4
stack_v2_sparse_classes_30k_train_007047
Implement the Python class `XLNetEncoderTest` described below. Class description: Tests :class:`~texar.tf.modules.XLNetEncoder` class. Method signatures and docstrings: - def test_model_loading(self): Tests model loading functionality. - def test_hparams(self): Tests the priority of the encoder architecture parameter...
Implement the Python class `XLNetEncoderTest` described below. Class description: Tests :class:`~texar.tf.modules.XLNetEncoder` class. Method signatures and docstrings: - def test_model_loading(self): Tests model loading functionality. - def test_hparams(self): Tests the priority of the encoder architecture parameter...
0704b3d4c93915b9a6f96b725e49ae20bf5d1e90
<|skeleton|> class XLNetEncoderTest: """Tests :class:`~texar.tf.modules.XLNetEncoder` class.""" def test_model_loading(self): """Tests model loading functionality.""" <|body_0|> def test_hparams(self): """Tests the priority of the encoder architecture parameter.""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XLNetEncoderTest: """Tests :class:`~texar.tf.modules.XLNetEncoder` class.""" def test_model_loading(self): """Tests model loading functionality.""" inputs = tf.placeholder(dtype=tf.int32, shape=[None, None]) for pretrained_model_name in XLNetEncoder.available_checkpoints(): ...
the_stack_v2_python_sparse
texar/tf/modules/encoders/xlnet_encoder_test.py
arita37/texar
train
2
ab473e48183d95ef12932b7c1151ce6c242a0d49
[ "if not devices:\n devices = [0]\nself._device_queue = Queue()\nself._done_queue = Queue()\nfor d in devices:\n self._device_queue.put(str(d))\n_LOGGER.info(f'Initialized profiler runner with devices: {devices}')\nself._timeout = timeout\nself._executor = concurrent.futures.ThreadPoolExecutor(max_workers=len(...
<|body_start_0|> if not devices: devices = [0] self._device_queue = Queue() self._done_queue = Queue() for d in devices: self._device_queue.put(str(d)) _LOGGER.info(f'Initialized profiler runner with devices: {devices}') self._timeout = timeout ...
Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on its dedicated GPU. This property hasn't bee...
ProfilerRunner
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfilerRunner: """Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on i...
stack_v2_sparse_classes_36k_train_016458
12,702
permissive
[ { "docstring": "Parameters ---------- devices : List[str] device identifiers (contents of {CUDA,HIP}_VISIBLE_DEVICES) postprocessing_delegate : object responsible for postprocessing results after futures completion timeout : int timeout to wait for all profilers completion in seconds", "name": "__init__", ...
3
stack_v2_sparse_classes_30k_train_017065
Implement the Python class `ProfilerRunner` described below. Class description: Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each...
Implement the Python class `ProfilerRunner` described below. Class description: Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each...
c60dc19788217556ba12ea378c02b9fd0aea9ffe
<|skeleton|> class ProfilerRunner: """Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProfilerRunner: """Another parallel runner to execute profilers on multiple GPUs in parallel It uses a process pool for implementation, avoiding process creation overhead The size of the process pool is equal to the number of provided GPUs, so ~ideally~ each process should execute a profiler on its dedicated ...
the_stack_v2_python_sparse
python/aitemplate/backend/profiler_runner.py
facebookincubator/AITemplate
train
4,065
eb02282443b4919f4245f332e019d276eb806544
[ "self.options.declare('in_name', types=str)\nself.options.declare('out_name', types=str)\nself.options.declare('shape', types=tuple)\nself.options.declare('constraint_size', types=int, default=1)\nself.options.declare('lower_flag', types=bool, default=False)\nself.options.declare('rho', 50.0, desc='Constraint Aggre...
<|body_start_0|> self.options.declare('in_name', types=str) self.options.declare('out_name', types=str) self.options.declare('shape', types=tuple) self.options.declare('constraint_size', types=int, default=1) self.options.declare('lower_flag', types=bool, default=False) s...
KSComp
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KSComp: def initialize(self): """Declare options.""" <|body_0|> def setup(self): """Declare inputs, outputs, and derivatives for the KS component.""" <|body_1|> def compute(self, inputs, outputs): """Compute the output of the KS function. Paramet...
stack_v2_sparse_classes_36k_train_016459
4,368
no_license
[ { "docstring": "Declare options.", "name": "initialize", "signature": "def initialize(self)" }, { "docstring": "Declare inputs, outputs, and derivatives for the KS component.", "name": "setup", "signature": "def setup(self)" }, { "docstring": "Compute the output of the KS functio...
4
stack_v2_sparse_classes_30k_train_002074
Implement the Python class `KSComp` described below. Class description: Implement the KSComp class. Method signatures and docstrings: - def initialize(self): Declare options. - def setup(self): Declare inputs, outputs, and derivatives for the KS component. - def compute(self, inputs, outputs): Compute the output of t...
Implement the Python class `KSComp` described below. Class description: Implement the KSComp class. Method signatures and docstrings: - def initialize(self): Declare options. - def setup(self): Declare inputs, outputs, and derivatives for the KS component. - def compute(self, inputs, outputs): Compute the output of t...
439a6f68f37b69f19d859e775a78c6c1eb16b7a1
<|skeleton|> class KSComp: def initialize(self): """Declare options.""" <|body_0|> def setup(self): """Declare inputs, outputs, and derivatives for the KS component.""" <|body_1|> def compute(self, inputs, outputs): """Compute the output of the KS function. Paramet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KSComp: def initialize(self): """Declare options.""" self.options.declare('in_name', types=str) self.options.declare('out_name', types=str) self.options.declare('shape', types=tuple) self.options.declare('constraint_size', types=int, default=1) self.options.decl...
the_stack_v2_python_sparse
lsdo_cubesat/utils/ks_comp.py
vgucsd/cubesat
train
0
111c9845685a67f03f3fb81282a62e7b2956ee17
[ "self.que = collections.deque(maxlen=size)\nself.size = size\nself.s = 0", "que = self.que\nif len(que) == self.size:\n self.s -= que.popleft()\nque.append(val)\nself.s += val\nreturn float(self.s) / len(que)" ]
<|body_start_0|> self.que = collections.deque(maxlen=size) self.size = size self.s = 0 <|end_body_0|> <|body_start_1|> que = self.que if len(que) == self.size: self.s -= que.popleft() que.append(val) self.s += val return float(self.s) / len(qu...
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.que = collections.deque(maxlen=s...
stack_v2_sparse_classes_36k_train_016460
733
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_005752
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: ...
4e1f2fd08316354d8ef2babac6bb355f8acdeaef
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" self.que = collections.deque(maxlen=size) self.size = size self.s = 0 def next(self, val): """:type val: int :rtype: float""" que = self.que if len(q...
the_stack_v2_python_sparse
leetcode/346_Moving_Average_from_Data_Stream.py
JinXJinX/practice
train
0
a6b67a05aa54125d2195b5b30c293370bc4e10cc
[ "base_options = _BaseOptions(model_asset_path=model_path)\noptions = InteractiveSegmenterOptions(base_options=base_options)\nreturn cls.create_from_options(options)", "output_streams = [':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME])]\nif options.output_confidence_masks:\n output_streams.append(':'.join([_CONFI...
<|body_start_0|> base_options = _BaseOptions(model_asset_path=model_path) options = InteractiveSegmenterOptions(base_options=base_options) return cls.create_from_options(options) <|end_body_0|> <|body_start_1|> output_streams = [':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME])] if...
Class that performs interactive segmentation on images. Users can represent user interaction through `RegionOfInterest`, which gives a hint to InteractiveSegmenter to perform segmentation focusing on the given region of interest. The API expects a TFLite model with mandatory TFLite Model Metadata. Input tensor: (kTfLit...
InteractiveSegmenter
[ "Apache-2.0", "dtoa" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InteractiveSegmenter: """Class that performs interactive segmentation on images. Users can represent user interaction through `RegionOfInterest`, which gives a hint to InteractiveSegmenter to perform segmentation focusing on the given region of interest. The API expects a TFLite model with mandat...
stack_v2_sparse_classes_36k_train_016461
10,462
permissive
[ { "docstring": "Creates an `InteractiveSegmenter` object from a TensorFlow Lite model and the default `InteractiveSegmenterOptions`. Note that the created `InteractiveSegmenter` instance is in image mode, for performing image segmentation on single image inputs. Args: model_path: Path to the model. Returns: `In...
3
null
Implement the Python class `InteractiveSegmenter` described below. Class description: Class that performs interactive segmentation on images. Users can represent user interaction through `RegionOfInterest`, which gives a hint to InteractiveSegmenter to perform segmentation focusing on the given region of interest. The...
Implement the Python class `InteractiveSegmenter` described below. Class description: Class that performs interactive segmentation on images. Users can represent user interaction through `RegionOfInterest`, which gives a hint to InteractiveSegmenter to perform segmentation focusing on the given region of interest. The...
007824594bf1d07c7c1467df03a43886f8a4b3ad
<|skeleton|> class InteractiveSegmenter: """Class that performs interactive segmentation on images. Users can represent user interaction through `RegionOfInterest`, which gives a hint to InteractiveSegmenter to perform segmentation focusing on the given region of interest. The API expects a TFLite model with mandat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InteractiveSegmenter: """Class that performs interactive segmentation on images. Users can represent user interaction through `RegionOfInterest`, which gives a hint to InteractiveSegmenter to perform segmentation focusing on the given region of interest. The API expects a TFLite model with mandatory TFLite Mo...
the_stack_v2_python_sparse
mediapipe/tasks/python/vision/interactive_segmenter.py
google/mediapipe
train
23,940
927227f189fbf77b4efee31e0086986f19a31976
[ "self.block_rule_type_one = {'icon': constants.RULE_NODE_ICON, 'text': constants.BLOCK_RULE_TREE_KIND_ONE_NAME, 'data': {'rule_id': 0, 'is_root': True, 'rule_type': 'block_rule_1'}, 'state': {'opened': True}, 'children': []}\nself.block_rule_type_two = {'icon': constants.RULE_NODE_ICON, 'text': constants.BLOCK_RULE...
<|body_start_0|> self.block_rule_type_one = {'icon': constants.RULE_NODE_ICON, 'text': constants.BLOCK_RULE_TREE_KIND_ONE_NAME, 'data': {'rule_id': 0, 'is_root': True, 'rule_type': 'block_rule_1'}, 'state': {'opened': True}, 'children': []} self.block_rule_type_two = {'icon': constants.RULE_NODE_ICON, '...
Rule_Tree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rule_Tree: def __init__(self): """!@brief init parent node of rules @param @pre @post @note @return @author Gin Chen @date 2017/12/20""" <|body_0|> def toReturn(self): """!@brief return data rule tree and block rule tree @param @pre @post @note @return data rule tree...
stack_v2_sparse_classes_36k_train_016462
14,409
no_license
[ { "docstring": "!@brief init parent node of rules @param @pre @post @note @return @author Gin Chen @date 2017/12/20", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "!@brief return data rule tree and block rule tree @param @pre @post @note @return data rule tree and bloc...
2
null
Implement the Python class `Rule_Tree` described below. Class description: Implement the Rule_Tree class. Method signatures and docstrings: - def __init__(self): !@brief init parent node of rules @param @pre @post @note @return @author Gin Chen @date 2017/12/20 - def toReturn(self): !@brief return data rule tree and ...
Implement the Python class `Rule_Tree` described below. Class description: Implement the Rule_Tree class. Method signatures and docstrings: - def __init__(self): !@brief init parent node of rules @param @pre @post @note @return @author Gin Chen @date 2017/12/20 - def toReturn(self): !@brief return data rule tree and ...
10d1307609f96eee99e3cd220135dc3b73936451
<|skeleton|> class Rule_Tree: def __init__(self): """!@brief init parent node of rules @param @pre @post @note @return @author Gin Chen @date 2017/12/20""" <|body_0|> def toReturn(self): """!@brief return data rule tree and block rule tree @param @pre @post @note @return data rule tree...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rule_Tree: def __init__(self): """!@brief init parent node of rules @param @pre @post @note @return @author Gin Chen @date 2017/12/20""" self.block_rule_type_one = {'icon': constants.RULE_NODE_ICON, 'text': constants.BLOCK_RULE_TREE_KIND_ONE_NAME, 'data': {'rule_id': 0, 'is_root': True, 'rule_...
the_stack_v2_python_sparse
backend/apolo/apolomgr/resource/common/common_policy_tree/policy_tree.py
renxchen/asuka
train
0
a0d76895e28f09417d36b0ef92499a4a098f0cc9
[ "def cal(indexes: List[int]) -> int:\n res, left = (0, 0)\n for right in range(len(indexes)):\n while left <= right and indexes[right] - indexes[left] + 1 > k + right - left + 1:\n left += 1\n res = max(res, right - left + 1)\n return res\nmp = defaultdict(list)\nfor i, v in enumer...
<|body_start_0|> def cal(indexes: List[int]) -> int: res, left = (0, 0) for right in range(len(indexes)): while left <= right and indexes[right] - indexes[left] + 1 > k + right - left + 1: left += 1 res = max(res, right - left + 1) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestEqualSubarray(self, nums: List[int], k: int) -> int: """哈希表+不定长滑动窗口""" <|body_0|> def longestEqualSubarray2(self, nums: List[int], k: int) -> int: """二分+定长滑动窗口""" <|body_1|> <|end_skeleton|> <|body_start_0|> def cal(indexes: Lis...
stack_v2_sparse_classes_36k_train_016463
2,316
no_license
[ { "docstring": "哈希表+不定长滑动窗口", "name": "longestEqualSubarray", "signature": "def longestEqualSubarray(self, nums: List[int], k: int) -> int" }, { "docstring": "二分+定长滑动窗口", "name": "longestEqualSubarray2", "signature": "def longestEqualSubarray2(self, nums: List[int], k: int) -> int" } ]
2
stack_v2_sparse_classes_30k_train_014402
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestEqualSubarray(self, nums: List[int], k: int) -> int: 哈希表+不定长滑动窗口 - def longestEqualSubarray2(self, nums: List[int], k: int) -> int: 二分+定长滑动窗口
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestEqualSubarray(self, nums: List[int], k: int) -> int: 哈希表+不定长滑动窗口 - def longestEqualSubarray2(self, nums: List[int], k: int) -> int: 二分+定长滑动窗口 <|skeleton|> class Solut...
7e79e26bb8f641868561b186e34c1127ed63c9e0
<|skeleton|> class Solution: def longestEqualSubarray(self, nums: List[int], k: int) -> int: """哈希表+不定长滑动窗口""" <|body_0|> def longestEqualSubarray2(self, nums: List[int], k: int) -> int: """二分+定长滑动窗口""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestEqualSubarray(self, nums: List[int], k: int) -> int: """哈希表+不定长滑动窗口""" def cal(indexes: List[int]) -> int: res, left = (0, 0) for right in range(len(indexes)): while left <= right and indexes[right] - indexes[left] + 1 > k + right - ...
the_stack_v2_python_sparse
16_滑动窗口/2831. 找出最长等值子数组.py
981377660LMT/algorithm-study
train
225
f899d4e2c3627bdd3816386c0e610bf62e9e3bb1
[ "self.capacity = capacity\nself.values = {}\nself.freq_time = {}\nself.least_used = []\nself.update = set()\nself.time = 0", "self.time += 1\nif key in self.values:\n self.update.add(key)\n self.freq_time[key] = (self.freq_time[key][0] + 1, self.time)\n return self.values[key]\nreturn -1", "if self.cap...
<|body_start_0|> self.capacity = capacity self.values = {} self.freq_time = {} self.least_used = [] self.update = set() self.time = 0 <|end_body_0|> <|body_start_1|> self.time += 1 if key in self.values: self.update.add(key) self.f...
LFUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_016464
4,992
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
stack_v2_sparse_classes_30k_train_005952
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
36d7f9e967a62db77622e0888f61999d7f37579a
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LFUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.values = {} self.freq_time = {} self.least_used = [] self.update = set() self.time = 0 def get(self, key): """:type key: int :rtype: int""" ...
the_stack_v2_python_sparse
P0460.py
westgate458/LeetCode
train
0
72cd529cee2c41262ac730a775a1704dae8c85ba
[ "if not head or not head.next:\n return head\ncur = self.reverseList(head.next)\nhead.next.next = head\nhead.next = None\nreturn cur", "if not head or not head.next:\n return head\ncur, pre = (None, head)\nwhile pre:\n t = pre.next\n pre.next = cur\n cur, pre = (pre, t)\nreturn cur" ]
<|body_start_0|> if not head or not head.next: return head cur = self.reverseList(head.next) head.next.next = head head.next = None return cur <|end_body_0|> <|body_start_1|> if not head or not head.next: return head cur, pre = (None, head...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head: ListNode) -> ListNode: """递归方法 :param head: :return:""" <|body_0|> def reverseList2(self, head: ListNode) -> ListNode: """双指针 使用中间节点存储以前的值, 把当前节点的next指向前面,然后把两个指针依次后移 :param head: :return:""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_016465
1,212
no_license
[ { "docstring": "递归方法 :param head: :return:", "name": "reverseList", "signature": "def reverseList(self, head: ListNode) -> ListNode" }, { "docstring": "双指针 使用中间节点存储以前的值, 把当前节点的next指向前面,然后把两个指针依次后移 :param head: :return:", "name": "reverseList2", "signature": "def reverseList2(self, head: ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head: ListNode) -> ListNode: 递归方法 :param head: :return: - def reverseList2(self, head: ListNode) -> ListNode: 双指针 使用中间节点存储以前的值, 把当前节点的next指向前面,然后把两个指针依次后移 :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head: ListNode) -> ListNode: 递归方法 :param head: :return: - def reverseList2(self, head: ListNode) -> ListNode: 双指针 使用中间节点存储以前的值, 把当前节点的next指向前面,然后把两个指针依次后移 :...
578cacff5851c5c2522981693c34e3c318002d30
<|skeleton|> class Solution: def reverseList(self, head: ListNode) -> ListNode: """递归方法 :param head: :return:""" <|body_0|> def reverseList2(self, head: ListNode) -> ListNode: """双指针 使用中间节点存储以前的值, 把当前节点的next指向前面,然后把两个指针依次后移 :param head: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverseList(self, head: ListNode) -> ListNode: """递归方法 :param head: :return:""" if not head or not head.next: return head cur = self.reverseList(head.next) head.next.next = head head.next = None return cur def reverseList2(self, he...
the_stack_v2_python_sparse
剑指offer/反转链表.py
cjrzs/MyLeetCode
train
8
52e4e25fe8965a2eeb15cd600a31e3fa831cfbb3
[ "super(LinearTransformFineCoattention, self).__init__()\nwith self.init_scope():\n self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1)\n self.j_layer = GraphLinear(hidden_dim, out_dim)\nself.hidden_dim = hidden_dim\nself.out_dim = out_dim\nself.activation = activation", "mb = atoms_1.shape[0]\nN_1...
<|body_start_0|> super(LinearTransformFineCoattention, self).__init__() with self.init_scope(): self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1) self.j_layer = GraphLinear(hidden_dim, out_dim) self.hidden_dim = hidden_dim self.out_dim = out_dim ...
TODO
LinearTransformFineCoattention
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearTransformFineCoattention: """TODO""" def __init__(self, hidden_dim, out_dim, activation=functions.tanh): """:param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation""" <|body_0|> def __call__(self, atoms_1, g_1, atom...
stack_v2_sparse_classes_36k_train_016466
4,044
permissive
[ { "docstring": ":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation", "name": "__init__", "signature": "def __init__(self, hidden_dim, out_dim, activation=functions.tanh)" }, { "docstring": ":param atoms_1: atomic representation of molecule 1...
3
stack_v2_sparse_classes_30k_train_012861
Implement the Python class `LinearTransformFineCoattention` described below. Class description: TODO Method signatures and docstrings: - def __init__(self, hidden_dim, out_dim, activation=functions.tanh): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation - def _...
Implement the Python class `LinearTransformFineCoattention` described below. Class description: TODO Method signatures and docstrings: - def __init__(self, hidden_dim, out_dim, activation=functions.tanh): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation - def _...
21b64a3c8cc9bc33718ae09c65aa917e575132eb
<|skeleton|> class LinearTransformFineCoattention: """TODO""" def __init__(self, hidden_dim, out_dim, activation=functions.tanh): """:param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation""" <|body_0|> def __call__(self, atoms_1, g_1, atom...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearTransformFineCoattention: """TODO""" def __init__(self, hidden_dim, out_dim, activation=functions.tanh): """:param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation""" super(LinearTransformFineCoattention, self).__init__() wit...
the_stack_v2_python_sparse
models/coattention/lt_fine_coattention.py
Minys233/GCN-BMP
train
1
ed7b0b9e14418a4cf83d91b1cd44a4ad3018d8df
[ "super().__init__(title, group_name)\nself.compound = compound\nrt_ref: metob.RtReference = compound['identification'].rt_references[0]\nself.rt_range: Tuple[float, float] = (rt_ref.rt_min, rt_ref.rt_max)\nself.rt_peak: float = rt_ref.rt_peak\nself.rt_buffer = rt_buffer", "super().plot(ax, back_color)\nself._draw...
<|body_start_0|> super().__init__(title, group_name) self.compound = compound rt_ref: metob.RtReference = compound['identification'].rt_references[0] self.rt_range: Tuple[float, float] = (rt_ref.rt_min, rt_ref.rt_max) self.rt_peak: float = rt_ref.rt_peak self.rt_buffer = ...
EIC for one compound within a single sample
CompoundEic
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompoundEic: """EIC for one compound within a single sample""" def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float=0.5): """compound: Compound instance rt_buffer: amount of time in minutes to show to each side of rt_min/rt_max/rt_peak""" ...
stack_v2_sparse_classes_36k_train_016467
3,948
permissive
[ { "docstring": "compound: Compound instance rt_buffer: amount of time in minutes to show to each side of rt_min/rt_max/rt_peak", "name": "__init__", "signature": "def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float=0.5)" }, { "docstring": "Draw plot of EIC ...
4
stack_v2_sparse_classes_30k_train_020867
Implement the Python class `CompoundEic` described below. Class description: EIC for one compound within a single sample Method signatures and docstrings: - def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float=0.5): compound: Compound instance rt_buffer: amount of time in minutes...
Implement the Python class `CompoundEic` described below. Class description: EIC for one compound within a single sample Method signatures and docstrings: - def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float=0.5): compound: Compound instance rt_buffer: amount of time in minutes...
909ede3d1fe75fa5d64c6ff1b4c6016dc3df6746
<|skeleton|> class CompoundEic: """EIC for one compound within a single sample""" def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float=0.5): """compound: Compound instance rt_buffer: amount of time in minutes to show to each side of rt_min/rt_max/rt_peak""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompoundEic: """EIC for one compound within a single sample""" def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float=0.5): """compound: Compound instance rt_buffer: amount of time in minutes to show to each side of rt_min/rt_max/rt_peak""" super().__in...
the_stack_v2_python_sparse
metatlas/plots/compound_eic.py
biorack/metatlas
train
10
79fe33879daaf7191e44567c3d43c9c598e32f2b
[ "media = self.media_info(media_pk)\nassert media.media_type == 8, 'Must been album'\npaths = []\nfor resource in media.resources:\n filename = f'{media.user.username}_{resource.pk}'\n if resource.media_type == 1:\n paths.append(self.photo_download_by_url(resource.thumbnail_url, filename, folder))\n ...
<|body_start_0|> media = self.media_info(media_pk) assert media.media_type == 8, 'Must been album' paths = [] for resource in media.resources: filename = f'{media.user.username}_{resource.pk}' if resource.media_type == 1: paths.append(self.photo_do...
Helper class to download album
DownloadAlbumMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DownloadAlbumMixin: """Helper class to download album""" def album_download(self, media_pk: int, folder: Path='') -> List[Path]: """Download your album Parameters ---------- media_pk: int PK for the album you want to download folder: Path, optional Directory in which you want to down...
stack_v2_sparse_classes_36k_train_016468
8,777
permissive
[ { "docstring": "Download your album Parameters ---------- media_pk: int PK for the album you want to download folder: Path, optional Directory in which you want to download the album, default is \"\" and will download the files to working directory. Returns ------- List[Path] List of path for all the files down...
2
stack_v2_sparse_classes_30k_train_017273
Implement the Python class `DownloadAlbumMixin` described below. Class description: Helper class to download album Method signatures and docstrings: - def album_download(self, media_pk: int, folder: Path='') -> List[Path]: Download your album Parameters ---------- media_pk: int PK for the album you want to download f...
Implement the Python class `DownloadAlbumMixin` described below. Class description: Helper class to download album Method signatures and docstrings: - def album_download(self, media_pk: int, folder: Path='') -> List[Path]: Download your album Parameters ---------- media_pk: int PK for the album you want to download f...
14922b4038de0b693c6dd396c7ee0b57e626f32e
<|skeleton|> class DownloadAlbumMixin: """Helper class to download album""" def album_download(self, media_pk: int, folder: Path='') -> List[Path]: """Download your album Parameters ---------- media_pk: int PK for the album you want to download folder: Path, optional Directory in which you want to down...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DownloadAlbumMixin: """Helper class to download album""" def album_download(self, media_pk: int, folder: Path='') -> List[Path]: """Download your album Parameters ---------- media_pk: int PK for the album you want to download folder: Path, optional Directory in which you want to download the albu...
the_stack_v2_python_sparse
instagrapi/mixins/album.py
bedefaced/instagrapi
train
1
5b200bed84a3c38dbb7e90eeb52bb2e1ad1a36b7
[ "if not s:\n return 0\ndp = [0] * (len(s) + 1)\ndp[0] = 1\nfor i in range(1, len(s) + 1):\n if s[i - 1] != '0':\n dp[i] += dp[i - 1]\n if i != 1 and s[i - 2:i] > '09' and (s[i - 2:i] < '27'):\n dp[i] += dp[i - 2]\nreturn dp[len(s)]", "if s.startswith('0'):\n return 0\nn = len(s)\ndp = [1...
<|body_start_0|> if not s: return 0 dp = [0] * (len(s) + 1) dp[0] = 1 for i in range(1, len(s) + 1): if s[i - 1] != '0': dp[i] += dp[i - 1] if i != 1 and s[i - 2:i] > '09' and (s[i - 2:i] < '27'): dp[i] += dp[i - 2] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numDecodings_20211226(self, s: str) -> int: """状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]""" <|body_0|> def numDecodings(self, s: str) -> int: """状态: dp[i]: 若前 i 个字符可以解码, 表示前 i 个字符可以解码的方法数 若前 i 个字符不能解码,那整个字符串肯定不...
stack_v2_sparse_classes_36k_train_016469
1,633
no_license
[ { "docstring": "状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]", "name": "numDecodings_20211226", "signature": "def numDecodings_20211226(self, s: str) -> int" }, { "docstring": "状态: dp[i]: 若前 i 个字符可以解码, 表示前 i 个字符可以解码的方法数 若前 i 个字符不能解码,那整个字符串肯定不能解码,我们无需再进行下去了...
2
stack_v2_sparse_classes_30k_train_021062
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numDecodings_20211226(self, s: str) -> int: 状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2] - def numDecodings(self, s: str) -> int: 状态: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numDecodings_20211226(self, s: str) -> int: 状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2] - def numDecodings(self, s: str) -> int: 状态: ...
f350b3d6e59fd5771e11ec0b466f9ba5eeb8e927
<|skeleton|> class Solution: def numDecodings_20211226(self, s: str) -> int: """状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]""" <|body_0|> def numDecodings(self, s: str) -> int: """状态: dp[i]: 若前 i 个字符可以解码, 表示前 i 个字符可以解码的方法数 若前 i 个字符不能解码,那整个字符串肯定不...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numDecodings_20211226(self, s: str) -> int: """状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]""" if not s: return 0 dp = [0] * (len(s) + 1) dp[0] = 1 for i in range(1, len(s) + 1): if s[i - 1] !...
the_stack_v2_python_sparse
leetcode/python/91.py
ShawnDong98/Algorithm-Book
train
0
79a6fc90ebd8d2a827cbc40eecab2f38f78fecf6
[ "super(SentimentRNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embedding = nn.Embedding(vocab_size, embedding_dim)\nself.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)\nself.dropout = nn.Dropout(0.3)\nself...
<|body_start_0|> super(SentimentRNN, self).__init__() self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim self.embedding = nn.Embedding(vocab_size, embedding_dim) self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, ...
The RNN model that will be used to perform Sentiment analysis. vocab_size: Size of our vocabulary or the range of values for our input, word tokens. output_size: Size of our desired output; the number of class scores we want to output (pos/neg). embedding_dim: Number of columns in the embedding lookup table; size of ou...
SentimentRNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SentimentRNN: """The RNN model that will be used to perform Sentiment analysis. vocab_size: Size of our vocabulary or the range of values for our input, word tokens. output_size: Size of our desired output; the number of class scores we want to output (pos/neg). embedding_dim: Number of columns i...
stack_v2_sparse_classes_36k_train_016470
14,084
permissive
[ { "docstring": "Initialize the model by setting up the layers.", "name": "__init__", "signature": "def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5)" }, { "docstring": "Perform a forward pass of our model on some input and hidden state.", "name":...
3
stack_v2_sparse_classes_30k_train_016834
Implement the Python class `SentimentRNN` described below. Class description: The RNN model that will be used to perform Sentiment analysis. vocab_size: Size of our vocabulary or the range of values for our input, word tokens. output_size: Size of our desired output; the number of class scores we want to output (pos/n...
Implement the Python class `SentimentRNN` described below. Class description: The RNN model that will be used to perform Sentiment analysis. vocab_size: Size of our vocabulary or the range of values for our input, word tokens. output_size: Size of our desired output; the number of class scores we want to output (pos/n...
b9b54564f94aadfc3c71ff513da0f05ef85d22a8
<|skeleton|> class SentimentRNN: """The RNN model that will be used to perform Sentiment analysis. vocab_size: Size of our vocabulary or the range of values for our input, word tokens. output_size: Size of our desired output; the number of class scores we want to output (pos/neg). embedding_dim: Number of columns i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SentimentRNN: """The RNN model that will be used to perform Sentiment analysis. vocab_size: Size of our vocabulary or the range of values for our input, word tokens. output_size: Size of our desired output; the number of class scores we want to output (pos/neg). embedding_dim: Number of columns in the embeddi...
the_stack_v2_python_sparse
dl/pytorch/rnn/sentiment.py
xta0/Python-Playground
train
0
82538a4576d08100583c46aa593b218dbe36934e
[ "self._resolver = resolver\nself._port = port\nself._lock_monitor_cb = lock_monitor_cb", "results = {}\nrequests = {}\nassert isinstance(body, dict)\nassert len(body) == len(hosts)\nassert compat.all((isinstance(v, (str, bytes)) for v in body.values()))\nassert frozenset((h[2] for h in hosts)) == frozenset(body),...
<|body_start_0|> self._resolver = resolver self._port = port self._lock_monitor_cb = lock_monitor_cb <|end_body_0|> <|body_start_1|> results = {} requests = {} assert isinstance(body, dict) assert len(body) == len(hosts) assert compat.all((isinstance(v, (...
_RpcProcessor
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _RpcProcessor: def __init__(self, resolver, port, lock_monitor_cb=None): """Initializes this class. @param resolver: callable accepting a list of node UUIDs or hostnames, returning a list of tuples containing name, IP address and original name of the resolved node. IP address can be the ...
stack_v2_sparse_classes_36k_train_016471
33,673
permissive
[ { "docstring": "Initializes this class. @param resolver: callable accepting a list of node UUIDs or hostnames, returning a list of tuples containing name, IP address and original name of the resolved node. IP address can be the name or the special value L{_OFFLINE} to mark offline machines. @type port: int @par...
4
null
Implement the Python class `_RpcProcessor` described below. Class description: Implement the _RpcProcessor class. Method signatures and docstrings: - def __init__(self, resolver, port, lock_monitor_cb=None): Initializes this class. @param resolver: callable accepting a list of node UUIDs or hostnames, returning a lis...
Implement the Python class `_RpcProcessor` described below. Class description: Implement the _RpcProcessor class. Method signatures and docstrings: - def __init__(self, resolver, port, lock_monitor_cb=None): Initializes this class. @param resolver: callable accepting a list of node UUIDs or hostnames, returning a lis...
456ea285a7583183c2c8e5bcffe9006ec8a9d658
<|skeleton|> class _RpcProcessor: def __init__(self, resolver, port, lock_monitor_cb=None): """Initializes this class. @param resolver: callable accepting a list of node UUIDs or hostnames, returning a list of tuples containing name, IP address and original name of the resolved node. IP address can be the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _RpcProcessor: def __init__(self, resolver, port, lock_monitor_cb=None): """Initializes this class. @param resolver: callable accepting a list of node UUIDs or hostnames, returning a list of tuples containing name, IP address and original name of the resolved node. IP address can be the name or the sp...
the_stack_v2_python_sparse
lib/rpc/node.py
ganeti/ganeti
train
465
c211c64f6568d18d2cd296e515ff53f1bfb117ef
[ "production_multiplier = 1\nstart_years = Incentives._data['start_year']\nif len(start_years[start_years <= vehicle.model_year]) > 0:\n cache_key = max(start_years[start_years <= vehicle.model_year])\n if cache_key in Incentives._data:\n calcs = Incentives._data[cache_key]\n for calc, multiplier...
<|body_start_0|> production_multiplier = 1 start_years = Incentives._data['start_year'] if len(start_years[start_years <= vehicle.model_year]) > 0: cache_key = max(start_years[start_years <= vehicle.model_year]) if cache_key in Incentives._data: calcs = In...
**Loads and provides access to GHG incentives.**
Incentives
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Incentives: """**Loads and provides access to GHG incentives.**""" def get_production_multiplier(vehicle): """Get production multiplier (if any) for the given vehicle. Args: vehicle (Vehicle): the vehicle to get the multiplier for Returns: The production multiplier, if applicable, or...
stack_v2_sparse_classes_36k_train_016472
5,113
no_license
[ { "docstring": "Get production multiplier (if any) for the given vehicle. Args: vehicle (Vehicle): the vehicle to get the multiplier for Returns: The production multiplier, if applicable, or 1.0", "name": "get_production_multiplier", "signature": "def get_production_multiplier(vehicle)" }, { "do...
2
null
Implement the Python class `Incentives` described below. Class description: **Loads and provides access to GHG incentives.** Method signatures and docstrings: - def get_production_multiplier(vehicle): Get production multiplier (if any) for the given vehicle. Args: vehicle (Vehicle): the vehicle to get the multiplier ...
Implement the Python class `Incentives` described below. Class description: **Loads and provides access to GHG incentives.** Method signatures and docstrings: - def get_production_multiplier(vehicle): Get production multiplier (if any) for the given vehicle. Args: vehicle (Vehicle): the vehicle to get the multiplier ...
afe912c57383b9de90ef30820f7977c3367a30c4
<|skeleton|> class Incentives: """**Loads and provides access to GHG incentives.**""" def get_production_multiplier(vehicle): """Get production multiplier (if any) for the given vehicle. Args: vehicle (Vehicle): the vehicle to get the multiplier for Returns: The production multiplier, if applicable, or...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Incentives: """**Loads and provides access to GHG incentives.**""" def get_production_multiplier(vehicle): """Get production multiplier (if any) for the given vehicle. Args: vehicle (Vehicle): the vehicle to get the multiplier for Returns: The production multiplier, if applicable, or 1.0""" ...
the_stack_v2_python_sparse
omega_model/policy/incentives.py
USEPA/EPA_OMEGA_Model
train
17
9a13a641f8ec42e9ed6e1dc4fca9529199bc50fe
[ "res = 0\nn = len(prices)\nif n <= 1:\n return 0\nminpre = prices[0]\nfor i in range(1, n):\n res = max(prices[i] - minpre, res)\n minpre = min(prices[i], minpre)\nreturn res", "res = 0\nn = len(prices)\nif n <= 1:\n return 0\ndp = [[0 for i in range(2)] for j in range(n)]\ndp[0][0] = 0\ndp[0][1] = -p...
<|body_start_0|> res = 0 n = len(prices) if n <= 1: return 0 minpre = prices[0] for i in range(1, n): res = max(prices[i] - minpre, res) minpre = min(prices[i], minpre) return res <|end_body_0|> <|body_start_1|> res = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """只交易一次""" <|body_0|> def maxProfit(self, prices: List[int]) -> int: """给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_016473
1,188
no_license
[ { "docstring": "只交易一次", "name": "maxProfit", "signature": "def maxProfit(self, prices: List[int]) -> int" }, { "docstring": "给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。", "name": "maxProfit", "signature": "def maxProfi...
2
stack_v2_sparse_classes_30k_train_010663
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 只交易一次 - def maxProfit(self, prices: List[int]) -> int: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 只交易一次 - def maxProfit(self, prices: List[int]) -> int: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票...
cb3587242195bb3f2626231af2da13b90945a4d5
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """只交易一次""" <|body_0|> def maxProfit(self, prices: List[int]) -> int: """给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices: List[int]) -> int: """只交易一次""" res = 0 n = len(prices) if n <= 1: return 0 minpre = prices[0] for i in range(1, n): res = max(prices[i] - minpre, res) minpre = min(prices[i], minpre) ...
the_stack_v2_python_sparse
MianShi/zijie/买卖股票的最佳时机N121.py
lionheartStark/sword_towards_offer
train
0
731a6d470386933676630447a2b9fbc42ca67924
[ "self.busbars = busbars\nself.entries = dict()\nself.columns = constants.GUI.busbar_columns\nself.vertical_busbars = constants.GUI.vertical_busbars\nself.master = master\nself.master.protocol('WM_DELETE_WINDOW', self.on_closing)\nself.master.title = 'Identified Busbars'\nlbl = Tk.Label(self.master, text='Edit busba...
<|body_start_0|> self.busbars = busbars self.entries = dict() self.columns = constants.GUI.busbar_columns self.vertical_busbars = constants.GUI.vertical_busbars self.master = master self.master.protocol('WM_DELETE_WINDOW', self.on_closing) self.master.title = 'Ide...
Produces a new window which is used to contain a list of busbars which can be edited by the user and then adjusted to produce the required output.
BusbarsWindow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BusbarsWindow: """Produces a new window which is used to contain a list of busbars which can be edited by the user and then adjusted to produce the required output.""" def __init__(self, master, busbars=list()): """Produce window which contains details of all the busbars that will be...
stack_v2_sparse_classes_36k_train_016474
27,259
no_license
[ { "docstring": "Produce window which contains details of all the busbars that will be faulted and the ability to edit the busbars lists :param Tk.Tk() master: This is the main window master which this one will be popped up on-top of :param list busbars: List of busbars to be faulted will initially be populated ...
5
stack_v2_sparse_classes_30k_train_018222
Implement the Python class `BusbarsWindow` described below. Class description: Produces a new window which is used to contain a list of busbars which can be edited by the user and then adjusted to produce the required output. Method signatures and docstrings: - def __init__(self, master, busbars=list()): Produce wind...
Implement the Python class `BusbarsWindow` described below. Class description: Produces a new window which is used to contain a list of busbars which can be edited by the user and then adjusted to produce the required output. Method signatures and docstrings: - def __init__(self, master, busbars=list()): Produce wind...
16c479e31e1d02eadb64bd0452324c9d3af4ca9e
<|skeleton|> class BusbarsWindow: """Produces a new window which is used to contain a list of busbars which can be edited by the user and then adjusted to produce the required output.""" def __init__(self, master, busbars=list()): """Produce window which contains details of all the busbars that will be...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BusbarsWindow: """Produces a new window which is used to contain a list of busbars which can be edited by the user and then adjusted to produce the required output.""" def __init__(self, master, busbars=list()): """Produce window which contains details of all the busbars that will be faulted and ...
the_stack_v2_python_sparse
g74/gui.py
NegarShams/JK7938_SHEPD_FaultLevels
train
0
6a97151cbeabba5790948417ac96426ba1e8480c
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DefenderDetectedMalwareActions()", "from .defender_threat_action import DefenderThreatAction\nfrom .defender_threat_action import DefenderThreatAction\nfields: Dict[str, Callable[[Any], None]] = {'highSeverity': lambda n: setattr(self,...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return DefenderDetectedMalwareActions() <|end_body_0|> <|body_start_1|> from .defender_threat_action import DefenderThreatAction from .defender_threat_action import DefenderThreatAction ...
Specify Defender’s actions to take on detected Malware per threat level.
DefenderDetectedMalwareActions
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DefenderDetectedMalwareActions: """Specify Defender’s actions to take on detected Malware per threat level.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DefenderDetectedMalwareActions: """Creates a new instance of the appropriate class based on disc...
stack_v2_sparse_classes_36k_train_016475
3,857
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: DefenderDetectedMalwareActions", "name": "create_from_discriminator_value", "signature": "def create_from_di...
3
null
Implement the Python class `DefenderDetectedMalwareActions` described below. Class description: Specify Defender’s actions to take on detected Malware per threat level. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DefenderDetectedMalwareActions: Crea...
Implement the Python class `DefenderDetectedMalwareActions` described below. Class description: Specify Defender’s actions to take on detected Malware per threat level. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DefenderDetectedMalwareActions: Crea...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class DefenderDetectedMalwareActions: """Specify Defender’s actions to take on detected Malware per threat level.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DefenderDetectedMalwareActions: """Creates a new instance of the appropriate class based on disc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DefenderDetectedMalwareActions: """Specify Defender’s actions to take on detected Malware per threat level.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DefenderDetectedMalwareActions: """Creates a new instance of the appropriate class based on discriminator val...
the_stack_v2_python_sparse
msgraph/generated/models/defender_detected_malware_actions.py
microsoftgraph/msgraph-sdk-python
train
135
f2aed85036073f6f73e79d026b88aeb6163f0b08
[ "if final_structure.formula != initial_structure.formula:\n raise ValueError('Initial and final structures have different ' + 'formulas!')\nself.initial = initial_structure\nself.final = final_structure", "initial_vol = self.initial.lattice.volume\nfinal_vol = self.final.lattice.volume\nreturn final_vol / init...
<|body_start_0|> if final_structure.formula != initial_structure.formula: raise ValueError('Initial and final structures have different ' + 'formulas!') self.initial = initial_structure self.final = final_structure <|end_body_0|> <|body_start_1|> initial_vol = self.initial.l...
This class analyzes the relaxation in a calculation.
RelaxationAnalyzer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelaxationAnalyzer: """This class analyzes the relaxation in a calculation.""" def __init__(self, initial_structure, final_structure): """Please note that the input and final structures should have the same ordering of sites. This is typically the case for most computational codes. A...
stack_v2_sparse_classes_36k_train_016476
24,388
permissive
[ { "docstring": "Please note that the input and final structures should have the same ordering of sites. This is typically the case for most computational codes. Args: initial_structure (Structure): Initial input structure to calculation. final_structure (Structure): Final output structure from calculation.", ...
4
null
Implement the Python class `RelaxationAnalyzer` described below. Class description: This class analyzes the relaxation in a calculation. Method signatures and docstrings: - def __init__(self, initial_structure, final_structure): Please note that the input and final structures should have the same ordering of sites. T...
Implement the Python class `RelaxationAnalyzer` described below. Class description: This class analyzes the relaxation in a calculation. Method signatures and docstrings: - def __init__(self, initial_structure, final_structure): Please note that the input and final structures should have the same ordering of sites. T...
62ecae1c7382a41861e3a5d9b9c8dd1207472409
<|skeleton|> class RelaxationAnalyzer: """This class analyzes the relaxation in a calculation.""" def __init__(self, initial_structure, final_structure): """Please note that the input and final structures should have the same ordering of sites. This is typically the case for most computational codes. A...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelaxationAnalyzer: """This class analyzes the relaxation in a calculation.""" def __init__(self, initial_structure, final_structure): """Please note that the input and final structures should have the same ordering of sites. This is typically the case for most computational codes. Args: initial_...
the_stack_v2_python_sparse
pymatgen/analysis/structure_analyzer.py
montoyjh/pymatgen
train
2
14d17d6a2ffa10a70eef465f3a0027e703359b52
[ "user = self.personalize_page_and_get_user()\nif not user:\n self.redirect(users.create_login_url(self.request.uri), normalize=False)\n return\nstudent = Student.get_enrolled_student_by_email(user.email())\nif student:\n self.redirect('/course')\n return\ncan_register = self.app_context.get_environ()['r...
<|body_start_0|> user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri), normalize=False) return student = Student.get_enrolled_student_by_email(user.email()) if student: self.redirect('/course')...
Handler for course registration.
RegisterHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegisterHandler: """Handler for course registration.""" def get(self): """Handles GET request.""" <|body_0|> def post(self): """Handles POST requests.""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = self.personalize_page_and_get_user() ...
stack_v2_sparse_classes_36k_train_016477
24,555
permissive
[ { "docstring": "Handles GET request.", "name": "get", "signature": "def get(self)" }, { "docstring": "Handles POST requests.", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_004445
Implement the Python class `RegisterHandler` described below. Class description: Handler for course registration. Method signatures and docstrings: - def get(self): Handles GET request. - def post(self): Handles POST requests.
Implement the Python class `RegisterHandler` described below. Class description: Handler for course registration. Method signatures and docstrings: - def get(self): Handles GET request. - def post(self): Handles POST requests. <|skeleton|> class RegisterHandler: """Handler for course registration.""" def ge...
1bd1eeb41ad77f31c95897916efdb4a5a9cef2a8
<|skeleton|> class RegisterHandler: """Handler for course registration.""" def get(self): """Handles GET request.""" <|body_0|> def post(self): """Handles POST requests.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegisterHandler: """Handler for course registration.""" def get(self): """Handles GET request.""" user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri), normalize=False) return student = Stud...
the_stack_v2_python_sparse
coursebuilder/controllers/utils.py
xaferima/Malware-MetasploitLab
train
1
0771dde3c88db872a004e7b7d169c40014b13677
[ "self.dataframe = df\nself.rows_count = None\nself.variables_count = None\nself.has_error = False\nself.error_messages = []\nself.final_output = OrderedDict()\nself.set_values()", "if self.dataframe is not None:\n self.rows_count = self.dataframe.shape[0]\n self.variables_count = len(self.dataframe.columns)...
<|body_start_0|> self.dataframe = df self.rows_count = None self.variables_count = None self.has_error = False self.error_messages = [] self.final_output = OrderedDict() self.set_values() <|end_body_0|> <|body_start_1|> if self.dataframe is not None: ...
DatasetLevelInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatasetLevelInfo: def __init__(self, df): """This class sets the dataset level info of the preprocess file.""" <|body_0|> def set_values(self): """"dataset": { "row_cnt": 1000, "variable_cnt": 25 }""" <|body_1|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_36k_train_016478
1,809
permissive
[ { "docstring": "This class sets the dataset level info of the preprocess file.", "name": "__init__", "signature": "def __init__(self, df)" }, { "docstring": "\"dataset\": { \"row_cnt\": 1000, \"variable_cnt\": 25 }", "name": "set_values", "signature": "def set_values(self)" } ]
2
stack_v2_sparse_classes_30k_train_020692
Implement the Python class `DatasetLevelInfo` described below. Class description: Implement the DatasetLevelInfo class. Method signatures and docstrings: - def __init__(self, df): This class sets the dataset level info of the preprocess file. - def set_values(self): "dataset": { "row_cnt": 1000, "variable_cnt": 25 }
Implement the Python class `DatasetLevelInfo` described below. Class description: Implement the DatasetLevelInfo class. Method signatures and docstrings: - def __init__(self, df): This class sets the dataset level info of the preprocess file. - def set_values(self): "dataset": { "row_cnt": 1000, "variable_cnt": 25 } ...
9461522219f5ef0f4877f24c8f5923e462bd9557
<|skeleton|> class DatasetLevelInfo: def __init__(self, df): """This class sets the dataset level info of the preprocess file.""" <|body_0|> def set_values(self): """"dataset": { "row_cnt": 1000, "variable_cnt": 25 }""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatasetLevelInfo: def __init__(self, df): """This class sets the dataset level info of the preprocess file.""" self.dataframe = df self.rows_count = None self.variables_count = None self.has_error = False self.error_messages = [] self.final_output = Orde...
the_stack_v2_python_sparse
preprocess/raven_preprocess/dataset_level_info_util.py
TwoRavens/raven-metadata-service
train
0
bc93425ccf2ea0bf2112737c247253ba64b772e4
[ "paginator, page, qs, has_other_pages = self.paginate_queryset(queryset, self.paginate_by)\nprev = paginator.previous_page_number if paginator.has_previous() else None\nnext = paginator.next_page_number if paginator.has_other_pages() else None\nreturn {'count': len(queryset), 'total_pages': paginator.num_pages, 'pr...
<|body_start_0|> paginator, page, qs, has_other_pages = self.paginate_queryset(queryset, self.paginate_by) prev = paginator.previous_page_number if paginator.has_previous() else None next = paginator.next_page_number if paginator.has_other_pages() else None return {'count': len(queryset)...
Movies
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Movies: def custom_paginate_queryset(self, queryset): """Дополнение встроенного пагинатора""" <|body_0|> def get_context_data(self, *, object_list=None, **kwargs): """Возвращает постраничную информацию о фильмах""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_016479
3,990
no_license
[ { "docstring": "Дополнение встроенного пагинатора", "name": "custom_paginate_queryset", "signature": "def custom_paginate_queryset(self, queryset)" }, { "docstring": "Возвращает постраничную информацию о фильмах", "name": "get_context_data", "signature": "def get_context_data(self, *, ob...
2
stack_v2_sparse_classes_30k_train_019266
Implement the Python class `Movies` described below. Class description: Implement the Movies class. Method signatures and docstrings: - def custom_paginate_queryset(self, queryset): Дополнение встроенного пагинатора - def get_context_data(self, *, object_list=None, **kwargs): Возвращает постраничную информацию о филь...
Implement the Python class `Movies` described below. Class description: Implement the Movies class. Method signatures and docstrings: - def custom_paginate_queryset(self, queryset): Дополнение встроенного пагинатора - def get_context_data(self, *, object_list=None, **kwargs): Возвращает постраничную информацию о филь...
95f6520de331cb762a4351acf3bbea10e570f040
<|skeleton|> class Movies: def custom_paginate_queryset(self, queryset): """Дополнение встроенного пагинатора""" <|body_0|> def get_context_data(self, *, object_list=None, **kwargs): """Возвращает постраничную информацию о фильмах""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Movies: def custom_paginate_queryset(self, queryset): """Дополнение встроенного пагинатора""" paginator, page, qs, has_other_pages = self.paginate_queryset(queryset, self.paginate_by) prev = paginator.previous_page_number if paginator.has_previous() else None next = paginator.n...
the_stack_v2_python_sparse
admin_service/api/v1/views.py
frbgd/Auth_sprint_2-1
train
0
94950b9d0d2420b80d50b149182f0325d557d4d9
[ "l = 0\nr = len(List) - 1\nif l > r:\n return None\nif l == r:\n return TreeNode(List[l])\nmid = int((l + r) / 2)\nroot = TreeNode(List[mid])\nroot.left = self.build_tree(List[:mid])\nroot.right = self.build_tree(List[mid + 1:])\nreturn root", "if not root:\n return []\nqueue = []\nresult = []\nqueue.app...
<|body_start_0|> l = 0 r = len(List) - 1 if l > r: return None if l == r: return TreeNode(List[l]) mid = int((l + r) / 2) root = TreeNode(List[mid]) root.left = self.build_tree(List[:mid]) root.right = self.build_tree(List[mid + 1:]...
二叉树结构类
BinaryTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryTree: """二叉树结构类""" def build_tree(self, List): """构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归""" <|body_0|> def PrintFromTopToBottom(self, root): """从上往下打印二叉树——层序遍历""" <|body_1|> def Mirror(self, root): ...
stack_v2_sparse_classes_36k_train_016480
4,754
no_license
[ { "docstring": "构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归", "name": "build_tree", "signature": "def build_tree(self, List)" }, { "docstring": "从上往下打印二叉树——层序遍历", "name": "PrintFromTopToBottom", "signature": "def PrintFromTopToBottom(self, root)" }, ...
3
stack_v2_sparse_classes_30k_train_021478
Implement the Python class `BinaryTree` described below. Class description: 二叉树结构类 Method signatures and docstrings: - def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归 - def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历 - def Mirror(self, root): 构造二叉树镜像
Implement the Python class `BinaryTree` described below. Class description: 二叉树结构类 Method signatures and docstrings: - def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归 - def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历 - def Mirror(self, root): 构造二叉树镜像 <|...
4e4f739402b95691f6c91411da26d7d3bfe042b6
<|skeleton|> class BinaryTree: """二叉树结构类""" def build_tree(self, List): """构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归""" <|body_0|> def PrintFromTopToBottom(self, root): """从上往下打印二叉树——层序遍历""" <|body_1|> def Mirror(self, root): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryTree: """二叉树结构类""" def build_tree(self, List): """构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归""" l = 0 r = len(List) - 1 if l > r: return None if l == r: return TreeNode(List[l]) mid = int((l +...
the_stack_v2_python_sparse
剑指offer/58.对称的二叉树.py
hugechuanqi/Algorithms-and-Data-Structures
train
3
1b78c7d9d8a926db4786577ea8ebd650eecd1d3c
[ "super(LandmarkGeneratorMultipleHeatmap, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)\nself.output_size_np = list(reversed(self.output_size))\nself.sigma = sigma\nself.scale_factor = scale_factor\nself.normalize_center = normalize_cent...
<|body_start_0|> super(LandmarkGeneratorMultipleHeatmap, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation) self.output_size_np = list(reversed(self.output_size)) self.sigma = sigma self.scale_factor = scale_facto...
Generates heatmap images with multiple Gaussian peaks
LandmarkGeneratorMultipleHeatmap
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LandmarkGeneratorMultipleHeatmap: """Generates heatmap images with multiple Gaussian peaks""" def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformatio...
stack_v2_sparse_classes_36k_train_016481
16,690
no_license
[ { "docstring": "Initializer :param output_size: output image size :param sigma: Gaussian sigma :param scale_factor: heatmap scale factor, each value of the Gaussian will be multiplied with this value :param normalize_center: if True, the value on the center is set to scale_factor otherwise, the default gaussian...
2
stack_v2_sparse_classes_30k_train_019255
Implement the Python class `LandmarkGeneratorMultipleHeatmap` described below. Class description: Generates heatmap images with multiple Gaussian peaks Method signatures and docstrings: - def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_...
Implement the Python class `LandmarkGeneratorMultipleHeatmap` described below. Class description: Generates heatmap images with multiple Gaussian peaks Method signatures and docstrings: - def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_...
ef6cee91264ba1fe6b40d9823a07647b95bcc2c4
<|skeleton|> class LandmarkGeneratorMultipleHeatmap: """Generates heatmap images with multiple Gaussian peaks""" def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformatio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LandmarkGeneratorMultipleHeatmap: """Generates heatmap images with multiple Gaussian peaks""" def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformation=None): ...
the_stack_v2_python_sparse
generators/landmark_generator.py
XiaoweiXu/MedicalDataAugmentationTool
train
1
67e9754a63d7c48778858b96bf7967510c6daf8f
[ "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...
[Google Service Control API](/service-control/overview) Lets clients check and report operations against a [managed service][google.api.servicemanagement.v1.ManagedService].
ServiceControllerServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceControllerServicer: """[Google Service Control API](/service-control/overview) Lets clients check and report operations against a [managed service][google.api.servicemanagement.v1.ManagedService].""" def Check(self, request, context): """Checks an operation with Google Service...
stack_v2_sparse_classes_36k_train_016482
4,241
no_license
[ { "docstring": "Checks an operation with Google Service Control to decide whether the given operation should proceed. It should be called before the operation is executed. If feasible, the client should cache the check results and reuse them for 60 seconds. In case of server errors, the client can rely on the c...
2
stack_v2_sparse_classes_30k_train_010513
Implement the Python class `ServiceControllerServicer` described below. Class description: [Google Service Control API](/service-control/overview) Lets clients check and report operations against a [managed service][google.api.servicemanagement.v1.ManagedService]. Method signatures and docstrings: - def Check(self, r...
Implement the Python class `ServiceControllerServicer` described below. Class description: [Google Service Control API](/service-control/overview) Lets clients check and report operations against a [managed service][google.api.servicemanagement.v1.ManagedService]. Method signatures and docstrings: - def Check(self, r...
d7424d21aa0dc121acc4d64b427ba365a3581a20
<|skeleton|> class ServiceControllerServicer: """[Google Service Control API](/service-control/overview) Lets clients check and report operations against a [managed service][google.api.servicemanagement.v1.ManagedService].""" def Check(self, request, context): """Checks an operation with Google Service...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServiceControllerServicer: """[Google Service Control API](/service-control/overview) Lets clients check and report operations against a [managed service][google.api.servicemanagement.v1.ManagedService].""" def Check(self, request, context): """Checks an operation with Google Service Control to d...
the_stack_v2_python_sparse
google/api/servicecontrol/v1/service_controller_pb2_grpc.py
msachtler/bazel-event-protocol-parser
train
1
73e4cba34ad5d0d2fb6c6a1b912917176c9c1390
[ "self.register('M1', torch.randn(hdim, idim))\nself.register('b1', torch.randn(hdim))\nself.register('M2', torch.randn(odim, hdim))\nself.register('b2', torch.randn(odim))", "assert x.shape[0] == self.M1.shape[1]\nh = torch.mv(self.M1, x) + self.b1\nreturn torch.mv(self.M2, torch.sigmoid(h)) + self.b2" ]
<|body_start_0|> self.register('M1', torch.randn(hdim, idim)) self.register('b1', torch.randn(hdim)) self.register('M2', torch.randn(odim, hdim)) self.register('b2', torch.randn(odim)) <|end_body_0|> <|body_start_1|> assert x.shape[0] == self.M1.shape[1] h = torch.mv(sel...
Feed-forward network as a network module.
FFN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FFN: """Feed-forward network as a network module.""" def __init__(self, idim: int, hdim: int, odim: int): """Create a feed-forward network. Args: idim: size of the input vector hdim: size of the hidden vector odim: size of the output vector""" <|body_0|> def forward(self...
stack_v2_sparse_classes_36k_train_016483
1,267
no_license
[ { "docstring": "Create a feed-forward network. Args: idim: size of the input vector hdim: size of the hidden vector odim: size of the output vector", "name": "__init__", "signature": "def __init__(self, idim: int, hdim: int, odim: int)" }, { "docstring": "Transform the input vector using the und...
2
stack_v2_sparse_classes_30k_train_016921
Implement the Python class `FFN` described below. Class description: Feed-forward network as a network module. Method signatures and docstrings: - def __init__(self, idim: int, hdim: int, odim: int): Create a feed-forward network. Args: idim: size of the input vector hdim: size of the hidden vector odim: size of the ...
Implement the Python class `FFN` described below. Class description: Feed-forward network as a network module. Method signatures and docstrings: - def __init__(self, idim: int, hdim: int, odim: int): Create a feed-forward network. Args: idim: size of the input vector hdim: size of the hidden vector odim: size of the ...
80911390bf23bba71435c4318d181c87b26f293d
<|skeleton|> class FFN: """Feed-forward network as a network module.""" def __init__(self, idim: int, hdim: int, odim: int): """Create a feed-forward network. Args: idim: size of the input vector hdim: size of the hidden vector odim: size of the output vector""" <|body_0|> def forward(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FFN: """Feed-forward network as a network module.""" def __init__(self, idim: int, hdim: int, odim: int): """Create a feed-forward network. Args: idim: size of the input vector hdim: size of the hidden vector odim: size of the output vector""" self.register('M1', torch.randn(hdim, idim)) ...
the_stack_v2_python_sparse
lang-rec/code/ffn.py
javierdelcampo/hhu-dl-materials-2019
train
0
2cf2edd25c0f87c671c3af1bca5be7385563ec60
[ "super().__init__()\nself.vocab_size = vocab_size\nself.embed_size = embed_size\nself.lstm_size = lstm_size\nself.output_size = output_size\nself.lstm_layers = lstm_layers\nself.dropout = dropout\nself.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embed_size)\nself.lstm = nn.LSTM(embed_size, lst...
<|body_start_0|> super().__init__() self.vocab_size = vocab_size self.embed_size = embed_size self.lstm_size = lstm_size self.output_size = output_size self.lstm_layers = lstm_layers self.dropout = dropout self.embedding = nn.Embedding(num_embeddings=vocab...
BidirectionalLSTM
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BidirectionalLSTM: def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): """Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : Th...
stack_v2_sparse_classes_36k_train_016484
11,718
no_license
[ { "docstring": "Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : The LSTM layer size. hidden_dim output_size : The output size. lstm_layers : The number of LSTM layers. n_layers dropout : The d...
3
stack_v2_sparse_classes_30k_train_015731
Implement the Python class `BidirectionalLSTM` described below. Class description: Implement the BidirectionalLSTM class. Method signatures and docstrings: - def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): Initialize the model by setting up the layers. Parameters ------...
Implement the Python class `BidirectionalLSTM` described below. Class description: Implement the BidirectionalLSTM class. Method signatures and docstrings: - def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): Initialize the model by setting up the layers. Parameters ------...
0cdabea4afb58af71b909fbde7a9260eaa2b7849
<|skeleton|> class BidirectionalLSTM: def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): """Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BidirectionalLSTM: def __init__(self, vocab_size, embed_size, lstm_size, output_size, lstm_layers=1, dropout=0.1): """Initialize the model by setting up the layers. Parameters ---------- vocab_size : The vocabulary size. embed_size : The embedding layer size. embedding_dim lstm_size : The LSTM layer s...
the_stack_v2_python_sparse
trial_calculations_2/LSTMs.py
ThesisNegatif/Thesis
train
2
3332b6d13b909c30ff5df8fca65e4657cb0d06f9
[ "super(CurlDiffusion, self).__init__(variables=[velocity, vorticity], **kwds)\nself.velocity = velocity\nself.vorticity = vorticity\nraise ValueError('This operator is obsolete and must be reviewed. Do not use it.')", "if self._comm is None:\n from hysop.mpi.main_var import main_comm a...
<|body_start_0|> super(CurlDiffusion, self).__init__(variables=[velocity, vorticity], **kwds) self.velocity = velocity self.vorticity = vorticity raise ValueError('This operator is obsolete and must be reviewed. Do not use it.') <|end_body_0|> <|body_start_1|> ...
Diffusion operator {eqnarray*} \\omega = Op(\\omega) } with : {eqnarray*} rac{\\partial \\omega}{\\partial t} &=& u\\Delta\\omega }
CurlDiffusion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CurlDiffusion: """Diffusion operator {eqnarray*} \\omega = Op(\\omega) } with : {eqnarray*} rac{\\partial \\omega}{\\partial t} &=& u\\Delta\\omega }""" def __init__(self, velocity, vorticity, **kwds): """Constructor. Create a Diffusion operator using FFT. @param velocity ContinuousV...
stack_v2_sparse_classes_36k_train_016485
2,499
no_license
[ { "docstring": "Constructor. Create a Diffusion operator using FFT. @param velocity ContinuousVectorField : velocity variable. @param vorticity ContinuousVectorField : vorticity variable. @param viscosity : viscosity of the considered medium.", "name": "__init__", "signature": "def __init__(self, veloci...
2
null
Implement the Python class `CurlDiffusion` described below. Class description: Diffusion operator {eqnarray*} \\omega = Op(\\omega) } with : {eqnarray*} rac{\\partial \\omega}{\\partial t} &=& u\\Delta\\omega } Method signatures and docstrings: - def __init__(self, velocity, vorticity, **kwds): Constructor. Create a ...
Implement the Python class `CurlDiffusion` described below. Class description: Diffusion operator {eqnarray*} \\omega = Op(\\omega) } with : {eqnarray*} rac{\\partial \\omega}{\\partial t} &=& u\\Delta\\omega } Method signatures and docstrings: - def __init__(self, velocity, vorticity, **kwds): Constructor. Create a ...
60e9535ece75321367b19f1daf13e1ae014d6e81
<|skeleton|> class CurlDiffusion: """Diffusion operator {eqnarray*} \\omega = Op(\\omega) } with : {eqnarray*} rac{\\partial \\omega}{\\partial t} &=& u\\Delta\\omega }""" def __init__(self, velocity, vorticity, **kwds): """Constructor. Create a Diffusion operator using FFT. @param velocity ContinuousV...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CurlDiffusion: """Diffusion operator {eqnarray*} \\omega = Op(\\omega) } with : {eqnarray*} rac{\\partial \\omega}{\\partial t} &=& u\\Delta\\omega }""" def __init__(self, velocity, vorticity, **kwds): """Constructor. Create a Diffusion operator using FFT. @param velocity ContinuousVectorField : ...
the_stack_v2_python_sparse
hysop/operator/curlAndDiffusion.py
ljktest/tmp-tests
train
0
2724fd1e7bc09a955f1e5d13e87b1a834e4566ac
[ "super().__init__()\nself.tade1 = TADELayer(in_channels=in_channels, aux_channels=aux_channels, kernel_size=kernel_size, bias=bias, upsample_factor=1, upsample_mode=upsample_mode)\nself.gated_conv1 = nn.Conv1D(in_channels, in_channels * 2, kernel_size, 1, bias_attr=bias, padding=(kernel_size - 1) // 2)\nself.tade2 ...
<|body_start_0|> super().__init__() self.tade1 = TADELayer(in_channels=in_channels, aux_channels=aux_channels, kernel_size=kernel_size, bias=bias, upsample_factor=1, upsample_mode=upsample_mode) self.gated_conv1 = nn.Conv1D(in_channels, in_channels * 2, kernel_size, 1, bias_attr=bias, padding=(k...
TADEResBlock module.
TADEResBlock
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TADEResBlock: """TADEResBlock module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'): """Initialize TADEResBlock module.""" ...
stack_v2_sparse_classes_36k_train_016486
5,634
permissive
[ { "docstring": "Initialize TADEResBlock module.", "name": "__init__", "signature": "def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax')" }, { "docs...
2
null
Implement the Python class `TADEResBlock` described below. Class description: TADEResBlock module. Method signatures and docstrings: - def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_functio...
Implement the Python class `TADEResBlock` described below. Class description: TADEResBlock module. Method signatures and docstrings: - def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_functio...
17854a04d43c231eff66bfed9d6aa55e94a29e79
<|skeleton|> class TADEResBlock: """TADEResBlock module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'): """Initialize TADEResBlock module.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TADEResBlock: """TADEResBlock module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'): """Initialize TADEResBlock module.""" super()....
the_stack_v2_python_sparse
paddlespeech/t2s/modules/tade_res_block.py
anniyanvr/DeepSpeech-1
train
0
56e96af8c1b7f322f38209985edda0305a449f93
[ "assert len(input_list) > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.input_list = input_list", "print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nsum_dict = {}\nn = len(self.input_list)\nresult = []\nfor i in range(n - 1):\n for j in range(i + 1, n):\n total = self.input_list[i] + self.input_...
<|body_start_0|> assert len(input_list) > 0 super().__init__(self.PROBLEM_NAME) self.input_list = input_list <|end_body_0|> <|body_start_1|> print('Solving {} problem ...'.format(self.PROBLEM_NAME)) sum_dict = {} n = len(self.input_list) result = [] for i...
Equal
FourEqual
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FourEqual: """Equal""" def __init__(self, input_list): """FourEqual Args: input_list: Contains a list of integers Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the problem Note: Args: Returns: list Raises: None""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k_train_016487
1,642
no_license
[ { "docstring": "FourEqual Args: input_list: Contains a list of integers Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, input_list)" }, { "docstring": "Solve the problem Note: Args: Returns: list Raises: None", "name": "solve", "signature": "def solve(se...
2
stack_v2_sparse_classes_30k_train_005798
Implement the Python class `FourEqual` described below. Class description: Equal Method signatures and docstrings: - def __init__(self, input_list): FourEqual Args: input_list: Contains a list of integers Returns: None Raises: None - def solve(self): Solve the problem Note: Args: Returns: list Raises: None
Implement the Python class `FourEqual` described below. Class description: Equal Method signatures and docstrings: - def __init__(self, input_list): FourEqual Args: input_list: Contains a list of integers Returns: None Raises: None - def solve(self): Solve the problem Note: Args: Returns: list Raises: None <|skeleto...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class FourEqual: """Equal""" def __init__(self, input_list): """FourEqual Args: input_list: Contains a list of integers Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the problem Note: Args: Returns: list Raises: None""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FourEqual: """Equal""" def __init__(self, input_list): """FourEqual Args: input_list: Contains a list of integers Returns: None Raises: None""" assert len(input_list) > 0 super().__init__(self.PROBLEM_NAME) self.input_list = input_list def solve(self): """Solv...
the_stack_v2_python_sparse
python/problems/hashing/four_equal.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
e8fd645788a7ad5242c7bbe4e36fd0abcfb71464
[ "if arg == 'no_default':\n value = None\nelse:\n value = cls._get_from_registry(arg)\nreturn value", "if value is None:\n value = cls._default_value\nif isinstance(value, str):\n if value == 'no_default':\n value = None\n else:\n value = cls._get_from_registry(value)\nelif not isinsta...
<|body_start_0|> if arg == 'no_default': value = None else: value = cls._get_from_registry(arg) return value <|end_body_0|> <|body_start_1|> if value is None: value = cls._default_value if isinstance(value, str): if value == 'no_de...
The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology in effect ... pass To get the default cosmolog...
default_cosmology
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class default_cosmology: """The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology i...
stack_v2_sparse_classes_36k_train_016488
4,954
permissive
[ { "docstring": "Return a cosmology instance from a string.", "name": "get_cosmology_from_string", "signature": "def get_cosmology_from_string(cls, arg)" }, { "docstring": "Return a Cosmology given a value. Parameters ---------- value : None, str, or `~astropy.cosmology.Cosmology` Returns -------...
3
null
Implement the Python class `default_cosmology` described below. Class description: The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmolog...
Implement the Python class `default_cosmology` described below. Class description: The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmolog...
53188c39a23c33b72df5850ec59e31886f84e29d
<|skeleton|> class default_cosmology: """The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class default_cosmology: """The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology in effect ... ...
the_stack_v2_python_sparse
astropy/cosmology/realizations.py
astropy/astropy
train
3,922
d082b8c802214f69a5cb8e40b3826b3ca19f96f8
[ "thresholds = thresholds[:]\nassert thresholds[0] > 0\nthresholds.insert(0, -float('inf'))\nthresholds.append(float('inf'))\nassert all([low <= high for low, high in zip(thresholds[:-1], thresholds[1:])])\nassert all([l in [-1, 0, 1] for l in labels])\nassert len(labels) == len(thresholds) - 1\nself.thresholds = th...
<|body_start_0|> thresholds = thresholds[:] assert thresholds[0] > 0 thresholds.insert(0, -float('inf')) thresholds.append(float('inf')) assert all([low <= high for low, high in zip(thresholds[:-1], thresholds[1:])]) assert all([l in [-1, 0, 1] for l in labels]) a...
This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements. The matching is determined by the MxN match_quality_matrix, that characterizes how well each (gr...
Matcher
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Matcher: """This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements. The matching is determined by the MxN match_quality_matrix, t...
stack_v2_sparse_classes_36k_train_016489
6,256
permissive
[ { "docstring": "Args: thresholds (list): a list of thresholds used to stratify predictions into levels. labels (list): a list of values to label predictions belonging at each level. A label can be one of {-1, 0, 1} signifying {ignore, negative class, positive class}, respectively. allow_low_quality_matches (boo...
3
null
Implement the Python class `Matcher` described below. Class description: This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements. The matching is determ...
Implement the Python class `Matcher` described below. Class description: This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements. The matching is determ...
80307d2d5e06f06a8a677cc2653f23a4c56402ac
<|skeleton|> class Matcher: """This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements. The matching is determined by the MxN match_quality_matrix, t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Matcher: """This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements. The matching is determined by the MxN match_quality_matrix, that character...
the_stack_v2_python_sparse
detectron2/modeling/matcher.py
facebookresearch/detectron2
train
27,469
8d5f1ecbf42f6cc1a97ff8ceb7e70aef366b86c7
[ "self.all_endpoints_reachable = all_endpoints_reachable\nself.auto_register_target = auto_register_target\nself.auto_registration = auto_registration\nself.bandwidth_limit = bandwidth_limit\nself.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.compression_enabled = compression_en...
<|body_start_0|> self.all_endpoints_reachable = all_endpoints_reachable self.auto_register_target = auto_register_target self.auto_registration = auto_registration self.bandwidth_limit = bandwidth_limit self.cluster_id = cluster_id self.cluster_incarnation_id = cluster_in...
Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable from this local Cluster. If true, a service running ...
RegisterRemoteCluster
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegisterRemoteCluster: """Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable fro...
stack_v2_sparse_classes_36k_train_016490
10,649
permissive
[ { "docstring": "Constructor for the RegisterRemoteCluster class", "name": "__init__", "signature": "def __init__(self, all_endpoints_reachable=None, auto_register_target=None, auto_registration=None, bandwidth_limit=None, cluster_id=None, cluster_incarnation_id=None, compression_enabled=None, descriptio...
2
stack_v2_sparse_classes_30k_train_013239
Implement the Python class `RegisterRemoteCluster` described below. Class description: Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node)...
Implement the Python class `RegisterRemoteCluster` described below. Class description: Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node)...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RegisterRemoteCluster: """Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable fro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegisterRemoteCluster: """Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable from this local ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/register_remote_cluster.py
cohesity/management-sdk-python
train
24
4ed696d2a0a4dac761c54325ba5b9e822c0a8d50
[ "self.dynamics_net = ForwardModel(state_dim, action_dim)\nself.rewards_net = RewardModel(state_dim, action_dim)\nself.done_net = RewardModel(state_dim, action_dim)\nself.dyn_optimizer = tfa_optimizers.AdamW(learning_rate=learning_rate, weight_decay=weight_decay)\nself.reward_optimizer = tfa_optimizers.AdamW(learnin...
<|body_start_0|> self.dynamics_net = ForwardModel(state_dim, action_dim) self.rewards_net = RewardModel(state_dim, action_dim) self.done_net = RewardModel(state_dim, action_dim) self.dyn_optimizer = tfa_optimizers.AdamW(learning_rate=learning_rate, weight_decay=weight_decay) self...
A class that learns models and estimated returns via rollouts.
ModelBased
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelBased: """A class that learns models and estimated returns via rollouts.""" def __init__(self, state_dim, action_dim, learning_rate, weight_decay): """Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learnin...
stack_v2_sparse_classes_36k_train_016491
7,358
permissive
[ { "docstring": "Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learning_rate: Critic learning rate. weight_decay: Weight decay.", "name": "__init__", "signature": "def __init__(self, state_dim, action_dim, learning_rate, weight_de...
3
stack_v2_sparse_classes_30k_train_015455
Implement the Python class `ModelBased` described below. Class description: A class that learns models and estimated returns via rollouts. Method signatures and docstrings: - def __init__(self, state_dim, action_dim, learning_rate, weight_decay): Creates networks and optimizers for model based policy evaluation. Args...
Implement the Python class `ModelBased` described below. Class description: A class that learns models and estimated returns via rollouts. Method signatures and docstrings: - def __init__(self, state_dim, action_dim, learning_rate, weight_decay): Creates networks and optimizers for model based policy evaluation. Args...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ModelBased: """A class that learns models and estimated returns via rollouts.""" def __init__(self, state_dim, action_dim, learning_rate, weight_decay): """Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learnin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelBased: """A class that learns models and estimated returns via rollouts.""" def __init__(self, state_dim, action_dim, learning_rate, weight_decay): """Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learning_rate: Criti...
the_stack_v2_python_sparse
policy_eval/model_based.py
Jimmy-INL/google-research
train
1
21ef5f5f28107a6147b030dad6b0993fb04e5085
[ "\"\"\"\n 2 pointers jump.\n \"\"\"\nslow = nums[0]\nfast = nums[nums[0]]\nwhile slow != fast:\n slow = nums[slow]\n fast = nums[nums[fast]]\nfast = 0\nwhile slow != fast:\n slow = nums[slow]\n fast = nums[fast]\nreturn fast", "\"\"\"\n Using xor.\n \"\"\"\nxor = 0\nfor n i...
<|body_start_0|> """ 2 pointers jump. """ slow = nums[0] fast = nums[nums[0]] while slow != fast: slow = nums[slow] fast = nums[nums[fast]] fast = 0 while slow != fast: slow = nums[slow] fast ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rewrite(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> """ 2 pointers jump. ...
stack_v2_sparse_classes_36k_train_016492
3,095
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findDuplicate", "signature": "def findDuplicate(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "rewrite", "signature": "def rewrite(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_005408
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def rewrite(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def rewrite(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def findDuplicate...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rewrite(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" """ 2 pointers jump. """ slow = nums[0] fast = nums[nums[0]] while slow != fast: slow = nums[slow] fast = nums[nums[fast]] fa...
the_stack_v2_python_sparse
array/287_Find_the_Duplicate_Number.py
vsdrun/lc_public
train
6
635c5bee25dbb5c2f14c3e1cb6c16f805c9dc727
[ "Company = self.old_state.apps.get_model('company', 'company')\nsupplier = Company.objects.create(name='Supplier A', description='A great supplier!', is_supplier=True, is_customer=True)\nPurchaseOrder = self.old_state.apps.get_model('order', 'purchaseorder')\nSalesOrder = self.old_state.apps.get_model('order', 'sal...
<|body_start_0|> Company = self.old_state.apps.get_model('company', 'company') supplier = Company.objects.create(name='Supplier A', description='A great supplier!', is_supplier=True, is_customer=True) PurchaseOrder = self.old_state.apps.get_model('order', 'purchaseorder') SalesOrder = se...
Test entire schema migration.
TestRefIntMigrations
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRefIntMigrations: """Test entire schema migration.""" def prepare(self): """Create initial data set.""" <|body_0|> def test_ref_field(self): """Test that the 'reference_int' field has been created and is filled out correctly.""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_36k_train_016493
7,688
permissive
[ { "docstring": "Create initial data set.", "name": "prepare", "signature": "def prepare(self)" }, { "docstring": "Test that the 'reference_int' field has been created and is filled out correctly.", "name": "test_ref_field", "signature": "def test_ref_field(self)" } ]
2
stack_v2_sparse_classes_30k_train_017478
Implement the Python class `TestRefIntMigrations` described below. Class description: Test entire schema migration. Method signatures and docstrings: - def prepare(self): Create initial data set. - def test_ref_field(self): Test that the 'reference_int' field has been created and is filled out correctly.
Implement the Python class `TestRefIntMigrations` described below. Class description: Test entire schema migration. Method signatures and docstrings: - def prepare(self): Create initial data set. - def test_ref_field(self): Test that the 'reference_int' field has been created and is filled out correctly. <|skeleton|...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class TestRefIntMigrations: """Test entire schema migration.""" def prepare(self): """Create initial data set.""" <|body_0|> def test_ref_field(self): """Test that the 'reference_int' field has been created and is filled out correctly.""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestRefIntMigrations: """Test entire schema migration.""" def prepare(self): """Create initial data set.""" Company = self.old_state.apps.get_model('company', 'company') supplier = Company.objects.create(name='Supplier A', description='A great supplier!', is_supplier=True, is_cust...
the_stack_v2_python_sparse
InvenTree/order/test_migrations.py
inventree/InvenTree
train
3,077
c13c0c436c5e436f594253a29b25b05189225cb8
[ "ressource_options = default_ressource_options(request, current_app)\nif rss_name:\n RssUtils.validate_rss_name(rss_name)\n spec = {'name': {'$regex': rss_name}}\nelse:\n spec = {}\nresults = current_app.mongo.finder(cursor=current_app.mongo.rss, spec=spec)\ndata = [document for document in results]\nretur...
<|body_start_0|> ressource_options = default_ressource_options(request, current_app) if rss_name: RssUtils.validate_rss_name(rss_name) spec = {'name': {'$regex': rss_name}} else: spec = {} results = current_app.mongo.finder(cursor=current_app.mongo.rss...
docstrings
Rss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rss: """docstrings""" def get(self, rss_name=None): """retrieve the list of a rss""" <|body_0|> def post(self): """add a new rss @post data: <name> <url>""" <|body_1|> def patch(self, rss_name): """patch a rss for the givent rss_name paramete...
stack_v2_sparse_classes_36k_train_016494
2,828
permissive
[ { "docstring": "retrieve the list of a rss", "name": "get", "signature": "def get(self, rss_name=None)" }, { "docstring": "add a new rss @post data: <name> <url>", "name": "post", "signature": "def post(self)" }, { "docstring": "patch a rss for the givent rss_name parameter @patc...
3
stack_v2_sparse_classes_30k_train_011305
Implement the Python class `Rss` described below. Class description: docstrings Method signatures and docstrings: - def get(self, rss_name=None): retrieve the list of a rss - def post(self): add a new rss @post data: <name> <url> - def patch(self, rss_name): patch a rss for the givent rss_name parameter @patch data: ...
Implement the Python class `Rss` described below. Class description: docstrings Method signatures and docstrings: - def get(self, rss_name=None): retrieve the list of a rss - def post(self): add a new rss @post data: <name> <url> - def patch(self, rss_name): patch a rss for the givent rss_name parameter @patch data: ...
657304c8b017a98935de9728fc695abe8be7cc4f
<|skeleton|> class Rss: """docstrings""" def get(self, rss_name=None): """retrieve the list of a rss""" <|body_0|> def post(self): """add a new rss @post data: <name> <url>""" <|body_1|> def patch(self, rss_name): """patch a rss for the givent rss_name paramete...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rss: """docstrings""" def get(self, rss_name=None): """retrieve the list of a rss""" ressource_options = default_ressource_options(request, current_app) if rss_name: RssUtils.validate_rss_name(rss_name) spec = {'name': {'$regex': rss_name}} else: ...
the_stack_v2_python_sparse
Observer/api/resources/rss.py
Lujeni/old-projects
train
0
7c41143c55293f904525ce0bf5eb7734c14cb5f2
[ "self.n = n\nself.discount = discount\nself.products = products\nself.f = {}\nfor i in range(len(self.products)):\n self.f[self.products[i]] = i\nself.prices = prices\nself.cnt = 1", "ans = 0\nfor i in range(len(amount)):\n ans += self.prices[self.f[product[i]]] * amount[i]\nprint(self.cnt)\nif self.cnt % s...
<|body_start_0|> self.n = n self.discount = discount self.products = products self.f = {} for i in range(len(self.products)): self.f[self.products[i]] = i self.prices = prices self.cnt = 1 <|end_body_0|> <|body_start_1|> ans = 0 for i ...
Cashier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cashier: def __init__(self, n, discount, products, prices): """:type n: int :type discount: int :type products: List[int] :type prices: List[int]""" <|body_0|> def getBill(self, product, amount): """:type product: List[int] :type amount: List[int] :rtype: float""" ...
stack_v2_sparse_classes_36k_train_016495
1,021
no_license
[ { "docstring": ":type n: int :type discount: int :type products: List[int] :type prices: List[int]", "name": "__init__", "signature": "def __init__(self, n, discount, products, prices)" }, { "docstring": ":type product: List[int] :type amount: List[int] :rtype: float", "name": "getBill", ...
2
stack_v2_sparse_classes_30k_train_018958
Implement the Python class `Cashier` described below. Class description: Implement the Cashier class. Method signatures and docstrings: - def __init__(self, n, discount, products, prices): :type n: int :type discount: int :type products: List[int] :type prices: List[int] - def getBill(self, product, amount): :type pr...
Implement the Python class `Cashier` described below. Class description: Implement the Cashier class. Method signatures and docstrings: - def __init__(self, n, discount, products, prices): :type n: int :type discount: int :type products: List[int] :type prices: List[int] - def getBill(self, product, amount): :type pr...
67e9daecb7ffd8f7bcb2f120ad892498b1219327
<|skeleton|> class Cashier: def __init__(self, n, discount, products, prices): """:type n: int :type discount: int :type products: List[int] :type prices: List[int]""" <|body_0|> def getBill(self, product, amount): """:type product: List[int] :type amount: List[int] :rtype: float""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cashier: def __init__(self, n, discount, products, prices): """:type n: int :type discount: int :type products: List[int] :type prices: List[int]""" self.n = n self.discount = discount self.products = products self.f = {} for i in range(len(self.products)): ...
the_stack_v2_python_sparse
比赛/1357. 每隔 n 个顾客打折.py
Comyn-Echo/leeCode
train
0
773f27c380e747a39780b8067c349fce92a6a19c
[ "assert isinstance(response, requests.Response)\nif response.status_code != expected:\n raise RuntimeError('Expected %s %s for GET %s. Got %s %s instead.' % (expected, responses[expected], response.url, response.status_code, responses[response.status_code]))", "logger.debug('GET %s', url)\nresponse = cls.sessi...
<|body_start_0|> assert isinstance(response, requests.Response) if response.status_code != expected: raise RuntimeError('Expected %s %s for GET %s. Got %s %s instead.' % (expected, responses[expected], response.url, response.status_code, responses[response.status_code])) <|end_body_0|> <|bo...
A class which acts as a provider for other APIs by sharing a single requests session Used by other APIs to construct and share a single :class:`requests.Session` as well
Session
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Session: """A class which acts as a provider for other APIs by sharing a single requests session Used by other APIs to construct and share a single :class:`requests.Session` as well""" def check_code(cls, response, expected): """Check the HTTP response code from ``response`` against ...
stack_v2_sparse_classes_36k_train_016496
16,466
permissive
[ { "docstring": "Check the HTTP response code from ``response`` against an expected value. :param requests.Response response: The response to check the status code for :param int expected: The expected http response code :raises RuntimeError: Raised if the response's HTTP status code does not match ``expected``"...
3
stack_v2_sparse_classes_30k_train_006683
Implement the Python class `Session` described below. Class description: A class which acts as a provider for other APIs by sharing a single requests session Used by other APIs to construct and share a single :class:`requests.Session` as well Method signatures and docstrings: - def check_code(cls, response, expected)...
Implement the Python class `Session` described below. Class description: A class which acts as a provider for other APIs by sharing a single requests session Used by other APIs to construct and share a single :class:`requests.Session` as well Method signatures and docstrings: - def check_code(cls, response, expected)...
39210182a92e93c37a9f1c644fd5fcc1aa32f6d1
<|skeleton|> class Session: """A class which acts as a provider for other APIs by sharing a single requests session Used by other APIs to construct and share a single :class:`requests.Session` as well""" def check_code(cls, response, expected): """Check the HTTP response code from ``response`` against ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Session: """A class which acts as a provider for other APIs by sharing a single requests session Used by other APIs to construct and share a single :class:`requests.Session` as well""" def check_code(cls, response, expected): """Check the HTTP response code from ``response`` against an expected v...
the_stack_v2_python_sparse
pywincffi/dev/release.py
philip-h-dye/pywincffi
train
0
2a2bc64625ca19cc2c277b1bf402553d7a21e846
[ "super(RNNDecoder, self).__init__()\nself.units = units\nself.batch = batch\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, return_state=True, return_sequences=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(vocab)", "sa = SelfAtte...
<|body_start_0|> super(RNNDecoder, self).__init__() self.units = units self.batch = batch self.embedding = tf.keras.layers.Embedding(vocab, embedding) self.gru = tf.keras.layers.GRU(units, return_state=True, return_sequences=True, recurrent_initializer='glorot_uniform') s...
rnn decoder class
RNNDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNDecoder: """rnn decoder class""" def __init__(self, vocab, embedding, units, batch): """initialization method for RNNdecoder object vocab: int: size of output vocabulary embedding:int: dimensionality of embedding vector units: int: number of hidden units in RNN cell batch: int: ba...
stack_v2_sparse_classes_36k_train_016497
1,859
no_license
[ { "docstring": "initialization method for RNNdecoder object vocab: int: size of output vocabulary embedding:int: dimensionality of embedding vector units: int: number of hidden units in RNN cell batch: int: batch size", "name": "__init__", "signature": "def __init__(self, vocab, embedding, units, batch)...
2
null
Implement the Python class `RNNDecoder` described below. Class description: rnn decoder class Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): initialization method for RNNdecoder object vocab: int: size of output vocabulary embedding:int: dimensionality of embedding vector unit...
Implement the Python class `RNNDecoder` described below. Class description: rnn decoder class Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): initialization method for RNNdecoder object vocab: int: size of output vocabulary embedding:int: dimensionality of embedding vector unit...
d86b0e0cae2dd07c761f84a493abc895007873ee
<|skeleton|> class RNNDecoder: """rnn decoder class""" def __init__(self, vocab, embedding, units, batch): """initialization method for RNNdecoder object vocab: int: size of output vocabulary embedding:int: dimensionality of embedding vector units: int: number of hidden units in RNN cell batch: int: ba...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNNDecoder: """rnn decoder class""" def __init__(self, vocab, embedding, units, batch): """initialization method for RNNdecoder object vocab: int: size of output vocabulary embedding:int: dimensionality of embedding vector units: int: number of hidden units in RNN cell batch: int: batch size""" ...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/2-rnn_decoder.py
mag389/holbertonschool-machine_learning
train
2
258fa2d7c5873801c63264e09d57e339eeaa4b37
[ "super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob)])\nch = chans\nfor i in range(num_pool_layers - 1):\n self.down_sample_...
<|body_start_0|> super().__init__() self.in_chans = in_chans self.out_chans = out_chans self.chans = chans self.num_pool_layers = num_pool_layers self.drop_prob = drop_prob self.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob)]) ch...
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015.
UnetModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnetModel: """PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. S...
stack_v2_sparse_classes_36k_train_016498
30,521
no_license
[ { "docstring": "Args: in_chans (int): Number of channels in the input to the U-Net model. out_chans (int): Number of channels in the output to the U-Net model. chans (int): Number of output channels of the first convolution layer. num_pool_layers (int): Number of down-sampling and up-sampling layers. drop_prob ...
2
stack_v2_sparse_classes_30k_train_020177
Implement the Python class `UnetModel` described below. Class description: PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-...
Implement the Python class `UnetModel` described below. Class description: PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-...
219652c8a08c4f2f682acd9f95a4e1b3fd36b70b
<|skeleton|> class UnetModel: """PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. S...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UnetModel: """PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015...
the_stack_v2_python_sparse
lemawarersn_t1assist/models.py
Bala93/Holistic-MRI-Reconstruction
train
1
14523f4077c5ea0e661979e9f11bb409239a1e04
[ "QItemDelegate.paint(self, painter, option, index)\ncolumn = index.column()\nrow = index.row()\nrect = option.rect\nif column in [C.COL_NAME, C.COL_DESCRIPTION, C.COL_VERSION]:\n pen = QPen()\n pen.setWidth(1)\n pen.setColor(QColor('#ddd'))\n painter.setPen(pen)\n painter.drawLine(rect.topRight(), re...
<|body_start_0|> QItemDelegate.paint(self, painter, option, index) column = index.column() row = index.row() rect = option.rect if column in [C.COL_NAME, C.COL_DESCRIPTION, C.COL_VERSION]: pen = QPen() pen.setWidth(1) pen.setColor(QColor('#ddd'...
Custom delegate to handle selected/hovered behavior of rows.
CustomDelegate
[ "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomDelegate: """Custom delegate to handle selected/hovered behavior of rows.""" def paint(self, painter, option, index): """Override Qt method.""" <|body_0|> def sizeHint(self, style, model_index): """Override Qt method.""" <|body_1|> <|end_skeleton|>...
stack_v2_sparse_classes_36k_train_016499
31,099
permissive
[ { "docstring": "Override Qt method.", "name": "paint", "signature": "def paint(self, painter, option, index)" }, { "docstring": "Override Qt method.", "name": "sizeHint", "signature": "def sizeHint(self, style, model_index)" } ]
2
null
Implement the Python class `CustomDelegate` described below. Class description: Custom delegate to handle selected/hovered behavior of rows. Method signatures and docstrings: - def paint(self, painter, option, index): Override Qt method. - def sizeHint(self, style, model_index): Override Qt method.
Implement the Python class `CustomDelegate` described below. Class description: Custom delegate to handle selected/hovered behavior of rows. Method signatures and docstrings: - def paint(self, painter, option, index): Override Qt method. - def sizeHint(self, style, model_index): Override Qt method. <|skeleton|> clas...
74476c9f00ee43338af696da7e9cd02b273f9005
<|skeleton|> class CustomDelegate: """Custom delegate to handle selected/hovered behavior of rows.""" def paint(self, painter, option, index): """Override Qt method.""" <|body_0|> def sizeHint(self, style, model_index): """Override Qt method.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomDelegate: """Custom delegate to handle selected/hovered behavior of rows.""" def paint(self, painter, option, index): """Override Qt method.""" QItemDelegate.paint(self, painter, option, index) column = index.column() row = index.row() rect = option.rect ...
the_stack_v2_python_sparse
python/anaconda/lib/python2.7/site-packages/anaconda_navigator/widgets/manager/table.py
locolucco209/MongoScraper
train
3