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
a2b1488c59bb862c21c0f5b7ac30a7f82aeddd48
[ "self.random_state = random_state\nself.kernel_sizes = kernel_sizes\nself.filter_sizes = filter_sizes\nself.lstm_size = lstm_size\nself.dropout = dropout\nself.attention = attention\nsuper().__init__()", "from tensorflow import keras\nfrom sktime.networks.lstmfcn_layers import make_attention_lstm\ninput_layer = k...
<|body_start_0|> self.random_state = random_state self.kernel_sizes = kernel_sizes self.filter_sizes = filter_sizes self.lstm_size = lstm_size self.dropout = dropout self.attention = attention super().__init__() <|end_body_0|> <|body_start_1|> from tensor...
Implementation of LSTMFCNClassifier from Karim et al (2019) [1]. Overview -------- Combines an LSTM arm with a CNN arm. Optionally uses an attention mechanism in the LSTM which the author indicates provides improved performance. Notes ----- Ported from sktime-dl source code https://github.com/sktime/sktime-dl/blob/mast...
LSTMFCNNetwork
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTMFCNNetwork: """Implementation of LSTMFCNClassifier from Karim et al (2019) [1]. Overview -------- Combines an LSTM arm with a CNN arm. Optionally uses an attention mechanism in the LSTM which the author indicates provides improved performance. Notes ----- Ported from sktime-dl source code htt...
stack_v2_sparse_classes_36k_train_014300
3,786
permissive
[ { "docstring": "Initialize a new LSTMFCNNetwork object. Parameters ---------- kernel_sizes: List[int], default=[8, 5, 3] specifying the length of the 1D convolution windows filter_sizes: List[int], default=[128, 256, 128] size of filter for each conv layer random_state: int, default=0 seed to any needed random ...
2
null
Implement the Python class `LSTMFCNNetwork` described below. Class description: Implementation of LSTMFCNClassifier from Karim et al (2019) [1]. Overview -------- Combines an LSTM arm with a CNN arm. Optionally uses an attention mechanism in the LSTM which the author indicates provides improved performance. Notes ----...
Implement the Python class `LSTMFCNNetwork` described below. Class description: Implementation of LSTMFCNClassifier from Karim et al (2019) [1]. Overview -------- Combines an LSTM arm with a CNN arm. Optionally uses an attention mechanism in the LSTM which the author indicates provides improved performance. Notes ----...
70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f
<|skeleton|> class LSTMFCNNetwork: """Implementation of LSTMFCNClassifier from Karim et al (2019) [1]. Overview -------- Combines an LSTM arm with a CNN arm. Optionally uses an attention mechanism in the LSTM which the author indicates provides improved performance. Notes ----- Ported from sktime-dl source code htt...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LSTMFCNNetwork: """Implementation of LSTMFCNClassifier from Karim et al (2019) [1]. Overview -------- Combines an LSTM arm with a CNN arm. Optionally uses an attention mechanism in the LSTM which the author indicates provides improved performance. Notes ----- Ported from sktime-dl source code https://github.c...
the_stack_v2_python_sparse
sktime/networks/lstmfcn.py
sktime/sktime
train
1,117
86956a53d61e51c32ffb3b3f2a2af5a664c7fe8a
[ "C = sum(nums)\nif C % 2 != 0:\n return False\nC = C // 2\ndp = [False] * (C + 1)\nfor c in range(C + 1):\n dp[c] = nums[0] == c\nfor i in range(1, len(nums)):\n for j in range(C, -1, -1):\n if j >= nums[i]:\n dp[j] = dp[j] or dp[j - nums[i]]\n else:\n continue\nreturn d...
<|body_start_0|> C = sum(nums) if C % 2 != 0: return False C = C // 2 dp = [False] * (C + 1) for c in range(C + 1): dp[c] = nums[0] == c for i in range(1, len(nums)): for j in range(C, -1, -1): if j >= nums[i]: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition2(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> C = sum(nums) if C % 2 != 0: ...
stack_v2_sparse_classes_36k_train_014301
1,265
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition", "signature": "def canPartition(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition2", "signature": "def canPartition2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_015711
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition2(self, nums): :type nums: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition2(self, nums): :type nums: List[int] :rtype: bool <|skeleton|> class Solution: def canPar...
a32a1add8720de35e0ddc0c51efe781fb04c9d4a
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition2(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" C = sum(nums) if C % 2 != 0: return False C = C // 2 dp = [False] * (C + 1) for c in range(C + 1): dp[c] = nums[0] == c for i in range(1, len(nums)):...
the_stack_v2_python_sparse
动态规划/leetcode_416_Partition_Equal_Subset_Sum.py
cleverer123/Algorithm
train
0
cfe392df5f9776933bad3774e37c1d2977d1b334
[ "for line in stream:\n key, value = line.strip().split(' ', 1)\n key = key.strip('::')\n value = value.strip(';').strip('\"').strip()\n if not value:\n continue\n yield (key, value)", "fields = {'Package': 0, 'Version': 1, 'File': 2}\nfield_names = fields.keys()\nfield_count = len(field_name...
<|body_start_0|> for line in stream: key, value = line.strip().split(' ', 1) key = key.strip('::') value = value.strip(';').strip('"').strip() if not value: continue yield (key, value) <|end_body_0|> <|body_start_1|> fields = {...
AptParser
[ "GPL-1.0-or-later", "GPL-2.0-or-later", "OFL-1.1", "MS-PL", "AFL-2.1", "GPL-2.0-only", "Python-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AptParser: def config_reader(stream): """apt-config dump command parser Function consumes io.TextIOBase compatible objects as input and return iterator with parsed items :type stream collections.Iterable :rtype collections.Iterable :return tuple(key, value) Usage: for key, value in __con...
stack_v2_sparse_classes_36k_train_014302
4,287
permissive
[ { "docstring": "apt-config dump command parser Function consumes io.TextIOBase compatible objects as input and return iterator with parsed items :type stream collections.Iterable :rtype collections.Iterable :return tuple(key, value) Usage: for key, value in __config_reader(text_stream): ... Parsing subject: PRO...
3
null
Implement the Python class `AptParser` described below. Class description: Implement the AptParser class. Method signatures and docstrings: - def config_reader(stream): apt-config dump command parser Function consumes io.TextIOBase compatible objects as input and return iterator with parsed items :type stream collect...
Implement the Python class `AptParser` described below. Class description: Implement the AptParser class. Method signatures and docstrings: - def config_reader(stream): apt-config dump command parser Function consumes io.TextIOBase compatible objects as input and return iterator with parsed items :type stream collect...
23881f23577a65de396238998e8672d6c4c5a250
<|skeleton|> class AptParser: def config_reader(stream): """apt-config dump command parser Function consumes io.TextIOBase compatible objects as input and return iterator with parsed items :type stream collections.Iterable :rtype collections.Iterable :return tuple(key, value) Usage: for key, value in __con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AptParser: def config_reader(stream): """apt-config dump command parser Function consumes io.TextIOBase compatible objects as input and return iterator with parsed items :type stream collections.Iterable :rtype collections.Iterable :return tuple(key, value) Usage: for key, value in __config_reader(tex...
the_stack_v2_python_sparse
ambari-common/src/main/python/ambari_commons/repo_manager/apt_parser.py
apache/ambari
train
2,078
cc2b11a5423c0a22227250d7864cb64f00955fb1
[ "self.source_scene_name = bpy.context.scene.name\nself.target_asset_list = target_asset_list\nself.jsonoutput = None\n' Initialize logging variables '\nself.conout = False\nself.conoutmessage = None\nself.check = []\nself.error = []\nself.fail = []\nself.log = []\nself.success = []\nself.conoutmessage = '----------...
<|body_start_0|> self.source_scene_name = bpy.context.scene.name self.target_asset_list = target_asset_list self.jsonoutput = None ' Initialize logging variables ' self.conout = False self.conoutmessage = None self.check = [] self.error = [] self.f...
Write presets selections for each item in corresponding asset folder
JSONExportPresets
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSONExportPresets: """Write presets selections for each item in corresponding asset folder""" def __init__(self, target_asset_list): """Initialize general variables""" <|body_0|> def execute(self): """Process actions""" <|body_1|> def json_encoder(se...
stack_v2_sparse_classes_36k_train_014303
44,083
no_license
[ { "docstring": "Initialize general variables", "name": "__init__", "signature": "def __init__(self, target_asset_list)" }, { "docstring": "Process actions", "name": "execute", "signature": "def execute(self)" }, { "docstring": "Create JSON output from collection/sub-collection", ...
5
null
Implement the Python class `JSONExportPresets` described below. Class description: Write presets selections for each item in corresponding asset folder Method signatures and docstrings: - def __init__(self, target_asset_list): Initialize general variables - def execute(self): Process actions - def json_encoder(self):...
Implement the Python class `JSONExportPresets` described below. Class description: Write presets selections for each item in corresponding asset folder Method signatures and docstrings: - def __init__(self, target_asset_list): Initialize general variables - def execute(self): Process actions - def json_encoder(self):...
0788f00283d7c8c083aa5d554eb1f32c201adbd6
<|skeleton|> class JSONExportPresets: """Write presets selections for each item in corresponding asset folder""" def __init__(self, target_asset_list): """Initialize general variables""" <|body_0|> def execute(self): """Process actions""" <|body_1|> def json_encoder(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JSONExportPresets: """Write presets selections for each item in corresponding asset folder""" def __init__(self, target_asset_list): """Initialize general variables""" self.source_scene_name = bpy.context.scene.name self.target_asset_list = target_asset_list self.jsonoutpu...
the_stack_v2_python_sparse
repos/blender_addons/internal/2.7.x/addon_customprops_preset.py
BlenderCN-Org/working_files
train
0
362de0a7a2e1ac1a68f0152e50cdf6d41c3b7598
[ "self.host = host\nself.username = username\nself.password = password\nself.to_emails = to_emails\nself.subject = subject\nself.content = content", "msgRoot = MIMEMultipart('related')\nmsgRoot['Subject'] = self.subject\nmsgRoot['From'] = self.username\nmsgRoot['To'] = ','.join(self.to_emails)\nmsgRoot['Date'] = e...
<|body_start_0|> self.host = host self.username = username self.password = password self.to_emails = to_emails self.subject = subject self.content = content <|end_body_0|> <|body_start_1|> msgRoot = MIMEMultipart('related') msgRoot['Subject'] = self.subje...
MailSender
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MailSender: def __init__(self, host, username, password, to_emails, subject, content): """初始化 @param host 邮件服务端host @param username 用户名 @param password 密码 @param to_emails 发送到邮箱列表 @param title 标题 @param content 内容""" <|body_0|> def send_mail(self): """发送邮件""" ...
stack_v2_sparse_classes_36k_train_014304
2,042
permissive
[ { "docstring": "初始化 @param host 邮件服务端host @param username 用户名 @param password 密码 @param to_emails 发送到邮箱列表 @param title 标题 @param content 内容", "name": "__init__", "signature": "def __init__(self, host, username, password, to_emails, subject, content)" }, { "docstring": "发送邮件", "name": "send_m...
2
stack_v2_sparse_classes_30k_train_008465
Implement the Python class `MailSender` described below. Class description: Implement the MailSender class. Method signatures and docstrings: - def __init__(self, host, username, password, to_emails, subject, content): 初始化 @param host 邮件服务端host @param username 用户名 @param password 密码 @param to_emails 发送到邮箱列表 @param ti...
Implement the Python class `MailSender` described below. Class description: Implement the MailSender class. Method signatures and docstrings: - def __init__(self, host, username, password, to_emails, subject, content): 初始化 @param host 邮件服务端host @param username 用户名 @param password 密码 @param to_emails 发送到邮箱列表 @param ti...
931fca8fab9d7397c52cf9e76a76b1c60e190403
<|skeleton|> class MailSender: def __init__(self, host, username, password, to_emails, subject, content): """初始化 @param host 邮件服务端host @param username 用户名 @param password 密码 @param to_emails 发送到邮箱列表 @param title 标题 @param content 内容""" <|body_0|> def send_mail(self): """发送邮件""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MailSender: def __init__(self, host, username, password, to_emails, subject, content): """初始化 @param host 邮件服务端host @param username 用户名 @param password 密码 @param to_emails 发送到邮箱列表 @param title 标题 @param content 内容""" self.host = host self.username = username self.password = pas...
the_stack_v2_python_sparse
src/utils/send_email.py
Karmenzind/fp-server
train
180
1f838f72e7a20b99f4652bdd49781111b3a00c9c
[ "output_file_name = 'linux_account_analysis.txt'\noutput_file_path = os.path.join(self.output_dir, output_file_name)\noutput_evidence = ReportText(source_path=output_file_path)\ntry:\n collected_artifacts = extract_artifacts(artifact_names=['LoginPolicyConfiguration'], disk_path=evidence.local_path, output_dir=s...
<|body_start_0|> output_file_name = 'linux_account_analysis.txt' output_file_path = os.path.join(self.output_dir, output_file_name) output_evidence = ReportText(source_path=output_file_path) try: collected_artifacts = extract_artifacts(artifact_names=['LoginPolicyConfiguratio...
Task to analyze a Linux password file.
LinuxAccountAnalysisTask
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinuxAccountAnalysisTask: """Task to analyze a Linux password file.""" def run(self, evidence, result): """Run the Linux Account worker. Args: evidence (Evidence object): The evidence to process result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTask...
stack_v2_sparse_classes_36k_train_014305
5,092
permissive
[ { "docstring": "Run the Linux Account worker. Args: evidence (Evidence object): The evidence to process result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTaskResult object.", "name": "run", "signature": "def run(self, evidence, result)" }, { "docstring": "Extra...
3
stack_v2_sparse_classes_30k_train_013382
Implement the Python class `LinuxAccountAnalysisTask` described below. Class description: Task to analyze a Linux password file. Method signatures and docstrings: - def run(self, evidence, result): Run the Linux Account worker. Args: evidence (Evidence object): The evidence to process result (TurbiniaTaskResult): The...
Implement the Python class `LinuxAccountAnalysisTask` described below. Class description: Task to analyze a Linux password file. Method signatures and docstrings: - def run(self, evidence, result): Run the Linux Account worker. Args: evidence (Evidence object): The evidence to process result (TurbiniaTaskResult): The...
a756f4c625cf3796fc82d160f3c794c7e2039437
<|skeleton|> class LinuxAccountAnalysisTask: """Task to analyze a Linux password file.""" def run(self, evidence, result): """Run the Linux Account worker. Args: evidence (Evidence object): The evidence to process result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTask...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinuxAccountAnalysisTask: """Task to analyze a Linux password file.""" def run(self, evidence, result): """Run the Linux Account worker. Args: evidence (Evidence object): The evidence to process result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTaskResult object...
the_stack_v2_python_sparse
turbinia/workers/analysis/linux_acct.py
joachimmetz/turbinia
train
1
bf2f829c85d143ecb2efc1d2f3c5bf88e7f54b82
[ "self.instr = Instructions(reg, mem, alu)\nself.mem = mem\nself.reg = reg\nself.op_codes = {}\nself.op_codes[1] = self.instr.halt\nself.op_codes[32] = self.instr.add\nself.op_codes[33] = self.instr.lda\nself.op_codes[34] = self.instr.sta\nself.op_codes[35] = self.instr.jmp\nself.op_codes[36] = self.instr.sza\nself....
<|body_start_0|> self.instr = Instructions(reg, mem, alu) self.mem = mem self.reg = reg self.op_codes = {} self.op_codes[1] = self.instr.halt self.op_codes[32] = self.instr.add self.op_codes[33] = self.instr.lda self.op_codes[34] = self.instr.sta s...
Decode op codes into instructions.
Decoder
[ "Artistic-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decoder: """Decode op codes into instructions.""" def __init__(self, reg, mem, alu): """Create the op code instruction map.""" <|body_0|> def fetch_execute(self): """The fetch execute cycle. Fetch the next instruction and the value of the address following it. Th...
stack_v2_sparse_classes_36k_train_014306
5,867
permissive
[ { "docstring": "Create the op code instruction map.", "name": "__init__", "signature": "def __init__(self, reg, mem, alu)" }, { "docstring": "The fetch execute cycle. Fetch the next instruction and the value of the address following it. That value, typically an address itself, is passed to the i...
2
stack_v2_sparse_classes_30k_train_016553
Implement the Python class `Decoder` described below. Class description: Decode op codes into instructions. Method signatures and docstrings: - def __init__(self, reg, mem, alu): Create the op code instruction map. - def fetch_execute(self): The fetch execute cycle. Fetch the next instruction and the value of the add...
Implement the Python class `Decoder` described below. Class description: Decode op codes into instructions. Method signatures and docstrings: - def __init__(self, reg, mem, alu): Create the op code instruction map. - def fetch_execute(self): The fetch execute cycle. Fetch the next instruction and the value of the add...
75997d72ceefdc35fd3c76fe50676626cb2be887
<|skeleton|> class Decoder: """Decode op codes into instructions.""" def __init__(self, reg, mem, alu): """Create the op code instruction map.""" <|body_0|> def fetch_execute(self): """The fetch execute cycle. Fetch the next instruction and the value of the address following it. Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Decoder: """Decode op codes into instructions.""" def __init__(self, reg, mem, alu): """Create the op code instruction map.""" self.instr = Instructions(reg, mem, alu) self.mem = mem self.reg = reg self.op_codes = {} self.op_codes[1] = self.instr.halt ...
the_stack_v2_python_sparse
decoder.py
kmggh/python-simple-machine
train
0
2d43ee9133a47b53caef7d151d3fb3622d3d8ba1
[ "self.test_data_true = dictionary_class_helper_true()\nself.test_data_false = dictionary_class_helper_false()\nself.sock_conn_valid = socketconnection.SocketConnection(self.test_data_true.car_id)\nself.valid_dict = self.test_data_true.get_socket_dictionary()\nprint('Test suite: {}'.format(type(self).__name__))", ...
<|body_start_0|> self.test_data_true = dictionary_class_helper_true() self.test_data_false = dictionary_class_helper_false() self.sock_conn_valid = socketconnection.SocketConnection(self.test_data_true.car_id) self.valid_dict = self.test_data_true.get_socket_dictionary() print('T...
This class tests edge cases resulting in an invalid action Basically send a random integer as the action that is not one of the accepted actions.
TestInvalidAction
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestInvalidAction: """This class tests edge cases resulting in an invalid action Basically send a random integer as the action that is not one of the accepted actions.""" def setUp(self): """It is necessary to instantiate the data classes and extract the relevant dictionaries.""" ...
stack_v2_sparse_classes_36k_train_014307
23,291
no_license
[ { "docstring": "It is necessary to instantiate the data classes and extract the relevant dictionaries.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Vary loops through this to vary the extensiveness of the test.", "name": "test_invalid_action", "signature": "def te...
2
null
Implement the Python class `TestInvalidAction` described below. Class description: This class tests edge cases resulting in an invalid action Basically send a random integer as the action that is not one of the accepted actions. Method signatures and docstrings: - def setUp(self): It is necessary to instantiate the d...
Implement the Python class `TestInvalidAction` described below. Class description: This class tests edge cases resulting in an invalid action Basically send a random integer as the action that is not one of the accepted actions. Method signatures and docstrings: - def setUp(self): It is necessary to instantiate the d...
8f68cc2a6ca568e803a6bfea49a452a5b0c1a2cf
<|skeleton|> class TestInvalidAction: """This class tests edge cases resulting in an invalid action Basically send a random integer as the action that is not one of the accepted actions.""" def setUp(self): """It is necessary to instantiate the data classes and extract the relevant dictionaries.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestInvalidAction: """This class tests edge cases resulting in an invalid action Basically send a random integer as the action that is not one of the accepted actions.""" def setUp(self): """It is necessary to instantiate the data classes and extract the relevant dictionaries.""" self.tes...
the_stack_v2_python_sparse
AgentPi/agenttesting.py
JiewenGuan/Iot-Carshare
train
0
d4e2a0df87f091a6f573c49f5817d6cb699a8958
[ "list = []\nif root is None:\n return []\nlist += self.inorderTraversal(root.left)\nlist.append(root.val)\nlist += self.inorderTraversal(root.right)\nreturn list", "WHITE, GRAY = (0, 1)\nres = []\nstack = [(WHITE, root)]\nwhile stack:\n color, node = stack.pop()\n if node is None:\n continue\n ...
<|body_start_0|> list = [] if root is None: return [] list += self.inorderTraversal(root.left) list.append(root.val) list += self.inorderTraversal(root.right) return list <|end_body_0|> <|body_start_1|> WHITE, GRAY = (0, 1) res = [] st...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def inorderTraversal_iter(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> list = [] if...
stack_v2_sparse_classes_36k_train_014308
1,450
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "inorderTraversal", "signature": "def inorderTraversal(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "inorderTraversal_iter", "signature": "def inorderTraversal_iter(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_015176
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def inorderTraversal_iter(self, root): :type root: TreeNode :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def inorderTraversal_iter(self, root): :type root: TreeNode :rtype: List[int] <|skeleton|> class Solut...
3f4284330f9771037ca59e2e6a94122e51e58540
<|skeleton|> class Solution: def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def inorderTraversal_iter(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" list = [] if root is None: return [] list += self.inorderTraversal(root.left) list.append(root.val) list += self.inorderTraversal(root.right) return list...
the_stack_v2_python_sparse
Leetcode/94.二叉树的中序遍历.py
myf-algorithm/Leetcode
train
1
824a34fa39aca4984a49de66eaf92db46fc37cf3
[ "url = reverse('reports')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 302)", "url = reverse('reports')\nfor user in ['admin', 'poweruser', 'normaluser']:\n self.client.login(username=user, password='pass')\n response = self.client.get(url)\n self.assertEqual(response.status_c...
<|body_start_0|> url = reverse('reports') response = self.client.get(url) self.assertEqual(response.status_code, 302) <|end_body_0|> <|body_start_1|> url = reverse('reports') for user in ['admin', 'poweruser', 'normaluser']: self.client.login(username=user, password=...
PublishViewTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PublishViewTest: def test_reportview_anon_unauth_redirect(self): """Test that the ReportView redirects anonymous users""" <|body_0|> def test_reportview_auth(self): """Test that authenticated users can open the ReportView""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_014309
751
permissive
[ { "docstring": "Test that the ReportView redirects anonymous users", "name": "test_reportview_anon_unauth_redirect", "signature": "def test_reportview_anon_unauth_redirect(self)" }, { "docstring": "Test that authenticated users can open the ReportView", "name": "test_reportview_auth", "s...
2
stack_v2_sparse_classes_30k_train_001457
Implement the Python class `PublishViewTest` described below. Class description: Implement the PublishViewTest class. Method signatures and docstrings: - def test_reportview_anon_unauth_redirect(self): Test that the ReportView redirects anonymous users - def test_reportview_auth(self): Test that authenticated users c...
Implement the Python class `PublishViewTest` described below. Class description: Implement the PublishViewTest class. Method signatures and docstrings: - def test_reportview_anon_unauth_redirect(self): Test that the ReportView redirects anonymous users - def test_reportview_auth(self): Test that authenticated users c...
5db00d52574a62498036f526813878d11d873b54
<|skeleton|> class PublishViewTest: def test_reportview_anon_unauth_redirect(self): """Test that the ReportView redirects anonymous users""" <|body_0|> def test_reportview_auth(self): """Test that authenticated users can open the ReportView""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PublishViewTest: def test_reportview_anon_unauth_redirect(self): """Test that the ReportView redirects anonymous users""" url = reverse('reports') response = self.client.get(url) self.assertEqual(response.status_code, 302) def test_reportview_auth(self): """Test th...
the_stack_v2_python_sparse
prs2/reports/test_views.py
ScottEvansDBCA/prs
train
0
81c33081d7d7543742f48b8b034c3e4e9d75b05c
[ "self.dendogram = hierarchy.linkage(self.data.T, method)\nself.method = method\nreturn self.dendogram", "if not 'labels' in kwargs:\n kwargs['labels'] = self.data.T.index\nif not 'leaf_rotation' in kwargs:\n kwargs['leaf_rotation'] = 0\nif not 'orientation' in kwargs:\n kwargs['orientation'] = 'right'\ni...
<|body_start_0|> self.dendogram = hierarchy.linkage(self.data.T, method) self.method = method return self.dendogram <|end_body_0|> <|body_start_1|> if not 'labels' in kwargs: kwargs['labels'] = self.data.T.index if not 'leaf_rotation' in kwargs: kwargs['l...
Hierarchical clustering is a method of cluster analysis which seeks to build a hierarchy of clusters.
Linkage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Linkage: """Hierarchical clustering is a method of cluster analysis which seeks to build a hierarchy of clusters.""" def run(self, method: str='complete', metric: Union[str, Callable[[object], float]]='euclidean', optimal_ordering: bool=False) -> object: """Runs the hierarchical clus...
stack_v2_sparse_classes_36k_train_014310
3,306
no_license
[ { "docstring": "Runs the hierarchical clustering for the input vectors Args: method (str, optional, default=complete): Methods for calculating the distance between the newly formed cluster u and each v. <br/> See https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html . <br/> M...
2
null
Implement the Python class `Linkage` described below. Class description: Hierarchical clustering is a method of cluster analysis which seeks to build a hierarchy of clusters. Method signatures and docstrings: - def run(self, method: str='complete', metric: Union[str, Callable[[object], float]]='euclidean', optimal_or...
Implement the Python class `Linkage` described below. Class description: Hierarchical clustering is a method of cluster analysis which seeks to build a hierarchy of clusters. Method signatures and docstrings: - def run(self, method: str='complete', metric: Union[str, Callable[[object], float]]='euclidean', optimal_or...
adddd0b5cb67a50301ef5ae323c61bde57210cb8
<|skeleton|> class Linkage: """Hierarchical clustering is a method of cluster analysis which seeks to build a hierarchy of clusters.""" def run(self, method: str='complete', metric: Union[str, Callable[[object], float]]='euclidean', optimal_ordering: bool=False) -> object: """Runs the hierarchical clus...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Linkage: """Hierarchical clustering is a method of cluster analysis which seeks to build a hierarchy of clusters.""" def run(self, method: str='complete', metric: Union[str, Callable[[object], float]]='euclidean', optimal_ordering: bool=False) -> object: """Runs the hierarchical clustering for th...
the_stack_v2_python_sparse
venv/lib/python3.9/site-packages/compling/unsupervisedLearning/clustering/linkage.py
TheKing-coder68/Verselet
train
1
6ab84c58144f1aeee01eed6b54daae899ebaef69
[ "user, data = self.account.selectAccount()\njsonResponse = self.load(self.API_URL, get={'action': 'connectUser', 'login': user, 'password': data['password']})\nres = json_loads(jsonResponse)\nif res['response_code'] == 'ok':\n self.token = res['token']\n return True\nelse:\n return False", "if not self.a...
<|body_start_0|> user, data = self.account.selectAccount() jsonResponse = self.load(self.API_URL, get={'action': 'connectUser', 'login': user, 'password': data['password']}) res = json_loads(jsonResponse) if res['response_code'] == 'ok': self.token = res['token'] ...
MegaDebridEu
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MegaDebridEu: def api_load(self): """Connexion to the mega-debrid API Return True if succeed""" <|body_0|> def handlePremium(self, pyfile): """Debrid a link Return The debrided link if succeed or original link if fail""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_014311
1,758
no_license
[ { "docstring": "Connexion to the mega-debrid API Return True if succeed", "name": "api_load", "signature": "def api_load(self)" }, { "docstring": "Debrid a link Return The debrided link if succeed or original link if fail", "name": "handlePremium", "signature": "def handlePremium(self, p...
2
stack_v2_sparse_classes_30k_train_000082
Implement the Python class `MegaDebridEu` described below. Class description: Implement the MegaDebridEu class. Method signatures and docstrings: - def api_load(self): Connexion to the mega-debrid API Return True if succeed - def handlePremium(self, pyfile): Debrid a link Return The debrided link if succeed or origin...
Implement the Python class `MegaDebridEu` described below. Class description: Implement the MegaDebridEu class. Method signatures and docstrings: - def api_load(self): Connexion to the mega-debrid API Return True if succeed - def handlePremium(self, pyfile): Debrid a link Return The debrided link if succeed or origin...
ef6d859b92dbcace76abef04ef251ee0bf09cf8b
<|skeleton|> class MegaDebridEu: def api_load(self): """Connexion to the mega-debrid API Return True if succeed""" <|body_0|> def handlePremium(self, pyfile): """Debrid a link Return The debrided link if succeed or original link if fail""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MegaDebridEu: def api_load(self): """Connexion to the mega-debrid API Return True if succeed""" user, data = self.account.selectAccount() jsonResponse = self.load(self.API_URL, get={'action': 'connectUser', 'login': user, 'password': data['password']}) res = json_loads(jsonResp...
the_stack_v2_python_sparse
data/root-.pyload-config/userplugins/hoster/MegaDebridEu.py
kurtiss/htpc
train
0
d9a498e7ec694766c61d66025b59413bb71e96df
[ "super().__init__(data=data, sampling_rate=sampling_rate, time_intervals=time_intervals, include_start=include_start)\nself.eeg_result: Dict[str, pd.DataFrame] = {}\n'Dictionary with EEG processing result dataframes, split into different phases.\\n\\n '", "from mne.time_frequency import psd_array_welch\nee...
<|body_start_0|> super().__init__(data=data, sampling_rate=sampling_rate, time_intervals=time_intervals, include_start=include_start) self.eeg_result: Dict[str, pd.DataFrame] = {} 'Dictionary with EEG processing result dataframes, split into different phases.\n\n ' <|end_body_0|> <|body_...
Class for processing EEG data.
EegProcessor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EegProcessor: """Class for processing EEG data.""" def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]]]]=None, include_start: Optional[bool]=False): """Initializ...
stack_v2_sparse_classes_36k_train_014312
5,188
permissive
[ { "docstring": "Initialize an ``EegProcessor`` instance. You can either pass a data dictionary 'data_dict' containing EEG data or dataframe containing EEG data. For the latter, you can additionally supply time information via ``time_intervals`` parameter to automatically split the data into single phases. Param...
2
stack_v2_sparse_classes_30k_train_004587
Implement the Python class `EegProcessor` described below. Class description: Class for processing EEG data. Method signatures and docstrings: - def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]...
Implement the Python class `EegProcessor` described below. Class description: Class for processing EEG data. Method signatures and docstrings: - def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]...
5b2eab0b0e4b52c1b3997f760ad0d1ae33d1a81d
<|skeleton|> class EegProcessor: """Class for processing EEG data.""" def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]]]]=None, include_start: Optional[bool]=False): """Initializ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EegProcessor: """Class for processing EEG data.""" def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]]]]=None, include_start: Optional[bool]=False): """Initialize an ``EegPro...
the_stack_v2_python_sparse
src/biopsykit/signals/eeg/eeg.py
mad-lab-fau/BioPsyKit
train
35
9259970583166bb4060bf9853c86cbaa340eb743
[ "kwargs = super().get_form_kwargs()\nkwargs.update({'cart': Cart(self.request)})\nreturn kwargs", "cart_items = {}\nfor offer_form in form.forms:\n offer_form.is_valid()\n cart_items[str(offer_form.offer.pk)] = {'quantity': offer_form.cleaned_data['quantity']}\nself.request.session[CART_KEY] = cart_items\ns...
<|body_start_0|> kwargs = super().get_form_kwargs() kwargs.update({'cart': Cart(self.request)}) return kwargs <|end_body_0|> <|body_start_1|> cart_items = {} for offer_form in form.forms: offer_form.is_valid() cart_items[str(offer_form.offer.pk)] = {'quan...
Страница корзины.
CartView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CartView: """Страница корзины.""" def get_form_kwargs(self): """Передаём корзину пользователя в форму.""" <|body_0|> def form_valid(self, form): """Для уверенности мы пересохраняем данные из формы в сессию пользователя.""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_36k_train_014313
7,131
no_license
[ { "docstring": "Передаём корзину пользователя в форму.", "name": "get_form_kwargs", "signature": "def get_form_kwargs(self)" }, { "docstring": "Для уверенности мы пересохраняем данные из формы в сессию пользователя.", "name": "form_valid", "signature": "def form_valid(self, form)" } ]
2
null
Implement the Python class `CartView` described below. Class description: Страница корзины. Method signatures and docstrings: - def get_form_kwargs(self): Передаём корзину пользователя в форму. - def form_valid(self, form): Для уверенности мы пересохраняем данные из формы в сессию пользователя.
Implement the Python class `CartView` described below. Class description: Страница корзины. Method signatures and docstrings: - def get_form_kwargs(self): Передаём корзину пользователя в форму. - def form_valid(self, form): Для уверенности мы пересохраняем данные из формы в сессию пользователя. <|skeleton|> class Ca...
97c29690929693b172ab88a52c3b426b17461011
<|skeleton|> class CartView: """Страница корзины.""" def get_form_kwargs(self): """Передаём корзину пользователя в форму.""" <|body_0|> def form_valid(self, form): """Для уверенности мы пересохраняем данные из формы в сессию пользователя.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CartView: """Страница корзины.""" def get_form_kwargs(self): """Передаём корзину пользователя в форму.""" kwargs = super().get_form_kwargs() kwargs.update({'cart': Cart(self.request)}) return kwargs def form_valid(self, form): """Для уверенности мы пересохраня...
the_stack_v2_python_sparse
stationery/apps/cart/views.py
minidron/stationery
train
0
49f2864cb44f4ef69e6fcd9d945904d5e219b72e
[ "super(StreamPowerThresholdModel, self).__init__(input_file=input_file, params=params)\nself.flow_router = FlowRouter(self.grid, **self.params)\nself.lake_filler = DepressionFinderAndRouter(self.grid, **self.params)\nself.eroder = StreamPowerSmoothThresholdEroder(self.grid, K_sp=self.params['K_sp'], threshold_sp=se...
<|body_start_0|> super(StreamPowerThresholdModel, self).__init__(input_file=input_file, params=params) self.flow_router = FlowRouter(self.grid, **self.params) self.lake_filler = DepressionFinderAndRouter(self.grid, **self.params) self.eroder = StreamPowerSmoothThresholdEroder(self.grid, ...
A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term.
StreamPowerThresholdModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StreamPowerThresholdModel: """A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term.""" def __init__(self, input_file=None, params=None): """Initialize the StreamPowerThresholdModel.""" <...
stack_v2_sparse_classes_36k_train_014314
2,839
no_license
[ { "docstring": "Initialize the StreamPowerThresholdModel.", "name": "__init__", "signature": "def __init__(self, input_file=None, params=None)" }, { "docstring": "Advance model for one time-step of duration dt.", "name": "run_one_step", "signature": "def run_one_step(self, dt)" } ]
2
stack_v2_sparse_classes_30k_train_011814
Implement the Python class `StreamPowerThresholdModel` described below. Class description: A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term. Method signatures and docstrings: - def __init__(self, input_file=None, params=None...
Implement the Python class `StreamPowerThresholdModel` described below. Class description: A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term. Method signatures and docstrings: - def __init__(self, input_file=None, params=None...
3506ec741a7c8a170ea654d40c6119fefe1b93ba
<|skeleton|> class StreamPowerThresholdModel: """A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term.""" def __init__(self, input_file=None, params=None): """Initialize the StreamPowerThresholdModel.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StreamPowerThresholdModel: """A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term.""" def __init__(self, input_file=None, params=None): """Initialize the StreamPowerThresholdModel.""" super(StreamPo...
the_stack_v2_python_sparse
erosion_modeling_suite/erosion_model/single_component/stream_power_threshold/stream_power_threshold_model.py
kbarnhart/inverting_topography_postglacial
train
4
77932f13b4ac3231f02c16a782b358af9bea9d3b
[ "str_num = str(num)\nlength = len(str_num)\ndp = [0] * (length + 1)\ndp[-1] = 1\nfor i in range(length - 1, -1, -1):\n if 10 <= int(str_num[i:i + 2]) < 26:\n dp[i] += dp[i + 2]\n dp[i] += dp[i + 1]\nreturn dp[0]", "dp1 = dp2 = dp3 = 1\nwhile num > 0:\n if 10 <= num % 100 < 26:\n dp3 += dp1\...
<|body_start_0|> str_num = str(num) length = len(str_num) dp = [0] * (length + 1) dp[-1] = 1 for i in range(length - 1, -1, -1): if 10 <= int(str_num[i:i + 2]) < 26: dp[i] += dp[i + 2] dp[i] += dp[i + 1] return dp[0] <|end_body_0|> ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def translateNum(self, num): """:type num: int :rtype: int""" <|body_0|> def translateNum2(self, num): """:type num: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> str_num = str(num) length = len(str_num) d...
stack_v2_sparse_classes_36k_train_014315
700
permissive
[ { "docstring": ":type num: int :rtype: int", "name": "translateNum", "signature": "def translateNum(self, num)" }, { "docstring": ":type num: int :rtype: int", "name": "translateNum2", "signature": "def translateNum2(self, num)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def translateNum(self, num): :type num: int :rtype: int - def translateNum2(self, num): :type num: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def translateNum(self, num): :type num: int :rtype: int - def translateNum2(self, num): :type num: int :rtype: int <|skeleton|> class Solution: def translateNum(self, num):...
c8bf33af30569177c5276ffcd72a8d93ba4c402a
<|skeleton|> class Solution: def translateNum(self, num): """:type num: int :rtype: int""" <|body_0|> def translateNum2(self, num): """:type num: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def translateNum(self, num): """:type num: int :rtype: int""" str_num = str(num) length = len(str_num) dp = [0] * (length + 1) dp[-1] = 1 for i in range(length - 1, -1, -1): if 10 <= int(str_num[i:i + 2]) < 26: dp[i] += dp[i...
the_stack_v2_python_sparse
LCOF/41-50/46/46.py
xuychen/Leetcode
train
0
eba6c7127755c10078ef984a16ea5129996caaee
[ "assert style in ColorSchemeColorHighlighter._region_style_flags\nself._view = view\nself._color_scheme_builder = color_scheme_builder\nself._text_coloring = style == 'text'\nself._flags = ColorSchemeColorHighlighter._region_style_flags[style]\nself._name = name\nself._debug = debug", "if 'values' not in context:...
<|body_start_0|> assert style in ColorSchemeColorHighlighter._region_style_flags self._view = view self._color_scheme_builder = color_scheme_builder self._text_coloring = style == 'text' self._flags = ColorSchemeColorHighlighter._region_style_flags[style] self._name = nam...
A color highlighter that uses color scheme scopes to highlight colors.
ColorSchemeColorHighlighter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ColorSchemeColorHighlighter: """A color highlighter that uses color scheme scopes to highlight colors.""" def __init__(self, view, style, color_scheme_builder, name, debug): """Init a ColorSchemeColorHighlighter. Arguments: - view - a view to highlight colors in. - style - the style ...
stack_v2_sparse_classes_36k_train_014316
7,723
no_license
[ { "docstring": "Init a ColorSchemeColorHighlighter. Arguments: - view - a view to highlight colors in. - style - the style of color highlighting. - color_scheme_builder - the color scheme builder to build regions for colors. - name - the name of the color highlighter. - debug - whether to enable debug mode.", ...
4
stack_v2_sparse_classes_30k_train_010011
Implement the Python class `ColorSchemeColorHighlighter` described below. Class description: A color highlighter that uses color scheme scopes to highlight colors. Method signatures and docstrings: - def __init__(self, view, style, color_scheme_builder, name, debug): Init a ColorSchemeColorHighlighter. Arguments: - v...
Implement the Python class `ColorSchemeColorHighlighter` described below. Class description: A color highlighter that uses color scheme scopes to highlight colors. Method signatures and docstrings: - def __init__(self, view, style, color_scheme_builder, name, debug): Init a ColorSchemeColorHighlighter. Arguments: - v...
83d469af3fc11d1aedb5193976ef84c59b595d6c
<|skeleton|> class ColorSchemeColorHighlighter: """A color highlighter that uses color scheme scopes to highlight colors.""" def __init__(self, view, style, color_scheme_builder, name, debug): """Init a ColorSchemeColorHighlighter. Arguments: - view - a view to highlight colors in. - style - the style ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ColorSchemeColorHighlighter: """A color highlighter that uses color scheme scopes to highlight colors.""" def __init__(self, view, style, color_scheme_builder, name, debug): """Init a ColorSchemeColorHighlighter. Arguments: - view - a view to highlight colors in. - style - the style of color high...
the_stack_v2_python_sparse
.config/sublime-text-2/Packages/Color Highlighter/color_scheme_color_highlighter.py
Wallkerock/X-setup
train
10
4fb5a451ebf722022fd3f55c58b7a8f9f4de0cd4
[ "points = [[1, 3], [-2, 2]]\nK = 1\nexpected_out = [[-2, 2]]\nself.assertEqual(k_closest_brute_force(points, K), expected_out)\nself.assertEqual(k_closest_divide_conquer(points, K), expected_out)", "points = [[3, 3], [5, -1], [-2, 4]]\nK = 2\nexpected_out = [[3, 3], [-2, 4]]\nself.assertEqual(k_closest_brute_forc...
<|body_start_0|> points = [[1, 3], [-2, 2]] K = 1 expected_out = [[-2, 2]] self.assertEqual(k_closest_brute_force(points, K), expected_out) self.assertEqual(k_closest_divide_conquer(points, K), expected_out) <|end_body_0|> <|body_start_1|> points = [[3, 3], [5, -1], [-2,...
Unit test for k_closest problem.
TestKClosest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestKClosest: """Unit test for k_closest problem.""" def test_1(self): """The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points f...
stack_v2_sparse_classes_36k_train_014317
2,643
no_license
[ { "docstring": "The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].", "name": "test_1", "signature...
2
null
Implement the Python class `TestKClosest` described below. Class description: Unit test for k_closest problem. Method signatures and docstrings: - def test_1(self): The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is clos...
Implement the Python class `TestKClosest` described below. Class description: Unit test for k_closest problem. Method signatures and docstrings: - def test_1(self): The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is clos...
8105e1b20bf450a03a9bb910f344fc140e5ba703
<|skeleton|> class TestKClosest: """Unit test for k_closest problem.""" def test_1(self): """The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestKClosest: """Unit test for k_closest problem.""" def test_1(self): """The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points from the origi...
the_stack_v2_python_sparse
module_4/python/k_closest.py
vprusso/6-Weeks-to-Interview-Ready
train
6
0fec10dbe543db399a8f78a81dcec6ce15dc74af
[ "allowed_fields = super().filter_allowed_fields\nallowed_fields.remove('assignment_id')\nreturn allowed_fields", "assignment_id = self.request.matchdict.get('assignment_id')\nif assignment_id:\n query.filter(self.model.assignment_id == assignment_id)\nreturn query" ]
<|body_start_0|> allowed_fields = super().filter_allowed_fields allowed_fields.remove('assignment_id') return allowed_fields <|end_body_0|> <|body_start_1|> assignment_id = self.request.matchdict.get('assignment_id') if assignment_id: query.filter(self.model.assignme...
Assets service.
AssetService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssetService: """Assets service.""" def filter_allowed_fields(self): """List of fields allowed in filtering and sorting.""" <|body_0|> def default_filters(self, query) -> object: """Default filters for this Service.""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_014318
2,803
no_license
[ { "docstring": "List of fields allowed in filtering and sorting.", "name": "filter_allowed_fields", "signature": "def filter_allowed_fields(self)" }, { "docstring": "Default filters for this Service.", "name": "default_filters", "signature": "def default_filters(self, query) -> object" ...
2
stack_v2_sparse_classes_30k_train_002669
Implement the Python class `AssetService` described below. Class description: Assets service. Method signatures and docstrings: - def filter_allowed_fields(self): List of fields allowed in filtering and sorting. - def default_filters(self, query) -> object: Default filters for this Service.
Implement the Python class `AssetService` described below. Class description: Assets service. Method signatures and docstrings: - def filter_allowed_fields(self): List of fields allowed in filtering and sorting. - def default_filters(self, query) -> object: Default filters for this Service. <|skeleton|> class AssetS...
e85c0ba0992bccb80878e89ec791ee64754646b0
<|skeleton|> class AssetService: """Assets service.""" def filter_allowed_fields(self): """List of fields allowed in filtering and sorting.""" <|body_0|> def default_filters(self, query) -> object: """Default filters for this Service.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssetService: """Assets service.""" def filter_allowed_fields(self): """List of fields allowed in filtering and sorting.""" allowed_fields = super().filter_allowed_fields allowed_fields.remove('assignment_id') return allowed_fields def default_filters(self, query) -> ...
the_stack_v2_python_sparse
src/briefy/leica/views/assets.py
BriefyHQ/briefy.leica
train
0
9df7acce6cbe4b69599fafd287f95991fb96842b
[ "self.df_path = df_path\nself.sc = sc\nself.sql = sql\nself.df = sql.read.format('com.databricks.spark.csv').option('header', 'true').load(self.df_path)\nself.rulelist_filename = None\nself.rulelist = None\nself.id_field = id_field\nself.snippet_field = snippet_field", "print(rulelist_filename)\nself.rulelist_fil...
<|body_start_0|> self.df_path = df_path self.sc = sc self.sql = sql self.df = sql.read.format('com.databricks.spark.csv').option('header', 'true').load(self.df_path) self.rulelist_filename = None self.rulelist = None self.id_field = id_field self.snippet_f...
The parent class for creating and viewing labeled categories on a dataframe of snippets and other metadata
Categorizer
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Categorizer: """The parent class for creating and viewing labeled categories on a dataframe of snippets and other metadata""" def __init__(self, df_path, sc=sc, sql=sql, id_field='Url', snippet_field='Cleaned Snippet'): """:param df_path: Pandas df containing cleaned snippets and ids...
stack_v2_sparse_classes_36k_train_014319
4,874
permissive
[ { "docstring": ":param df_path: Pandas df containing cleaned snippets and ids (as a maximum) :param sc: spark context :param sql: spark.sql context :param id_field: the id field in source df :param snippet_field: the field containing the text data to search in", "name": "__init__", "signature": "def __i...
4
stack_v2_sparse_classes_30k_train_008242
Implement the Python class `Categorizer` described below. Class description: The parent class for creating and viewing labeled categories on a dataframe of snippets and other metadata Method signatures and docstrings: - def __init__(self, df_path, sc=sc, sql=sql, id_field='Url', snippet_field='Cleaned Snippet'): :par...
Implement the Python class `Categorizer` described below. Class description: The parent class for creating and viewing labeled categories on a dataframe of snippets and other metadata Method signatures and docstrings: - def __init__(self, df_path, sc=sc, sql=sql, id_field='Url', snippet_field='Cleaned Snippet'): :par...
b810c6e1a93a2ecaa9d6351449239d0a1833f971
<|skeleton|> class Categorizer: """The parent class for creating and viewing labeled categories on a dataframe of snippets and other metadata""" def __init__(self, df_path, sc=sc, sql=sql, id_field='Url', snippet_field='Cleaned Snippet'): """:param df_path: Pandas df containing cleaned snippets and ids...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Categorizer: """The parent class for creating and viewing labeled categories on a dataframe of snippets and other metadata""" def __init__(self, df_path, sc=sc, sql=sql, id_field='Url', snippet_field='Cleaned Snippet'): """:param df_path: Pandas df containing cleaned snippets and ids (as a maximu...
the_stack_v2_python_sparse
usherwood_ds/nlp/taxonomy/spark_regex_categorizer.py
Usherwood/usherwood_ds
train
2
fb0160eee3cdaf072a390a80cbebc6c22b58847e
[ "cls.require_notfound(path)\nNEW_SCRIPT_TEMPLATE = '\"\"\"%s\"\"\"\\n# Keep __doc__ to a single line\\nfrom pyClanSphere.upgrades.versions import *\\n\\n# use this or define your own if you need\\nmetadata = db.MetaData()\\n\\n# Define tables here\\n\\n\\n# Define the objects here\\n\\n\\ndef map_tables(mapper):\\n...
<|body_start_0|> cls.require_notfound(path) NEW_SCRIPT_TEMPLATE = '"""%s"""\n# Keep __doc__ to a single line\nfrom pyClanSphere.upgrades.versions import *\n\n# use this or define your own if you need\nmetadata = db.MetaData()\n\n# Define tables here\n\n\n# Define the objects here\n\n\ndef map_tables(map...
PythonScript
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PythonScript: def create(cls, path, **opts): """Create an empty migration script at specified path :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`""" <|body_0|> def run(self, engine, step): """Core method of Script file. Exectues ...
stack_v2_sparse_classes_36k_train_014320
8,942
permissive
[ { "docstring": "Create an empty migration script at specified path :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`", "name": "create", "signature": "def create(cls, path, **opts)" }, { "docstring": "Core method of Script file. Exectues :func:`update` or :func...
2
stack_v2_sparse_classes_30k_train_002910
Implement the Python class `PythonScript` described below. Class description: Implement the PythonScript class. Method signatures and docstrings: - def create(cls, path, **opts): Create an empty migration script at specified path :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>` - d...
Implement the Python class `PythonScript` described below. Class description: Implement the PythonScript class. Method signatures and docstrings: - def create(cls, path, **opts): Create an empty migration script at specified path :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>` - d...
03904b3de4ae2043c0ff2a68a50c5f916896b68d
<|skeleton|> class PythonScript: def create(cls, path, **opts): """Create an empty migration script at specified path :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`""" <|body_0|> def run(self, engine, step): """Core method of Script file. Exectues ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PythonScript: def create(cls, path, **opts): """Create an empty migration script at specified path :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`""" cls.require_notfound(path) NEW_SCRIPT_TEMPLATE = '"""%s"""\n# Keep __doc__ to a single line\nfrom p...
the_stack_v2_python_sparse
pyClanSphere/upgrades/customisation.py
jokey2k/pyClanSphere
train
1
6b1749c324eba4829dfd834bfda3bf544da7f8b9
[ "try:\n result = []\n for record in response:\n numOfIteration = 0\n original_map = target_map.copy()\n for key, value in target_map.items():\n if type(record[numOfIteration]) == datetime.datetime:\n target_map[key] = record[numOfIteration].strftime('%Y-%m-%d %H:...
<|body_start_0|> try: result = [] for record in response: numOfIteration = 0 original_map = target_map.copy() for key, value in target_map.items(): if type(record[numOfIteration]) == datetime.datetime: ...
DBreadHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBreadHelper: def map_response(self, response=[], target_map={}): """map_response() => Maps Database Query Response to Object. params => response (array)""" <|body_0|> def map_detail_response(self, response=[], target_map={}): """map_detail_response() => Maps Databas...
stack_v2_sparse_classes_36k_train_014321
3,601
no_license
[ { "docstring": "map_response() => Maps Database Query Response to Object. params => response (array)", "name": "map_response", "signature": "def map_response(self, response=[], target_map={})" }, { "docstring": "map_detail_response() => Maps Database Query Response to Object. params => response ...
2
null
Implement the Python class `DBreadHelper` described below. Class description: Implement the DBreadHelper class. Method signatures and docstrings: - def map_response(self, response=[], target_map={}): map_response() => Maps Database Query Response to Object. params => response (array) - def map_detail_response(self, r...
Implement the Python class `DBreadHelper` described below. Class description: Implement the DBreadHelper class. Method signatures and docstrings: - def map_response(self, response=[], target_map={}): map_response() => Maps Database Query Response to Object. params => response (array) - def map_detail_response(self, r...
bbe7c7e74313ed63d7765a16cf11fdf7f3ad706a
<|skeleton|> class DBreadHelper: def map_response(self, response=[], target_map={}): """map_response() => Maps Database Query Response to Object. params => response (array)""" <|body_0|> def map_detail_response(self, response=[], target_map={}): """map_detail_response() => Maps Databas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBreadHelper: def map_response(self, response=[], target_map={}): """map_response() => Maps Database Query Response to Object. params => response (array)""" try: result = [] for record in response: numOfIteration = 0 original_map = target...
the_stack_v2_python_sparse
skytrip/db_read/helper.py
NumanIbnMazid/reservation
train
1
593463b05855cb3ebffac5c7ec4c9ca85eaba891
[ "super().__init__()\nself._name = name\nself._cities = cities\nself._overhead_queue = queue", "for i, city in enumerate(self._cities, start=1):\n overhead_time = city_processor.ISSDataRequest.get_overhead_pass(city)\n logging.info('Producer %d is adding to the queue', self._name)\n self._overhead_queue.p...
<|body_start_0|> super().__init__() self._name = name self._cities = cities self._overhead_queue = queue <|end_body_0|> <|body_start_1|> for i, city in enumerate(self._cities, start=1): overhead_time = city_processor.ISSDataRequest.get_overhead_pass(city) ...
ProducerThread
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProducerThread: def __init__(self, cities: list, queue: CityOverheadTimeQueue, name: int): """This method initializes the class with a list of City Objects as well as a CityOverheadTimeQueue. :param cities: list(City) :param queue: CityOverheadTimeQueue :return: None""" <|body_0|...
stack_v2_sparse_classes_36k_train_014322
5,647
no_license
[ { "docstring": "This method initializes the class with a list of City Objects as well as a CityOverheadTimeQueue. :param cities: list(City) :param queue: CityOverheadTimeQueue :return: None", "name": "__init__", "signature": "def __init__(self, cities: list, queue: CityOverheadTimeQueue, name: int)" }...
2
stack_v2_sparse_classes_30k_val_000898
Implement the Python class `ProducerThread` described below. Class description: Implement the ProducerThread class. Method signatures and docstrings: - def __init__(self, cities: list, queue: CityOverheadTimeQueue, name: int): This method initializes the class with a list of City Objects as well as a CityOverheadTime...
Implement the Python class `ProducerThread` described below. Class description: Implement the ProducerThread class. Method signatures and docstrings: - def __init__(self, cities: list, queue: CityOverheadTimeQueue, name: int): This method initializes the class with a list of City Objects as well as a CityOverheadTime...
5fbc92a7ddd9103076a7095124b5ae108b002f03
<|skeleton|> class ProducerThread: def __init__(self, cities: list, queue: CityOverheadTimeQueue, name: int): """This method initializes the class with a list of City Objects as well as a CityOverheadTimeQueue. :param cities: list(City) :param queue: CityOverheadTimeQueue :return: None""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProducerThread: def __init__(self, cities: list, queue: CityOverheadTimeQueue, name: int): """This method initializes the class with a list of City Objects as well as a CityOverheadTimeQueue. :param cities: list(City) :param queue: CityOverheadTimeQueue :return: None""" super().__init__() ...
the_stack_v2_python_sparse
Labs/Lab10/producer_consumer.py
pyopoly/3522_A00699267
train
0
883e4b40ce9d3ed4c00311e6c40aac692aad3cc2
[ "if not head or not head.next:\n return head\ncount = 1\ncur = head\nwhile cur.next:\n cur = cur.next\n count += 1\nk = count - k % count\ncur.next = head\nwhile k > 0:\n cur = cur.next\n k -= 1\nhead = cur.next\ncur.next = None\nreturn head", "nums = []\nguard = ListNode(next=head)\nwhile head:\n ...
<|body_start_0|> if not head or not head.next: return head count = 1 cur = head while cur.next: cur = cur.next count += 1 k = count - k % count cur.next = head while k > 0: cur = cur.next k -= 1 h...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: """执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户""" <|body_0|> def rotateRight1(self, head: ListNode, k: int) -> ListNode: """执行用时: 44 ms , 在所有 Python3 提交中...
stack_v2_sparse_classes_36k_train_014323
2,485
no_license
[ { "docstring": "执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户", "name": "rotateRight", "signature": "def rotateRight(self, head: ListNode, k: int) -> ListNode" }, { "docstring": "执行用时: 44 ms , 在所有 Python3 提交中击败了 63.50% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotateRight(self, head: ListNode, k: int) -> ListNode: 执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户 - def rotateRight1(self, head:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotateRight(self, head: ListNode, k: int) -> ListNode: 执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户 - def rotateRight1(self, head:...
d613ed8a5a2c15ace7d513965b372d128845d66a
<|skeleton|> class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: """执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户""" <|body_0|> def rotateRight1(self, head: ListNode, k: int) -> ListNode: """执行用时: 44 ms , 在所有 Python3 提交中...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: """执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户""" if not head or not head.next: return head count = 1 cur = head while cur.next: cur...
the_stack_v2_python_sparse
旋转链表.py
nomboy/leetcode
train
0
7492e29f36ea40248a2dac87529e0290e6668ea4
[ "self.u1 = User.objects.create_user('user1', 'user@user.com', 'password')\nself.u2 = User.objects.create_user('user2', 'user@user.com', 'password')\ncreate_permission('permission1', description='Permission 1 description.')\ngive_permission_to('permission1', self.u1, self.u1, can_delegate=True)\ngive_permission_to('...
<|body_start_0|> self.u1 = User.objects.create_user('user1', 'user@user.com', 'password') self.u2 = User.objects.create_user('user2', 'user@user.com', 'password') create_permission('permission1', description='Permission 1 description.') give_permission_to('permission1', self.u1, self.u1,...
RequestsTests
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestsTests: def setUp(self): """Create some permissions and users.""" <|body_0|> def test_req_process(self): """Test that when a request is made for a user, it shows up in the dashboard.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.u1 = U...
stack_v2_sparse_classes_36k_train_014324
3,183
permissive
[ { "docstring": "Create some permissions and users.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that when a request is made for a user, it shows up in the dashboard.", "name": "test_req_process", "signature": "def test_req_process(self)" } ]
2
null
Implement the Python class `RequestsTests` described below. Class description: Implement the RequestsTests class. Method signatures and docstrings: - def setUp(self): Create some permissions and users. - def test_req_process(self): Test that when a request is made for a user, it shows up in the dashboard.
Implement the Python class `RequestsTests` described below. Class description: Implement the RequestsTests class. Method signatures and docstrings: - def setUp(self): Create some permissions and users. - def test_req_process(self): Test that when a request is made for a user, it shows up in the dashboard. <|skeleton...
059ed2b3308bda2af5e1942dc9967e6573dd6a53
<|skeleton|> class RequestsTests: def setUp(self): """Create some permissions and users.""" <|body_0|> def test_req_process(self): """Test that when a request is made for a user, it shows up in the dashboard.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RequestsTests: def setUp(self): """Create some permissions and users.""" self.u1 = User.objects.create_user('user1', 'user@user.com', 'password') self.u2 = User.objects.create_user('user2', 'user@user.com', 'password') create_permission('permission1', description='Permission 1 ...
the_stack_v2_python_sparse
expedient/src/python/expedient/clearinghouse/permissionmgmt/tests.py
dana-i2cat/felix
train
4
29a1f81b6cf6f160d3e819a697662b4bf8503e08
[ "with transaction.atomic(savepoint=True):\n self.task.started = now()\n self.task.save()\n signals.task_started.send(sender=self.flow_class, process=self.process, task=self.task)\n for task in self.process.active_tasks():\n if task != self.task:\n break\n else:\n self.process...
<|body_start_0|> with transaction.atomic(savepoint=True): self.task.started = now() self.task.save() signals.task_started.send(sender=self.flow_class, process=self.process, task=self.task) for task in self.process.active_tasks(): if task != self.ta...
Activation that finishes the flow process. .. graphviz:: digraph status { UNRIPE; NEW -> CANCELED [label="cancel"]; DONE -> NEW [label="undo"]; NEW -> DONE [label="perform"]; {rank = min;NEW} }
EndActivation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EndActivation: """Activation that finishes the flow process. .. graphviz:: digraph status { UNRIPE; NEW -> CANCELED [label="cancel"]; DONE -> NEW [label="undo"]; NEW -> DONE [label="perform"]; {rank = min;NEW} }""" def perform(self): """Finalize the flow. If there is no active task, ...
stack_v2_sparse_classes_36k_train_014325
24,697
permissive
[ { "docstring": "Finalize the flow. If there is no active task, process marked as finished. .. seealso:: :data:`viewflow.signals.task_started` .. seealso:: :data:`viewflow.signals.task_finished` .. seealso:: :data:`viewflow.signals.flow_finished`", "name": "perform", "signature": "def perform(self)" },...
3
stack_v2_sparse_classes_30k_val_001196
Implement the Python class `EndActivation` described below. Class description: Activation that finishes the flow process. .. graphviz:: digraph status { UNRIPE; NEW -> CANCELED [label="cancel"]; DONE -> NEW [label="undo"]; NEW -> DONE [label="perform"]; {rank = min;NEW} } Method signatures and docstrings: - def perfo...
Implement the Python class `EndActivation` described below. Class description: Activation that finishes the flow process. .. graphviz:: digraph status { UNRIPE; NEW -> CANCELED [label="cancel"]; DONE -> NEW [label="undo"]; NEW -> DONE [label="perform"]; {rank = min;NEW} } Method signatures and docstrings: - def perfo...
0267168bb90e8e9c85aecdd715972b9622b82384
<|skeleton|> class EndActivation: """Activation that finishes the flow process. .. graphviz:: digraph status { UNRIPE; NEW -> CANCELED [label="cancel"]; DONE -> NEW [label="undo"]; NEW -> DONE [label="perform"]; {rank = min;NEW} }""" def perform(self): """Finalize the flow. If there is no active task, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EndActivation: """Activation that finishes the flow process. .. graphviz:: digraph status { UNRIPE; NEW -> CANCELED [label="cancel"]; DONE -> NEW [label="undo"]; NEW -> DONE [label="perform"]; {rank = min;NEW} }""" def perform(self): """Finalize the flow. If there is no active task, process marke...
the_stack_v2_python_sparse
Scripts/ict/viewflow/activation.py
mspgeek/Client_Portal
train
6
1b27a07071ac669eed2ea6fd63abbb44245e8a56
[ "if amount == 0:\n return 0\nqueue = collections.deque(coins)\nd = {x: 1 for x in coins}\nwhile queue:\n cur = queue.popleft()\n if cur == amount:\n return d[cur]\n for i in coins:\n k = cur + i\n if k <= amount and (not k in d):\n queue.append(k)\n d[k] = d[cu...
<|body_start_0|> if amount == 0: return 0 queue = collections.deque(coins) d = {x: 1 for x in coins} while queue: cur = queue.popleft() if cur == amount: return d[cur] for i in coins: k = cur + i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def coinChange(self, coins, amount): """bfs AC :param coins: :param amount: :return:""" <|body_0|> def coinChange3(self, coins, amount): """完全背包问题 :param coins: :param amount: :return:""" <|body_1|> def coinChange2(self, coins, amount): ...
stack_v2_sparse_classes_36k_train_014326
2,469
no_license
[ { "docstring": "bfs AC :param coins: :param amount: :return:", "name": "coinChange", "signature": "def coinChange(self, coins, amount)" }, { "docstring": "完全背包问题 :param coins: :param amount: :return:", "name": "coinChange3", "signature": "def coinChange3(self, coins, amount)" }, { ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def coinChange(self, coins, amount): bfs AC :param coins: :param amount: :return: - def coinChange3(self, coins, amount): 完全背包问题 :param coins: :param amount: :return: - def coinC...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def coinChange(self, coins, amount): bfs AC :param coins: :param amount: :return: - def coinChange3(self, coins, amount): 完全背包问题 :param coins: :param amount: :return: - def coinC...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def coinChange(self, coins, amount): """bfs AC :param coins: :param amount: :return:""" <|body_0|> def coinChange3(self, coins, amount): """完全背包问题 :param coins: :param amount: :return:""" <|body_1|> def coinChange2(self, coins, amount): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def coinChange(self, coins, amount): """bfs AC :param coins: :param amount: :return:""" if amount == 0: return 0 queue = collections.deque(coins) d = {x: 1 for x in coins} while queue: cur = queue.popleft() if cur == amount:...
the_stack_v2_python_sparse
322_零钱兑换.py
lovehhf/LeetCode
train
0
47b8d4587edf5e941c97bcf02cf828571cc749d7
[ "self.host = host\nself.user = user\nself.private_key = private_key\nself.password = password\nself.stdout = stdout\nself.client = self._connect()", "try:\n client = SSHClient()\n client.set_missing_host_key_policy(AutoAddPolicy())\n if self.private_key:\n client.connect(self.host, username=self.u...
<|body_start_0|> self.host = host self.user = user self.private_key = private_key self.password = password self.stdout = stdout self.client = self._connect() <|end_body_0|> <|body_start_1|> try: client = SSHClient() client.set_missing_host...
A class that connects to remote server
Connection
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Connection: """A class that connects to remote server""" def __init__(self, host, user=None, private_key=None, password=None, stdout=False): """Initialize all required variables Args: host (str): Hostname or IP to connect user (str): User name to connect private_key (str): Private ke...
stack_v2_sparse_classes_36k_train_014327
2,862
permissive
[ { "docstring": "Initialize all required variables Args: host (str): Hostname or IP to connect user (str): User name to connect private_key (str): Private key to connect to load balancer password (password): Password for host stdout (bool): output stdout to console", "name": "__init__", "signature": "def...
3
null
Implement the Python class `Connection` described below. Class description: A class that connects to remote server Method signatures and docstrings: - def __init__(self, host, user=None, private_key=None, password=None, stdout=False): Initialize all required variables Args: host (str): Hostname or IP to connect user ...
Implement the Python class `Connection` described below. Class description: A class that connects to remote server Method signatures and docstrings: - def __init__(self, host, user=None, private_key=None, password=None, stdout=False): Initialize all required variables Args: host (str): Hostname or IP to connect user ...
5e9e504957403148e413326f65c3769bf9d8eb39
<|skeleton|> class Connection: """A class that connects to remote server""" def __init__(self, host, user=None, private_key=None, password=None, stdout=False): """Initialize all required variables Args: host (str): Hostname or IP to connect user (str): User name to connect private_key (str): Private ke...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Connection: """A class that connects to remote server""" def __init__(self, host, user=None, private_key=None, password=None, stdout=False): """Initialize all required variables Args: host (str): Hostname or IP to connect user (str): User name to connect private_key (str): Private key to connect ...
the_stack_v2_python_sparse
ocs_ci/utility/connection.py
red-hat-storage/ocs-ci
train
146
6895f11868462aa091d0e48854df6cdd16f4f47d
[ "skill_set = get_object_or_404(Instrument, slug=slug)\nself.check_object_permissions(request, skill_set)\nserializer = InstrumentRetrieveUpdateSerializer(skill_set, many=False)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)", "skill_set = get_object_or_404(Instrument, slug=slug)\nself.check_obj...
<|body_start_0|> skill_set = get_object_or_404(Instrument, slug=slug) self.check_object_permissions(request, skill_set) serializer = InstrumentRetrieveUpdateSerializer(skill_set, many=False) return Response(data=serializer.data, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|>...
InstrumentRetrieveUpdateAPIView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstrumentRetrieveUpdateAPIView: def get(self, request, slug=None): """Retrieve""" <|body_0|> def put(self, request, slug=None): """Update""" <|body_1|> <|end_skeleton|> <|body_start_0|> skill_set = get_object_or_404(Instrument, slug=slug) s...
stack_v2_sparse_classes_36k_train_014328
2,477
permissive
[ { "docstring": "Retrieve", "name": "get", "signature": "def get(self, request, slug=None)" }, { "docstring": "Update", "name": "put", "signature": "def put(self, request, slug=None)" } ]
2
null
Implement the Python class `InstrumentRetrieveUpdateAPIView` described below. Class description: Implement the InstrumentRetrieveUpdateAPIView class. Method signatures and docstrings: - def get(self, request, slug=None): Retrieve - def put(self, request, slug=None): Update
Implement the Python class `InstrumentRetrieveUpdateAPIView` described below. Class description: Implement the InstrumentRetrieveUpdateAPIView class. Method signatures and docstrings: - def get(self, request, slug=None): Retrieve - def put(self, request, slug=None): Update <|skeleton|> class InstrumentRetrieveUpdate...
98e1ff8bab7dda3492e5ff637bf5aafd111c840c
<|skeleton|> class InstrumentRetrieveUpdateAPIView: def get(self, request, slug=None): """Retrieve""" <|body_0|> def put(self, request, slug=None): """Update""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstrumentRetrieveUpdateAPIView: def get(self, request, slug=None): """Retrieve""" skill_set = get_object_or_404(Instrument, slug=slug) self.check_object_permissions(request, skill_set) serializer = InstrumentRetrieveUpdateSerializer(skill_set, many=False) return Respon...
the_stack_v2_python_sparse
mikaponics/instrument/views/resource/instrument_crud_api_views.py
mikaponics/mikaponics-back
train
4
d7c3e5d1a4d4224173c286b11ef56dcc505953a6
[ "n = len(s)\nst = [[0] * n for _ in range(n)]\nfor i in range(n - 1, -1, -1):\n for j in range(i, n):\n if j - i <= 1 and s[i] == s[j]:\n st[i][j] = 1\n elif st[i + 1][j - 1] and s[i] == s[j]:\n st[i][j] = 1\ndp = [0] * (n + 1)\nfor i in range(1, n + 1):\n dp[i] = min([dp[j...
<|body_start_0|> n = len(s) st = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): for j in range(i, n): if j - i <= 1 and s[i] == s[j]: st[i][j] = 1 elif st[i + 1][j - 1] and s[i] == s[j]: st[i][j] = 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minCut(self, s): """两次dp :param s: :return:""" <|body_0|> def minCut2(self, s): """dfs 妥妥的超时 res 存储所有可能的分割的次数 :type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(s) st = [[0] * n for _ in range(n)] ...
stack_v2_sparse_classes_36k_train_014329
2,232
no_license
[ { "docstring": "两次dp :param s: :return:", "name": "minCut", "signature": "def minCut(self, s)" }, { "docstring": "dfs 妥妥的超时 res 存储所有可能的分割的次数 :type s: str :rtype: int", "name": "minCut2", "signature": "def minCut2(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCut(self, s): 两次dp :param s: :return: - def minCut2(self, s): dfs 妥妥的超时 res 存储所有可能的分割的次数 :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCut(self, s): 两次dp :param s: :return: - def minCut2(self, s): dfs 妥妥的超时 res 存储所有可能的分割的次数 :type s: str :rtype: int <|skeleton|> class Solution: def minCut(self, s): ...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def minCut(self, s): """两次dp :param s: :return:""" <|body_0|> def minCut2(self, s): """dfs 妥妥的超时 res 存储所有可能的分割的次数 :type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minCut(self, s): """两次dp :param s: :return:""" n = len(s) st = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): for j in range(i, n): if j - i <= 1 and s[i] == s[j]: st[i][j] = 1 elif st[i +...
the_stack_v2_python_sparse
132_分割回文串 II.py
lovehhf/LeetCode
train
0
e6fbe557a1cec65b2bbe82599d29dd09e8cdc2f6
[ "if data is None:\n if lambtha < 1:\n raise ValueError('lambtha must be a positive value')\n else:\n self.lambtha = lambtha\nelse:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple valu...
<|body_start_0|> if data is None: if lambtha < 1: raise ValueError('lambtha must be a positive value') else: self.lambtha = lambtha else: if not isinstance(data, list): raise TypeError('data must be a list') ...
The Exponential Distribution class
Exponential
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exponential: """The Exponential Distribution class""" def __init__(self, data=None, lambtha=1.0): """init lambtha of data""" <|body_0|> def pdf(self, x): """The pdf for exponential distribution""" <|body_1|> def cdf(self, x): """The cumulativ...
stack_v2_sparse_classes_36k_train_014330
1,084
no_license
[ { "docstring": "init lambtha of data", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "The pdf for exponential distribution", "name": "pdf", "signature": "def pdf(self, x)" }, { "docstring": "The cumulative distribution function", ...
3
null
Implement the Python class `Exponential` described below. Class description: The Exponential Distribution class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): init lambtha of data - def pdf(self, x): The pdf for exponential distribution - def cdf(self, x): The cumulative distribution ...
Implement the Python class `Exponential` described below. Class description: The Exponential Distribution class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): init lambtha of data - def pdf(self, x): The pdf for exponential distribution - def cdf(self, x): The cumulative distribution ...
4200798bdbbe828db94e5585b62a595e3a96c3e6
<|skeleton|> class Exponential: """The Exponential Distribution class""" def __init__(self, data=None, lambtha=1.0): """init lambtha of data""" <|body_0|> def pdf(self, x): """The pdf for exponential distribution""" <|body_1|> def cdf(self, x): """The cumulativ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Exponential: """The Exponential Distribution class""" def __init__(self, data=None, lambtha=1.0): """init lambtha of data""" if data is None: if lambtha < 1: raise ValueError('lambtha must be a positive value') else: self.lambtha = l...
the_stack_v2_python_sparse
math/0x03-probability/exponential.py
JohnCook17/holbertonschool-machine_learning
train
3
f54c70bccf53b3a61009efc4e4c59dec03e03fc0
[ "kwds['channels'] = channels\nsuper().__init__(**kwds)\nfor channel in self.channels:\n channel[2].setMaximum(1.0)", "active = []\nincrement = []\nfor i, channel in enumerate(self.channels):\n if self.which_checked[i] and frame_number % channel[3].value() == 0:\n active.append(True)\n incremen...
<|body_start_0|> kwds['channels'] = channels super().__init__(**kwds) for channel in self.channels: channel[2].setMaximum(1.0) <|end_body_0|> <|body_start_1|> active = [] increment = [] for i, channel in enumerate(self.channels): if self.which_che...
Channels class for linear progression.
LinearChannels
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearChannels: """Channels class for linear progression.""" def __init__(self, channels=None, **kwds): """This is basically the same as for MathChannels. It also specifies a maximum value for the increment spin box.""" <|body_0|> def handleNewFrame(self, frame_number): ...
stack_v2_sparse_classes_36k_train_014331
25,535
permissive
[ { "docstring": "This is basically the same as for MathChannels. It also specifies a maximum value for the increment spin box.", "name": "__init__", "signature": "def __init__(self, channels=None, **kwds)" }, { "docstring": "Called when we get a new frame from the camera. Returns the which channe...
2
null
Implement the Python class `LinearChannels` described below. Class description: Channels class for linear progression. Method signatures and docstrings: - def __init__(self, channels=None, **kwds): This is basically the same as for MathChannels. It also specifies a maximum value for the increment spin box. - def hand...
Implement the Python class `LinearChannels` described below. Class description: Channels class for linear progression. Method signatures and docstrings: - def __init__(self, channels=None, **kwds): This is basically the same as for MathChannels. It also specifies a maximum value for the increment spin box. - def hand...
f185df3d23b231a26c46f33b0b91fffa86356dc4
<|skeleton|> class LinearChannels: """Channels class for linear progression.""" def __init__(self, channels=None, **kwds): """This is basically the same as for MathChannels. It also specifies a maximum value for the increment spin box.""" <|body_0|> def handleNewFrame(self, frame_number): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearChannels: """Channels class for linear progression.""" def __init__(self, channels=None, **kwds): """This is basically the same as for MathChannels. It also specifies a maximum value for the increment spin box.""" kwds['channels'] = channels super().__init__(**kwds) ...
the_stack_v2_python_sparse
storm_control/hal4000/progressions/progressions.py
ZhuangLab/storm-control
train
54
defeaceebf02603bd7b6a99f07f637d54018a87f
[ "assert isinstance(param_group, dict), 'param group must be a dict'\nparams = param_group['params']\nif isinstance(params, (torch.Tensor, crypten.CrypTensor)):\n param_group['params'] = [params]\nelif isinstance(params, set):\n raise TypeError('optimizer parameters need to be organized in ordered collections,...
<|body_start_0|> assert isinstance(param_group, dict), 'param group must be a dict' params = param_group['params'] if isinstance(params, (torch.Tensor, crypten.CrypTensor)): param_group['params'] = [params] elif isinstance(params, set): raise TypeError('optimizer ...
Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over values of dictionaries. Arguments: params (iterable): an iterable of :class:`...
Optimizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Optimizer: """Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over values of dictionaries. Arguments: param...
stack_v2_sparse_classes_36k_train_014332
4,383
permissive
[ { "docstring": "Add a param group to the :class:`Optimizer` s `param_groups`. This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the :class:`Optimizer` as training progresses. Arguments: param_group (dict): Specifies what Tensors should be optimized alo...
2
null
Implement the Python class `Optimizer` described below. Class description: Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over v...
Implement the Python class `Optimizer` described below. Class description: Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over v...
99c3a046b705c9d69d7a10fcab59a444ffbee39a
<|skeleton|> class Optimizer: """Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over values of dictionaries. Arguments: param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Optimizer: """Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over values of dictionaries. Arguments: params (iterable):...
the_stack_v2_python_sparse
crypten/optim/optimizer.py
facebookresearch/CrypTen
train
1,388
8d41b5aa0b39dd65c417649d1765dcc1e5f62eb8
[ "self.dic = {}\nself.queue = []\nself.remain = capacity", "if key not in self.dic:\n return -1\nelse:\n self.queue.remove(key)\n self.queue.append(key)\n return self.dic[key]", "if key in self.dic:\n self.queue.remove(key)\n self.queue.append(key)\nelse:\n if self.remain > 0:\n self....
<|body_start_0|> self.dic = {} self.queue = [] self.remain = capacity <|end_body_0|> <|body_start_1|> if key not in self.dic: return -1 else: self.queue.remove(key) self.queue.append(key) return self.dic[key] <|end_body_1|> <|body...
LRUCache2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache2: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_014333
3,363
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
null
Implement the Python class `LRUCache2` described below. Class description: Implement the LRUCache2 class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache2` described below. Class description: Implement the LRUCache2 class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> c...
1df8d93a8ecb8627899aadddb5dd5c5d0b144cdf
<|skeleton|> class LRUCache2: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache2: def __init__(self, capacity): """:type capacity: int""" self.dic = {} self.queue = [] self.remain = capacity def get(self, key): """:rtype: int""" if key not in self.dic: return -1 else: self.queue.remove(key) ...
the_stack_v2_python_sparse
LRU.py
zhuolikevin/Algorithm-Practices-Python
train
0
ae2442c4d6ad0fb664be80d134e8bc7feeee63a7
[ "if decay_time <= datetime.timedelta(0):\n raise ValueError('decay_time must have positive duration')\nself.decay_time = decay_time\nself.decay_factor = decay_factor", "timestamp, x = value\nif now is None:\n now = datetime.datetime.utcnow()\ndelta = now - timestamp\nif delta < datetime.timedelta(seconds=0)...
<|body_start_0|> if decay_time <= datetime.timedelta(0): raise ValueError('decay_time must have positive duration') self.decay_time = decay_time self.decay_factor = decay_factor <|end_body_0|> <|body_start_1|> timestamp, x = value if now is None: now = da...
TimeDecay class. Helps to update counters that require a time decay
TimeDecay
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeDecay: """TimeDecay class. Helps to update counters that require a time decay""" def __init__(self, decay_time, decay_factor=2.0): """decay_time is timedelta""" <|body_0|> def update_value(self, value, now=None): """Computes the updated value for the given ha...
stack_v2_sparse_classes_36k_train_014334
1,847
permissive
[ { "docstring": "decay_time is timedelta", "name": "__init__", "signature": "def __init__(self, decay_time, decay_factor=2.0)" }, { "docstring": "Computes the updated value for the given half-life. Args: value (tuple(datetime.datetime, numeric_type)): tuple with the numeric value we wish to updat...
2
stack_v2_sparse_classes_30k_train_011536
Implement the Python class `TimeDecay` described below. Class description: TimeDecay class. Helps to update counters that require a time decay Method signatures and docstrings: - def __init__(self, decay_time, decay_factor=2.0): decay_time is timedelta - def update_value(self, value, now=None): Computes the updated v...
Implement the Python class `TimeDecay` described below. Class description: TimeDecay class. Helps to update counters that require a time decay Method signatures and docstrings: - def __init__(self, decay_time, decay_factor=2.0): decay_time is timedelta - def update_value(self, value, now=None): Computes the updated v...
70280110ec342a6f6db1c102e96756fcc3c3c01b
<|skeleton|> class TimeDecay: """TimeDecay class. Helps to update counters that require a time decay""" def __init__(self, decay_time, decay_factor=2.0): """decay_time is timedelta""" <|body_0|> def update_value(self, value, now=None): """Computes the updated value for the given ha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TimeDecay: """TimeDecay class. Helps to update counters that require a time decay""" def __init__(self, decay_time, decay_factor=2.0): """decay_time is timedelta""" if decay_time <= datetime.timedelta(0): raise ValueError('decay_time must have positive duration') self....
the_stack_v2_python_sparse
pylib/util/time_decay.py
room77/py77
train
0
e910ff849bd391adad910ddebabb5cad65964106
[ "super().__init__()\nif shared_dim is None:\n shared_dim = num_filts * 2 ** n_sample\nshared_block_enc = block_cls(shared_dim)\nshared_block_gen = block_cls(shared_dim)\nself.encoder_a = encoder_cls(shared_block_enc, img_shape[0], num_filts, n_sample)\nself.encoder_b = encoder_cls(shared_block_enc, img_shape[0],...
<|body_start_0|> super().__init__() if shared_dim is None: shared_dim = num_filts * 2 ** n_sample shared_block_enc = block_cls(shared_dim) shared_block_gen = block_cls(shared_dim) self.encoder_a = encoder_cls(shared_block_enc, img_shape[0], num_filts, n_sample) ...
Class implementing Unsupervised Image-to-Image Translation Networks References ---------- `Paper <https://arxiv.org/abs/1703.00848>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this network into its parts (i. e. separa...
UNIT
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UNIT: """Class implementing Unsupervised Image-to-Image Translation Networks References ---------- `Paper <https://arxiv.org/abs/1703.00848>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this netw...
stack_v2_sparse_classes_36k_train_014335
8,177
permissive
[ { "docstring": "Parameters ---------- img_shape : tuple the shape of the images to translate from and to (including channels, excluding batch dimension) num_filts : int number of filters to use n_sample : int number of sampling layers per network shared_dim : int size of the shared dimension between generators ...
2
stack_v2_sparse_classes_30k_train_003597
Implement the Python class `UNIT` described below. Class description: Class implementing Unsupervised Image-to-Image Translation Networks References ---------- `Paper <https://arxiv.org/abs/1703.00848>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained networ...
Implement the Python class `UNIT` described below. Class description: Class implementing Unsupervised Image-to-Image Translation Networks References ---------- `Paper <https://arxiv.org/abs/1703.00848>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained networ...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class UNIT: """Class implementing Unsupervised Image-to-Image Translation Networks References ---------- `Paper <https://arxiv.org/abs/1703.00848>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this netw...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UNIT: """Class implementing Unsupervised Image-to-Image Translation Networks References ---------- `Paper <https://arxiv.org/abs/1703.00848>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to split this network into its ...
the_stack_v2_python_sparse
dlutils/models/gans/unit/unit.py
justusschock/dl-utils
train
15
642a58bca1175a1a8d6fb1df852720568e4c8709
[ "agent = Agent.query.filter_by(id=agent_id).first()\nif agent is None:\n return (jsonify(error='Agent %r not found' % agent_id), NOT_FOUND)\nout = []\nfor task in agent.tasks:\n task_dict = task.to_dict(unpack_relationships=False)\n task_dict['job'] = {'id': task.job.id, 'title': task.job.title, 'jobtype':...
<|body_start_0|> agent = Agent.query.filter_by(id=agent_id).first() if agent is None: return (jsonify(error='Agent %r not found' % agent_id), NOT_FOUND) out = [] for task in agent.tasks: task_dict = task.to_dict(unpack_relationships=False) task_dict['j...
TasksInAgentAPI
[ "BSD-3-Clause", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TasksInAgentAPI: def get(self, agent_id): """A ``GET`` to this endpoint will return a list of all tasks assigned to this agent. .. http:get:: /api/v1/agents/<str:agent_id>/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-139bd8057931/tasks/ HTTP...
stack_v2_sparse_classes_36k_train_014336
40,281
permissive
[ { "docstring": "A ``GET`` to this endpoint will return a list of all tasks assigned to this agent. .. http:get:: /api/v1/agents/<str:agent_id>/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-139bd8057931/tasks/ HTTP/1.1 Accept: application/json **Response** .. sourcec...
2
stack_v2_sparse_classes_30k_train_006542
Implement the Python class `TasksInAgentAPI` described below. Class description: Implement the TasksInAgentAPI class. Method signatures and docstrings: - def get(self, agent_id): A ``GET`` to this endpoint will return a list of all tasks assigned to this agent. .. http:get:: /api/v1/agents/<str:agent_id>/tasks/ HTTP/...
Implement the Python class `TasksInAgentAPI` described below. Class description: Implement the TasksInAgentAPI class. Method signatures and docstrings: - def get(self, agent_id): A ``GET`` to this endpoint will return a list of all tasks assigned to this agent. .. http:get:: /api/v1/agents/<str:agent_id>/tasks/ HTTP/...
ea04bbcb807eb669415c569417b4b1b68e75d29d
<|skeleton|> class TasksInAgentAPI: def get(self, agent_id): """A ``GET`` to this endpoint will return a list of all tasks assigned to this agent. .. http:get:: /api/v1/agents/<str:agent_id>/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-139bd8057931/tasks/ HTTP...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TasksInAgentAPI: def get(self, agent_id): """A ``GET`` to this endpoint will return a list of all tasks assigned to this agent. .. http:get:: /api/v1/agents/<str:agent_id>/tasks/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-139bd8057931/tasks/ HTTP/1.1 Accept: a...
the_stack_v2_python_sparse
pyfarm/master/api/agents.py
pyfarm/pyfarm-master
train
2
255af835c212721b7b9215d58b7305291fbb1c6b
[ "self.bars = bars\nself.symbol_list = self.bars.symbol_list\nself.events = events\nself.approvals_csv_dir = approvals_csv_dir\nself.approvals_data = pd.read_csv(approvals_csv_dir)\nself.approvals_data['catalyst_date'] = pd.to_datetime(self.approvals_data['catalyst_date'])\nself.bought = self._calculate_initial_boug...
<|body_start_0|> self.bars = bars self.symbol_list = self.bars.symbol_list self.events = events self.approvals_csv_dir = approvals_csv_dir self.approvals_data = pd.read_csv(approvals_csv_dir) self.approvals_data['catalyst_date'] = pd.to_datetime(self.approvals_data['catal...
Performs a biotech approval strategy where... PUT STUFF HERE
BiotechApprovalStrategy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BiotechApprovalStrategy: """Performs a biotech approval strategy where... PUT STUFF HERE""" def __init__(self, bars, events, approvals_csv_dir): """Initializes the Biotech approval strategy Parameters: bars - The DataHandler object that provides bar information events - The Event Que...
stack_v2_sparse_classes_36k_train_014337
4,941
no_license
[ { "docstring": "Initializes the Biotech approval strategy Parameters: bars - The DataHandler object that provides bar information events - The Event Queue object approvals_csv_dir - The path to the csv file that has the tickers and the approval dates", "name": "__init__", "signature": "def __init__(self...
3
stack_v2_sparse_classes_30k_train_010356
Implement the Python class `BiotechApprovalStrategy` described below. Class description: Performs a biotech approval strategy where... PUT STUFF HERE Method signatures and docstrings: - def __init__(self, bars, events, approvals_csv_dir): Initializes the Biotech approval strategy Parameters: bars - The DataHandler ob...
Implement the Python class `BiotechApprovalStrategy` described below. Class description: Performs a biotech approval strategy where... PUT STUFF HERE Method signatures and docstrings: - def __init__(self, bars, events, approvals_csv_dir): Initializes the Biotech approval strategy Parameters: bars - The DataHandler ob...
8fbaf833e03977fa8d0c6e073889ec75bee8f01b
<|skeleton|> class BiotechApprovalStrategy: """Performs a biotech approval strategy where... PUT STUFF HERE""" def __init__(self, bars, events, approvals_csv_dir): """Initializes the Biotech approval strategy Parameters: bars - The DataHandler object that provides bar information events - The Event Que...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BiotechApprovalStrategy: """Performs a biotech approval strategy where... PUT STUFF HERE""" def __init__(self, bars, events, approvals_csv_dir): """Initializes the Biotech approval strategy Parameters: bars - The DataHandler object that provides bar information events - The Event Queue object app...
the_stack_v2_python_sparse
strategy_biotechapproval.py
jonathan-soll/quantstrat_backtester
train
1
ceb4452c1d2962045cef531f5f74ea60a19c819d
[ "super(CustomBatchNormAutograd, self).__init__()\nself.n_neurons = n_neurons\nself.eps = eps\nself.params = nn.ParameterDict({'gamma': nn.Parameter(torch.ones(n_neurons)), 'beta': nn.Parameter(torch.zeros(n_neurons))})", "_n_batch, n_neurons = input.shape\nassert n_neurons == self.n_neurons\nmean = input.mean(dim...
<|body_start_0|> super(CustomBatchNormAutograd, self).__init__() self.n_neurons = n_neurons self.eps = eps self.params = nn.ParameterDict({'gamma': nn.Parameter(torch.ones(n_neurons)), 'beta': nn.Parameter(torch.zeros(n_neurons))}) <|end_body_0|> <|body_start_1|> _n_batch, n_neu...
This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automatic differentiation provided by PyTorch.
CustomBatchNormAutograd
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by...
stack_v2_sparse_classes_36k_train_014338
7,737
no_license
[ { "docstring": "Initializes CustomBatchNormAutograd object. Args: n_neurons: int specifying the number of neurons eps: small float to be added to the variance for stability", "name": "__init__", "signature": "def __init__(self, n_neurons, eps=1e-05)" }, { "docstring": "Compute the batch normaliz...
2
stack_v2_sparse_classes_30k_train_020812
Implement the Python class `CustomBatchNormAutograd` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need...
Implement the Python class `CustomBatchNormAutograd` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need...
b2cd0d67337b101f3e204e519625e1aaf3cea43b
<|skeleton|> class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automati...
the_stack_v2_python_sparse
assignment_1/code/custom_batchnorm.py
Ivan-Yovchev/uvadlc_practicals_2019
train
0
4fef52fd4a8284eee32ba3cbbb312e12e1593df7
[ "if not builder:\n raise ValueError('Instance builder is not specified')\nself._builder = builder", "osh = self._builder.buildNoNameInstance(number, hostname, system)\nosh.setContainer(containerOsh)\nreturn osh", "if not pdo:\n raise ValueError('Instance information is not specified')\nif not containerOsh...
<|body_start_0|> if not builder: raise ValueError('Instance builder is not specified') self._builder = builder <|end_body_0|> <|body_start_1|> osh = self._builder.buildNoNameInstance(number, hostname, system) osh.setContainer(containerOsh) return osh <|end_body_1|> ...
InstanceReporter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstanceReporter: def __init__(self, builder): """@types: InstanceBuilder""" <|body_0|> def reportNoNameInst(self, number, hostname, system, containerOsh): """@types: str, str, System, osh -> osh""" <|body_1|> def reportInstance(self, pdo, containerOsh):...
stack_v2_sparse_classes_36k_train_014339
14,040
no_license
[ { "docstring": "@types: InstanceBuilder", "name": "__init__", "signature": "def __init__(self, builder)" }, { "docstring": "@types: str, str, System, osh -> osh", "name": "reportNoNameInst", "signature": "def reportNoNameInst(self, number, hostname, system, containerOsh)" }, { "d...
3
stack_v2_sparse_classes_30k_val_000638
Implement the Python class `InstanceReporter` described below. Class description: Implement the InstanceReporter class. Method signatures and docstrings: - def __init__(self, builder): @types: InstanceBuilder - def reportNoNameInst(self, number, hostname, system, containerOsh): @types: str, str, System, osh -> osh - ...
Implement the Python class `InstanceReporter` described below. Class description: Implement the InstanceReporter class. Method signatures and docstrings: - def __init__(self, builder): @types: InstanceBuilder - def reportNoNameInst(self, number, hostname, system, containerOsh): @types: str, str, System, osh -> osh - ...
c431e809e8d0f82e1bca7e3429dd0245560b5680
<|skeleton|> class InstanceReporter: def __init__(self, builder): """@types: InstanceBuilder""" <|body_0|> def reportNoNameInst(self, number, hostname, system, containerOsh): """@types: str, str, System, osh -> osh""" <|body_1|> def reportInstance(self, pdo, containerOsh):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstanceReporter: def __init__(self, builder): """@types: InstanceBuilder""" if not builder: raise ValueError('Instance builder is not specified') self._builder = builder def reportNoNameInst(self, number, hostname, system, containerOsh): """@types: str, str, S...
the_stack_v2_python_sparse
reference/ucmdb/discovery/sap_abap.py
madmonkyang/cda-record
train
0
c9d23ccbbd241589058809c5c823b47d63d95db3
[ "self.table_names = []\nself.accepted_tables = []\nself.basic_tables = []\nself.badge_tables = []\nself.type_tables = []\nself.custom_tables = []\nself.pokemonByNumber = {}\nself.pokemonByName = {}\nself.__build_pokemon_list__\nself.__verify_database__\nself.__delete_unused_tables__", "for pokemon in BOT.schema['...
<|body_start_0|> self.table_names = [] self.accepted_tables = [] self.basic_tables = [] self.badge_tables = [] self.type_tables = [] self.custom_tables = [] self.pokemonByNumber = {} self.pokemonByName = {} self.__build_pokemon_list__ self....
Validates the database is created with the expected tables
Storage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Storage: """Validates the database is created with the expected tables""" def __init__(self): """Initializes list to validate against""" <|body_0|> def __build_pokemon_list__(self): """Creates validation with the pokemon""" <|body_1|> def __verify_da...
stack_v2_sparse_classes_36k_train_014340
2,844
permissive
[ { "docstring": "Initializes list to validate against", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Creates validation with the pokemon", "name": "__build_pokemon_list__", "signature": "def __build_pokemon_list__(self)" }, { "docstring": "Creates any t...
4
stack_v2_sparse_classes_30k_train_012031
Implement the Python class `Storage` described below. Class description: Validates the database is created with the expected tables Method signatures and docstrings: - def __init__(self): Initializes list to validate against - def __build_pokemon_list__(self): Creates validation with the pokemon - def __verify_databa...
Implement the Python class `Storage` described below. Class description: Validates the database is created with the expected tables Method signatures and docstrings: - def __init__(self): Initializes list to validate against - def __build_pokemon_list__(self): Creates validation with the pokemon - def __verify_databa...
b28775a348f400a98f54b6521ce57297ba538861
<|skeleton|> class Storage: """Validates the database is created with the expected tables""" def __init__(self): """Initializes list to validate against""" <|body_0|> def __build_pokemon_list__(self): """Creates validation with the pokemon""" <|body_1|> def __verify_da...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Storage: """Validates the database is created with the expected tables""" def __init__(self): """Initializes list to validate against""" self.table_names = [] self.accepted_tables = [] self.basic_tables = [] self.badge_tables = [] self.type_tables = [] ...
the_stack_v2_python_sparse
src/record_keeper/startup/storage.py
williamwissemann/record_keeper
train
0
fb3af232f47e3a0c26bfb739b84c004280112591
[ "self.start = start\nself.home = home\nrandom.seed(seed)\nself.left_limit = left_limit\nself.right_limit = right_limit", "walker = BoundedWalker(self.start, self.home, self.left_limit, self.right_limit)\nwhile not walker.is_at_home():\n walker.move()\nreturn walker.steps" ]
<|body_start_0|> self.start = start self.home = home random.seed(seed) self.left_limit = left_limit self.right_limit = right_limit <|end_body_0|> <|body_start_1|> walker = BoundedWalker(self.start, self.home, self.left_limit, self.right_limit) while not walker.is...
BoundedSimulation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BoundedSimulation: def __init__(self, start, home, seed, left_limit, right_limit): """Initialise the simulation Arguments --------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random generator seed left_limit : int The left b...
stack_v2_sparse_classes_36k_train_014341
2,633
no_license
[ { "docstring": "Initialise the simulation Arguments --------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random generator seed left_limit : int The left boundary of walker movement right_limit : int The right boundary of walker movement", "name...
2
stack_v2_sparse_classes_30k_train_000295
Implement the Python class `BoundedSimulation` described below. Class description: Implement the BoundedSimulation class. Method signatures and docstrings: - def __init__(self, start, home, seed, left_limit, right_limit): Initialise the simulation Arguments --------- start : int The walker's initial position home : i...
Implement the Python class `BoundedSimulation` described below. Class description: Implement the BoundedSimulation class. Method signatures and docstrings: - def __init__(self, start, home, seed, left_limit, right_limit): Initialise the simulation Arguments --------- start : int The walker's initial position home : i...
527f908422b559e6afc1ec025c04336d7a13828d
<|skeleton|> class BoundedSimulation: def __init__(self, start, home, seed, left_limit, right_limit): """Initialise the simulation Arguments --------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random generator seed left_limit : int The left b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BoundedSimulation: def __init__(self, start, home, seed, left_limit, right_limit): """Initialise the simulation Arguments --------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random generator seed left_limit : int The left boundary of wal...
the_stack_v2_python_sparse
src/nicolai_munsterhjelm_ex/ex05/bounded_sim.py
Nicomunster/INF200-2019-Exercises
train
0
04cbe688ff1a5ebf5e8deb7e3e1e989715926f78
[ "try:\n tinc = value.first()\nexcept AttributeError:\n tinc = value\nif tinc is None:\n return None\nreturn TincHostSerializer(tinc).to_native(tinc)", "if data:\n tinc_host = TincHost(pubkey=data.get('pubkey'))\n tinc_host.full_clean(exclude=['content_type', 'object_id', 'name'])\n return [tinc_...
<|body_start_0|> try: tinc = value.first() except AttributeError: tinc = value if tinc is None: return None return TincHostSerializer(tinc).to_native(tinc) <|end_body_0|> <|body_start_1|> if data: tinc_host = TincHost(pubkey=data.g...
TincHost writable serializer
TincHostRelatedField
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TincHostRelatedField: """TincHost writable serializer""" def to_native(self, value): """Convert to serialized fields""" <|body_0|> def from_native(self, data): """Return a list of tinc configuration objects""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_014342
2,992
no_license
[ { "docstring": "Convert to serialized fields", "name": "to_native", "signature": "def to_native(self, value)" }, { "docstring": "Return a list of tinc configuration objects", "name": "from_native", "signature": "def from_native(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_009412
Implement the Python class `TincHostRelatedField` described below. Class description: TincHost writable serializer Method signatures and docstrings: - def to_native(self, value): Convert to serialized fields - def from_native(self, data): Return a list of tinc configuration objects
Implement the Python class `TincHostRelatedField` described below. Class description: TincHost writable serializer Method signatures and docstrings: - def to_native(self, value): Convert to serialized fields - def from_native(self, data): Return a list of tinc configuration objects <|skeleton|> class TincHostRelated...
dd798dc9bd3321b17007ff131e7b1288a2cd3c36
<|skeleton|> class TincHostRelatedField: """TincHost writable serializer""" def to_native(self, value): """Convert to serialized fields""" <|body_0|> def from_native(self, data): """Return a list of tinc configuration objects""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TincHostRelatedField: """TincHost writable serializer""" def to_native(self, value): """Convert to serialized fields""" try: tinc = value.first() except AttributeError: tinc = value if tinc is None: return None return TincHostSer...
the_stack_v2_python_sparse
controller/apps/tinc/serializers.py
m00dy/vct-controller
train
2
9140d9f61f20b311ece85e8f4b5bb5cbf010c99c
[ "self.log_directory = log_directory\nself.ack_batch_size = ack_batch_size\nself._current_file_obj = None\nsuper(TopicLogger, self).__init__(*args, **kwargs)", "for filename in filenames:\n filepath = os.path.join(self.log_directory, filename)\n with open(filepath, 'r') as file_obj:\n for line in file...
<|body_start_0|> self.log_directory = log_directory self.ack_batch_size = ack_batch_size self._current_file_obj = None super(TopicLogger, self).__init__(*args, **kwargs) <|end_body_0|> <|body_start_1|> for filename in filenames: filepath = os.path.join(self.log_direc...
writes pubsub request messages to disk
TopicLogger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TopicLogger: """writes pubsub request messages to disk""" def __init__(self, log_directory, ack_batch_size=100, *args, **kwargs): """creates instance""" <|body_0|> def iter_pull_messages_from_log(self, filenames): """creates subscribe message objects from files i...
stack_v2_sparse_classes_36k_train_014343
10,989
permissive
[ { "docstring": "creates instance", "name": "__init__", "signature": "def __init__(self, log_directory, ack_batch_size=100, *args, **kwargs)" }, { "docstring": "creates subscribe message objects from files in log filenames is list of base filenames to read from", "name": "iter_pull_messages_f...
5
stack_v2_sparse_classes_30k_train_020235
Implement the Python class `TopicLogger` described below. Class description: writes pubsub request messages to disk Method signatures and docstrings: - def __init__(self, log_directory, ack_batch_size=100, *args, **kwargs): creates instance - def iter_pull_messages_from_log(self, filenames): creates subscribe message...
Implement the Python class `TopicLogger` described below. Class description: writes pubsub request messages to disk Method signatures and docstrings: - def __init__(self, log_directory, ack_batch_size=100, *args, **kwargs): creates instance - def iter_pull_messages_from_log(self, filenames): creates subscribe message...
d2deb42c25cf83816993015532194a5fc0c4146a
<|skeleton|> class TopicLogger: """writes pubsub request messages to disk""" def __init__(self, log_directory, ack_batch_size=100, *args, **kwargs): """creates instance""" <|body_0|> def iter_pull_messages_from_log(self, filenames): """creates subscribe message objects from files i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TopicLogger: """writes pubsub request messages to disk""" def __init__(self, log_directory, ack_batch_size=100, *args, **kwargs): """creates instance""" self.log_directory = log_directory self.ack_batch_size = ack_batch_size self._current_file_obj = None super(Topi...
the_stack_v2_python_sparse
gcloud/datastores/pubsub.py
pantheon-systems/etl-framework
train
2
b99068089f987ed177540500d348dd3fc61d08ed
[ "logging.info(f'Loading model {model_name} from master at {det_master}')\ncheckpoint = Determined(master=det_master).get_model(model_name).get_version()\nself.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ntrial = checkpoint.load(map_location=self.device)\nself.model = trial.model\nlogging.i...
<|body_start_0|> logging.info(f'Loading model {model_name} from master at {det_master}') checkpoint = Determined(master=det_master).get_model(model_name).get_version() self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') trial = checkpoint.load(map_location=self.dev...
Model template. You can load your model parameters in __init__ from a location accessible at runtime
MNISTModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MNISTModel: """Model template. You can load your model parameters in __init__ from a location accessible at runtime""" def __init__(self, det_master=None, model_name=None): """Add any initialization parameters. These will be passed at runtime from the graph definition parameters defi...
stack_v2_sparse_classes_36k_train_014344
1,767
permissive
[ { "docstring": "Add any initialization parameters. These will be passed at runtime from the graph definition parameters defined in your seldondeployment kubernetes resource manifest.", "name": "__init__", "signature": "def __init__(self, det_master=None, model_name=None)" }, { "docstring": "Retu...
2
stack_v2_sparse_classes_30k_train_019201
Implement the Python class `MNISTModel` described below. Class description: Model template. You can load your model parameters in __init__ from a location accessible at runtime Method signatures and docstrings: - def __init__(self, det_master=None, model_name=None): Add any initialization parameters. These will be pa...
Implement the Python class `MNISTModel` described below. Class description: Model template. You can load your model parameters in __init__ from a location accessible at runtime Method signatures and docstrings: - def __init__(self, det_master=None, model_name=None): Add any initialization parameters. These will be pa...
735a0dbedbf5972aef48461359df22d66d6c6588
<|skeleton|> class MNISTModel: """Model template. You can load your model parameters in __init__ from a location accessible at runtime""" def __init__(self, det_master=None, model_name=None): """Add any initialization parameters. These will be passed at runtime from the graph definition parameters defi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MNISTModel: """Model template. You can load your model parameters in __init__ from a location accessible at runtime""" def __init__(self, det_master=None, model_name=None): """Add any initialization parameters. These will be passed at runtime from the graph definition parameters defined in your s...
the_stack_v2_python_sparse
kubeflow_pipelines/seldon/model/MNISTModel.py
LittlePrince2021/works-with-determined
train
0
bccfe4ae034ae6553e56cf939a16ff87565aaf84
[ "if 'Could not attack sample:' in sample:\n return AttackResult.FAILED\n_, dest = map_string.split(' --> ')\nif 'FAILED' in dest:\n return AttackResult.FAILED\nelif 'SKIPPED' in dest:\n return AttackResult.SKIPPED\nelse:\n return AttackResult.SUCCESS", "if textattack_cls == 'ErrorAttackResult':\n r...
<|body_start_0|> if 'Could not attack sample:' in sample: return AttackResult.FAILED _, dest = map_string.split(' --> ') if 'FAILED' in dest: return AttackResult.FAILED elif 'SKIPPED' in dest: return AttackResult.SKIPPED else: retur...
AttackResult
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttackResult: def from_mapping_string(cls, map_string, sample): """Computes the attack result from a string in the formats LABEL, ..., LABEL --> LABEL, ..., LABEL LABEL, ..., LABEL --> [SKIPPED/FAILED]""" <|body_0|> def from_textattack_class(cls, textattack_cls): """...
stack_v2_sparse_classes_36k_train_014345
1,407
no_license
[ { "docstring": "Computes the attack result from a string in the formats LABEL, ..., LABEL --> LABEL, ..., LABEL LABEL, ..., LABEL --> [SKIPPED/FAILED]", "name": "from_mapping_string", "signature": "def from_mapping_string(cls, map_string, sample)" }, { "docstring": "Computes the attack result fr...
2
stack_v2_sparse_classes_30k_train_013606
Implement the Python class `AttackResult` described below. Class description: Implement the AttackResult class. Method signatures and docstrings: - def from_mapping_string(cls, map_string, sample): Computes the attack result from a string in the formats LABEL, ..., LABEL --> LABEL, ..., LABEL LABEL, ..., LABEL --> [S...
Implement the Python class `AttackResult` described below. Class description: Implement the AttackResult class. Method signatures and docstrings: - def from_mapping_string(cls, map_string, sample): Computes the attack result from a string in the formats LABEL, ..., LABEL --> LABEL, ..., LABEL LABEL, ..., LABEL --> [S...
a0673613f489f355ddef37c89f0a635c89a500e9
<|skeleton|> class AttackResult: def from_mapping_string(cls, map_string, sample): """Computes the attack result from a string in the formats LABEL, ..., LABEL --> LABEL, ..., LABEL LABEL, ..., LABEL --> [SKIPPED/FAILED]""" <|body_0|> def from_textattack_class(cls, textattack_cls): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttackResult: def from_mapping_string(cls, map_string, sample): """Computes the attack result from a string in the formats LABEL, ..., LABEL --> LABEL, ..., LABEL LABEL, ..., LABEL --> [SKIPPED/FAILED]""" if 'Could not attack sample:' in sample: return AttackResult.FAILED _...
the_stack_v2_python_sparse
experiments/attack_result.py
dumpmemory/SeqAttack
train
0
c1d61de8eae3b0b64386ce957dadc24817ca334c
[ "size = len(prices)\nif size <= 0:\n return 0\nminIdx = 0\nfor i in range(1, size):\n if prices[i] < prices[minIdx]:\n minIdx = i\nmaxPro = 0\nfor i in range(minIdx + 1, size):\n maxPro = max(maxPro, prices[i] - prices[minIdx])\nreturn maxPro", "size = len(prices)\nif size <= 0:\n return 0\nmax...
<|body_start_0|> size = len(prices) if size <= 0: return 0 minIdx = 0 for i in range(1, size): if prices[i] < prices[minIdx]: minIdx = i maxPro = 0 for i in range(minIdx + 1, size): maxPro = max(maxPro, prices[i] - price...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """直接解法:[2,4,1]不满足""" <|body_0|> def maxProfit1(self, prices: List[int]) -> int: """暴力解法:超时,遍历每一个数对,固定了买入时间 改变思路:上述前面2,4也符合但是没有计算,暴力,把每个数都当成最小值,然后计算和最大值的差别""" <|body_1|> def maxProfit2(self, prices...
stack_v2_sparse_classes_36k_train_014346
2,828
permissive
[ { "docstring": "直接解法:[2,4,1]不满足", "name": "maxProfit", "signature": "def maxProfit(self, prices: List[int]) -> int" }, { "docstring": "暴力解法:超时,遍历每一个数对,固定了买入时间 改变思路:上述前面2,4也符合但是没有计算,暴力,把每个数都当成最小值,然后计算和最大值的差别", "name": "maxProfit1", "signature": "def maxProfit1(self, prices: List[int]) -> ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 直接解法:[2,4,1]不满足 - def maxProfit1(self, prices: List[int]) -> int: 暴力解法:超时,遍历每一个数对,固定了买入时间 改变思路:上述前面2,4也符合但是没有计算,暴力,把每个数都当成最小值,然后计算和...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 直接解法:[2,4,1]不满足 - def maxProfit1(self, prices: List[int]) -> int: 暴力解法:超时,遍历每一个数对,固定了买入时间 改变思路:上述前面2,4也符合但是没有计算,暴力,把每个数都当成最小值,然后计算和...
e8a1c6cae6547cbcb6e8494be6df685f3e7c837c
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """直接解法:[2,4,1]不满足""" <|body_0|> def maxProfit1(self, prices: List[int]) -> int: """暴力解法:超时,遍历每一个数对,固定了买入时间 改变思路:上述前面2,4也符合但是没有计算,暴力,把每个数都当成最小值,然后计算和最大值的差别""" <|body_1|> def maxProfit2(self, prices...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices: List[int]) -> int: """直接解法:[2,4,1]不满足""" size = len(prices) if size <= 0: return 0 minIdx = 0 for i in range(1, size): if prices[i] < prices[minIdx]: minIdx = i maxPro = 0 for ...
the_stack_v2_python_sparse
lcof/63-gu-piao-de-zui-da-li-run-lcof.py
yuenliou/leetcode
train
0
30494a7b1a538396380a9897b4209b08a10edfaa
[ "try:\n ScfUser.objects.get(email=data)\nexcept:\n raise ParseError('User {} does not exist'.format(data))\nreturn data", "newPassword = data.get('newPassword')\nif newPassword and newPassword != data.get('newPasswordConfirm'):\n raise ParseError('newPassword did not match newPasswordConfirm')\nreturn da...
<|body_start_0|> try: ScfUser.objects.get(email=data) except: raise ParseError('User {} does not exist'.format(data)) return data <|end_body_0|> <|body_start_1|> newPassword = data.get('newPassword') if newPassword and newPassword != data.get('newPassword...
User reset password serializer
UserPasswordResetSerializer
[ "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause", "AGPL-3.0-only", "GPL-1.0-or-later", "Python-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserPasswordResetSerializer: """User reset password serializer""" def validate_email(self, data): """check email is exist or not""" <|body_0|> def validate(self, data): """validate password""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_36k_train_014347
4,134
permissive
[ { "docstring": "check email is exist or not", "name": "validate_email", "signature": "def validate_email(self, data)" }, { "docstring": "validate password", "name": "validate", "signature": "def validate(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_006015
Implement the Python class `UserPasswordResetSerializer` described below. Class description: User reset password serializer Method signatures and docstrings: - def validate_email(self, data): check email is exist or not - def validate(self, data): validate password
Implement the Python class `UserPasswordResetSerializer` described below. Class description: User reset password serializer Method signatures and docstrings: - def validate_email(self, data): check email is exist or not - def validate(self, data): validate password <|skeleton|> class UserPasswordResetSerializer: ...
4df3f46e35eb8fcab796be27fc1cc7fa7ed561f3
<|skeleton|> class UserPasswordResetSerializer: """User reset password serializer""" def validate_email(self, data): """check email is exist or not""" <|body_0|> def validate(self, data): """validate password""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserPasswordResetSerializer: """User reset password serializer""" def validate_email(self, data): """check email is exist or not""" try: ScfUser.objects.get(email=data) except: raise ParseError('User {} does not exist'.format(data)) return data ...
the_stack_v2_python_sparse
SCRM/ums/serializers.py
aricent/secure-cloud-native-fabric
train
2
06c0fcfbc7a04ef95670ddba3889f66c1b6c2c84
[ "self.readservice = readservice\nif u_context:\n self.user_context = u_context\n self.username = u_context.user\n if u_context.context == u_context.ChoicesOfView.COMMON:\n self.use_user = None\n else:\n self.use_user = u_context.user", "from bl.person import Person\nsource = self.readser...
<|body_start_0|> self.readservice = readservice if u_context: self.user_context = u_context self.username = u_context.user if u_context.context == u_context.ChoicesOfView.COMMON: self.use_user = None else: self.use_user = u_...
Public methods for accessing active database. Returns a PersonResult object
DbReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DbReader: """Public methods for accessing active database. Returns a PersonResult object""" def __init__(self, readservice, u_context=None): """Create a reader object with db driver and user context. - readservice Neo4jReadService or Neo4jWriteDriver""" <|body_0|> def ge...
stack_v2_sparse_classes_36k_train_014348
3,432
no_license
[ { "docstring": "Create a reader object with db driver and user context. - readservice Neo4jReadService or Neo4jWriteDriver", "name": "__init__", "signature": "def __init__(self, readservice, u_context=None)" }, { "docstring": "Read the source, repository and events etc referencing this source. R...
2
stack_v2_sparse_classes_30k_train_014248
Implement the Python class `DbReader` described below. Class description: Public methods for accessing active database. Returns a PersonResult object Method signatures and docstrings: - def __init__(self, readservice, u_context=None): Create a reader object with db driver and user context. - readservice Neo4jReadServ...
Implement the Python class `DbReader` described below. Class description: Public methods for accessing active database. Returns a PersonResult object Method signatures and docstrings: - def __init__(self, readservice, u_context=None): Create a reader object with db driver and user context. - readservice Neo4jReadServ...
0f8d6ba035e3cca8dc756531b7cc51029a549a4f
<|skeleton|> class DbReader: """Public methods for accessing active database. Returns a PersonResult object""" def __init__(self, readservice, u_context=None): """Create a reader object with db driver and user context. - readservice Neo4jReadService or Neo4jWriteDriver""" <|body_0|> def ge...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DbReader: """Public methods for accessing active database. Returns a PersonResult object""" def __init__(self, readservice, u_context=None): """Create a reader object with db driver and user context. - readservice Neo4jReadService or Neo4jWriteDriver""" self.readservice = readservice ...
the_stack_v2_python_sparse
pe/db_reader.py
kkujansuu/stk
train
0
dd260005932a3e6e0390ea379d23d90165dd1aeb
[ "rs = ta.transforms.Resample()\nself.nsr = noise_lvl\nself.noises = []\nself.probs = []\nself.nsr_scalar = []\nself.reverber = ReverbEcho()\nnoise_dirs = os.listdir(noise_dir)\nnoise_dirs.sort()\nfor index, directory in enumerate(noise_dirs):\n directory = './noises/' + str(directory)\n print(directory)\n ...
<|body_start_0|> rs = ta.transforms.Resample() self.nsr = noise_lvl self.noises = [] self.probs = [] self.nsr_scalar = [] self.reverber = ReverbEcho() noise_dirs = os.listdir(noise_dir) noise_dirs.sort() for index, directory in enumerate(noise_dirs...
Noiser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Noiser: def __init__(self, noise_dir, noise_lvl=0.4, probs=[], nsr_scalar=[]): """add noise to signal, where noise is randomly selected wav from noise_dir. noise_lvl = ratio of noise to signal (additive)""" <|body_0|> def add_noise(self, sig): """sig is expected to b...
stack_v2_sparse_classes_36k_train_014349
22,249
no_license
[ { "docstring": "add noise to signal, where noise is randomly selected wav from noise_dir. noise_lvl = ratio of noise to signal (additive)", "name": "__init__", "signature": "def __init__(self, noise_dir, noise_lvl=0.4, probs=[], nsr_scalar=[])" }, { "docstring": "sig is expected to be one-dimens...
2
stack_v2_sparse_classes_30k_train_013837
Implement the Python class `Noiser` described below. Class description: Implement the Noiser class. Method signatures and docstrings: - def __init__(self, noise_dir, noise_lvl=0.4, probs=[], nsr_scalar=[]): add noise to signal, where noise is randomly selected wav from noise_dir. noise_lvl = ratio of noise to signal ...
Implement the Python class `Noiser` described below. Class description: Implement the Noiser class. Method signatures and docstrings: - def __init__(self, noise_dir, noise_lvl=0.4, probs=[], nsr_scalar=[]): add noise to signal, where noise is randomly selected wav from noise_dir. noise_lvl = ratio of noise to signal ...
6b4567c0bc1325a36b0d08fdf0f4fdcf8d803909
<|skeleton|> class Noiser: def __init__(self, noise_dir, noise_lvl=0.4, probs=[], nsr_scalar=[]): """add noise to signal, where noise is randomly selected wav from noise_dir. noise_lvl = ratio of noise to signal (additive)""" <|body_0|> def add_noise(self, sig): """sig is expected to b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Noiser: def __init__(self, noise_dir, noise_lvl=0.4, probs=[], nsr_scalar=[]): """add noise to signal, where noise is randomly selected wav from noise_dir. noise_lvl = ratio of noise to signal (additive)""" rs = ta.transforms.Resample() self.nsr = noise_lvl self.noises = [] ...
the_stack_v2_python_sparse
real-time-python-app/app.py
ashwinahuja/chvoice
train
1
d7d635572e3004d7b7b925f8210a82fd016d9d15
[ "super().__init__()\nself.setWindowTitle('Add brain regions')\nself.ui()\nself.main_window = main_window\nself.setStyleSheet(update_css(style, palette))\nself.timer = QtCore.QTimer(self)\nself.timer.setInterval(1500)\nself.timer.timeout.connect(self.close)\nself.timer.start()", "self.setGeometry(self.left, self.t...
<|body_start_0|> super().__init__() self.setWindowTitle('Add brain regions') self.ui() self.main_window = main_window self.setStyleSheet(update_css(style, palette)) self.timer = QtCore.QTimer(self) self.timer.setInterval(1500) self.timer.timeout.connect(se...
ScreenshotModal
[ "BSD-3-Clause", "GPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScreenshotModal: def __init__(self, main_window, palette): """Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the App's main window palette: main_window's palette, used to style widgets""" <|body_0|> def u...
stack_v2_sparse_classes_36k_train_014350
1,389
permissive
[ { "docstring": "Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the App's main window palette: main_window's palette, used to style widgets", "name": "__init__", "signature": "def __init__(self, main_window, palette)" }, { "do...
2
null
Implement the Python class `ScreenshotModal` described below. Class description: Implement the ScreenshotModal class. Method signatures and docstrings: - def __init__(self, main_window, palette): Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the ...
Implement the Python class `ScreenshotModal` described below. Class description: Implement the ScreenshotModal class. Method signatures and docstrings: - def __init__(self, main_window, palette): Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the ...
a14ead80c1dbc75f20a145a49394dc467c4f7bf1
<|skeleton|> class ScreenshotModal: def __init__(self, main_window, palette): """Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the App's main window palette: main_window's palette, used to style widgets""" <|body_0|> def u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScreenshotModal: def __init__(self, main_window, palette): """Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the App's main window palette: main_window's palette, used to style widgets""" super().__init__() self.set...
the_stack_v2_python_sparse
brainrender/gui/widgets/screenshot_modal.py
brainglobe/brainrender
train
345
1b50cfca45dbede218987bf76d7966f12b05a7d3
[ "self._fwdm.clear()\nself._invm.clear()\nself._sntl.nxt = self._sntl.prv = self._sntl", "if not self:\n raise KeyError('mapping is empty')\nkey = next((reversed if last else iter)(self))\nval = self._pop(key)\nreturn (key, val)", "node = self._fwdm[key]\nnode.prv.nxt = node.nxt\nnode.nxt.prv = node.prv\nsntl...
<|body_start_0|> self._fwdm.clear() self._invm.clear() self._sntl.nxt = self._sntl.prv = self._sntl <|end_body_0|> <|body_start_1|> if not self: raise KeyError('mapping is empty') key = next((reversed if last else iter)(self)) val = self._pop(key) ret...
Mutable bidict type that maintains items in insertion order.
OrderedBidict
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderedBidict: """Mutable bidict type that maintains items in insertion order.""" def clear(self) -> None: """Remove all items.""" <|body_0|> def popitem(self, last: bool=True) -> _t.Tuple[KT, VT]: """*x.popitem() → (k, v)* Remove and return the most recently add...
stack_v2_sparse_classes_36k_train_014351
3,409
permissive
[ { "docstring": "Remove all items.", "name": "clear", "signature": "def clear(self) -> None" }, { "docstring": "*x.popitem() → (k, v)* Remove and return the most recently added item as a (key, value) pair if *last* is True, else the least recently added item. :raises KeyError: if *x* is empty.", ...
3
null
Implement the Python class `OrderedBidict` described below. Class description: Mutable bidict type that maintains items in insertion order. Method signatures and docstrings: - def clear(self) -> None: Remove all items. - def popitem(self, last: bool=True) -> _t.Tuple[KT, VT]: *x.popitem() → (k, v)* Remove and return ...
Implement the Python class `OrderedBidict` described below. Class description: Mutable bidict type that maintains items in insertion order. Method signatures and docstrings: - def clear(self) -> None: Remove all items. - def popitem(self, last: bool=True) -> _t.Tuple[KT, VT]: *x.popitem() → (k, v)* Remove and return ...
95b7a061eabd6f2b607fba79e007186030f02720
<|skeleton|> class OrderedBidict: """Mutable bidict type that maintains items in insertion order.""" def clear(self) -> None: """Remove all items.""" <|body_0|> def popitem(self, last: bool=True) -> _t.Tuple[KT, VT]: """*x.popitem() → (k, v)* Remove and return the most recently add...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrderedBidict: """Mutable bidict type that maintains items in insertion order.""" def clear(self) -> None: """Remove all items.""" self._fwdm.clear() self._invm.clear() self._sntl.nxt = self._sntl.prv = self._sntl def popitem(self, last: bool=True) -> _t.Tuple[KT, VT]...
the_stack_v2_python_sparse
Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/bidict/_orderedbidict.py
icl-rocketry/Avionics
train
9
da310b3991feb15ed362c955412aefb1f5b50f75
[ "for treasury in self:\n if treasury.date_from:\n self.env['payment.treasury'].compute_payments(treasury.id, treasury.date_from)\nreturn True", "for treasury in self:\n if treasury.date_from:\n self.env['sale.purchase.treasury'].compute_sale_purchase(treasury.id, treasury.date_from)\nreturn Tr...
<|body_start_0|> for treasury in self: if treasury.date_from: self.env['payment.treasury'].compute_payments(treasury.id, treasury.date_from) return True <|end_body_0|> <|body_start_1|> for treasury in self: if treasury.date_from: self.env[...
Object for the treasury
treasury
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class treasury: """Object for the treasury""" def compute_payment_list(self): """Fonction qui calcule les payments fait sur l'année sélectionnée""" <|body_0|> def compute_sale_purchase_list(self): """Fonction qui calcule le montant des ventes et achats en cours""" ...
stack_v2_sparse_classes_36k_train_014352
43,695
no_license
[ { "docstring": "Fonction qui calcule les payments fait sur l'année sélectionnée", "name": "compute_payment_list", "signature": "def compute_payment_list(self)" }, { "docstring": "Fonction qui calcule le montant des ventes et achats en cours", "name": "compute_sale_purchase_list", "signat...
4
null
Implement the Python class `treasury` described below. Class description: Object for the treasury Method signatures and docstrings: - def compute_payment_list(self): Fonction qui calcule les payments fait sur l'année sélectionnée - def compute_sale_purchase_list(self): Fonction qui calcule le montant des ventes et ac...
Implement the Python class `treasury` described below. Class description: Object for the treasury Method signatures and docstrings: - def compute_payment_list(self): Fonction qui calcule les payments fait sur l'année sélectionnée - def compute_sale_purchase_list(self): Fonction qui calcule le montant des ventes et ac...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class treasury: """Object for the treasury""" def compute_payment_list(self): """Fonction qui calcule les payments fait sur l'année sélectionnée""" <|body_0|> def compute_sale_purchase_list(self): """Fonction qui calcule le montant des ventes et achats en cours""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class treasury: """Object for the treasury""" def compute_payment_list(self): """Fonction qui calcule les payments fait sur l'année sélectionnée""" for treasury in self: if treasury.date_from: self.env['payment.treasury'].compute_payments(treasury.id, treasury.date_f...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/control_management/treasury.py
kazacube-mziouadi/ceci
train
0
7b7924948f0443af3feaeb9bfc275d5664c8d0b5
[ "def bfs(depth, start, value_list):\n res.append(value_list)\n if depth == len(nums):\n return\n for i in range(start, len(nums)):\n bfs(depth + 1, i + 1, value_list + [nums[i]])\nres = []\nbfs(0, 0, [])\nreturn res", "print('nums', nums)\nif len(nums) <= 1:\n return [nums]\nans = []\nfo...
<|body_start_0|> def bfs(depth, start, value_list): res.append(value_list) if depth == len(nums): return for i in range(start, len(nums)): bfs(depth + 1, i + 1, value_list + [nums[i]]) res = [] bfs(0, 0, []) return res <...
所有的子集和排列
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """所有的子集和排列""" def subsets(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def permute(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> def bfs(de...
stack_v2_sparse_classes_36k_train_014353
1,108
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "subsets", "signature": "def subsets(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "permute", "signature": "def permute(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: 所有的子集和排列 Method signatures and docstrings: - def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]] - def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: 所有的子集和排列 Method signatures and docstrings: - def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]] - def permute(self, nums): :type nums: List[int] :rtype: List[List[int]] <|skeleton|> class Solution: """所有的子集和排列""" d...
4105e18050b15fc0409c75353ad31be17187dd34
<|skeleton|> class Solution: """所有的子集和排列""" def subsets(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def permute(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """所有的子集和排列""" def subsets(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" def bfs(depth, start, value_list): res.append(value_list) if depth == len(nums): return for i in range(start, len(nums)): ...
the_stack_v2_python_sparse
subsets.py
NeilWangziyu/Leetcode_py
train
2
468bae5ec28104a9163c2753881fc5d728ffdfc2
[ "featuregroups, training_datasets, features_to_featuregroups, featurestore, settings, storage_connectors, online_featurestore_connector = self._parse_featurestore_metadata(metadata_json)\nself.featuregroups = featuregroups\nself.training_datasets = training_datasets\nself.features_to_featuregroups = features_to_fea...
<|body_start_0|> featuregroups, training_datasets, features_to_featuregroups, featurestore, settings, storage_connectors, online_featurestore_connector = self._parse_featurestore_metadata(metadata_json) self.featuregroups = featuregroups self.training_datasets = training_datasets self.fe...
Represents feature store metadata. This metadata is used by the feature store client to determine how to fetch and push features from/to the feature store
FeaturestoreMetadata
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeaturestoreMetadata: """Represents feature store metadata. This metadata is used by the feature store client to determine how to fetch and push features from/to the feature store""" def __init__(self, metadata_json): """Initialize the featurestore metadata from JSON payload Args: :m...
stack_v2_sparse_classes_36k_train_014354
5,002
permissive
[ { "docstring": "Initialize the featurestore metadata from JSON payload Args: :metadata_json: JSON metadata about the featurestore returned from Hopsworks REST API", "name": "__init__", "signature": "def __init__(self, metadata_json)" }, { "docstring": "Parses the featurestore metadata from the R...
2
stack_v2_sparse_classes_30k_train_017684
Implement the Python class `FeaturestoreMetadata` described below. Class description: Represents feature store metadata. This metadata is used by the feature store client to determine how to fetch and push features from/to the feature store Method signatures and docstrings: - def __init__(self, metadata_json): Initia...
Implement the Python class `FeaturestoreMetadata` described below. Class description: Represents feature store metadata. This metadata is used by the feature store client to determine how to fetch and push features from/to the feature store Method signatures and docstrings: - def __init__(self, metadata_json): Initia...
cf0f85a774663cb9324fa6ff561070bbfc8f126d
<|skeleton|> class FeaturestoreMetadata: """Represents feature store metadata. This metadata is used by the feature store client to determine how to fetch and push features from/to the feature store""" def __init__(self, metadata_json): """Initialize the featurestore metadata from JSON payload Args: :m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeaturestoreMetadata: """Represents feature store metadata. This metadata is used by the feature store client to determine how to fetch and push features from/to the feature store""" def __init__(self, metadata_json): """Initialize the featurestore metadata from JSON payload Args: :metadata_json:...
the_stack_v2_python_sparse
hops/featurestore_impl/dao/common/featurestore_metadata.py
logicalclocks/hopsworks-cloud-sdk
train
1
83453fed0c0ce8f86fc7bef9d46dca2095f24657
[ "application_id = self.application.id\nassert _assert__application_id(application_id)\ndatas = await self.http.application_role_connection_metadata_get_all(application_id)\nreturn [ApplicationRoleConnectionMetadata.from_data(data) for data in datas]", "application_id = self.application.id\nassert _assert__applica...
<|body_start_0|> application_id = self.application.id assert _assert__application_id(application_id) datas = await self.http.application_role_connection_metadata_get_all(application_id) return [ApplicationRoleConnectionMetadata.from_data(data) for data in datas] <|end_body_0|> <|body_st...
ClientCompoundApplicationRoleConnectionEndpoints
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientCompoundApplicationRoleConnectionEndpoints: async def application_role_connection_metadata_get_all(self): """Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata`...
stack_v2_sparse_classes_36k_train_014355
2,417
permissive
[ { "docstring": "Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata` Raises ------ ConnectionError No internet connection. DiscordException If any exception was received from the Discord API....
2
null
Implement the Python class `ClientCompoundApplicationRoleConnectionEndpoints` described below. Class description: Implement the ClientCompoundApplicationRoleConnectionEndpoints class. Method signatures and docstrings: - async def application_role_connection_metadata_get_all(self): Requests all the role connection met...
Implement the Python class `ClientCompoundApplicationRoleConnectionEndpoints` described below. Class description: Implement the ClientCompoundApplicationRoleConnectionEndpoints class. Method signatures and docstrings: - async def application_role_connection_metadata_get_all(self): Requests all the role connection met...
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class ClientCompoundApplicationRoleConnectionEndpoints: async def application_role_connection_metadata_get_all(self): """Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClientCompoundApplicationRoleConnectionEndpoints: async def application_role_connection_metadata_get_all(self): """Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata` Raises ------...
the_stack_v2_python_sparse
hata/discord/client/compounds/application_role_connection.py
HuyaneMatsu/hata
train
3
8c6ae71451ac45506c7377355a4c0fffa888944f
[ "self.head = LinkNode(0)\nself.tail = self.head\nself.length = 0", "if index < 0 or index >= self.length:\n return -1\nnode = self.head.next\nfor i in range(index):\n node = node.next\nreturn node.val", "node = LinkNode(val)\nnode.next = self.head.next\nself.head.next = node\nself.length = self.length + 1...
<|body_start_0|> self.head = LinkNode(0) self.tail = self.head self.length = 0 <|end_body_0|> <|body_start_1|> if index < 0 or index >= self.length: return -1 node = self.head.next for i in range(index): node = node.next return node.val <|...
MyLinkedList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyLinkedList: def __init__(self): """Initialize your data structure here.""" <|body_0|> def get(self, index: int) -> int: """Get the value of the index-th node in the linked list. If the index is invalid, return -1.""" <|body_1|> def addAtHead(self, val:...
stack_v2_sparse_classes_36k_train_014356
2,897
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1.", "name": "get", "signature": "def get(self, index: int) -> int" },...
6
null
Implement the Python class `MyLinkedList` described below. Class description: Implement the MyLinkedList class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If the index is invali...
Implement the Python class `MyLinkedList` described below. Class description: Implement the MyLinkedList class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If the index is invali...
3b13a02f9c8273f9794a57b948d2655792707f37
<|skeleton|> class MyLinkedList: def __init__(self): """Initialize your data structure here.""" <|body_0|> def get(self, index: int) -> int: """Get the value of the index-th node in the linked list. If the index is invalid, return -1.""" <|body_1|> def addAtHead(self, val:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyLinkedList: def __init__(self): """Initialize your data structure here.""" self.head = LinkNode(0) self.tail = self.head self.length = 0 def get(self, index: int) -> int: """Get the value of the index-th node in the linked list. If the index is invalid, return -1...
the_stack_v2_python_sparse
linklist/myLinkedList.py
gsy/leetcode
train
1
9c82e85aef149e48556d92afbf473b7c33b72592
[ "errors: dict[str, str] = {}\nhost: str = data[CONF_HOST]\nport: int = data[CONF_PORT]\nusername: str = data[CONF_USERNAME]\npassword: str = data[CONF_PASSWORD]\nverify_ssl: bool = data[CONF_VERIFY_SSL]\nuptime_robot_api = UptimeKuma(async_get_clientsession(self.hass), f'{host}:{port}', username, password, verify_s...
<|body_start_0|> errors: dict[str, str] = {} host: str = data[CONF_HOST] port: int = data[CONF_PORT] username: str = data[CONF_USERNAME] password: str = data[CONF_PASSWORD] verify_ssl: bool = data[CONF_VERIFY_SSL] uptime_robot_api = UptimeKuma(async_get_clientsess...
Handle a config flow for Uptime Kuma.
ConfigFlow
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigFlow: """Handle a config flow for Uptime Kuma.""" async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: """Validate the user input allows us to connect.""" <|body_0|> async def async_step_user(self, user_input: dict[str, Any] | None=...
stack_v2_sparse_classes_36k_train_014357
2,760
permissive
[ { "docstring": "Validate the user input allows us to connect.", "name": "_validate_input", "signature": "async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]" }, { "docstring": "Handle the initial step.", "name": "async_step_user", "signature": "async def ...
2
stack_v2_sparse_classes_30k_train_012771
Implement the Python class `ConfigFlow` described below. Class description: Handle a config flow for Uptime Kuma. Method signatures and docstrings: - async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: Validate the user input allows us to connect. - async def async_step_user(self, us...
Implement the Python class `ConfigFlow` described below. Class description: Handle a config flow for Uptime Kuma. Method signatures and docstrings: - async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: Validate the user input allows us to connect. - async def async_step_user(self, us...
8548d9999ddd54f13d6a307e013abcb8c897a74e
<|skeleton|> class ConfigFlow: """Handle a config flow for Uptime Kuma.""" async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: """Validate the user input allows us to connect.""" <|body_0|> async def async_step_user(self, user_input: dict[str, Any] | None=...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigFlow: """Handle a config flow for Uptime Kuma.""" async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: """Validate the user input allows us to connect.""" errors: dict[str, str] = {} host: str = data[CONF_HOST] port: int = data[CONF_P...
the_stack_v2_python_sparse
custom_components/uptime_kuma/config_flow.py
bacco007/HomeAssistantConfig
train
98
81ea3d1d961f8c3e9afd973b5778055e3b73dc77
[ "util.validate_columns(df, self.marker_column)\nutil.validate_columns(df, self.orderby_columns)\nutil.validate_columns(df, self.groupby_columns)\nutil.validate_empty_df(df)", "self._validate_input(df)\ndf_ordered = util.sort_values(df, self.orderby_columns, self.ascending)\ndf_grouped = util.groupby(df_ordered, s...
<|body_start_0|> util.validate_columns(df, self.marker_column) util.validate_columns(df, self.orderby_columns) util.validate_columns(df, self.groupby_columns) util.validate_empty_df(df) <|end_body_0|> <|body_start_1|> self._validate_input(df) df_ordered = util.sort_value...
Provides `transform` and `validate_input` methods common to more than one implementation of the pandas interval identification wrangler. The `transform` has several shared responsibilities. It sorts and groups the data before applying the `_transform` method which needs to be implemented by every wrangler subclassing t...
_BaseIntervalIdentifier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _BaseIntervalIdentifier: """Provides `transform` and `validate_input` methods common to more than one implementation of the pandas interval identification wrangler. The `transform` has several shared responsibilities. It sorts and groups the data before applying the `_transform` method which need...
stack_v2_sparse_classes_36k_train_014358
13,674
permissive
[ { "docstring": "Checks input data frame in regard to column names and empty data. Parameters ---------- df: pd.DataFrame Dataframe to be validated.", "name": "_validate_input", "signature": "def _validate_input(self, df: pd.DataFrame)" }, { "docstring": "Extract interval ids from given dataframe...
2
stack_v2_sparse_classes_30k_val_000707
Implement the Python class `_BaseIntervalIdentifier` described below. Class description: Provides `transform` and `validate_input` methods common to more than one implementation of the pandas interval identification wrangler. The `transform` has several shared responsibilities. It sorts and groups the data before appl...
Implement the Python class `_BaseIntervalIdentifier` described below. Class description: Provides `transform` and `validate_input` methods common to more than one implementation of the pandas interval identification wrangler. The `transform` has several shared responsibilities. It sorts and groups the data before appl...
8561f5f267303e664487ae67095085fcea4308c9
<|skeleton|> class _BaseIntervalIdentifier: """Provides `transform` and `validate_input` methods common to more than one implementation of the pandas interval identification wrangler. The `transform` has several shared responsibilities. It sorts and groups the data before applying the `_transform` method which need...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _BaseIntervalIdentifier: """Provides `transform` and `validate_input` methods common to more than one implementation of the pandas interval identification wrangler. The `transform` has several shared responsibilities. It sorts and groups the data before applying the `_transform` method which needs to be imple...
the_stack_v2_python_sparse
src/pywrangler/pandas/wranglers/interval_identifier.py
mansenfranzen/pywrangler
train
15
0a49a12b7aeef8bb51ffca1c6ad60c8a35ed2151
[ "self.id: uuid.UUID = uuid.uuid4()\nself.state: 'State' = state\nself.name: str = name\nself._cities: Set['City'] = set()", "self._cities.add(city)\nif reflexive:\n city.associate(self, reflexive=False)" ]
<|body_start_0|> self.id: uuid.UUID = uuid.uuid4() self.state: 'State' = state self.name: str = name self._cities: Set['City'] = set() <|end_body_0|> <|body_start_1|> self._cities.add(city) if reflexive: city.associate(self, reflexive=False) <|end_body_1|>
A country.
County
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class County: """A country.""" def __init__(self, name: str, state: 'State'): """:param name: the name of the state :param state: the state in which the county resides""" <|body_0|> def associate(self, city: 'City', reflexive: bool=True): """Associate this county with ...
stack_v2_sparse_classes_36k_train_014359
8,831
permissive
[ { "docstring": ":param name: the name of the state :param state: the state in which the county resides", "name": "__init__", "signature": "def __init__(self, name: str, state: 'State')" }, { "docstring": "Associate this county with a city. :param city: the city which which the county is associat...
2
stack_v2_sparse_classes_30k_train_015116
Implement the Python class `County` described below. Class description: A country. Method signatures and docstrings: - def __init__(self, name: str, state: 'State'): :param name: the name of the state :param state: the state in which the county resides - def associate(self, city: 'City', reflexive: bool=True): Associ...
Implement the Python class `County` described below. Class description: A country. Method signatures and docstrings: - def __init__(self, name: str, state: 'State'): :param name: the name of the state :param state: the state in which the county resides - def associate(self, city: 'City', reflexive: bool=True): Associ...
f0750799eade79405e3f52e1a2a61dfd4e88dd4f
<|skeleton|> class County: """A country.""" def __init__(self, name: str, state: 'State'): """:param name: the name of the state :param state: the state in which the county resides""" <|body_0|> def associate(self, city: 'City', reflexive: bool=True): """Associate this county with ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class County: """A country.""" def __init__(self, name: str, state: 'State'): """:param name: the name of the state :param state: the state in which the county resides""" self.id: uuid.UUID = uuid.uuid4() self.state: 'State' = state self.name: str = name self._cities: Se...
the_stack_v2_python_sparse
Python_lib/cliff/model.py
mndarren/Code-Lib
train
8
28851718890d5678e2cccebb8a9d30ecdead9791
[ "accts = []\nfor account in accounts:\n accts.append(str(account.user_id))\nreturn accts", "locs = []\nfor location in locations:\n polygon = location.bbox\n extent = list(polygon.extent)\n locs.extend(extent)\nreturn locs", "terms = []\nfor searchterm in searchterms:\n if searchterm.is_phrase():...
<|body_start_0|> accts = [] for account in accounts: accts.append(str(account.user_id)) return accts <|end_body_0|> <|body_start_1|> locs = [] for location in locations: polygon = location.bbox extent = list(polygon.extent) locs.ex...
Class for accessing the Twitter Streaming API.
PublicStreamsAPI
[ "MIT", "LicenseRef-scancode-proprietary-license", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-copyleft" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PublicStreamsAPI: """Class for accessing the Twitter Streaming API.""" def _format_followees_param(accounts): """Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.""" <|body_0|> def _format...
stack_v2_sparse_classes_36k_train_014360
10,023
permissive
[ { "docstring": "Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.", "name": "_format_followees_param", "signature": "def _format_followees_param(accounts)" }, { "docstring": "Takes a list of Location objects and r...
5
null
Implement the Python class `PublicStreamsAPI` described below. Class description: Class for accessing the Twitter Streaming API. Method signatures and docstrings: - def _format_followees_param(accounts): Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delive...
Implement the Python class `PublicStreamsAPI` described below. Class description: Class for accessing the Twitter Streaming API. Method signatures and docstrings: - def _format_followees_param(accounts): Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delive...
a379a134c0c5af14df4ed2afa066c1626506b754
<|skeleton|> class PublicStreamsAPI: """Class for accessing the Twitter Streaming API.""" def _format_followees_param(accounts): """Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.""" <|body_0|> def _format...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PublicStreamsAPI: """Class for accessing the Twitter Streaming API.""" def _format_followees_param(accounts): """Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.""" accts = [] for account in accoun...
the_stack_v2_python_sparse
Incident-Response/Tools/cyphon/cyphon/platforms/twitter/handlers.py
foss2cyber/Incident-Playbook
train
1
3e05973f6ac5ea06f6720404166b62a28046930a
[ "left = []\nself.rt = 0\n\ndef dfs(root, pos, level):\n if not root:\n return\n if len(left) < level + 1:\n left.append(pos)\n self.rt = max(self.rt, pos - left[level] + 1)\n dfs(root.left, pos * 2 + 1, level + 1)\n dfs(root.right, pos * 2 + 2, level + 1)\ndfs(root, 0, 0)\nreturn self.r...
<|body_start_0|> left = [] self.rt = 0 def dfs(root, pos, level): if not root: return if len(left) < level + 1: left.append(pos) self.rt = max(self.rt, pos - left[level] + 1) dfs(root.left, pos * 2 + 1, level + 1) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def widthOfBinaryTree_dfs(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def widthOfBinaryTree_bfs(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> left = [] self.rt =...
stack_v2_sparse_classes_36k_train_014361
1,553
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "widthOfBinaryTree_dfs", "signature": "def widthOfBinaryTree_dfs(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "widthOfBinaryTree_bfs", "signature": "def widthOfBinaryTree_bfs(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_019186
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def widthOfBinaryTree_dfs(self, root): :type root: TreeNode :rtype: int - def widthOfBinaryTree_bfs(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def widthOfBinaryTree_dfs(self, root): :type root: TreeNode :rtype: int - def widthOfBinaryTree_bfs(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: ...
0e99f9a5226507706b3ee66fd04bae813755ef40
<|skeleton|> class Solution: def widthOfBinaryTree_dfs(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def widthOfBinaryTree_bfs(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def widthOfBinaryTree_dfs(self, root): """:type root: TreeNode :rtype: int""" left = [] self.rt = 0 def dfs(root, pos, level): if not root: return if len(left) < level + 1: left.append(pos) self.rt =...
the_stack_v2_python_sparse
medium/tree/test_662_Maximum_Width_of_Binary_Tree.py
wuxu1019/leetcode_sophia
train
1
2c0b573bef54e07444b9d2a19ef33f6860c54143
[ "n_row = len(board)\nif n_row <= 2:\n return\nn_col = len(board[0])\nif n_col <= 2:\n return\nqueue = deque()\nfor i in [0, n_row - 1]:\n for j in range(n_col):\n if board[i][j] == 'O':\n queue.append((i, j))\nfor i in range(1, n_row - 1):\n for j in [0, n_col - 1]:\n if board[i...
<|body_start_0|> n_row = len(board) if n_row <= 2: return n_col = len(board[0]) if n_col <= 2: return queue = deque() for i in [0, n_row - 1]: for j in range(n_col): if board[i][j] == 'O': queue.appen...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def solve(self, board: List[List[str]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def solve2(self, board: List[List[str]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_014362
3,118
no_license
[ { "docstring": "Do not return anything, modify board in-place instead.", "name": "solve", "signature": "def solve(self, board: List[List[str]]) -> None" }, { "docstring": "Do not return anything, modify board in-place instead.", "name": "solve2", "signature": "def solve2(self, board: Lis...
2
stack_v2_sparse_classes_30k_train_013655
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead. - def solve2(self, board: List[List[str]]) -> None: Do not return anything...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead. - def solve2(self, board: List[List[str]]) -> None: Do not return anything...
e52d24990122e07a976612dd9cea42fa1d778f60
<|skeleton|> class Solution: def solve(self, board: List[List[str]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def solve2(self, board: List[List[str]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def solve(self, board: List[List[str]]) -> None: """Do not return anything, modify board in-place instead.""" n_row = len(board) if n_row <= 2: return n_col = len(board[0]) if n_col <= 2: return queue = deque() for i in ...
the_stack_v2_python_sparse
python/0130_surrounded_regions.py
forest-sky-sea/Leetcode-Problems
train
1
02cb5e2a47f634fb905fc7d9c62d4fee83368cfa
[ "super(Classifier, self).__init__()\nself.fc1 = blk.LinearReLU(in_dim=num_channels, out_dim=128)\nself.fc2 = blk.LinearReLU(in_dim=128, out_dim=64)\nself.fc3 = nn.Linear(in_features=64, out_features=2)", "y = F.relu(self.fc1(x))\ny = F.relu(self.fc2(y))\ny = self.fc3(y)\nreturn y" ]
<|body_start_0|> super(Classifier, self).__init__() self.fc1 = blk.LinearReLU(in_dim=num_channels, out_dim=128) self.fc2 = blk.LinearReLU(in_dim=128, out_dim=64) self.fc3 = nn.Linear(in_features=64, out_features=2) <|end_body_0|> <|body_start_1|> y = F.relu(self.fc1(x)) ...
Classifier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Classifier: def __init__(self, num_channels: int): """represents the correlation and concatenation classifying heads. :param num_channels: feature dimension of the merged vector.""" <|body_0|> def forward(self, x: torch.Tensor) -> torch.Tensor: """forward pass implem...
stack_v2_sparse_classes_36k_train_014363
965
permissive
[ { "docstring": "represents the correlation and concatenation classifying heads. :param num_channels: feature dimension of the merged vector.", "name": "__init__", "signature": "def __init__(self, num_channels: int)" }, { "docstring": "forward pass implementation. :param x: input tensor. :return:...
2
stack_v2_sparse_classes_30k_train_021347
Implement the Python class `Classifier` described below. Class description: Implement the Classifier class. Method signatures and docstrings: - def __init__(self, num_channels: int): represents the correlation and concatenation classifying heads. :param num_channels: feature dimension of the merged vector. - def forw...
Implement the Python class `Classifier` described below. Class description: Implement the Classifier class. Method signatures and docstrings: - def __init__(self, num_channels: int): represents the correlation and concatenation classifying heads. :param num_channels: feature dimension of the merged vector. - def forw...
583e6868864582f081f18689124e74e9ca169f28
<|skeleton|> class Classifier: def __init__(self, num_channels: int): """represents the correlation and concatenation classifying heads. :param num_channels: feature dimension of the merged vector.""" <|body_0|> def forward(self, x: torch.Tensor) -> torch.Tensor: """forward pass implem...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Classifier: def __init__(self, num_channels: int): """represents the correlation and concatenation classifying heads. :param num_channels: feature dimension of the merged vector.""" super(Classifier, self).__init__() self.fc1 = blk.LinearReLU(in_dim=num_channels, out_dim=128) s...
the_stack_v2_python_sparse
models/classifier.py
beaupreda/domain-networks
train
1
888f8d30eafb54a3a3b15c30e988ee44c2ead35b
[ "self.config = {'inline_class': ['math', \"Inline math is SVG wrapped in a <span> tag, this option adds a class name to it - Default: 'math'\"], 'display_class': ['math', \"Display math is SVG wrapped in a <div> tag, this option adds a class name to it - Default: 'math'\"], 'smart_dollar': [True, \"Use mdx_math_svg...
<|body_start_0|> self.config = {'inline_class': ['math', "Inline math is SVG wrapped in a <span> tag, this option adds a class name to it - Default: 'math'"], 'display_class': ['math', "Display math is SVG wrapped in a <div> tag, this option adds a class name to it - Default: 'math'"], 'smart_dollar': [True, "U...
Adds MathSvg extension to Markdown class.
MathSvgExtension
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MathSvgExtension: """Adds MathSvg extension to Markdown class.""" def __init__(self, *args, **kwargs): """Initialize.""" <|body_0|> def extendMarkdown(self, md): """Extend the inline and block processor objects.""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_014364
22,334
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Extend the inline and block processor objects.", "name": "extendMarkdown", "signature": "def extendMarkdown(self, md)" } ]
2
stack_v2_sparse_classes_30k_val_000209
Implement the Python class `MathSvgExtension` described below. Class description: Adds MathSvg extension to Markdown class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize. - def extendMarkdown(self, md): Extend the inline and block processor objects.
Implement the Python class `MathSvgExtension` described below. Class description: Adds MathSvg extension to Markdown class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize. - def extendMarkdown(self, md): Extend the inline and block processor objects. <|skeleton|> class MathSvgExt...
45c862669d8d4e72c95f6b278819379a1c1e68d4
<|skeleton|> class MathSvgExtension: """Adds MathSvg extension to Markdown class.""" def __init__(self, *args, **kwargs): """Initialize.""" <|body_0|> def extendMarkdown(self, md): """Extend the inline and block processor objects.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MathSvgExtension: """Adds MathSvg extension to Markdown class.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = {'inline_class': ['math', "Inline math is SVG wrapped in a <span> tag, this option adds a class name to it - Default: 'math'"], 'display_class': ['math', ...
the_stack_v2_python_sparse
pylbm_ui/widgets/mdx_math_svg.py
gouarin/pylbm_ui
train
0
b4dc1fcdd1aad4db485cb445eabea1fd477eedfb
[ "input_spec = TensorSpec((10,), torch.float32)\nembedding = input_spec.ones(outer_dims=(1,))\nnet = OnehotCategoricalProjectionNetwork(input_size=input_spec.shape[0], mode=mode, action_spec=BoundedTensorSpec((1,), minimum=0, maximum=4), logits_init_output_factor=0)\ndist, _ = net(embedding)\nself.assertTrue(isinsta...
<|body_start_0|> input_spec = TensorSpec((10,), torch.float32) embedding = input_spec.ones(outer_dims=(1,)) net = OnehotCategoricalProjectionNetwork(input_size=input_spec.shape[0], mode=mode, action_spec=BoundedTensorSpec((1,), minimum=0, maximum=4), logits_init_output_factor=0) dist, _ ...
TestOnehotCategoricalProjectionNetwork
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestOnehotCategoricalProjectionNetwork: def test_onehot_categorical_uniform_projection_net(self, mode): """A zero-weight net generates uniform actions.""" <|body_0|> def test_onehot_samples(self, mode): """Samples from the projection net are onehot vectors.""" ...
stack_v2_sparse_classes_36k_train_014365
19,986
permissive
[ { "docstring": "A zero-weight net generates uniform actions.", "name": "test_onehot_categorical_uniform_projection_net", "signature": "def test_onehot_categorical_uniform_projection_net(self, mode)" }, { "docstring": "Samples from the projection net are onehot vectors.", "name": "test_onehot...
4
stack_v2_sparse_classes_30k_train_004811
Implement the Python class `TestOnehotCategoricalProjectionNetwork` described below. Class description: Implement the TestOnehotCategoricalProjectionNetwork class. Method signatures and docstrings: - def test_onehot_categorical_uniform_projection_net(self, mode): A zero-weight net generates uniform actions. - def tes...
Implement the Python class `TestOnehotCategoricalProjectionNetwork` described below. Class description: Implement the TestOnehotCategoricalProjectionNetwork class. Method signatures and docstrings: - def test_onehot_categorical_uniform_projection_net(self, mode): A zero-weight net generates uniform actions. - def tes...
b00ff2fa5e660de31020338ba340263183fbeaa4
<|skeleton|> class TestOnehotCategoricalProjectionNetwork: def test_onehot_categorical_uniform_projection_net(self, mode): """A zero-weight net generates uniform actions.""" <|body_0|> def test_onehot_samples(self, mode): """Samples from the projection net are onehot vectors.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestOnehotCategoricalProjectionNetwork: def test_onehot_categorical_uniform_projection_net(self, mode): """A zero-weight net generates uniform actions.""" input_spec = TensorSpec((10,), torch.float32) embedding = input_spec.ones(outer_dims=(1,)) net = OnehotCategoricalProjectio...
the_stack_v2_python_sparse
alf/networks/projection_networks_test.py
HorizonRobotics/alf
train
288
0231692cc20d662f02f1c475ae7d6f398306d9ae
[ "super().__init__()\nself.N = N\nself.h = h\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_dim=input_vocab, output_dim=dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nblocks = []\nfor i in range(N):\n blocks.append(EncoderBlock(dm, h, hidden, drop_rate))\nself.blocks =...
<|body_start_0|> super().__init__() self.N = N self.h = h self.dm = dm self.embedding = tf.keras.layers.Embedding(input_dim=input_vocab, output_dim=dm) self.positional_encoding = positional_encoding(max_seq_len, self.dm) blocks = [] for i in range(N): ...
DecoderBlock class
Encoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Encoder: """DecoderBlock class""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units in the fully connected layer. drop_...
stack_v2_sparse_classes_36k_train_014366
13,062
no_license
[ { "docstring": "Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units in the fully connected layer. drop_rate: (float) the dropout rate.", "name": "__init__", "signature": "def __init__(self, N, dm, h, hidden, input_vocab, ma...
2
null
Implement the Python class `Encoder` described below. Class description: DecoderBlock class Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the n...
Implement the Python class `Encoder` described below. Class description: DecoderBlock class Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the n...
75274394adb52d740f6cd4000cc00bbde44b9b72
<|skeleton|> class Encoder: """DecoderBlock class""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units in the fully connected layer. drop_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Encoder: """DecoderBlock class""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units in the fully connected layer. drop_rate: (float)...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-transformer.py
jdarangop/holbertonschool-machine_learning
train
2
2dc192f442495bcb6f32d9f428ebcdeb503f565c
[ "super(YetiYaraCollector, self).__init__(state, name=name, critical=critical)\nself.rule_name_filter = ''\nself.api_key = ''\nself.api_root = ''", "self.logger.info(f'Name filter: {rule_name_filter}')\nself.rule_name_filter = rule_name_filter or ''\nself.api_key = api_key\nself.api_root = api_root", "self.logge...
<|body_start_0|> super(YetiYaraCollector, self).__init__(state, name=name, critical=critical) self.rule_name_filter = '' self.api_key = '' self.api_root = '' <|end_body_0|> <|body_start_1|> self.logger.info(f'Name filter: {rule_name_filter}') self.rule_name_filter = rule...
Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. http://localhost:8080/api/
YetiYaraCollector
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YetiYaraCollector: """Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. ...
stack_v2_sparse_classes_36k_train_014367
2,688
permissive
[ { "docstring": "Initializes a YaraCollector module.", "name": "__init__", "signature": "def __init__(self, state: DFTimewolfState, name: Optional[str]=None, critical: bool=False) -> None" }, { "docstring": "Sets up the YaraCollector module. Args: rule_name_filter: A string by which to filter Yar...
3
null
Implement the Python class `YetiYaraCollector` described below. Class description: Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. ...
Implement the Python class `YetiYaraCollector` described below. Class description: Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. ...
bcea85b1ce7a0feb2aa28b5be4fc6ae124e8ca3c
<|skeleton|> class YetiYaraCollector: """Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class YetiYaraCollector: """Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. http://localh...
the_stack_v2_python_sparse
dftimewolf/lib/collectors/yara.py
log2timeline/dftimewolf
train
248
3e02d2f87eefcadc2cf07da85cc4ebcb7c5c312c
[ "super().__init__(properties=properties, data=data, bounds=bounds, geometry=geometry, interior_ring=interior_ring, source=source, copy=copy, _use_data=_use_data)\nself._initialise_netcdf(source)\nself._initialise_original_filenames(source)", "if _title is None:\n _title = 'Auxiliary coordinate: ' + self.identi...
<|body_start_0|> super().__init__(properties=properties, data=data, bounds=bounds, geometry=geometry, interior_ring=interior_ring, source=source, copy=copy, _use_data=_use_data) self._initialise_netcdf(source) self._initialise_original_filenames(source) <|end_body_0|> <|body_start_1|> i...
An auxiliary coordinate construct of the CF data model. An auxiliary coordinate construct provides information which locate the cells of the domain and which depend on a subset of the domain axis constructs. Auxiliary coordinate constructs have to be used, instead of dimension coordinate constructs, when a single domai...
AuxiliaryCoordinate
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuxiliaryCoordinate: """An auxiliary coordinate construct of the CF data model. An auxiliary coordinate construct provides information which locate the cells of the domain and which depend on a subset of the domain axis constructs. Auxiliary coordinate constructs have to be used, instead of dimen...
stack_v2_sparse_classes_36k_train_014368
3,896
permissive
[ { "docstring": "**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Parameter example:* ``properties={'standard_name': 'latitude'}`` {{init data: data_like, optional}} {{init bounds: `Bounds`, optional}} {{init geometry: `str`, optional}} {{init interior_ring: `InteriorRing`, optional}} {{ini...
2
null
Implement the Python class `AuxiliaryCoordinate` described below. Class description: An auxiliary coordinate construct of the CF data model. An auxiliary coordinate construct provides information which locate the cells of the domain and which depend on a subset of the domain axis constructs. Auxiliary coordinate const...
Implement the Python class `AuxiliaryCoordinate` described below. Class description: An auxiliary coordinate construct of the CF data model. An auxiliary coordinate construct provides information which locate the cells of the domain and which depend on a subset of the domain axis constructs. Auxiliary coordinate const...
142accf27fbbc052473b4eee47daf0e81c88df3a
<|skeleton|> class AuxiliaryCoordinate: """An auxiliary coordinate construct of the CF data model. An auxiliary coordinate construct provides information which locate the cells of the domain and which depend on a subset of the domain axis constructs. Auxiliary coordinate constructs have to be used, instead of dimen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuxiliaryCoordinate: """An auxiliary coordinate construct of the CF data model. An auxiliary coordinate construct provides information which locate the cells of the domain and which depend on a subset of the domain axis constructs. Auxiliary coordinate constructs have to be used, instead of dimension coordina...
the_stack_v2_python_sparse
cfdm/auxiliarycoordinate.py
NCAS-CMS/cfdm
train
29
8e09b3c90ae813ea92a0fea935d9497c4608d498
[ "super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)", "if mask is not None:\n mask = mask.unsqueeze(1)\nn_batches = query.size(0)\nquery, key, v...
<|body_start_0|> super(MultiHeadedAttention, self).__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h self.linears = clones(nn.Linear(d_model, d_model), 4) self.attn = None self.dropout = nn.Dropout(p=dropout) <|end_body_0|> <|body_start_1|> ...
MultiHeadedAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadedAttention: def __init__(self, h, d_model, dropout=0.1): """param h: number of heads param d_model: model dimension param dropout: dropout rate""" <|body_0|> def forward(self, query, key, value, mask=None): """Calculates multiheaded attention and then appli...
stack_v2_sparse_classes_36k_train_014369
11,359
no_license
[ { "docstring": "param h: number of heads param d_model: model dimension param dropout: dropout rate", "name": "__init__", "signature": "def __init__(self, h, d_model, dropout=0.1)" }, { "docstring": "Calculates multiheaded attention and then applies a linear transformation param query: query ten...
2
stack_v2_sparse_classes_30k_train_013489
Implement the Python class `MultiHeadedAttention` described below. Class description: Implement the MultiHeadedAttention class. Method signatures and docstrings: - def __init__(self, h, d_model, dropout=0.1): param h: number of heads param d_model: model dimension param dropout: dropout rate - def forward(self, query...
Implement the Python class `MultiHeadedAttention` described below. Class description: Implement the MultiHeadedAttention class. Method signatures and docstrings: - def __init__(self, h, d_model, dropout=0.1): param h: number of heads param d_model: model dimension param dropout: dropout rate - def forward(self, query...
c0b2f83a7d4c0d5fa5effb7584e0e0acc6f877a0
<|skeleton|> class MultiHeadedAttention: def __init__(self, h, d_model, dropout=0.1): """param h: number of heads param d_model: model dimension param dropout: dropout rate""" <|body_0|> def forward(self, query, key, value, mask=None): """Calculates multiheaded attention and then appli...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiHeadedAttention: def __init__(self, h, d_model, dropout=0.1): """param h: number of heads param d_model: model dimension param dropout: dropout rate""" super(MultiHeadedAttention, self).__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h s...
the_stack_v2_python_sparse
src/main/base_models/architectures/Transformer.py
iesl/institution_hierarchies
train
3
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9
[ "if not is_string(name):\n raise TypeError('Instance name must be a string')\nif properties is not None and (not isinstance(properties, dict)):\n raise TypeError('Instance properties must be a dictionary or None')\nname = name.strip()\nif not name:\n raise ValueError(\"Invalid instance name '{0}'\".format(...
<|body_start_0|> if not is_string(name): raise TypeError('Instance name must be a string') if properties is not None and (not isinstance(properties, dict)): raise TypeError('Instance properties must be a dictionary or None') name = name.strip() if not name: ...
Decorator that sets up a future instance of a component
Instantiate
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Instantiate: """Decorator that sets up a future instance of a component""" def __init__(self, name, properties=None): """Sets up the decorator :param name: Instance name :param properties: Instance properties""" <|body_0|> def __call__(self, factory_class): """Se...
stack_v2_sparse_classes_36k_train_014370
41,418
permissive
[ { "docstring": "Sets up the decorator :param name: Instance name :param properties: Instance properties", "name": "__init__", "signature": "def __init__(self, name, properties=None)" }, { "docstring": "Sets up and registers the instances descriptions :param factory_class: The factory class to in...
2
stack_v2_sparse_classes_30k_train_001724
Implement the Python class `Instantiate` described below. Class description: Decorator that sets up a future instance of a component Method signatures and docstrings: - def __init__(self, name, properties=None): Sets up the decorator :param name: Instance name :param properties: Instance properties - def __call__(sel...
Implement the Python class `Instantiate` described below. Class description: Decorator that sets up a future instance of a component Method signatures and docstrings: - def __init__(self, name, properties=None): Sets up the decorator :param name: Instance name :param properties: Instance properties - def __call__(sel...
686556cdde20beba77ae202de9969be46feed5e2
<|skeleton|> class Instantiate: """Decorator that sets up a future instance of a component""" def __init__(self, name, properties=None): """Sets up the decorator :param name: Instance name :param properties: Instance properties""" <|body_0|> def __call__(self, factory_class): """Se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Instantiate: """Decorator that sets up a future instance of a component""" def __init__(self, name, properties=None): """Sets up the decorator :param name: Instance name :param properties: Instance properties""" if not is_string(name): raise TypeError('Instance name must be a ...
the_stack_v2_python_sparse
python/src/lib/python/pelix/ipopo/decorators.py
cohorte/cohorte-runtime
train
3
5da4494b1b1818424d71ccbb1b66db0bb9dc17b7
[ "for project_id, instances in resource_from_api.iteritems():\n for instance in instances:\n yield {'project_id': project_id, 'id': instance.get('id'), 'creation_timestamp': parser.format_timestamp(instance.get('creationTimestamp'), self.MYSQL_DATETIME_FORMAT), 'name': instance.get('name'), 'description': ...
<|body_start_0|> for project_id, instances in resource_from_api.iteritems(): for instance in instances: yield {'project_id': project_id, 'id': instance.get('id'), 'creation_timestamp': parser.format_timestamp(instance.get('creationTimestamp'), self.MYSQL_DATETIME_FORMAT), 'name': ins...
Load compute instances for all projects.
LoadInstancesPipeline
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadInstancesPipeline: """Load compute instances for all projects.""" def _transform(self, resource_from_api): """Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance prop...
stack_v2_sparse_classes_36k_train_014371
4,162
permissive
[ { "docstring": "Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance properties.", "name": "_transform", "signature": "def _transform(self, resource_from_api)" }, { "docstring": "Retr...
3
stack_v2_sparse_classes_30k_train_002160
Implement the Python class `LoadInstancesPipeline` described below. Class description: Load compute instances for all projects. Method signatures and docstrings: - def _transform(self, resource_from_api): Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed...
Implement the Python class `LoadInstancesPipeline` described below. Class description: Load compute instances for all projects. Method signatures and docstrings: - def _transform(self, resource_from_api): Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed...
a6a1aa7464cda2ad5948e3e8876eb8dded5e2514
<|skeleton|> class LoadInstancesPipeline: """Load compute instances for all projects.""" def _transform(self, resource_from_api): """Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance prop...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoadInstancesPipeline: """Load compute instances for all projects.""" def _transform(self, resource_from_api): """Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance properties.""" ...
the_stack_v2_python_sparse
google/cloud/security/inventory/pipelines/load_instances_pipeline.py
shimizu19691210/forseti-security
train
1
6ce8a912bf1d9ff03e395e3bba7cc8379c7a9491
[ "self.__questions = Questions(data_file_path)\nself.__players = players\nself.__answers = list()", "n_questions = len(self.__questions.get_questions())\nfor player in range(self.__players):\n print('\\nQuestions for player {}'.format(player + 1))\n print('----------------------\\n\\n')\n n_answered = lis...
<|body_start_0|> self.__questions = Questions(data_file_path) self.__players = players self.__answers = list() <|end_body_0|> <|body_start_1|> n_questions = len(self.__questions.get_questions()) for player in range(self.__players): print('\nQuestions for player {}'.f...
Quiz class.
Quiz
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Quiz: """Quiz class.""" def __init__(self, players, data_file_path): """Constructor. :param players: Number of players. :param data_file_path: Text file to read the questions and answers from.""" <|body_0|> def run(self): """Run a the quiz.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_014372
4,115
no_license
[ { "docstring": "Constructor. :param players: Number of players. :param data_file_path: Text file to read the questions and answers from.", "name": "__init__", "signature": "def __init__(self, players, data_file_path)" }, { "docstring": "Run a the quiz.", "name": "run", "signature": "def ...
3
null
Implement the Python class `Quiz` described below. Class description: Quiz class. Method signatures and docstrings: - def __init__(self, players, data_file_path): Constructor. :param players: Number of players. :param data_file_path: Text file to read the questions and answers from. - def run(self): Run a the quiz. -...
Implement the Python class `Quiz` described below. Class description: Quiz class. Method signatures and docstrings: - def __init__(self, players, data_file_path): Constructor. :param players: Number of players. :param data_file_path: Text file to read the questions and answers from. - def run(self): Run a the quiz. -...
33bf532b397f21290d6f85631466d90964aab4ad
<|skeleton|> class Quiz: """Quiz class.""" def __init__(self, players, data_file_path): """Constructor. :param players: Number of players. :param data_file_path: Text file to read the questions and answers from.""" <|body_0|> def run(self): """Run a the quiz.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Quiz: """Quiz class.""" def __init__(self, players, data_file_path): """Constructor. :param players: Number of players. :param data_file_path: Text file to read the questions and answers from.""" self.__questions = Questions(data_file_path) self.__players = players self.__...
the_stack_v2_python_sparse
ass12/quiz.py
deadbok/eal_programming
train
1
0fcbae6be239682fbbc1516b9c78a8536a6e68d5
[ "self.W = np.random.randn(H, V)\nself.W /= np.sqrt(H)\nself.b = np.zeros(V)\nself.x = None", "if W is not None and b is not None:\n self.W = W\n self.b = b\nN, T, H = x.shape\nV = self.b.shape[0]\nself.x = x\nreturn np.dot(x.reshape(N * T, H), self.W).reshape(N, T, V) + self.b", "N, T, H = self.x.shape\nV...
<|body_start_0|> self.W = np.random.randn(H, V) self.W /= np.sqrt(H) self.b = np.zeros(V) self.x = None <|end_body_0|> <|body_start_1|> if W is not None and b is not None: self.W = W self.b = b N, T, H = x.shape V = self.b.shape[0] ...
TemporalAffineLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemporalAffineLayer: def __init__(self, H, V): """Args: H (int): Dimension of hidden state from LSTM cell. V (int): Number of words in the vocabulary.""" <|body_0|> def forward(self, x, W=None, b=None): """Forward pass for temporarl affine layer. The input is a set o...
stack_v2_sparse_classes_36k_train_014373
2,707
no_license
[ { "docstring": "Args: H (int): Dimension of hidden state from LSTM cell. V (int): Number of words in the vocabulary.", "name": "__init__", "signature": "def __init__(self, H, V)" }, { "docstring": "Forward pass for temporarl affine layer. The input is a set of H-dimensional vectors arranged into...
4
stack_v2_sparse_classes_30k_train_006003
Implement the Python class `TemporalAffineLayer` described below. Class description: Implement the TemporalAffineLayer class. Method signatures and docstrings: - def __init__(self, H, V): Args: H (int): Dimension of hidden state from LSTM cell. V (int): Number of words in the vocabulary. - def forward(self, x, W=None...
Implement the Python class `TemporalAffineLayer` described below. Class description: Implement the TemporalAffineLayer class. Method signatures and docstrings: - def __init__(self, H, V): Args: H (int): Dimension of hidden state from LSTM cell. V (int): Number of words in the vocabulary. - def forward(self, x, W=None...
7da789ef34d5e5bcf9033cfbe0ff5df607b2437a
<|skeleton|> class TemporalAffineLayer: def __init__(self, H, V): """Args: H (int): Dimension of hidden state from LSTM cell. V (int): Number of words in the vocabulary.""" <|body_0|> def forward(self, x, W=None, b=None): """Forward pass for temporarl affine layer. The input is a set o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TemporalAffineLayer: def __init__(self, H, V): """Args: H (int): Dimension of hidden state from LSTM cell. V (int): Number of words in the vocabulary.""" self.W = np.random.randn(H, V) self.W /= np.sqrt(H) self.b = np.zeros(V) self.x = None def forward(self, x, W=N...
the_stack_v2_python_sparse
recurrent_neural_networks/rnn/temporal_affine_layer.py
calvinfeng/machine-learning-notebook
train
38
744d9780587aec75e5eec500a1dfc4f54ac8362e
[ "if isinstance(values, list):\n for value in values:\n self.append(value)\nelse:\n raise TypeError('Please package your item into a list!')", "new_node = Node(value, None, None)\nif self.head is None:\n self.head = self.tail = new_node\nelse:\n new_node.prev = self.tail\n new_node.next = Non...
<|body_start_0|> if isinstance(values, list): for value in values: self.append(value) else: raise TypeError('Please package your item into a list!') <|end_body_0|> <|body_start_1|> new_node = Node(value, None, None) if self.head is None: ...
Define a double pointered list.
DoublyLinkedList
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DoublyLinkedList: """Define a double pointered list.""" def __init__(self, values): """Accept a list of values and generate a chain of Nodes using those values.""" <|body_0|> def append(self, value): """Append a value to the tail of the linked list.""" <|...
stack_v2_sparse_classes_36k_train_014374
3,676
permissive
[ { "docstring": "Accept a list of values and generate a chain of Nodes using those values.", "name": "__init__", "signature": "def __init__(self, values)" }, { "docstring": "Append a value to the tail of the linked list.", "name": "append", "signature": "def append(self, value)" }, { ...
6
stack_v2_sparse_classes_30k_train_019535
Implement the Python class `DoublyLinkedList` described below. Class description: Define a double pointered list. Method signatures and docstrings: - def __init__(self, values): Accept a list of values and generate a chain of Nodes using those values. - def append(self, value): Append a value to the tail of the linke...
Implement the Python class `DoublyLinkedList` described below. Class description: Define a double pointered list. Method signatures and docstrings: - def __init__(self, values): Accept a list of values and generate a chain of Nodes using those values. - def append(self, value): Append a value to the tail of the linke...
35d7b3af8c6e745838d25e42be88c49382461c8a
<|skeleton|> class DoublyLinkedList: """Define a double pointered list.""" def __init__(self, values): """Accept a list of values and generate a chain of Nodes using those values.""" <|body_0|> def append(self, value): """Append a value to the tail of the linked list.""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DoublyLinkedList: """Define a double pointered list.""" def __init__(self, values): """Accept a list of values and generate a chain of Nodes using those values.""" if isinstance(values, list): for value in values: self.append(value) else: ra...
the_stack_v2_python_sparse
src/dll.py
nadiabahrami/data-structures
train
0
6d813bb102040147e9879520800106159d9225b8
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserTrainingStatusInfo()", "from .training_status import TrainingStatus\nfrom .training_status import TrainingStatus\nfields: Dict[str, Callable[[Any], None]] = {'assignedDateTime': lambda n: setattr(self, 'assigned_date_time', n.get_d...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UserTrainingStatusInfo() <|end_body_0|> <|body_start_1|> from .training_status import TrainingStatus from .training_status import TrainingStatus fields: Dict[str, Callable[[Any],...
UserTrainingStatusInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserTrainingStatusInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserTrainingStatusInfo: """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 ...
stack_v2_sparse_classes_36k_train_014375
3,696
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: UserTrainingStatusInfo", "name": "create_from_discriminator_value", "signature": "def create_from_discrimina...
3
null
Implement the Python class `UserTrainingStatusInfo` described below. Class description: Implement the UserTrainingStatusInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserTrainingStatusInfo: Creates a new instance of the appropriate class b...
Implement the Python class `UserTrainingStatusInfo` described below. Class description: Implement the UserTrainingStatusInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserTrainingStatusInfo: Creates a new instance of the appropriate class b...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UserTrainingStatusInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserTrainingStatusInfo: """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 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserTrainingStatusInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserTrainingStatusInfo: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret...
the_stack_v2_python_sparse
msgraph/generated/models/user_training_status_info.py
microsoftgraph/msgraph-sdk-python
train
135
72edcdf99f2acf4130917b530d7be7a117ffe091
[ "self.inputFile = inputFile\nself.logLevel = logLevel\nlogging.basicConfig(level=self.logLevel)\nself.dConditions = {}\ntry:\n self.filehandle = open(self.inputFile, 'r')\nexcept Exception as e:\n logging.error(e)\n sys.exit(1)", "for idx, line in enumerate(self.filehandle):\n currentLine = line.strip...
<|body_start_0|> self.inputFile = inputFile self.logLevel = logLevel logging.basicConfig(level=self.logLevel) self.dConditions = {} try: self.filehandle = open(self.inputFile, 'r') except Exception as e: logging.error(e) sys.exit(1) <|e...
ExpNucFileParser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpNucFileParser: def __init__(self, inputFile='', logLevel='ERROR'): """Constructor""" <|body_0|> def parse(self): """parse file""" <|body_1|> def getlLabels(self): """return list of labels""" <|body_2|> def getlConditions(self): ...
stack_v2_sparse_classes_36k_train_014376
2,378
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, inputFile='', logLevel='ERROR')" }, { "docstring": "parse file", "name": "parse", "signature": "def parse(self)" }, { "docstring": "return list of labels", "name": "getlLabels", "signature"...
6
stack_v2_sparse_classes_30k_train_004330
Implement the Python class `ExpNucFileParser` described below. Class description: Implement the ExpNucFileParser class. Method signatures and docstrings: - def __init__(self, inputFile='', logLevel='ERROR'): Constructor - def parse(self): parse file - def getlLabels(self): return list of labels - def getlConditions(s...
Implement the Python class `ExpNucFileParser` described below. Class description: Implement the ExpNucFileParser class. Method signatures and docstrings: - def __init__(self, inputFile='', logLevel='ERROR'): Constructor - def parse(self): parse file - def getlLabels(self): return list of labels - def getlConditions(s...
ee0be5513d6a429b07b057d0ddd3fd617a1073d7
<|skeleton|> class ExpNucFileParser: def __init__(self, inputFile='', logLevel='ERROR'): """Constructor""" <|body_0|> def parse(self): """parse file""" <|body_1|> def getlLabels(self): """return list of labels""" <|body_2|> def getlConditions(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExpNucFileParser: def __init__(self, inputFile='', logLevel='ERROR'): """Constructor""" self.inputFile = inputFile self.logLevel = logLevel logging.basicConfig(level=self.logLevel) self.dConditions = {} try: self.filehandle = open(self.inputFile, 'r'...
the_stack_v2_python_sparse
MSTS/Parser/ExpNucFileParser.py
nlapalu/MSTS
train
0
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f
[ "self.num_locations = num_locations\nself.coverages_per_location = coverages_per_location\nself.num_areaperils = num_areaperils\nself.num_vulnerabilities = num_vulnerabilities\nself.dtypes = OrderedDict([('item_id', 'i'), ('coverage_id', 'i'), ('areaperil_id', 'i'), ('vulnerability_id', 'i'), ('group_id', 'i')])\ns...
<|body_start_0|> self.num_locations = num_locations self.coverages_per_location = coverages_per_location self.num_areaperils = num_areaperils self.num_vulnerabilities = num_vulnerabilities self.dtypes = OrderedDict([('item_id', 'i'), ('coverage_id', 'i'), ('areaperil_id', 'i'), (...
Generate data for Items dummy model Oasis file. This file lists the exposure items for which ground up loss will be sampled. Attributes: generate_data: Generate Items dummy model Oasis file data.
ItemsFile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ItemsFile: """Generate data for Items dummy model Oasis file. This file lists the exposure items for which ground up loss will be sampled. Attributes: generate_data: Generate Items dummy model Oasis file data.""" def __init__(self, num_locations, coverages_per_location, num_areaperils, num_v...
stack_v2_sparse_classes_36k_train_014377
39,722
permissive
[ { "docstring": "Initialise Items file class. Args: num_locations (int): number of locations. coverages_per_location (int): number of coverage types per location. num_areaperils (int): number of areaperils. num_vulnerabilities (int): number of vulnerabilities. random_seed (float): random seed for random number g...
2
null
Implement the Python class `ItemsFile` described below. Class description: Generate data for Items dummy model Oasis file. This file lists the exposure items for which ground up loss will be sampled. Attributes: generate_data: Generate Items dummy model Oasis file data. Method signatures and docstrings: - def __init_...
Implement the Python class `ItemsFile` described below. Class description: Generate data for Items dummy model Oasis file. This file lists the exposure items for which ground up loss will be sampled. Attributes: generate_data: Generate Items dummy model Oasis file data. Method signatures and docstrings: - def __init_...
23e704c335629ccd010969b1090446cfa3f384d5
<|skeleton|> class ItemsFile: """Generate data for Items dummy model Oasis file. This file lists the exposure items for which ground up loss will be sampled. Attributes: generate_data: Generate Items dummy model Oasis file data.""" def __init__(self, num_locations, coverages_per_location, num_areaperils, num_v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ItemsFile: """Generate data for Items dummy model Oasis file. This file lists the exposure items for which ground up loss will be sampled. Attributes: generate_data: Generate Items dummy model Oasis file data.""" def __init__(self, num_locations, coverages_per_location, num_areaperils, num_vulnerabilitie...
the_stack_v2_python_sparse
oasislmf/computation/data/dummy_model/generate.py
OasisLMF/OasisLMF
train
122
8404f2fa5e730c2f4fabfb99f1919574d48586fb
[ "super(NumpyDeserializer, self).__init__(accept=accept)\nself.dtype = dtype\nself.allow_pickle = allow_pickle", "try:\n if content_type == 'text/csv':\n return np.genfromtxt(codecs.getreader('utf-8')(stream), delimiter=',', dtype=self.dtype)\n if content_type == 'application/json':\n return np...
<|body_start_0|> super(NumpyDeserializer, self).__init__(accept=accept) self.dtype = dtype self.allow_pickle = allow_pickle <|end_body_0|> <|body_start_1|> try: if content_type == 'text/csv': return np.genfromtxt(codecs.getreader('utf-8')(stream), delimiter='...
Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array.
NumpyDeserializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumpyDeserializer: """Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array."...
stack_v2_sparse_classes_36k_train_014378
12,360
permissive
[ { "docstring": "Initialize a ``NumpyDeserializer`` instance. Args: dtype (str): The dtype of the data (default: None). accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that is expected from the inference endpoint (default: \"application/x-npy\"). allow_pickle (bool): Allow loadi...
2
stack_v2_sparse_classes_30k_train_013290
Implement the Python class `NumpyDeserializer` described below. Class description: Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy....
Implement the Python class `NumpyDeserializer` described below. Class description: Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy....
8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85
<|skeleton|> class NumpyDeserializer: """Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumpyDeserializer: """Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array.""" def _...
the_stack_v2_python_sparse
src/sagemaker/base_deserializers.py
aws/sagemaker-python-sdk
train
2,050
9253f01e88adce33444245fcf2b4fbd744be6a7d
[ "errors = []\nif not file_path or file_path.isspace():\n errors.append(VerifierError(subject=self, local_error='Gromacs file name is white space.', global_error='Gromacs file not specified.'))\nif ext is not None:\n if not file_path.endswith('.{}'.format(ext)):\n errors.append(VerifierError(subject=sel...
<|body_start_0|> errors = [] if not file_path or file_path.isspace(): errors.append(VerifierError(subject=self, local_error='Gromacs file name is white space.', global_error='Gromacs file not specified.')) if ext is not None: if not file_path.endswith('.{}'.format(ext)): ...
Class containing all input parameters for a single molecular fragment in a Gromacs simulation
FragmentDataSourceModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FragmentDataSourceModel: """Class containing all input parameters for a single molecular fragment in a Gromacs simulation""" def _file_check(self, file_path, ext=None): """Performs a series of checks on selected Gromacs file located at file_path Parameters ---------- file_path: str F...
stack_v2_sparse_classes_36k_train_014379
2,768
permissive
[ { "docstring": "Performs a series of checks on selected Gromacs file located at file_path Parameters ---------- file_path: str File path for Gromacs input file ext: str, optional Expected extension of Gromacs input file", "name": "_file_check", "signature": "def _file_check(self, file_path, ext=None)" ...
2
stack_v2_sparse_classes_30k_train_000874
Implement the Python class `FragmentDataSourceModel` described below. Class description: Class containing all input parameters for a single molecular fragment in a Gromacs simulation Method signatures and docstrings: - def _file_check(self, file_path, ext=None): Performs a series of checks on selected Gromacs file lo...
Implement the Python class `FragmentDataSourceModel` described below. Class description: Class containing all input parameters for a single molecular fragment in a Gromacs simulation Method signatures and docstrings: - def _file_check(self, file_path, ext=None): Performs a series of checks on selected Gromacs file lo...
1518185e4cdab824d57570bc5df6c719f1f11bea
<|skeleton|> class FragmentDataSourceModel: """Class containing all input parameters for a single molecular fragment in a Gromacs simulation""" def _file_check(self, file_path, ext=None): """Performs a series of checks on selected Gromacs file located at file_path Parameters ---------- file_path: str F...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FragmentDataSourceModel: """Class containing all input parameters for a single molecular fragment in a Gromacs simulation""" def _file_check(self, file_path, ext=None): """Performs a series of checks on selected Gromacs file located at file_path Parameters ---------- file_path: str File path for ...
the_stack_v2_python_sparse
force_gromacs/data_sources/fragment/fragment_model.py
force-h2020/force-bdss-plugin-gromacs
train
0
46b0455592dded788b789dc9ba1a14f76d5a3ae3
[ "self.type_mapping_dict = copy.deepcopy(type_dict)\nself.params_mapping_dict = copy.deepcopy(params_dict)\nself.backend_type = None\nif vega.is_torch_backend():\n self.backend_type = 'torch'\nelif vega.is_tf_backend():\n self.backend_type = 'tf'\nelif vega.is_ms_backend():\n self.backend_type = 'ms'\nelse:...
<|body_start_0|> self.type_mapping_dict = copy.deepcopy(type_dict) self.params_mapping_dict = copy.deepcopy(params_dict) self.backend_type = None if vega.is_torch_backend(): self.backend_type = 'torch' elif vega.is_tf_backend(): self.backend_type = 'tf' ...
Config mapping according to backend. :param module_type: module type in trainer, 'optim', 'loss' or 'lr_scheduler' :type module_type: str
ConfigBackendMapping
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigBackendMapping: """Config mapping according to backend. :param module_type: module type in trainer, 'optim', 'loss' or 'lr_scheduler' :type module_type: str""" def __init__(self, type_dict, params_dict): """Init config backend mapping.""" <|body_0|> def backend_map...
stack_v2_sparse_classes_36k_train_014380
2,721
permissive
[ { "docstring": "Init config backend mapping.", "name": "__init__", "signature": "def __init__(self, type_dict, params_dict)" }, { "docstring": "Map config to specific backend. :param config: original config from config file :type config: Config or dict :return: config after mapping to backend :r...
2
stack_v2_sparse_classes_30k_train_020532
Implement the Python class `ConfigBackendMapping` described below. Class description: Config mapping according to backend. :param module_type: module type in trainer, 'optim', 'loss' or 'lr_scheduler' :type module_type: str Method signatures and docstrings: - def __init__(self, type_dict, params_dict): Init config ba...
Implement the Python class `ConfigBackendMapping` described below. Class description: Config mapping according to backend. :param module_type: module type in trainer, 'optim', 'loss' or 'lr_scheduler' :type module_type: str Method signatures and docstrings: - def __init__(self, type_dict, params_dict): Init config ba...
12e37a1991eb6771a2999fe0a46ddda920c47948
<|skeleton|> class ConfigBackendMapping: """Config mapping according to backend. :param module_type: module type in trainer, 'optim', 'loss' or 'lr_scheduler' :type module_type: str""" def __init__(self, type_dict, params_dict): """Init config backend mapping.""" <|body_0|> def backend_map...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigBackendMapping: """Config mapping according to backend. :param module_type: module type in trainer, 'optim', 'loss' or 'lr_scheduler' :type module_type: str""" def __init__(self, type_dict, params_dict): """Init config backend mapping.""" self.type_mapping_dict = copy.deepcopy(type_...
the_stack_v2_python_sparse
vega/trainer/modules/config_bakcend_map.py
huawei-noah/vega
train
850
c5a7613b0bb497ee9afaf672fd1ded36f1afebfb
[ "if isinstance(value, bytes):\n value = value.decode('utf-8')\nreturn value", "if isinstance(value, bytes):\n value = value.decode('utf-8')\nresult = repr(value)\nif six.PY2 and result.startswith('u'):\n result = result[1:].decode('unicode-escape')\nreturn result" ]
<|body_start_0|> if isinstance(value, bytes): value = value.decode('utf-8') return value <|end_body_0|> <|body_start_1|> if isinstance(value, bytes): value = value.decode('utf-8') result = repr(value) if six.PY2 and result.startswith('u'): res...
Base class for serialization for strings. This will encode to a string, and ensure the results are consistent across Python 2 and 3. Version Added: 2.2
StringSerialization
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StringSerialization: """Base class for serialization for strings. This will encode to a string, and ensure the results are consistent across Python 2 and 3. Version Added: 2.2""" def serialize_to_signature(cls, value): """Serialize a string to JSON-compatible string. Args: value (byt...
stack_v2_sparse_classes_36k_train_014381
30,104
permissive
[ { "docstring": "Serialize a string to JSON-compatible string. Args: value (bytes or unicode): The string to serialize. If a byte string, it's expected to contain UTF-8 data. Returns: unicode: The resulting string.", "name": "serialize_to_signature", "signature": "def serialize_to_signature(cls, value)" ...
2
stack_v2_sparse_classes_30k_train_001219
Implement the Python class `StringSerialization` described below. Class description: Base class for serialization for strings. This will encode to a string, and ensure the results are consistent across Python 2 and 3. Version Added: 2.2 Method signatures and docstrings: - def serialize_to_signature(cls, value): Seria...
Implement the Python class `StringSerialization` described below. Class description: Base class for serialization for strings. This will encode to a string, and ensure the results are consistent across Python 2 and 3. Version Added: 2.2 Method signatures and docstrings: - def serialize_to_signature(cls, value): Seria...
756eedeacc41f77111a557fc13dee559cb94f433
<|skeleton|> class StringSerialization: """Base class for serialization for strings. This will encode to a string, and ensure the results are consistent across Python 2 and 3. Version Added: 2.2""" def serialize_to_signature(cls, value): """Serialize a string to JSON-compatible string. Args: value (byt...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StringSerialization: """Base class for serialization for strings. This will encode to a string, and ensure the results are consistent across Python 2 and 3. Version Added: 2.2""" def serialize_to_signature(cls, value): """Serialize a string to JSON-compatible string. Args: value (bytes or unicode...
the_stack_v2_python_sparse
django_evolution/serialization.py
beanbaginc/django-evolution
train
22
e87a8683d4300f34018575e8d42abaf0fb780b5c
[ "self._graph = graph\nself.opset = util.default(opset, 11)\nself.optimize = util.default(optimize, True)", "(graph, output_names), _ = util.invoke_if_callable(self._graph)\ninput_names = list(tf_util.get_input_metadata(graph).keys())\ngraphdef = graph.as_graph_def()\nif self.optimize:\n graphdef = tf2onnx.tfon...
<|body_start_0|> self._graph = graph self.opset = util.default(opset, 11) self.optimize = util.default(optimize, True) <|end_body_0|> <|body_start_1|> (graph, output_names), _ = util.invoke_if_callable(self._graph) input_names = list(tf_util.get_input_metadata(graph).keys()) ...
Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter.
OnnxFromTfGraph
[ "Apache-2.0", "BSD-3-Clause", "MIT", "ISC", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OnnxFromTfGraph: """Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter.""" def __init__(self, graph, opset=None, optimize=None): """Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf....
stack_v2_sparse_classes_36k_train_014382
37,448
permissive
[ { "docstring": "Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf.Graph, Sequence[str]]]): A tuple containing a TensorFlow graph and output names or a callable that returns one. opset (int): The ONNX opset to use during conversion. optimize (bool): ...
2
stack_v2_sparse_classes_30k_test_000728
Implement the Python class `OnnxFromTfGraph` described below. Class description: Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter. Method signatures and docstrings: - def __init__(self, graph, opset=None, optimize=None): Converts a TensorFlow model into ONNX. Args: graph (Unio...
Implement the Python class `OnnxFromTfGraph` described below. Class description: Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter. Method signatures and docstrings: - def __init__(self, graph, opset=None, optimize=None): Converts a TensorFlow model into ONNX. Args: graph (Unio...
a167852705d74bcc619d8fad0af4b9e4d84472fc
<|skeleton|> class OnnxFromTfGraph: """Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter.""" def __init__(self, graph, opset=None, optimize=None): """Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OnnxFromTfGraph: """Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter.""" def __init__(self, graph, opset=None, optimize=None): """Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf.Graph, Sequen...
the_stack_v2_python_sparse
tools/Polygraphy/polygraphy/backend/onnx/loader.py
NVIDIA/TensorRT
train
8,026
5b393a001338ee30598d34b5fa07ad5a691e7e9b
[ "with SIMPLE_FILE_PATH.open() as auth_file:\n for line in auth_file.readlines():\n match = re.match('(^STEAM_[0,1]{1}:[0,1]{1}:[0-9]+)', line)\n if match:\n self.add(match.group(0))", "if uniqueid in self:\n return True\nreturn False" ]
<|body_start_0|> with SIMPLE_FILE_PATH.open() as auth_file: for line in auth_file.readlines(): match = re.match('(^STEAM_[0,1]{1}:[0,1]{1}:[0-9]+)', line) if match: self.add(match.group(0)) <|end_body_0|> <|body_start_1|> if uniqueid in se...
Class used to determine if a player is authorized
_SimpleAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _SimpleAuth: """Class used to determine if a player is authorized""" def _parse_admins(self): """Method used to get all uniqueids that are authorized on the server""" <|body_0|> def is_player_authorized(self, uniqueid, level, permission, flag): """Method used to ...
stack_v2_sparse_classes_36k_train_014383
2,351
no_license
[ { "docstring": "Method used to get all uniqueids that are authorized on the server", "name": "_parse_admins", "signature": "def _parse_admins(self)" }, { "docstring": "Method used to check if a player is authorized", "name": "is_player_authorized", "signature": "def is_player_authorized(...
2
stack_v2_sparse_classes_30k_train_008392
Implement the Python class `_SimpleAuth` described below. Class description: Class used to determine if a player is authorized Method signatures and docstrings: - def _parse_admins(self): Method used to get all uniqueids that are authorized on the server - def is_player_authorized(self, uniqueid, level, permission, f...
Implement the Python class `_SimpleAuth` described below. Class description: Class used to determine if a player is authorized Method signatures and docstrings: - def _parse_admins(self): Method used to get all uniqueids that are authorized on the server - def is_player_authorized(self, uniqueid, level, permission, f...
b84df87f67ecb0fb2487e68e8b4b6bee3944f506
<|skeleton|> class _SimpleAuth: """Class used to determine if a player is authorized""" def _parse_admins(self): """Method used to get all uniqueids that are authorized on the server""" <|body_0|> def is_player_authorized(self, uniqueid, level, permission, flag): """Method used to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _SimpleAuth: """Class used to determine if a player is authorized""" def _parse_admins(self): """Method used to get all uniqueids that are authorized on the server""" with SIMPLE_FILE_PATH.open() as auth_file: for line in auth_file.readlines(): match = re.match...
the_stack_v2_python_sparse
addons/source-python/packages/source-python/auth/providers/simple.py
aurorapar/Source.Python
train
0
345e3f8062c01205fe5dabe7f95fd75b69aaec68
[ "mission_id = self.search(cr, uid, [('parent_id', 'in', ids)], context=context)\nif mission_id:\n raise osv.except_osv(_('Warning!'), _('You cannot delete this mission category because it is parent to another mission category'))\nreturn super(mission_category, self).unlink(cr, uid, ids, context)", "default = {...
<|body_start_0|> mission_id = self.search(cr, uid, [('parent_id', 'in', ids)], context=context) if mission_id: raise osv.except_osv(_('Warning!'), _('You cannot delete this mission category because it is parent to another mission category')) return super(mission_category, self).unlin...
mission_category
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class mission_category: def unlink(self, cr, uid, ids, context=None): """This method prevent to delete record if it has parent return super & raise exception""" <|body_0|> def copy(self, cr, uid, id, default=None, context=None): """This method prevent to duplicate record i...
stack_v2_sparse_classes_36k_train_014384
17,962
no_license
[ { "docstring": "This method prevent to delete record if it has parent return super & raise exception", "name": "unlink", "signature": "def unlink(self, cr, uid, ids, context=None)" }, { "docstring": "This method prevent to duplicate record if it has parent return super & raise exception", "n...
2
null
Implement the Python class `mission_category` described below. Class description: Implement the mission_category class. Method signatures and docstrings: - def unlink(self, cr, uid, ids, context=None): This method prevent to delete record if it has parent return super & raise exception - def copy(self, cr, uid, id, d...
Implement the Python class `mission_category` described below. Class description: Implement the mission_category class. Method signatures and docstrings: - def unlink(self, cr, uid, ids, context=None): This method prevent to delete record if it has parent return super & raise exception - def copy(self, cr, uid, id, d...
0b997095c260d58b026440967fea3a202bef7efb
<|skeleton|> class mission_category: def unlink(self, cr, uid, ids, context=None): """This method prevent to delete record if it has parent return super & raise exception""" <|body_0|> def copy(self, cr, uid, id, default=None, context=None): """This method prevent to duplicate record i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class mission_category: def unlink(self, cr, uid, ids, context=None): """This method prevent to delete record if it has parent return super & raise exception""" mission_id = self.search(cr, uid, [('parent_id', 'in', ids)], context=context) if mission_id: raise osv.except_osv(_('W...
the_stack_v2_python_sparse
v_7/Dongola/common/hr_mission/hr_mission.py
musabahmed/baba
train
0
30fbd48d36f28a7a5ab0a7f1f029417b24e7957e
[ "if metadata is None:\n metadata = {}\nsecret = self.create(value=value, contributor=contributor, metadata=metadata, expires=expires)\nreturn str(secret.handle)", "queryset = self.all()\nif contributor is not None:\n queryset = queryset.filter(contributor=contributor)\nsecret = queryset.get(handle=handle)\n...
<|body_start_0|> if metadata is None: metadata = {} secret = self.create(value=value, contributor=contributor, metadata=metadata, expires=expires) return str(secret.handle) <|end_body_0|> <|body_start_1|> queryset = self.all() if contributor is not None: ...
Manager for Secret objects.
SecretManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecretManager: """Manager for Secret objects.""" def create_secret(self, value, contributor, metadata=None, expires=None): """Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata d...
stack_v2_sparse_classes_36k_train_014385
2,264
permissive
[ { "docstring": "Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata dictionary (must be JSON serializable) :param expires: Optional date/time of expiry (defaults to None, which means that the secret never ex...
2
null
Implement the Python class `SecretManager` described below. Class description: Manager for Secret objects. Method signatures and docstrings: - def create_secret(self, value, contributor, metadata=None, expires=None): Create a new secret, returning its handle. :param value: Secret value to store :param contributor: Us...
Implement the Python class `SecretManager` described below. Class description: Manager for Secret objects. Method signatures and docstrings: - def create_secret(self, value, contributor, metadata=None, expires=None): Create a new secret, returning its handle. :param value: Secret value to store :param contributor: Us...
25c0c45235ef37beb45c1af4c917fbbae6282016
<|skeleton|> class SecretManager: """Manager for Secret objects.""" def create_secret(self, value, contributor, metadata=None, expires=None): """Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecretManager: """Manager for Secret objects.""" def create_secret(self, value, contributor, metadata=None, expires=None): """Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata dictionary (mu...
the_stack_v2_python_sparse
resolwe/flow/models/secret.py
genialis/resolwe
train
35
46692a96e0f31433821ea622d366179306bb7cbc
[ "torch.nn.Module.__init__(self)\nif hidden_size % num_heads:\n raise ValueError('hidden size must be a multiple of the number of attention heads')\nself.attention = Attention(hidden_size, hidden_size, num_heads, hidden_size // num_heads, dropout=dropout, initializer_range=initializer_range)\nself.encoder_attenti...
<|body_start_0|> torch.nn.Module.__init__(self) if hidden_size % num_heads: raise ValueError('hidden size must be a multiple of the number of attention heads') self.attention = Attention(hidden_size, hidden_size, num_heads, hidden_size // num_heads, dropout=dropout, initializer_range...
TransformerDecoder
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransformerDecoder: def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): """hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer ...
stack_v2_sparse_classes_36k_train_014386
6,126
permissive
[ { "docstring": "hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer dropout - dropout probability (0. means \"no dropout\")", "name": "__init__", "signature": "def __init__(self, hidden_size=768, num_hea...
2
stack_v2_sparse_classes_30k_train_009882
Implement the Python class `TransformerDecoder` described below. Class description: Implement the TransformerDecoder class. Method signatures and docstrings: - def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): hidden_size - hidden size, must be multiple of...
Implement the Python class `TransformerDecoder` described below. Class description: Implement the TransformerDecoder class. Method signatures and docstrings: - def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): hidden_size - hidden size, must be multiple of...
84c1c9507b3b1bffd2a08a86efaf9bc9955271e0
<|skeleton|> class TransformerDecoder: def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): """hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransformerDecoder: def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): """hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer dropout - drop...
the_stack_v2_python_sparse
tbert/transformer.py
qianrenjian/tbert
train
0
0d98ccd859c6f267cb0472b419c3f42886f8608e
[ "try:\n session_duration = int(getenv('SESSION_DURATION'))\nexcept Exception:\n session_duration = 0\nself.session_duration = session_duration", "session_id = super().create_session(user_id)\nif session_id is None:\n return None\nsession_dictionary = {'user_id': user_id, 'created_at': datetime.now()}\nSe...
<|body_start_0|> try: session_duration = int(getenv('SESSION_DURATION')) except Exception: session_duration = 0 self.session_duration = session_duration <|end_body_0|> <|body_start_1|> session_id = super().create_session(user_id) if session_id is None: ...
Session expiration authentification methods
SessionExpAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionExpAuth: """Session expiration authentification methods""" def __init__(self): """Initialize class""" <|body_0|> def create_session(self, user_id=None): """Creates a session ID""" <|body_1|> def user_id_for_session_id(self, session_id=None): ...
stack_v2_sparse_classes_36k_train_014387
1,681
no_license
[ { "docstring": "Initialize class", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Creates a session ID", "name": "create_session", "signature": "def create_session(self, user_id=None)" }, { "docstring": "Returns a user ID for a given session ID", "na...
3
stack_v2_sparse_classes_30k_train_002308
Implement the Python class `SessionExpAuth` described below. Class description: Session expiration authentification methods Method signatures and docstrings: - def __init__(self): Initialize class - def create_session(self, user_id=None): Creates a session ID - def user_id_for_session_id(self, session_id=None): Retur...
Implement the Python class `SessionExpAuth` described below. Class description: Session expiration authentification methods Method signatures and docstrings: - def __init__(self): Initialize class - def create_session(self, user_id=None): Creates a session ID - def user_id_for_session_id(self, session_id=None): Retur...
151c5c063b15c8474c1fa4ab5ce27f94f36c42b5
<|skeleton|> class SessionExpAuth: """Session expiration authentification methods""" def __init__(self): """Initialize class""" <|body_0|> def create_session(self, user_id=None): """Creates a session ID""" <|body_1|> def user_id_for_session_id(self, session_id=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionExpAuth: """Session expiration authentification methods""" def __init__(self): """Initialize class""" try: session_duration = int(getenv('SESSION_DURATION')) except Exception: session_duration = 0 self.session_duration = session_duration ...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_exp_auth.py
Gzoref/holbertonschool-web_back_end
train
0
9086f73c862baf94f5f88a771a3da38584ce2846
[ "self.interval = interval\nthread = threading.Thread(target=self.run, args=())\nthread.start()", "while True:\n global uri\n daemon = Pyro4.Daemon()\n uri = daemon.register(Client)\n daemon.requestLoop()" ]
<|body_start_0|> self.interval = interval thread = threading.Thread(target=self.run, args=()) thread.start() <|end_body_0|> <|body_start_1|> while True: global uri daemon = Pyro4.Daemon() uri = daemon.register(Client) daemon.requestLoop() ...
Threading example class The run() method will be started and it will run in the background until the application exits.
ThreadingExample
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThreadingExample: """Threading example class The run() method will be started and it will run in the background until the application exits.""" def __init__(self, interval=1): """Constructor :type interval: int :param interval: Check interval, in seconds""" <|body_0|> de...
stack_v2_sparse_classes_36k_train_014388
3,896
permissive
[ { "docstring": "Constructor :type interval: int :param interval: Check interval, in seconds", "name": "__init__", "signature": "def __init__(self, interval=1)" }, { "docstring": "Method that runs forever", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_002665
Implement the Python class `ThreadingExample` described below. Class description: Threading example class The run() method will be started and it will run in the background until the application exits. Method signatures and docstrings: - def __init__(self, interval=1): Constructor :type interval: int :param interval:...
Implement the Python class `ThreadingExample` described below. Class description: Threading example class The run() method will be started and it will run in the background until the application exits. Method signatures and docstrings: - def __init__(self, interval=1): Constructor :type interval: int :param interval:...
0039e0eb5ad9b4e03e703c7c51295907fec6708d
<|skeleton|> class ThreadingExample: """Threading example class The run() method will be started and it will run in the background until the application exits.""" def __init__(self, interval=1): """Constructor :type interval: int :param interval: Check interval, in seconds""" <|body_0|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThreadingExample: """Threading example class The run() method will be started and it will run in the background until the application exits.""" def __init__(self, interval=1): """Constructor :type interval: int :param interval: Check interval, in seconds""" self.interval = interval ...
the_stack_v2_python_sparse
src/example_applications/client_constraint.py
mazerius/khronos
train
1
519127431cccfbb2ff502a3520b9ee554721da20
[ "super(HiveNamedPartitionSensor, self).__init__(host, port, **kwargs)\nself._table_name = table_name\nself._partition_names = partition_names", "with self._hive_metastore_client as client:\n try:\n for partition_name in self._partition_names:\n client.get_partition_by_name(self._schema, self....
<|body_start_0|> super(HiveNamedPartitionSensor, self).__init__(host, port, **kwargs) self._table_name = table_name self._partition_names = partition_names <|end_body_0|> <|body_start_1|> with self._hive_metastore_client as client: try: for partition_name in ...
HiveNamedPartitionSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HiveNamedPartitionSensor: def __init__(self, table_name, partition_names, host, port, **kwargs): """This class allows sensing for a specific named Hive Partition. This is the preferred partition sensing operator because it is more efficient than evaluating a filter expression. :param Tex...
stack_v2_sparse_classes_36k_train_014389
4,900
permissive
[ { "docstring": "This class allows sensing for a specific named Hive Partition. This is the preferred partition sensing operator because it is more efficient than evaluating a filter expression. :param Text table_name: The name of the table :param Text partition_name: The name of the partition to listen for (exa...
2
null
Implement the Python class `HiveNamedPartitionSensor` described below. Class description: Implement the HiveNamedPartitionSensor class. Method signatures and docstrings: - def __init__(self, table_name, partition_names, host, port, **kwargs): This class allows sensing for a specific named Hive Partition. This is the ...
Implement the Python class `HiveNamedPartitionSensor` described below. Class description: Implement the HiveNamedPartitionSensor class. Method signatures and docstrings: - def __init__(self, table_name, partition_names, host, port, **kwargs): This class allows sensing for a specific named Hive Partition. This is the ...
2eb9ce7aacaab6e49c1fc901c14c7b0d6b479523
<|skeleton|> class HiveNamedPartitionSensor: def __init__(self, table_name, partition_names, host, port, **kwargs): """This class allows sensing for a specific named Hive Partition. This is the preferred partition sensing operator because it is more efficient than evaluating a filter expression. :param Tex...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HiveNamedPartitionSensor: def __init__(self, table_name, partition_names, host, port, **kwargs): """This class allows sensing for a specific named Hive Partition. This is the preferred partition sensing operator because it is more efficient than evaluating a filter expression. :param Text table_name: ...
the_stack_v2_python_sparse
flytekit/contrib/sensors/impl.py
jbrambleDC/flytekit
train
1
1b7af39a5c162e424b89882d5a61d07c970bd236
[ "ap.fit.Beam.__init__(self, freqs)\nself.width = width\nself.length = length", "vec_n = np.array(xyz)\nvec_z = np.array([0.0, 0.0, 1.0])\nnz = np.dot(vec_n, vec_z)\nif nz <= 0:\n return 0.0\nelse:\n vec_u = np.array([1.0, 0.0, 0.0])\n vec_v = np.array([0.0, 1.0, 0.0])\n nu = np.dot(vec_n, vec_u)\n ...
<|body_start_0|> ap.fit.Beam.__init__(self, freqs) self.width = width self.length = length <|end_body_0|> <|body_start_1|> vec_n = np.array(xyz) vec_z = np.array([0.0, 0.0, 1.0]) nz = np.dot(vec_n, vec_z) if nz <= 0: return 0.0 else: ...
Represent the cylinder parabolic antenna beam.
BeamCylinder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BeamCylinder: """Represent the cylinder parabolic antenna beam.""" def __init__(self, freqs, width, length=0.0): """Arguments: - `freqs`: frequencies (in GHz) at bin centers across spectrum.; - `width`: the cylinder width (EW direction), in unit m; - `length`: the spacing between too...
stack_v2_sparse_classes_36k_train_014390
12,022
no_license
[ { "docstring": "Arguments: - `freqs`: frequencies (in GHz) at bin centers across spectrum.; - `width`: the cylinder width (EW direction), in unit m; - `length`: the spacing between too feeds (NS direction), in unit m.", "name": "__init__", "signature": "def __init__(self, freqs, width, length=0.0)" },...
2
stack_v2_sparse_classes_30k_train_004362
Implement the Python class `BeamCylinder` described below. Class description: Represent the cylinder parabolic antenna beam. Method signatures and docstrings: - def __init__(self, freqs, width, length=0.0): Arguments: - `freqs`: frequencies (in GHz) at bin centers across spectrum.; - `width`: the cylinder width (EW d...
Implement the Python class `BeamCylinder` described below. Class description: Represent the cylinder parabolic antenna beam. Method signatures and docstrings: - def __init__(self, freqs, width, length=0.0): Arguments: - `freqs`: frequencies (in GHz) at bin centers across spectrum.; - `width`: the cylinder width (EW d...
7d2fe26a80abd165cc8fe13ccd2115cfa9b32232
<|skeleton|> class BeamCylinder: """Represent the cylinder parabolic antenna beam.""" def __init__(self, freqs, width, length=0.0): """Arguments: - `freqs`: frequencies (in GHz) at bin centers across spectrum.; - `width`: the cylinder width (EW direction), in unit m; - `length`: the spacing between too...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BeamCylinder: """Represent the cylinder parabolic antenna beam.""" def __init__(self, freqs, width, length=0.0): """Arguments: - `freqs`: frequencies (in GHz) at bin centers across spectrum.; - `width`: the cylinder width (EW direction), in unit m; - `length`: the spacing between too feeds (NS di...
the_stack_v2_python_sparse
src/cylinder.py
zuoshifan/TianlaiSim
train
0
5abe3ea4b8896ca7082c89be224152eec67140fb
[ "self.attempt_number = attempt_number\nself.delta_size_bytes = delta_size_bytes\nself.indexing_status = indexing_status\nself.is_app_consistent = is_app_consistent\nself.is_full_backup = is_full_backup\nself.job_run_id = job_run_id\nself.local_mount_path = local_mount_path\nself.logical_size_bytes = logical_size_by...
<|body_start_0|> self.attempt_number = attempt_number self.delta_size_bytes = delta_size_bytes self.indexing_status = indexing_status self.is_app_consistent = is_app_consistent self.is_full_backup = is_full_backup self.job_run_id = job_run_id self.local_mount_path...
Implementation of the 'SnapshotVersion' model. Specifies information about snapshots of a backup object. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successfully captured after three attempts, this fi...
SnapshotVersion
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnapshotVersion: """Implementation of the 'SnapshotVersion' model. Specifies information about snapshots of a backup object. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successf...
stack_v2_sparse_classes_36k_train_014391
7,459
permissive
[ { "docstring": "Constructor for the SnapshotVersion class", "name": "__init__", "signature": "def __init__(self, attempt_number=None, delta_size_bytes=None, indexing_status=None, is_app_consistent=None, is_full_backup=None, job_run_id=None, local_mount_path=None, logical_size_bytes=None, physical_size_b...
2
null
Implement the Python class `SnapshotVersion` described below. Class description: Implementation of the 'SnapshotVersion' model. Specifies information about snapshots of a backup object. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. ...
Implement the Python class `SnapshotVersion` described below. Class description: Implementation of the 'SnapshotVersion' model. Specifies information about snapshots of a backup object. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class SnapshotVersion: """Implementation of the 'SnapshotVersion' model. Specifies information about snapshots of a backup object. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successf...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnapshotVersion: """Implementation of the 'SnapshotVersion' model. Specifies information about snapshots of a backup object. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successfully captured...
the_stack_v2_python_sparse
cohesity_management_sdk/models/snapshot_version.py
cohesity/management-sdk-python
train
24
91a8c173d38077969ad7e6248ed289583bc40360
[ "command = config.editor\nif jumpIndex:\n line = text[:jumpIndex].count('\\n')\n column = jumpIndex - (text[:jumpIndex].rfind('\\n') + 1)\nelse:\n line = column = 0\nif config.editor.startswith('kate'):\n command += ' -l %i -c %i' % (line + 1, column + 1)\nelif config.editor.startswith('gedit'):\n co...
<|body_start_0|> command = config.editor if jumpIndex: line = text[:jumpIndex].count('\n') column = jumpIndex - (text[:jumpIndex].rfind('\n') + 1) else: line = column = 0 if config.editor.startswith('kate'): command += ' -l %i -c %i' % (lin...
Text editor.
TextEditor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextEditor: """Text editor.""" def command(self, tempFilename, text, jumpIndex=None): """Return editor selected in user-config.py.""" <|body_0|> def convertLinebreaks(self, text): """Convert line-breaks.""" <|body_1|> def restoreLinebreaks(self, text...
stack_v2_sparse_classes_36k_train_014392
4,743
permissive
[ { "docstring": "Return editor selected in user-config.py.", "name": "command", "signature": "def command(self, tempFilename, text, jumpIndex=None)" }, { "docstring": "Convert line-breaks.", "name": "convertLinebreaks", "signature": "def convertLinebreaks(self, text)" }, { "docstr...
4
stack_v2_sparse_classes_30k_train_019743
Implement the Python class `TextEditor` described below. Class description: Text editor. Method signatures and docstrings: - def command(self, tempFilename, text, jumpIndex=None): Return editor selected in user-config.py. - def convertLinebreaks(self, text): Convert line-breaks. - def restoreLinebreaks(self, text): R...
Implement the Python class `TextEditor` described below. Class description: Text editor. Method signatures and docstrings: - def command(self, tempFilename, text, jumpIndex=None): Return editor selected in user-config.py. - def convertLinebreaks(self, text): Convert line-breaks. - def restoreLinebreaks(self, text): R...
2461ccc6d24153790a1b1c0378348f99997c4eca
<|skeleton|> class TextEditor: """Text editor.""" def command(self, tempFilename, text, jumpIndex=None): """Return editor selected in user-config.py.""" <|body_0|> def convertLinebreaks(self, text): """Convert line-breaks.""" <|body_1|> def restoreLinebreaks(self, text...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextEditor: """Text editor.""" def command(self, tempFilename, text, jumpIndex=None): """Return editor selected in user-config.py.""" command = config.editor if jumpIndex: line = text[:jumpIndex].count('\n') column = jumpIndex - (text[:jumpIndex].rfind('\n'...
the_stack_v2_python_sparse
pywikibot/editor.py
speedydeletion/pywikibot
train
1
032133a028228459d6333aa26c0fa1b825308a76
[ "generations = []\ntask_index = 0\nprevious_generations = None\nfor _ in range(NUMBER_OF_GENERATIONS):\n test_ranges = range(task_index, task_index + NUMBER_OF_TASKS)\n tasks = [IdentifierMockTask(STEERING_TEST_STAGE, t) for t in test_ranges]\n steering_tasks = set(tasks)\n current_generation = MockGene...
<|body_start_0|> generations = [] task_index = 0 previous_generations = None for _ in range(NUMBER_OF_GENERATIONS): test_ranges = range(task_index, task_index + NUMBER_OF_TASKS) tasks = [IdentifierMockTask(STEERING_TEST_STAGE, t) for t in test_ranges] ...
This class test the steering method. The steering algorithm should return if there is no new task in the initial generation. The steering algorithm should send all the tasks to the next stage and should terminate once there is no pending generation. A generation is pending if it contains pending task. A task is pending...
SteeringTest
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SteeringTest: """This class test the steering method. The steering algorithm should return if there is no new task in the initial generation. The steering algorithm should send all the tasks to the next stage and should terminate once there is no pending generation. A generation is pending if it ...
stack_v2_sparse_classes_36k_train_014393
5,497
permissive
[ { "docstring": "Test that the steering algorithm processes all the tasks properly. Test that the steering algorithm sends all the tasks to the next stage. Test that the steering algorithm terminates once all the tasks have been processed, i.e., the results for the tasks are all ready.", "name": "testSteerin...
2
null
Implement the Python class `SteeringTest` described below. Class description: This class test the steering method. The steering algorithm should return if there is no new task in the initial generation. The steering algorithm should send all the tasks to the next stage and should terminate once there is no pending gen...
Implement the Python class `SteeringTest` described below. Class description: This class test the steering method. The steering algorithm should return if there is no new task in the initial generation. The steering algorithm should send all the tasks to the next stage and should terminate once there is no pending gen...
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
<|skeleton|> class SteeringTest: """This class test the steering method. The steering algorithm should return if there is no new task in the initial generation. The steering algorithm should send all the tasks to the next stage and should terminate once there is no pending generation. A generation is pending if it ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SteeringTest: """This class test the steering method. The steering algorithm should return if there is no new task in the initial generation. The steering algorithm should send all the tasks to the next stage and should terminate once there is no pending generation. A generation is pending if it contains pend...
the_stack_v2_python_sparse
app/src/main/java/com/syd/source/aosp/external/toolchain-utils/bestflags/steering_test.py
lz-purple/Source
train
4
3b3124f2bcf27e33bedb4e9360e4a4fa1eb5dc21
[ "self.internal_dict = {}\nfor i in dictionary.items():\n self.internal_dict[i[0]] = i[1]", "result = 0\nfor i in self.internal_dict.items():\n result += hash(i[0]) + hash(i[1])\nreturn result", "for i in self.internal_dict.items():\n if d.internal_dict[i[0]] != i[1]:\n return False\nreturn True"...
<|body_start_0|> self.internal_dict = {} for i in dictionary.items(): self.internal_dict[i[0]] = i[1] <|end_body_0|> <|body_start_1|> result = 0 for i in self.internal_dict.items(): result += hash(i[0]) + hash(i[1]) return result <|end_body_1|> <|body_st...
Odpowiednik frozenset dla zbiorów, czyli słownik, który nie jest modyfikowalny, a dzięki temu może być np. elementem zbiorów, albo kluczem w innym słowniku.
FrozenDictionary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrozenDictionary: """Odpowiednik frozenset dla zbiorów, czyli słownik, który nie jest modyfikowalny, a dzięki temu może być np. elementem zbiorów, albo kluczem w innym słowniku.""" def __init__(self, dictionary): """Tworzy nowy zamrożony słownik z podanego słownika""" <|body_...
stack_v2_sparse_classes_36k_train_014394
4,370
no_license
[ { "docstring": "Tworzy nowy zamrożony słownik z podanego słownika", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": "Zwraca hasz słownika (int)", "name": "__hash__", "signature": "def __hash__(self)" }, { "docstring": "Porównuje nasz słownik z ...
4
stack_v2_sparse_classes_30k_train_019396
Implement the Python class `FrozenDictionary` described below. Class description: Odpowiednik frozenset dla zbiorów, czyli słownik, który nie jest modyfikowalny, a dzięki temu może być np. elementem zbiorów, albo kluczem w innym słowniku. Method signatures and docstrings: - def __init__(self, dictionary): Tworzy nowy...
Implement the Python class `FrozenDictionary` described below. Class description: Odpowiednik frozenset dla zbiorów, czyli słownik, który nie jest modyfikowalny, a dzięki temu może być np. elementem zbiorów, albo kluczem w innym słowniku. Method signatures and docstrings: - def __init__(self, dictionary): Tworzy nowy...
cb0ff06a6b94ef5aa23adcfd2672365ceecaab56
<|skeleton|> class FrozenDictionary: """Odpowiednik frozenset dla zbiorów, czyli słownik, który nie jest modyfikowalny, a dzięki temu może być np. elementem zbiorów, albo kluczem w innym słowniku.""" def __init__(self, dictionary): """Tworzy nowy zamrożony słownik z podanego słownika""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrozenDictionary: """Odpowiednik frozenset dla zbiorów, czyli słownik, który nie jest modyfikowalny, a dzięki temu może być np. elementem zbiorów, albo kluczem w innym słowniku.""" def __init__(self, dictionary): """Tworzy nowy zamrożony słownik z podanego słownika""" self.internal_dict =...
the_stack_v2_python_sparse
labs/lab_5.py
MichalSzewczyk/python-learning
train
0
d482198d2918ff18e254e2be319fa6ce6e5e1274
[ "if not value:\n return []\nif isinstance(value, basestring):\n values = value.split(',')\n return [x.strip() for x in values if x.strip()]\nelse:\n return value", "super(MultiEmailField, self).validate(value)\nfor email in value:\n validate_email(email)" ]
<|body_start_0|> if not value: return [] if isinstance(value, basestring): values = value.split(',') return [x.strip() for x in values if x.strip()] else: return value <|end_body_0|> <|body_start_1|> super(MultiEmailField, self).validate(v...
MultiEmailField
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiEmailField: def to_python(self, value): """Normalize data to a list of strings.""" <|body_0|> def validate(self, value): """Check if value consists only of valid emails.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not value: ...
stack_v2_sparse_classes_36k_train_014395
3,815
permissive
[ { "docstring": "Normalize data to a list of strings.", "name": "to_python", "signature": "def to_python(self, value)" }, { "docstring": "Check if value consists only of valid emails.", "name": "validate", "signature": "def validate(self, value)" } ]
2
stack_v2_sparse_classes_30k_train_011678
Implement the Python class `MultiEmailField` described below. Class description: Implement the MultiEmailField class. Method signatures and docstrings: - def to_python(self, value): Normalize data to a list of strings. - def validate(self, value): Check if value consists only of valid emails.
Implement the Python class `MultiEmailField` described below. Class description: Implement the MultiEmailField class. Method signatures and docstrings: - def to_python(self, value): Normalize data to a list of strings. - def validate(self, value): Check if value consists only of valid emails. <|skeleton|> class Mult...
aeaae292fbd55aca1b6043227ec105e67d73367f
<|skeleton|> class MultiEmailField: def to_python(self, value): """Normalize data to a list of strings.""" <|body_0|> def validate(self, value): """Check if value consists only of valid emails.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiEmailField: def to_python(self, value): """Normalize data to a list of strings.""" if not value: return [] if isinstance(value, basestring): values = value.split(',') return [x.strip() for x in values if x.strip()] else: retu...
the_stack_v2_python_sparse
ietf/utils/fields.py
omunroe-com/ietfdb2
train
2
53b4a1cbbf1dd4744a57e15fb25741cbbf2c088d
[ "response = self.client.get(reverse('polls:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'No polls available.')\nself.assertQuerysetEqual(response.context['questions'], [])", "time = timezone.now()\ncreate_question('Question_1', -5)\ncreate_question('Question_2', -1)\nrespon...
<|body_start_0|> response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'No polls available.') self.assertQuerysetEqual(response.context['questions'], []) <|end_body_0|> <|body_start_1|> time = timezone.now() ...
QuestionIndexViewTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuestionIndexViewTests: def test_index_view_with_no_questions(self): """If no questions exist, an appropriate message should be displayed.""" <|body_0|> def test_index_view_with_past_questions(self): """If questions exist with pub_date in the past, they should be vis...
stack_v2_sparse_classes_36k_train_014396
4,246
no_license
[ { "docstring": "If no questions exist, an appropriate message should be displayed.", "name": "test_index_view_with_no_questions", "signature": "def test_index_view_with_no_questions(self)" }, { "docstring": "If questions exist with pub_date in the past, they should be visible in the view.", ...
3
null
Implement the Python class `QuestionIndexViewTests` described below. Class description: Implement the QuestionIndexViewTests class. Method signatures and docstrings: - def test_index_view_with_no_questions(self): If no questions exist, an appropriate message should be displayed. - def test_index_view_with_past_questi...
Implement the Python class `QuestionIndexViewTests` described below. Class description: Implement the QuestionIndexViewTests class. Method signatures and docstrings: - def test_index_view_with_no_questions(self): If no questions exist, an appropriate message should be displayed. - def test_index_view_with_past_questi...
acbb6d21a8182feabcb3329e17c76ac3af375255
<|skeleton|> class QuestionIndexViewTests: def test_index_view_with_no_questions(self): """If no questions exist, an appropriate message should be displayed.""" <|body_0|> def test_index_view_with_past_questions(self): """If questions exist with pub_date in the past, they should be vis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuestionIndexViewTests: def test_index_view_with_no_questions(self): """If no questions exist, an appropriate message should be displayed.""" response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'No polls a...
the_stack_v2_python_sparse
pythonTutorial/django/mysite/polls/tests.py
rajatgirotra/study
train
6
0f645ee91782f286c68d418dd060752e7354a76d
[ "for entry in self._async_current_entries():\n if entry.data.get(CONF_HOST) == host and entry.data[CONF_PORT] == port:\n if updates is not None:\n changed = self.hass.config_entries.async_update_entry(entry, data={**entry.data, **updates})\n if changed and reload_on_update and (entry...
<|body_start_0|> for entry in self._async_current_entries(): if entry.data.get(CONF_HOST) == host and entry.data[CONF_PORT] == port: if updates is not None: changed = self.hass.config_entries.async_update_entry(entry, data={**entry.data, **updates}) ...
Handle a config flow for DSMR.
DSMRFlowHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DSMRFlowHandler: """Handle a config flow for DSMR.""" def _abort_if_host_port_configured(self, port: str, host: str=None, updates: Optional[Dict[Any, Any]]=None, reload_on_update: bool=True): """Test if host and port are already configured.""" <|body_0|> async def async_...
stack_v2_sparse_classes_36k_train_014397
6,055
permissive
[ { "docstring": "Test if host and port are already configured.", "name": "_abort_if_host_port_configured", "signature": "def _abort_if_host_port_configured(self, port: str, host: str=None, updates: Optional[Dict[Any, Any]]=None, reload_on_update: bool=True)" }, { "docstring": "Handle the initial ...
2
stack_v2_sparse_classes_30k_train_001505
Implement the Python class `DSMRFlowHandler` described below. Class description: Handle a config flow for DSMR. Method signatures and docstrings: - def _abort_if_host_port_configured(self, port: str, host: str=None, updates: Optional[Dict[Any, Any]]=None, reload_on_update: bool=True): Test if host and port are alread...
Implement the Python class `DSMRFlowHandler` described below. Class description: Handle a config flow for DSMR. Method signatures and docstrings: - def _abort_if_host_port_configured(self, port: str, host: str=None, updates: Optional[Dict[Any, Any]]=None, reload_on_update: bool=True): Test if host and port are alread...
ed4ab403deaed9e8c95e0db728477fcb012bf4fa
<|skeleton|> class DSMRFlowHandler: """Handle a config flow for DSMR.""" def _abort_if_host_port_configured(self, port: str, host: str=None, updates: Optional[Dict[Any, Any]]=None, reload_on_update: bool=True): """Test if host and port are already configured.""" <|body_0|> async def async_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DSMRFlowHandler: """Handle a config flow for DSMR.""" def _abort_if_host_port_configured(self, port: str, host: str=None, updates: Optional[Dict[Any, Any]]=None, reload_on_update: bool=True): """Test if host and port are already configured.""" for entry in self._async_current_entries(): ...
the_stack_v2_python_sparse
homeassistant/components/dsmr/config_flow.py
tchellomello/home-assistant
train
8
eb329a3c3167ea5b7392eeeda6985c37d3a3b532
[ "classes = {b'\\xff': Header, b'[': Package}\nif not packetPrefix in classes:\n return None\nreturn classes[packetPrefix]", "if data is None:\n return\npacketPrefix = data[:1]\nCLASS = self.getClass(packetPrefix)\nif not CLASS:\n raise Exception('Packet %s is not found' % binascii.hexlify(packetPrefix).d...
<|body_start_0|> classes = {b'\xff': Header, b'[': Package} if not packetPrefix in classes: return None return classes[packetPrefix] <|end_body_0|> <|body_start_1|> if data is None: return packetPrefix = data[:1] CLASS = self.getClass(packetPrefix...
Packet factory
PacketFactory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PacketFactory: """Packet factory""" def getClass(cls, packetPrefix): """Returns a tag class by number @param packetPrefix: one byte buffer""" <|body_0|> def getInstance(self, data=None): """Returns a tag instance by its number""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_014398
15,657
no_license
[ { "docstring": "Returns a tag class by number @param packetPrefix: one byte buffer", "name": "getClass", "signature": "def getClass(cls, packetPrefix)" }, { "docstring": "Returns a tag instance by its number", "name": "getInstance", "signature": "def getInstance(self, data=None)" } ]
2
stack_v2_sparse_classes_30k_train_004592
Implement the Python class `PacketFactory` described below. Class description: Packet factory Method signatures and docstrings: - def getClass(cls, packetPrefix): Returns a tag class by number @param packetPrefix: one byte buffer - def getInstance(self, data=None): Returns a tag instance by its number
Implement the Python class `PacketFactory` described below. Class description: Packet factory Method signatures and docstrings: - def getClass(cls, packetPrefix): Returns a tag class by number @param packetPrefix: one byte buffer - def getInstance(self, data=None): Returns a tag instance by its number <|skeleton|> c...
4a4bc730252ece695b2773388812e2d59d4947ce
<|skeleton|> class PacketFactory: """Packet factory""" def getClass(cls, packetPrefix): """Returns a tag class by number @param packetPrefix: one byte buffer""" <|body_0|> def getInstance(self, data=None): """Returns a tag instance by its number""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PacketFactory: """Packet factory""" def getClass(cls, packetPrefix): """Returns a tag class by number @param packetPrefix: one byte buffer""" classes = {b'\xff': Header, b'[': Package} if not packetPrefix in classes: return None return classes[packetPrefix] ...
the_stack_v2_python_sparse
lib/handlers/autolink/packets.py
maprox/pipe
train
4
3fbb41778a5cb4febca5f851543837f52ddf960c
[ "if not isinstance(vref_vs_tau, list):\n vref_vs_tau = [vref_vs_tau]\nif len(vref_vs_tau) == 1:\n plt.plot(vref_vs_tau[0][:, 0], vref_vs_tau[0][:, 1], 'k')\nelse:\n for vref in vref_vs_tau:\n plt.plot(vref[:, 0], vref[:, 1])\nplt.xlabel('Time (a.u.)')\nplt.ylabel('$\\\\mathrm{E_{ref}}$ ($\\\\mathrm{...
<|body_start_0|> if not isinstance(vref_vs_tau, list): vref_vs_tau = [vref_vs_tau] if len(vref_vs_tau) == 1: plt.plot(vref_vs_tau[0][:, 0], vref_vs_tau[0][:, 1], 'k') else: for vref in vref_vs_tau: plt.plot(vref[:, 0], vref[:, 1]) plt.x...
A very basic plotting class that will use matplotlib to generate various plots using results from PyVibDMC/AnalyzeWfn/SimInfo.
Plotter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Plotter: """A very basic plotting class that will use matplotlib to generate various plots using results from PyVibDMC/AnalyzeWfn/SimInfo.""" def plt_vref_vs_tau(vref_vs_tau, save_name='vref_vs_tau.png'): """Takes in the vref vs tau array from a DMC sim and plots it. Can also take in...
stack_v2_sparse_classes_36k_train_014399
4,642
permissive
[ { "docstring": "Takes in the vref vs tau array from a DMC sim and plots it. Can also take in many vref_vs_tau arrays and plot them successively :param vref_vs_tau: The vref_vs_tau array from the *sim_info.hdf5 file. Can be a list of these as well. :type vref_vs_tau: str or list :param save_name: The name of the...
4
stack_v2_sparse_classes_30k_train_002370
Implement the Python class `Plotter` described below. Class description: A very basic plotting class that will use matplotlib to generate various plots using results from PyVibDMC/AnalyzeWfn/SimInfo. Method signatures and docstrings: - def plt_vref_vs_tau(vref_vs_tau, save_name='vref_vs_tau.png'): Takes in the vref v...
Implement the Python class `Plotter` described below. Class description: A very basic plotting class that will use matplotlib to generate various plots using results from PyVibDMC/AnalyzeWfn/SimInfo. Method signatures and docstrings: - def plt_vref_vs_tau(vref_vs_tau, save_name='vref_vs_tau.png'): Takes in the vref v...
c8ef4970d91d32f08fd938de4d2bcbc1fa7f81b4
<|skeleton|> class Plotter: """A very basic plotting class that will use matplotlib to generate various plots using results from PyVibDMC/AnalyzeWfn/SimInfo.""" def plt_vref_vs_tau(vref_vs_tau, save_name='vref_vs_tau.png'): """Takes in the vref vs tau array from a DMC sim and plots it. Can also take in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Plotter: """A very basic plotting class that will use matplotlib to generate various plots using results from PyVibDMC/AnalyzeWfn/SimInfo.""" def plt_vref_vs_tau(vref_vs_tau, save_name='vref_vs_tau.png'): """Takes in the vref vs tau array from a DMC sim and plots it. Can also take in many vref_vs...
the_stack_v2_python_sparse
pyvibdmc/analysis/plotter.py
rjdirisio/pyvibdmc
train
10