blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
11ef01f03025f4049d8a9c4b631680f48a632216
[ "self.operands: List[Operand] = list(operands)\nfor i in range(len(self.operands)):\n self.operands[i] = Operand.validate_operand(self.operands[i])\nsuper().__init__()", "incomplete_expression = False\nfor operand in self.operands:\n if not issubclass(type(operand), Operand):\n raise RuntimeError(f'O...
<|body_start_0|> self.operands: List[Operand] = list(operands) for i in range(len(self.operands)): self.operands[i] = Operand.validate_operand(self.operands[i]) super().__init__() <|end_body_0|> <|body_start_1|> incomplete_expression = False for operand in self.opera...
And operator class for filtering JumpStart content.
And
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class And: """And operator class for filtering JumpStart content.""" def __init__(self, *operands: Union[Operand, str]) -> None: """Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated.""" <|body_0|> d...
stack_v2_sparse_classes_75kplus_train_009100
16,623
permissive
[ { "docstring": "Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated.", "name": "__init__", "signature": "def __init__(self, *operands: Union[Operand, str]) -> None" }, { "docstring": "Evaluates operator. Raises: Runtime...
3
stack_v2_sparse_classes_30k_train_032965
Implement the Python class `And` described below. Class description: And operator class for filtering JumpStart content. Method signatures and docstrings: - def __init__(self, *operands: Union[Operand, str]) -> None: Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the o...
Implement the Python class `And` described below. Class description: And operator class for filtering JumpStart content. Method signatures and docstrings: - def __init__(self, *operands: Union[Operand, str]) -> None: Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the o...
8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85
<|skeleton|> class And: """And operator class for filtering JumpStart content.""" def __init__(self, *operands: Union[Operand, str]) -> None: """Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated.""" <|body_0|> d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class And: """And operator class for filtering JumpStart content.""" def __init__(self, *operands: Union[Operand, str]) -> None: """Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated.""" self.operands: List[Operand] =...
the_stack_v2_python_sparse
src/sagemaker/jumpstart/filters.py
aws/sagemaker-python-sdk
train
2,050
448505e7ae0e80d6a293fbe24ffb03f0408df040
[ "super(Position, self).__init__()\nself.dropout = nn.Dropout(p=dropout)\nself.vocabSize = vocabSize\nself.embSize = embSize", "inputs = inputs.transpose(0, 1)\npos = torch.zeros(self.vocabSize, self.embSize)\nposition = torch.arange(0, self.vocabSize, dtype=torch.float).unsqueeze(1)\ndiv = torch.exp(torch.arange(...
<|body_start_0|> super(Position, self).__init__() self.dropout = nn.Dropout(p=dropout) self.vocabSize = vocabSize self.embSize = embSize <|end_body_0|> <|body_start_1|> inputs = inputs.transpose(0, 1) pos = torch.zeros(self.vocabSize, self.embSize) position = tor...
Position
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Position: def __init__(self, vocabSize, embSize, dropout=dropout): """@doc: 该类负责生成输出序列的位置编码信息,并与原输入(已通过词嵌入层)相加后返回 @author: Alpaca-Man @date: 2021/2/22 @param: { vocabSize: 单词表长度 (=enVocabSize or deVocabSize) embSize: Position Encoding 出的维度(=embSize) } @return: { }""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_009101
13,592
no_license
[ { "docstring": "@doc: 该类负责生成输出序列的位置编码信息,并与原输入(已通过词嵌入层)相加后返回 @author: Alpaca-Man @date: 2021/2/22 @param: { vocabSize: 单词表长度 (=enVocabSize or deVocabSize) embSize: Position Encoding 出的维度(=embSize) } @return: { }", "name": "__init__", "signature": "def __init__(self, vocabSize, embSize, dropout=dropout)" ...
2
stack_v2_sparse_classes_30k_train_006245
Implement the Python class `Position` described below. Class description: Implement the Position class. Method signatures and docstrings: - def __init__(self, vocabSize, embSize, dropout=dropout): @doc: 该类负责生成输出序列的位置编码信息,并与原输入(已通过词嵌入层)相加后返回 @author: Alpaca-Man @date: 2021/2/22 @param: { vocabSize: 单词表长度 (=enVocabSize...
Implement the Python class `Position` described below. Class description: Implement the Position class. Method signatures and docstrings: - def __init__(self, vocabSize, embSize, dropout=dropout): @doc: 该类负责生成输出序列的位置编码信息,并与原输入(已通过词嵌入层)相加后返回 @author: Alpaca-Man @date: 2021/2/22 @param: { vocabSize: 单词表长度 (=enVocabSize...
49824925970f0439634dc66a7f19edc512f18a5f
<|skeleton|> class Position: def __init__(self, vocabSize, embSize, dropout=dropout): """@doc: 该类负责生成输出序列的位置编码信息,并与原输入(已通过词嵌入层)相加后返回 @author: Alpaca-Man @date: 2021/2/22 @param: { vocabSize: 单词表长度 (=enVocabSize or deVocabSize) embSize: Position Encoding 出的维度(=embSize) } @return: { }""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Position: def __init__(self, vocabSize, embSize, dropout=dropout): """@doc: 该类负责生成输出序列的位置编码信息,并与原输入(已通过词嵌入层)相加后返回 @author: Alpaca-Man @date: 2021/2/22 @param: { vocabSize: 单词表长度 (=enVocabSize or deVocabSize) embSize: Position Encoding 出的维度(=embSize) } @return: { }""" super(Position, self).__in...
the_stack_v2_python_sparse
Transformer/standard/Math.py
Alpaca-Man/NLP-Newcomer
train
1
9e47d023686ece645382a63815da1c5e97720387
[ "super(BitVectorSFEWrapper, self).__init__()\nself.agent = agent\nself.baseline_type = baseline_type", "scores = self.agent(*args, **kwargs)\ndistr = Bernoulli(logits=scores)\nentropy = distr.entropy().sum(dim=1)\nsample = distr.sample()\nreturn (sample, scores, entropy)" ]
<|body_start_0|> super(BitVectorSFEWrapper, self).__init__() self.agent = agent self.baseline_type = baseline_type <|end_body_0|> <|body_start_1|> scores = self.agent(*args, **kwargs) distr = Bernoulli(logits=scores) entropy = distr.entropy().sum(dim=1) sample = ...
SFE Wrapper for a network that parameterizes independent Bernoulli distributions. Assumes that the during the forward pass, the network returns scores for the Bernoulli parameters. The wrapper transforms them into a tuple of (sample from the Bernoulli, log-prob of the sample, entropy for the independent Bernoulli).
BitVectorSFEWrapper
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BitVectorSFEWrapper: """SFE Wrapper for a network that parameterizes independent Bernoulli distributions. Assumes that the during the forward pass, the network returns scores for the Bernoulli parameters. The wrapper transforms them into a tuple of (sample from the Bernoulli, log-prob of the samp...
stack_v2_sparse_classes_75kplus_train_009102
10,120
permissive
[ { "docstring": "Arguments: agent -- The agent to be wrapped. agent.forward() has to output scores for each Bernoulli baseline_type {str} -- which baseline to use. Either 'runavg' or 'sample'.", "name": "__init__", "signature": "def __init__(self, agent, baseline_type)" }, { "docstring": "Forward...
2
stack_v2_sparse_classes_30k_train_025017
Implement the Python class `BitVectorSFEWrapper` described below. Class description: SFE Wrapper for a network that parameterizes independent Bernoulli distributions. Assumes that the during the forward pass, the network returns scores for the Bernoulli parameters. The wrapper transforms them into a tuple of (sample f...
Implement the Python class `BitVectorSFEWrapper` described below. Class description: SFE Wrapper for a network that parameterizes independent Bernoulli distributions. Assumes that the during the forward pass, the network returns scores for the Bernoulli parameters. The wrapper transforms them into a tuple of (sample f...
e161e55432f5e30fedf7eae8ae11189c01bcd54a
<|skeleton|> class BitVectorSFEWrapper: """SFE Wrapper for a network that parameterizes independent Bernoulli distributions. Assumes that the during the forward pass, the network returns scores for the Bernoulli parameters. The wrapper transforms them into a tuple of (sample from the Bernoulli, log-prob of the samp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BitVectorSFEWrapper: """SFE Wrapper for a network that parameterizes independent Bernoulli distributions. Assumes that the during the forward pass, the network returns scores for the Bernoulli parameters. The wrapper transforms them into a tuple of (sample from the Bernoulli, log-prob of the sample, entropy f...
the_stack_v2_python_sparse
mnist_ssvae/lvmhelpers/sfe.py
Zirui0623/EvSoftmax
train
0
6c466735505a7f34bd2a953f7b30d61c22164565
[ "fs = fs or self.fs\nassert fs is not None and fs > 0, '`fs` must be positive'\nassert granularity > 0, '`granularity` must be positive'\nif not hasattr(self, 'sleep_stage_names'):\n assert class_map is not None, '`class_map` must be provided'\nelse:\n class_map = class_map or {k: len(self.sleep_stage_names) ...
<|body_start_0|> fs = fs or self.fs assert fs is not None and fs > 0, '`fs` must be positive' assert granularity > 0, '`granularity` must be positive' if not hasattr(self, 'sleep_stage_names'): assert class_map is not None, '`class_map` must be provided' else: ...
A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting
PSGDataBaseMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PSGDataBaseMixin: """A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting""" def sleep_stage_intervals_to_mask(self, intervals: Dict[str, List[List[int]]], fs: Optional[int]=None, granularity: int=30, cla...
stack_v2_sparse_classes_75kplus_train_009103
49,393
permissive
[ { "docstring": "Convert sleep stage intervals to sleep stage mask. Parameters ---------- intervals : dict Sleep stage intervals, in the format of dict of list of lists of int. Keys are sleep stages and values are lists of lists of start and end indices of the sleep stages. fs : int, optional Sampling frequency ...
2
stack_v2_sparse_classes_30k_train_002965
Implement the Python class `PSGDataBaseMixin` described below. Class description: A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting Method signatures and docstrings: - def sleep_stage_intervals_to_mask(self, intervals: Dict[str...
Implement the Python class `PSGDataBaseMixin` described below. Class description: A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting Method signatures and docstrings: - def sleep_stage_intervals_to_mask(self, intervals: Dict[str...
a40c65f4fefa83ba7d3d184072a4c05627b7e226
<|skeleton|> class PSGDataBaseMixin: """A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting""" def sleep_stage_intervals_to_mask(self, intervals: Dict[str, List[List[int]]], fs: Optional[int]=None, granularity: int=30, cla...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PSGDataBaseMixin: """A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting""" def sleep_stage_intervals_to_mask(self, intervals: Dict[str, List[List[int]]], fs: Optional[int]=None, granularity: int=30, class_map: Optio...
the_stack_v2_python_sparse
torch_ecg/databases/base.py
DeepPSP/torch_ecg
train
111
065a333c7e98a7e2387df0f73a6e6ec2bb96106a
[ "self.change_status_accum(form)\nself.data_collect_terminal_remark(form)\nreturn super().form_valid(form)", "accum_in_form = form.cleaned_data['accumulator']\nif DataCollectTerminal.objects.filter(name=form.cleaned_data['name']):\n accum_in_db = DataCollectTerminal.objects.get(slug=self.object.slug).accumulato...
<|body_start_0|> self.change_status_accum(form) self.data_collect_terminal_remark(form) return super().form_valid(form) <|end_body_0|> <|body_start_1|> accum_in_form = form.cleaned_data['accumulator'] if DataCollectTerminal.objects.filter(name=form.cleaned_data['name']): ...
Extension when creating and updating a terminal to change the battery status.
ModifiedMethodFormValidMixim
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModifiedMethodFormValidMixim: """Extension when creating and updating a terminal to change the battery status.""" def form_valid(self, form): """Redefined method for enabling business logic when creating and modifying data collect terminals.""" <|body_0|> def change_stat...
stack_v2_sparse_classes_75kplus_train_009104
3,556
no_license
[ { "docstring": "Redefined method for enabling business logic when creating and modifying data collect terminals.", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "Called to change the state of the battery. Possible states: 1. Installed 2. Uninstalled", "nam...
3
stack_v2_sparse_classes_30k_train_047768
Implement the Python class `ModifiedMethodFormValidMixim` described below. Class description: Extension when creating and updating a terminal to change the battery status. Method signatures and docstrings: - def form_valid(self, form): Redefined method for enabling business logic when creating and modifying data coll...
Implement the Python class `ModifiedMethodFormValidMixim` described below. Class description: Extension when creating and updating a terminal to change the battery status. Method signatures and docstrings: - def form_valid(self, form): Redefined method for enabling business logic when creating and modifying data coll...
5aa1565a7e7f4ea03cb92fd2b8db964c02aca27b
<|skeleton|> class ModifiedMethodFormValidMixim: """Extension when creating and updating a terminal to change the battery status.""" def form_valid(self, form): """Redefined method for enabling business logic when creating and modifying data collect terminals.""" <|body_0|> def change_stat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ModifiedMethodFormValidMixim: """Extension when creating and updating a terminal to change the battery status.""" def form_valid(self, form): """Redefined method for enabling business logic when creating and modifying data collect terminals.""" self.change_status_accum(form) self....
the_stack_v2_python_sparse
dct/mixins.py
Singlelogic/inportal
train
0
43379f8c8a0940847d1d5a156ec10f67705c7587
[ "self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]", "def gen_step():\n direction = choice([1, -1])\n distance = choice([0, 1, 2, 3, 4, 5])\n return distance * direction\nwhile len(self.x_values) < self.num_points:\n x_step = gen_step()\n y_step = gen_step()\n if x_step == 0...
<|body_start_0|> self.num_points = num_points self.x_values = [0] self.y_values = [0] <|end_body_0|> <|body_start_1|> def gen_step(): direction = choice([1, -1]) distance = choice([0, 1, 2, 3, 4, 5]) return distance * direction while len(self....
Take a walk.
RandomWalk
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomWalk: """Take a walk.""" def __init__(self, num_points=50000): """Init the walk.""" <|body_0|> def fill_walk(self): """Calculate the walk""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.num_points = num_points self.x_values = ...
stack_v2_sparse_classes_75kplus_train_009105
1,359
no_license
[ { "docstring": "Init the walk.", "name": "__init__", "signature": "def __init__(self, num_points=50000)" }, { "docstring": "Calculate the walk", "name": "fill_walk", "signature": "def fill_walk(self)" } ]
2
null
Implement the Python class `RandomWalk` described below. Class description: Take a walk. Method signatures and docstrings: - def __init__(self, num_points=50000): Init the walk. - def fill_walk(self): Calculate the walk
Implement the Python class `RandomWalk` described below. Class description: Take a walk. Method signatures and docstrings: - def __init__(self, num_points=50000): Init the walk. - def fill_walk(self): Calculate the walk <|skeleton|> class RandomWalk: """Take a walk.""" def __init__(self, num_points=50000): ...
13369ff58423008e81950ddc9c20589bb3842691
<|skeleton|> class RandomWalk: """Take a walk.""" def __init__(self, num_points=50000): """Init the walk.""" <|body_0|> def fill_walk(self): """Calculate the walk""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandomWalk: """Take a walk.""" def __init__(self, num_points=50000): """Init the walk.""" self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): """Calculate the walk""" def gen_step(): direction = choice(...
the_stack_v2_python_sparse
python_crash_course/project_2/random_walk.py
jcmarsh/Research_Notes
train
3
94c1c735e48c65dc64ce437f239fd89a7bfe982b
[ "self.X = x\nself.KEEPPRO = keep_pro\nself.CLASSNUM = class_num\nself.MODELPATH = model_path\nself.nn()", "conv_1 = convLayer(self.X, 11, 11, 4, 4, 96, 'conv1', 'VALID')\npool_1 = tf.nn.max_pool(conv_1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID', name='pool1')\nlrn_1 = tf.nn.lrn(pool_1, depth_radiu...
<|body_start_0|> self.X = x self.KEEPPRO = keep_pro self.CLASSNUM = class_num self.MODELPATH = model_path self.nn() <|end_body_0|> <|body_start_1|> conv_1 = convLayer(self.X, 11, 11, 4, 4, 96, 'conv1', 'VALID') pool_1 = tf.nn.max_pool(conv_1, ksize=[1, 3, 3, 1], ...
descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model
alexnet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class alexnet: """descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model""" def __init__(self, x, keep_pro, class_num, model_path='bvlc_alexnet.npy'): """descrption: to initialize parameters for a...
stack_v2_sparse_classes_75kplus_train_009106
6,866
no_license
[ { "docstring": "descrption: to initialize parameters for alexnet model Args: x: input data[image] keep_pro: keep alive probility of neruial units class_num: numbers of class model_path: the trained model file", "name": "__init__", "signature": "def __init__(self, x, keep_pro, class_num, model_path='bvlc...
3
stack_v2_sparse_classes_30k_train_003817
Implement the Python class `alexnet` described below. Class description: descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model Method signatures and docstrings: - def __init__(self, x, keep_pro, class_num, model_path='bvlc_...
Implement the Python class `alexnet` described below. Class description: descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model Method signatures and docstrings: - def __init__(self, x, keep_pro, class_num, model_path='bvlc_...
4b44860d8849155fc91134faf1f4beb45c8c5df8
<|skeleton|> class alexnet: """descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model""" def __init__(self, x, keep_pro, class_num, model_path='bvlc_alexnet.npy'): """descrption: to initialize parameters for a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class alexnet: """descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model""" def __init__(self, x, keep_pro, class_num, model_path='bvlc_alexnet.npy'): """descrption: to initialize parameters for alexnet model ...
the_stack_v2_python_sparse
alexnet/main.py
GinkgoX/tensorfolw_cnn
train
0
38e93468f35782a73e204ee3e21215108f1be936
[ "if args:\n self.message = args[0]\nelse:\n self.message = None", "print('calling str')\nif self.message:\n return 'MyCustomError, {0} '.format(self.message)\nelse:\n return 'MyCustomError has been raised'" ]
<|body_start_0|> if args: self.message = args[0] else: self.message = None <|end_body_0|> <|body_start_1|> print('calling str') if self.message: return 'MyCustomError, {0} '.format(self.message) else: return 'MyCustomError has been...
Documentation for a class. Herit from Exception @throws Exception
MyCustomError
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyCustomError: """Documentation for a class. Herit from Exception @throws Exception""" def __init__(self, *args): """Documentation for a function. Constructor""" <|body_0|> def __str__(self): """Documentation for a function. @return string that triggers Exception...
stack_v2_sparse_classes_75kplus_train_009107
2,814
permissive
[ { "docstring": "Documentation for a function. Constructor", "name": "__init__", "signature": "def __init__(self, *args)" }, { "docstring": "Documentation for a function. @return string that triggers Exception", "name": "__str__", "signature": "def __str__(self)" } ]
2
stack_v2_sparse_classes_30k_test_001842
Implement the Python class `MyCustomError` described below. Class description: Documentation for a class. Herit from Exception @throws Exception Method signatures and docstrings: - def __init__(self, *args): Documentation for a function. Constructor - def __str__(self): Documentation for a function. @return string th...
Implement the Python class `MyCustomError` described below. Class description: Documentation for a class. Herit from Exception @throws Exception Method signatures and docstrings: - def __init__(self, *args): Documentation for a function. Constructor - def __str__(self): Documentation for a function. @return string th...
1a20978a29ab285f80a35c7b55fc484c40d20bbb
<|skeleton|> class MyCustomError: """Documentation for a class. Herit from Exception @throws Exception""" def __init__(self, *args): """Documentation for a function. Constructor""" <|body_0|> def __str__(self): """Documentation for a function. @return string that triggers Exception...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyCustomError: """Documentation for a class. Herit from Exception @throws Exception""" def __init__(self, *args): """Documentation for a function. Constructor""" if args: self.message = args[0] else: self.message = None def __str__(self): """Do...
the_stack_v2_python_sparse
Includes/personnal/except.py
WikiLibs/Parser
train
0
6f60157e7883c47cb91311452d7f68b9eea9356c
[ "super(FineTuneModel, self).__init__()\nself.emb_size = emb_size\nself.emb_dimension = emb_dimension\nself.p = p\nself.sigma = sigma\nself.i_embeddings = nn.Embedding(emb_size, emb_dimension)\nself.u_embeddings = nn.Embedding(emb_size, emb_dimension)\nself.v_embeddings = nn.Embedding(emb_size, emb_dimension)\nself....
<|body_start_0|> super(FineTuneModel, self).__init__() self.emb_size = emb_size self.emb_dimension = emb_dimension self.p = p self.sigma = sigma self.i_embeddings = nn.Embedding(emb_size, emb_dimension) self.u_embeddings = nn.Embedding(emb_size, emb_dimension) ...
Skip gram model of word2vec. Attributes: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. u_embedding: Embedding for center word. v_embedding: Embedding for neibor words.
FineTuneModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FineTuneModel: """Skip gram model of word2vec. Attributes: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. u_embedding: Embedding for center word. v_embedding: Embedding for neibor words.""" def __init__(self, emb_size, emb_dimension, p, sigma, wvector...
stack_v2_sparse_classes_75kplus_train_009108
3,989
no_license
[ { "docstring": "Initialize model parameters. Apply for two embedding layers. Initialize layer weight Args: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. Returns: None", "name": "__init__", "signature": "def __init__(self, emb_size, emb_dimension, p, sigma, wvect...
2
stack_v2_sparse_classes_30k_train_040372
Implement the Python class `FineTuneModel` described below. Class description: Skip gram model of word2vec. Attributes: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. u_embedding: Embedding for center word. v_embedding: Embedding for neibor words. Method signatures and docstri...
Implement the Python class `FineTuneModel` described below. Class description: Skip gram model of word2vec. Attributes: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. u_embedding: Embedding for center word. v_embedding: Embedding for neibor words. Method signatures and docstri...
6b00d0d096b5b9700cd50f6a99a43db5b1ee26a3
<|skeleton|> class FineTuneModel: """Skip gram model of word2vec. Attributes: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. u_embedding: Embedding for center word. v_embedding: Embedding for neibor words.""" def __init__(self, emb_size, emb_dimension, p, sigma, wvector...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FineTuneModel: """Skip gram model of word2vec. Attributes: emb_size: Embedding size. emb_dimention: Embedding dimention, typically from 50 to 500. u_embedding: Embedding for center word. v_embedding: Embedding for neibor words.""" def __init__(self, emb_size, emb_dimension, p, sigma, wvector, cvector): ...
the_stack_v2_python_sparse
model.py
Yueqi-Zhang/fine-tune-w2v-v2
train
0
f009b954cd1b6723345209efa03753a98023a1fa
[ "params = ParamsParser(request.GET)\nfile_hash = params.str('hash', desc='文件hash值')\nmeta = ResourcesMeta.objects.filter(hash=file_hash)\nnhash = ResourceLogic.get_upload_token(file_hash)\nif meta.exists():\n logic = ResourceLogic(self.auth, meta[0])\n ok, v_token = logic.upload_finish(nhash, '')\n if ok:\...
<|body_start_0|> params = ParamsParser(request.GET) file_hash = params.str('hash', desc='文件hash值') meta = ResourcesMeta.objects.filter(hash=file_hash) nhash = ResourceLogic.get_upload_token(file_hash) if meta.exists(): logic = ResourceLogic(self.auth, meta[0]) ...
ResourcesInfoView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourcesInfoView: def get(self, request): """获取上传令牌 1-资源已存在 秒传,0-获取上传token :param request: :return:""" <|body_0|> def post(self, request): """完成上传 :param request: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> params = ParamsParser(reques...
stack_v2_sparse_classes_75kplus_train_009109
2,290
no_license
[ { "docstring": "获取上传令牌 1-资源已存在 秒传,0-获取上传token :param request: :return:", "name": "get", "signature": "def get(self, request)" }, { "docstring": "完成上传 :param request: :return:", "name": "post", "signature": "def post(self, request)" } ]
2
null
Implement the Python class `ResourcesInfoView` described below. Class description: Implement the ResourcesInfoView class. Method signatures and docstrings: - def get(self, request): 获取上传令牌 1-资源已存在 秒传,0-获取上传token :param request: :return: - def post(self, request): 完成上传 :param request: :return:
Implement the Python class `ResourcesInfoView` described below. Class description: Implement the ResourcesInfoView class. Method signatures and docstrings: - def get(self, request): 获取上传令牌 1-资源已存在 秒传,0-获取上传token :param request: :return: - def post(self, request): 完成上传 :param request: :return: <|skeleton|> class Reso...
7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b
<|skeleton|> class ResourcesInfoView: def get(self, request): """获取上传令牌 1-资源已存在 秒传,0-获取上传token :param request: :return:""" <|body_0|> def post(self, request): """完成上传 :param request: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResourcesInfoView: def get(self, request): """获取上传令牌 1-资源已存在 秒传,0-获取上传token :param request: :return:""" params = ParamsParser(request.GET) file_hash = params.str('hash', desc='文件hash值') meta = ResourcesMeta.objects.filter(hash=file_hash) nhash = ResourceLogic.get_upload...
the_stack_v2_python_sparse
FireHydrant/server/resources/views/info.py
shoogoome/FireHydrant
train
4
00cf4f5b1317ed365c3cc3ddb25df182a73f78c5
[ "inner_text = '编辑'\nselector = 'view.swiper-box>view>view.operation>view.operation-btn'\nel_swiper = self.page.get_element('view.page').get_element('swiper')\nel_preview = el_swiper.get_element('swiper-item>preview#release')\nel_preview.click()\nself.page.sleep(1)\nel_btn = el_preview.get_element(selector, inner_te...
<|body_start_0|> inner_text = '编辑' selector = 'view.swiper-box>view>view.operation>view.operation-btn' el_swiper = self.page.get_element('view.page').get_element('swiper') el_preview = el_swiper.get_element('swiper-item>preview#release') el_preview.click() self.page.sleep...
Elements
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Elements: def edit_btn(self): """编辑 按钮""" <|body_0|> def release_btn(self): """发布 按钮""" <|body_1|> def title_inputbox(self): """广告标题 输入框""" <|body_2|> <|end_skeleton|> <|body_start_0|> inner_text = '编辑' selector = 'view....
stack_v2_sparse_classes_75kplus_train_009110
2,466
no_license
[ { "docstring": "编辑 按钮", "name": "edit_btn", "signature": "def edit_btn(self)" }, { "docstring": "发布 按钮", "name": "release_btn", "signature": "def release_btn(self)" }, { "docstring": "广告标题 输入框", "name": "title_inputbox", "signature": "def title_inputbox(self)" } ]
3
stack_v2_sparse_classes_30k_train_003745
Implement the Python class `Elements` described below. Class description: Implement the Elements class. Method signatures and docstrings: - def edit_btn(self): 编辑 按钮 - def release_btn(self): 发布 按钮 - def title_inputbox(self): 广告标题 输入框
Implement the Python class `Elements` described below. Class description: Implement the Elements class. Method signatures and docstrings: - def edit_btn(self): 编辑 按钮 - def release_btn(self): 发布 按钮 - def title_inputbox(self): 广告标题 输入框 <|skeleton|> class Elements: def edit_btn(self): """编辑 按钮""" <...
3011071556a3fa097d951a1823a4870cc4cc81e1
<|skeleton|> class Elements: def edit_btn(self): """编辑 按钮""" <|body_0|> def release_btn(self): """发布 按钮""" <|body_1|> def title_inputbox(self): """广告标题 输入框""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Elements: def edit_btn(self): """编辑 按钮""" inner_text = '编辑' selector = 'view.swiper-box>view>view.operation>view.operation-btn' el_swiper = self.page.get_element('view.page').get_element('swiper') el_preview = el_swiper.get_element('swiper-item>preview#release') ...
the_stack_v2_python_sparse
sevenautotest/testobjects/pages/apppages/yy/preview_page.py
hotswwkyo/SevenPytest
train
3
dfa9694fd6f3cbdfaa4fd6de256c7a65031315d0
[ "try:\n cls.abrir_conexion()\n sql = 'SELECT idProdTipArt, idTipoArticulo, fecha, cantidad FROM prodTipArt WHERE estado != \"eliminado\" order by fecha DESC;'\n cls.cursor.execute(sql)\n prods_ = cls.curs...
<|body_start_0|> try: cls.abrir_conexion() sql = 'SELECT idProdTipArt, idTipoArticulo, fecha, cantidad FROM prodTipArt WHERE estado != "eliminado" order by fecha DESC;' cls.cur...
DatosProduccion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatosProduccion: def get_all_articulos(cls): """Obtiene todas las producciones de artículos de la BD.""" <|body_0|> def get_all_insumos(cls): """Obtiene todas las producciones de insumos de la BD.""" <|body_1|> def add(cls, id, fecha, cant, kind): ...
stack_v2_sparse_classes_75kplus_train_009111
5,809
no_license
[ { "docstring": "Obtiene todas las producciones de artículos de la BD.", "name": "get_all_articulos", "signature": "def get_all_articulos(cls)" }, { "docstring": "Obtiene todas las producciones de insumos de la BD.", "name": "get_all_insumos", "signature": "def get_all_insumos(cls)" }, ...
5
stack_v2_sparse_classes_30k_train_002763
Implement the Python class `DatosProduccion` described below. Class description: Implement the DatosProduccion class. Method signatures and docstrings: - def get_all_articulos(cls): Obtiene todas las producciones de artículos de la BD. - def get_all_insumos(cls): Obtiene todas las producciones de insumos de la BD. - ...
Implement the Python class `DatosProduccion` described below. Class description: Implement the DatosProduccion class. Method signatures and docstrings: - def get_all_articulos(cls): Obtiene todas las producciones de artículos de la BD. - def get_all_insumos(cls): Obtiene todas las producciones de insumos de la BD. - ...
57ca674dba4dabd2526c450ba7210933240f19c5
<|skeleton|> class DatosProduccion: def get_all_articulos(cls): """Obtiene todas las producciones de artículos de la BD.""" <|body_0|> def get_all_insumos(cls): """Obtiene todas las producciones de insumos de la BD.""" <|body_1|> def add(cls, id, fecha, cant, kind): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DatosProduccion: def get_all_articulos(cls): """Obtiene todas las producciones de artículos de la BD.""" try: cls.abrir_conexion() sql = 'SELECT idProdTipArt, idTipoArticulo, fecha, cantidad...
the_stack_v2_python_sparse
data/data_produccion.py
JoaquinCardonaRuiz/proyecto-final
train
0
b70e73edb101e6303b655e31f58aa1ebc22cac70
[ "super(Segmentor, self).__init__(parameters)\nself.layer_list = add_conv_block(self.Conv, self.BatchNorm, in_channels=anatomy_factors, out_channels=self.base_filters * 4)\nself.layer_list += add_conv_block(self.Conv, self.BatchNorm, in_channels=self.base_filters * 4, out_channels=self.base_filters * 4)\nself.conv =...
<|body_start_0|> super(Segmentor, self).__init__(parameters) self.layer_list = add_conv_block(self.Conv, self.BatchNorm, in_channels=anatomy_factors, out_channels=self.base_filters * 4) self.layer_list += add_conv_block(self.Conv, self.BatchNorm, in_channels=self.base_filters * 4, out_channels=s...
Segmentor
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Segmentor: def __init__(self, parameters, anatomy_factors): """Segmentor module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. Attributes: layer_list (list): List of layers in the Seg...
stack_v2_sparse_classes_75kplus_train_009112
14,834
permissive
[ { "docstring": "Segmentor module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. Attributes: layer_list (list): List of layers in the Segmentor module. conv (nn.Conv2d): Convolutional layer to generate the fi...
3
stack_v2_sparse_classes_30k_train_000746
Implement the Python class `Segmentor` described below. Class description: Implement the Segmentor class. Method signatures and docstrings: - def __init__(self, parameters, anatomy_factors): Segmentor module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The numbe...
Implement the Python class `Segmentor` described below. Class description: Implement the Segmentor class. Method signatures and docstrings: - def __init__(self, parameters, anatomy_factors): Segmentor module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The numbe...
72eb99f68205afd5f8d49a3bb6cfc08cfd467582
<|skeleton|> class Segmentor: def __init__(self, parameters, anatomy_factors): """Segmentor module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. Attributes: layer_list (list): List of layers in the Seg...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Segmentor: def __init__(self, parameters, anatomy_factors): """Segmentor module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. Attributes: layer_list (list): List of layers in the Segmentor module....
the_stack_v2_python_sparse
GANDLF/models/sdnet.py
mlcommons/GaNDLF
train
45
c6734c33e219c22a9e8c6ca61abbb50d24202103
[ "super(Decoder, self).__init__()\nn_position = max_length + 1\nself.max_length = max_length\nself.d_model = d_model\nself.position_enc = nn.Embedding(n_position, d_word_vec, padding_idx=common.PAD)\nself.position_enc.weight.data = position_encoding_init(n_position, d_word_vec)\nself.tgt_word_emb = nn.Embedding(n_tg...
<|body_start_0|> super(Decoder, self).__init__() n_position = max_length + 1 self.max_length = max_length self.d_model = d_model self.position_enc = nn.Embedding(n_position, d_word_vec, padding_idx=common.PAD) self.position_enc.weight.data = position_encoding_init(n_posit...
DecoderLayerブロックからなるDecoderのクラス
Decoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decoder: """DecoderLayerブロックからなるDecoderのクラス""" def __init__(self, n_tgt_vocab, max_length, n_layers=6, n_head=8, d_k=64, d_v=64, d_word_vec=512, d_model=512, d_inner_hid=1024, dropout=0.1): """:param n_tgt_vocab: int, 出力言語の語彙数 :param max_length: int, 最大系列長 :param n_layers: int, レイヤー数...
stack_v2_sparse_classes_75kplus_train_009113
6,788
no_license
[ { "docstring": ":param n_tgt_vocab: int, 出力言語の語彙数 :param max_length: int, 最大系列長 :param n_layers: int, レイヤー数 :param n_head: int, ヘッド数 :param d_k: int, keyベクトルの次元数 :param d_v: int, valueベクトルの次元数 :param d_word_vec: int, 単語の埋め込みの次元数 :param d_model: int, 隠れ層の次元数 :param d_inner_hid: int, Position Wise Feed Forward Ne...
2
stack_v2_sparse_classes_30k_train_049199
Implement the Python class `Decoder` described below. Class description: DecoderLayerブロックからなるDecoderのクラス Method signatures and docstrings: - def __init__(self, n_tgt_vocab, max_length, n_layers=6, n_head=8, d_k=64, d_v=64, d_word_vec=512, d_model=512, d_inner_hid=1024, dropout=0.1): :param n_tgt_vocab: int, 出力言語の語彙数 ...
Implement the Python class `Decoder` described below. Class description: DecoderLayerブロックからなるDecoderのクラス Method signatures and docstrings: - def __init__(self, n_tgt_vocab, max_length, n_layers=6, n_head=8, d_k=64, d_v=64, d_word_vec=512, d_model=512, d_inner_hid=1024, dropout=0.1): :param n_tgt_vocab: int, 出力言語の語彙数 ...
7218e8c6d2d65406421bf59827053377f01732e2
<|skeleton|> class Decoder: """DecoderLayerブロックからなるDecoderのクラス""" def __init__(self, n_tgt_vocab, max_length, n_layers=6, n_head=8, d_k=64, d_v=64, d_word_vec=512, d_model=512, d_inner_hid=1024, dropout=0.1): """:param n_tgt_vocab: int, 出力言語の語彙数 :param max_length: int, 最大系列長 :param n_layers: int, レイヤー数...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Decoder: """DecoderLayerブロックからなるDecoderのクラス""" def __init__(self, n_tgt_vocab, max_length, n_layers=6, n_head=8, d_k=64, d_v=64, d_word_vec=512, d_model=512, d_inner_hid=1024, dropout=0.1): """:param n_tgt_vocab: int, 出力言語の語彙数 :param max_length: int, 最大系列長 :param n_layers: int, レイヤー数 :param n_hea...
the_stack_v2_python_sparse
chap4/decoder.py
himkt/deeplearning4nlp
train
1
012588622b4eb7bfba1cde1f599dd65aaae0f6f0
[ "image = pygame.Surface(self.size)\nimage.fill(chaser.colour)\nsuper().__init__(image)\nself.velocity = (int(chaser.direction * self.speed), 0)\nself.rect.center = chaser.rect.center", "self.rect.move_ip(self.velocity)\nself.blit_to(display)\nif self.rect.colliderect(other_player.rect):\n return True" ]
<|body_start_0|> image = pygame.Surface(self.size) image.fill(chaser.colour) super().__init__(image) self.velocity = (int(chaser.direction * self.speed), 0) self.rect.center = chaser.rect.center <|end_body_0|> <|body_start_1|> self.rect.move_ip(self.velocity) sel...
Sprite subclass for the player's bullet.
Bullet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bullet: """Sprite subclass for the player's bullet.""" def __init__(self, chaser): """Create the bullet.""" <|body_0|> def update(self, other_player, display): """Update the bullet. The update involves moveing the bullet, blitting it to the display, and checking ...
stack_v2_sparse_classes_75kplus_train_009114
9,555
no_license
[ { "docstring": "Create the bullet.", "name": "__init__", "signature": "def __init__(self, chaser)" }, { "docstring": "Update the bullet. The update involves moveing the bullet, blitting it to the display, and checking if the bullet has hit the opponent.", "name": "update", "signature": "...
2
stack_v2_sparse_classes_30k_train_016504
Implement the Python class `Bullet` described below. Class description: Sprite subclass for the player's bullet. Method signatures and docstrings: - def __init__(self, chaser): Create the bullet. - def update(self, other_player, display): Update the bullet. The update involves moveing the bullet, blitting it to the d...
Implement the Python class `Bullet` described below. Class description: Sprite subclass for the player's bullet. Method signatures and docstrings: - def __init__(self, chaser): Create the bullet. - def update(self, other_player, display): Update the bullet. The update involves moveing the bullet, blitting it to the d...
e7bbc0f7cfab13a2e16baa4c931d3a412c86277c
<|skeleton|> class Bullet: """Sprite subclass for the player's bullet.""" def __init__(self, chaser): """Create the bullet.""" <|body_0|> def update(self, other_player, display): """Update the bullet. The update involves moveing the bullet, blitting it to the display, and checking ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Bullet: """Sprite subclass for the player's bullet.""" def __init__(self, chaser): """Create the bullet.""" image = pygame.Surface(self.size) image.fill(chaser.colour) super().__init__(image) self.velocity = (int(chaser.direction * self.speed), 0) self.rect...
the_stack_v2_python_sparse
GunTag.py
Chig00/Python
train
1
56664c7aa798a03005308ea681b36c9b85effbaf
[ "n = len(piles)\ndp = [[[0, 0] for _ in range(n)] for _ in range(n)]\nfor i in range(n):\n dp[i][i][0] = piles[i]\nfor i in range(n - 2, -1, -1):\n for j in range(i + 1, n):\n left = piles[i] + dp[i + 1][j][1]\n right = piles[j] + dp[i][j - 1][1]\n if left > right:\n dp[i][j][0...
<|body_start_0|> n = len(piles) dp = [[[0, 0] for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i][0] = piles[i] for i in range(n - 2, -1, -1): for j in range(i + 1, n): left = piles[i] + dp[i + 1][j][1] right = piles[j...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" <|body_0|> def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(piles) dp = [[[0, 0] for _ ...
stack_v2_sparse_classes_75kplus_train_009115
1,689
no_license
[ { "docstring": ":type piles: List[int] :rtype: bool", "name": "stoneGame", "signature": "def stoneGame(self, piles)" }, { "docstring": ":type piles: List[int] :rtype: bool", "name": "stoneGame", "signature": "def stoneGame(self, piles)" } ]
2
stack_v2_sparse_classes_30k_train_010371
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def stoneGame(self, piles): :type piles: List[int] :rtype: bool - def stoneGame(self, piles): :type piles: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def stoneGame(self, piles): :type piles: List[int] :rtype: bool - def stoneGame(self, piles): :type piles: List[int] :rtype: bool <|skeleton|> class Solution: def stoneGame...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" <|body_0|> def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" n = len(piles) dp = [[[0, 0] for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i][0] = piles[i] for i in range(n - 2, -1, -1): for j in range(i + 1, n): ...
the_stack_v2_python_sparse
0877_Stone_Game.py
bingli8802/leetcode
train
0
4057a5d8f4fb473914ff1f6f8c7c14c9efb501eb
[ "if data is not None:\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 values')\n mean = sum(data) / len(data)\n self.lambtha = 1 / mean\nelse:\n if lambtha <= 0:\n raise ValueError('lamb...
<|body_start_0|> if data is not None: if not isinstance(data, list): raise TypeError('data must be a list') if len(data) <= 2: raise ValueError('data must contain multiple values') mean = sum(data) / len(data) self.lambtha = 1 / mea...
Exponential class
Exponential
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exponential: """Exponential class""" def __init__(self, data=None, lambtha=1.0): """Class contructor""" <|body_0|> def pdf(self, x): """Calculates the value of the PDF for a given time period""" <|body_1|> def cdf(self, x): """Calculates the ...
stack_v2_sparse_classes_75kplus_train_009116
1,196
no_license
[ { "docstring": "Class contructor", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "Calculates the value of the PDF for a given time period", "name": "pdf", "signature": "def pdf(self, x)" }, { "docstring": "Calculates the value of ...
3
stack_v2_sparse_classes_30k_train_029830
Implement the Python class `Exponential` described below. Class description: Exponential class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Class contructor - def pdf(self, x): Calculates the value of the PDF for a given time period - def cdf(self, x): Calculates the value of the CD...
Implement the Python class `Exponential` described below. Class description: Exponential class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Class contructor - def pdf(self, x): Calculates the value of the PDF for a given time period - def cdf(self, x): Calculates the value of the CD...
23162e01761cfa56158a1ebc88ac7709ff1c2af2
<|skeleton|> class Exponential: """Exponential class""" def __init__(self, data=None, lambtha=1.0): """Class contructor""" <|body_0|> def pdf(self, x): """Calculates the value of the PDF for a given time period""" <|body_1|> def cdf(self, x): """Calculates the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Exponential: """Exponential class""" def __init__(self, data=None, lambtha=1.0): """Class contructor""" if data is not None: if not isinstance(data, list): raise TypeError('data must be a list') if len(data) <= 2: raise ValueError('d...
the_stack_v2_python_sparse
math/0x03-probability/exponential.py
emmanavarro/holbertonschool-machine_learning
train
0
fa1427fa9a6d84ce1a50449404e9fe79792ff85a
[ "def gcd(a, b):\n while b != 0:\n tmp = b\n b = a % b\n a = tmp\n return a\nif x + y < z:\n return False\nif x == z or y == z or x + y == z:\n return True\nreturn z % gcd(x, y) == 0", "import collections\nvisited = collections.defaultdict(dict)\nq = collections.deque([(0, 0)])\nwh...
<|body_start_0|> def gcd(a, b): while b != 0: tmp = b b = a % b a = tmp return a if x + y < z: return False if x == z or y == z or x + y == z: return True return z % gcd(x, y) == 0 <|end_body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canMeasureWater(self, x, y, z): """:type x: int :type y: int :type z: int :rtype: bool""" <|body_0|> def canMeasureWater_BFS(self, x, y, z): """:type x: int :type y: int :type z: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_75kplus_train_009117
2,358
no_license
[ { "docstring": ":type x: int :type y: int :type z: int :rtype: bool", "name": "canMeasureWater", "signature": "def canMeasureWater(self, x, y, z)" }, { "docstring": ":type x: int :type y: int :type z: int :rtype: bool", "name": "canMeasureWater_BFS", "signature": "def canMeasureWater_BFS...
2
stack_v2_sparse_classes_30k_train_041590
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canMeasureWater(self, x, y, z): :type x: int :type y: int :type z: int :rtype: bool - def canMeasureWater_BFS(self, x, y, z): :type x: int :type y: int :type z: int :rtype: b...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canMeasureWater(self, x, y, z): :type x: int :type y: int :type z: int :rtype: bool - def canMeasureWater_BFS(self, x, y, z): :type x: int :type y: int :type z: int :rtype: b...
0a7aa09a2b95e4caca5b5123fb735ceb5c01e992
<|skeleton|> class Solution: def canMeasureWater(self, x, y, z): """:type x: int :type y: int :type z: int :rtype: bool""" <|body_0|> def canMeasureWater_BFS(self, x, y, z): """:type x: int :type y: int :type z: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def canMeasureWater(self, x, y, z): """:type x: int :type y: int :type z: int :rtype: bool""" def gcd(a, b): while b != 0: tmp = b b = a % b a = tmp return a if x + y < z: return False ...
the_stack_v2_python_sparse
water-and-jug-problem.py
onestarshang/leetcode
train
0
c760dc7427dd51cb426bc6395585109deb83b3d1
[ "self.assertIsInstance(table, agate.Table)\nself.assertSequenceEqual(table.column_names, names)\nself.assertSequenceEqual([c.name for c in table.columns], names)\nfor row in table.rows:\n self.assertSequenceEqual(row.keys(), names)", "self.assertIsInstance(table, agate.Table)\ntable_types = table.column_types\...
<|body_start_0|> self.assertIsInstance(table, agate.Table) self.assertSequenceEqual(table.column_names, names) self.assertSequenceEqual([c.name for c in table.columns], names) for row in table.rows: self.assertSequenceEqual(row.keys(), names) <|end_body_0|> <|body_start_1|> ...
Unittest case for quickly asserting logic about tables.
AgateTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AgateTestCase: """Unittest case for quickly asserting logic about tables.""" def assertColumnNames(self, table, names): """Verify the column names in the given table match what is expected.""" <|body_0|> def assertColumnTypes(self, table, types): """Verify the co...
stack_v2_sparse_classes_75kplus_train_009118
1,908
permissive
[ { "docstring": "Verify the column names in the given table match what is expected.", "name": "assertColumnNames", "signature": "def assertColumnNames(self, table, names)" }, { "docstring": "Verify the column types in the given table are of the expected types.", "name": "assertColumnTypes", ...
4
stack_v2_sparse_classes_30k_train_017848
Implement the Python class `AgateTestCase` described below. Class description: Unittest case for quickly asserting logic about tables. Method signatures and docstrings: - def assertColumnNames(self, table, names): Verify the column names in the given table match what is expected. - def assertColumnTypes(self, table, ...
Implement the Python class `AgateTestCase` described below. Class description: Unittest case for quickly asserting logic about tables. Method signatures and docstrings: - def assertColumnNames(self, table, names): Verify the column names in the given table match what is expected. - def assertColumnTypes(self, table, ...
a53c2b12452152e61d7c5e5eb0df27e66c266684
<|skeleton|> class AgateTestCase: """Unittest case for quickly asserting logic about tables.""" def assertColumnNames(self, table, names): """Verify the column names in the given table match what is expected.""" <|body_0|> def assertColumnTypes(self, table, types): """Verify the co...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AgateTestCase: """Unittest case for quickly asserting logic about tables.""" def assertColumnNames(self, table, names): """Verify the column names in the given table match what is expected.""" self.assertIsInstance(table, agate.Table) self.assertSequenceEqual(table.column_names, n...
the_stack_v2_python_sparse
agate/testcase.py
wireservice/agate
train
724
fa59991c242f91334023698aec44921ed3d3cf65
[ "n = len(arr)\ndp = [[0] * n for _ in range(n)]\nleafs = [[0] * n for _ in range(n)]\nfor i in range(n):\n dp[i][i] = 0\n leafs[i][i] = arr[i]\nfor l in range(2, n + 1):\n for i in range(n - l + 1):\n j = i + l - 1\n dp[i][j] = min((dp[i][k] + dp[k + 1][j] + leafs[i][k] * leafs[k + 1][j] for ...
<|body_start_0|> n = len(arr) dp = [[0] * n for _ in range(n)] leafs = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 0 leafs[i][i] = arr[i] for l in range(2, n + 1): for i in range(n - l + 1): j = i + l - 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mctFromLeafValues1(self, arr: List[int]) -> int: """dynamic programming""" <|body_0|> def mctFromLeafValues2(self, arr: List[int]) -> int: """greedy""" <|body_1|> def mctFromLeafValues3(self, arr: List[int]) -> int: """monotonic dec...
stack_v2_sparse_classes_75kplus_train_009119
2,353
no_license
[ { "docstring": "dynamic programming", "name": "mctFromLeafValues1", "signature": "def mctFromLeafValues1(self, arr: List[int]) -> int" }, { "docstring": "greedy", "name": "mctFromLeafValues2", "signature": "def mctFromLeafValues2(self, arr: List[int]) -> int" }, { "docstring": "m...
3
stack_v2_sparse_classes_30k_train_003601
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mctFromLeafValues1(self, arr: List[int]) -> int: dynamic programming - def mctFromLeafValues2(self, arr: List[int]) -> int: greedy - def mctFromLeafValues3(self, arr: List[in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mctFromLeafValues1(self, arr: List[int]) -> int: dynamic programming - def mctFromLeafValues2(self, arr: List[int]) -> int: greedy - def mctFromLeafValues3(self, arr: List[in...
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Solution: def mctFromLeafValues1(self, arr: List[int]) -> int: """dynamic programming""" <|body_0|> def mctFromLeafValues2(self, arr: List[int]) -> int: """greedy""" <|body_1|> def mctFromLeafValues3(self, arr: List[int]) -> int: """monotonic dec...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def mctFromLeafValues1(self, arr: List[int]) -> int: """dynamic programming""" n = len(arr) dp = [[0] * n for _ in range(n)] leafs = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 0 leafs[i][i] = arr[i] for l in range...
the_stack_v2_python_sparse
Leetcode 1130. Minimum Cost Tree From Leaf Values.py
Chaoran-sjsu/leetcode
train
0
f15a19cd880e9aa2493ba5c09890ab222f517f1d
[ "assert category in ERROR_CATEGORIES\nself.relpath = relpath\nself.category = category\nself.message = message\nself.fix_it = fix_it\nERROR_COUNTS[category] += 1\nif not FLAGS.counts and self.category not in FLAGS.ignore:\n print(f'\\r\\x1b[K{relpath}: {shell.ShellEscapeCodes.YELLOW}{message}{shell.ShellEscapeC...
<|body_start_0|> assert category in ERROR_CATEGORIES self.relpath = relpath self.category = category self.message = message self.fix_it = fix_it ERROR_COUNTS[category] += 1 if not FLAGS.counts and self.category not in FLAGS.ignore: print(f'\r\x1b[K{rel...
A linter error.
Error
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Error: """A linter error.""" def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): """Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other out...
stack_v2_sparse_classes_75kplus_train_009120
24,661
permissive
[ { "docstring": "Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other output is to stderr.", "name": "__init__", "signature": "def __init__(self, relpath: str, category: str, message: str, f...
2
stack_v2_sparse_classes_30k_train_046645
Implement the Python class `Error` described below. Class description: A linter error. Method signatures and docstrings: - def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag wa...
Implement the Python class `Error` described below. Class description: A linter error. Method signatures and docstrings: - def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag wa...
aab7f16bd1f3546f81e349fc6e2325fb17beb851
<|skeleton|> class Error: """A linter error.""" def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): """Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other out...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Error: """A linter error.""" def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): """Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other output is to std...
the_stack_v2_python_sparse
util/photolib/linters.py
tszdanger/phd
train
0
3517b4163199387526767f7f9c9fc5ee07ae98cd
[ "try:\n self.assessVers = AssessmentVersion.objects.get(pk=self.kwargs['assessIR'])\nexcept AssessmentVersion.DoesNotExist:\n raise Http404('No asssessment matches the URL.')\nreturn super(SupplementUpload, self).dispatch(request, *args, **kwargs)", "self.assessVers.supplements.add(self.object)\nself.assess...
<|body_start_0|> try: self.assessVers = AssessmentVersion.objects.get(pk=self.kwargs['assessIR']) except AssessmentVersion.DoesNotExist: raise Http404('No asssessment matches the URL.') return super(SupplementUpload, self).dispatch(request, *args, **kwargs) <|end_body_0|>...
View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`
SupplementUpload
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SupplementUpload: """View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`""" def dispatch(self, request, *args, **kwargs): """Dispatch view and attach assessment to instance Args: reque...
stack_v2_sparse_classes_75kplus_train_009121
27,436
no_license
[ { "docstring": "Dispatch view and attach assessment to instance Args: request (HttpRequest): request to view page Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` Returns: HttpResponse : response of page to request", "name": "dispatch", "signa...
3
stack_v2_sparse_classes_30k_train_015076
Implement the Python class `SupplementUpload` described below. Class description: View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` Method signatures and docstrings: - def dispatch(self, request, *args, **kwargs): Di...
Implement the Python class `SupplementUpload` described below. Class description: View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` Method signatures and docstrings: - def dispatch(self, request, *args, **kwargs): Di...
472a6fd487811002a60a7812ae2eef941e7182cc
<|skeleton|> class SupplementUpload: """View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`""" def dispatch(self, request, *args, **kwargs): """Dispatch view and attach assessment to instance Args: reque...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SupplementUpload: """View to upload supplements to assessments Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion`""" def dispatch(self, request, *args, **kwargs): """Dispatch view and attach assessment to instance Args: request (HttpReque...
the_stack_v2_python_sparse
AACForm/makeReports/views/assessment_views.py
jdboyd-github/AAC-Capstone
train
0
7aff9ffb83ebad4affe7dd63e536d48ab48ff480
[ "dataset_type_ref = kwargs.pop('dataset_type_id', None)\nsuper(DatasetFilterForm, self).__init__(*args, **kwargs)\nself.fields['dataset_type_ref'].queryset = DatasetType.objects.using('agdc').all()\nif dataset_type_ref is not None:\n self.fields['dataset_type_ref'].initial = [dataset_type_ref]", "cleaned_data ...
<|body_start_0|> dataset_type_ref = kwargs.pop('dataset_type_id', None) super(DatasetFilterForm, self).__init__(*args, **kwargs) self.fields['dataset_type_ref'].queryset = DatasetType.objects.using('agdc').all() if dataset_type_ref is not None: self.fields['dataset_type_ref']...
Filter datasets based on the dataset type and metadata attributes on the eo metadata type
DatasetFilterForm
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatasetFilterForm: """Filter datasets based on the dataset type and metadata attributes on the eo metadata type""" def __init__(self, *args, **kwargs): """Initialize the dataset filtering form. If a dataset type id is provided, set the default""" <|body_0|> def clean(sel...
stack_v2_sparse_classes_75kplus_train_009122
6,092
permissive
[ { "docstring": "Initialize the dataset filtering form. If a dataset type id is provided, set the default", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Clean the dataset filter form This uses manually set defaults to allow for 'blank' inputs while sti...
2
null
Implement the Python class `DatasetFilterForm` described below. Class description: Filter datasets based on the dataset type and metadata attributes on the eo metadata type Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the dataset filtering form. If a dataset type id is provided,...
Implement the Python class `DatasetFilterForm` described below. Class description: Filter datasets based on the dataset type and metadata attributes on the eo metadata type Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the dataset filtering form. If a dataset type id is provided,...
ef50e918df89313f130d735e7cb7c0a069da410e
<|skeleton|> class DatasetFilterForm: """Filter datasets based on the dataset type and metadata attributes on the eo metadata type""" def __init__(self, *args, **kwargs): """Initialize the dataset filtering form. If a dataset type id is provided, set the default""" <|body_0|> def clean(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DatasetFilterForm: """Filter datasets based on the dataset type and metadata attributes on the eo metadata type""" def __init__(self, *args, **kwargs): """Initialize the dataset filtering form. If a dataset type id is provided, set the default""" dataset_type_ref = kwargs.pop('dataset_typ...
the_stack_v2_python_sparse
apps/data_cube_manager/forms/dataset.py
ceos-seo/data_cube_ui
train
47
6c952ce6ef498b3213542d60cb26c72a2df90e6d
[ "self.x = x\nself.fs = fs\nself.N = len(self.x)\nself.K = K", "X = np.zeros(self.N, dtype=np.complex)\nE = np.zeros(self.N)\nX_K = np.zeros(self.K, dtype=np.complex)\nindex = np.zeros(self.K)\nfor k in range(self.N):\n for n in range(self.N):\n X[k] = X[k] + 1 / np.sqrt(self.N) * self.x[n] * np.exp(-1j ...
<|body_start_0|> self.x = x self.fs = fs self.N = len(self.x) self.K = K <|end_body_0|> <|body_start_1|> X = np.zeros(self.N, dtype=np.complex) E = np.zeros(self.N) X_K = np.zeros(self.K, dtype=np.complex) index = np.zeros(self.K) for k in range(s...
idft Inverse Discrete Fourier transform.
dft_K_q16
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class dft_K_q16: """idft Inverse Discrete Fourier transform.""" def __init__(self, x, fs, K): """:param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT.""" ...
stack_v2_sparse_classes_75kplus_train_009123
25,417
no_license
[ { "docstring": ":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT.", "name": "__init__", "signature": "def __init__(self, x, fs, K)" }, { "docstring": "\\\\\\\\\\\\ ...
2
stack_v2_sparse_classes_30k_train_005139
Implement the Python class `dft_K_q16` described below. Class description: idft Inverse Discrete Fourier transform. Method signatures and docstrings: - def __init__(self, x, fs, K): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the num...
Implement the Python class `dft_K_q16` described below. Class description: idft Inverse Discrete Fourier transform. Method signatures and docstrings: - def __init__(self, x, fs, K): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the num...
b72322cfc6d81c996117cea2160ee312da62d3ed
<|skeleton|> class dft_K_q16: """idft Inverse Discrete Fourier transform.""" def __init__(self, x, fs, K): """:param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class dft_K_q16: """idft Inverse Discrete Fourier transform.""" def __init__(self, x, fs, K): """:param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT.""" self.x = x ...
the_stack_v2_python_sparse
Inverse Discrete Fourier Transform/iDFT_main.py
FG-14/Signals-and-Information-Processing-DSP-
train
0
1c6f84bb944056f260a756becdcc0a09fd26a69a
[ "self.classification = classification\nself.features = features\nself.method = method", "local_importance_values = np.array(local_importance_values)\nif len(local_importance_values.shape) == 2 and self.classification:\n local_importance_values = np.array([-local_importance_values, local_importance_values])\nkw...
<|body_start_0|> self.classification = classification self.features = features self.method = method <|end_body_0|> <|body_start_1|> local_importance_values = np.array(local_importance_values) if len(local_importance_values.shape) == 2 and self.classification: local_i...
An adapter for creating an interpret-community explanation from local importance values. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression explanation. :type classification: bool :param method: The explanation method used to ex...
ExplanationAdapter
[ "MIT", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExplanationAdapter: """An adapter for creating an interpret-community explanation from local importance values. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression explanation. :type classification: bool :p...
stack_v2_sparse_classes_75kplus_train_009124
5,841
permissive
[ { "docstring": "Create the explanation adapter. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression explanation. :type classification: bool :param method: The explanation method used to explain the model (e.g., SHAP, LIME...
3
null
Implement the Python class `ExplanationAdapter` described below. Class description: An adapter for creating an interpret-community explanation from local importance values. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression exp...
Implement the Python class `ExplanationAdapter` described below. Class description: An adapter for creating an interpret-community explanation from local importance values. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression exp...
00922df124204420402e13ec8f1b4ca9781e42f1
<|skeleton|> class ExplanationAdapter: """An adapter for creating an interpret-community explanation from local importance values. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression explanation. :type classification: bool :p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExplanationAdapter: """An adapter for creating an interpret-community explanation from local importance values. :param features: A list of feature names. :type features: list[str] :param classification: Indicates if this is a classification or regression explanation. :type classification: bool :param method: ...
the_stack_v2_python_sparse
python/interpret_community/adapter/explanation_adapter.py
interpretml/interpret-community
train
403
5099bf229b2f61b77a1825e272aaa4efc46d72d5
[ "super().__init__(resolver)\nself.cmd: str = 'looking'\nself.target: Optional[Pose] = target\nself.object: Object = object.bullet_world_object if object else object", "if not self.target and self.object:\n self.target = self.object.get_pose()\nreturn self.Motion(self.cmd, self.target)" ]
<|body_start_0|> super().__init__(resolver) self.cmd: str = 'looking' self.target: Optional[Pose] = target self.object: Object = object.bullet_world_object if object else object <|end_body_0|> <|body_start_1|> if not self.target and self.object: self.target = self.ob...
Lets the robot look at a point
LookingMotion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LookingMotion: """Lets the robot look at a point""" def __init__(self, target: Optional[Pose]=None, object: Optional[ObjectDesignatorDescription.Object]=None, resolver: Optional[Callable]=None): """Moves the head of the robot such that the camera points towards the given location. If...
stack_v2_sparse_classes_75kplus_train_009125
20,871
no_license
[ { "docstring": "Moves the head of the robot such that the camera points towards the given location. If ``target`` and ``object`` are given ``target`` will be preferred. :param target: Position and orientation of the target :param object: An Object in the BulletWorld :param resolver: Alternative resolver that re...
2
null
Implement the Python class `LookingMotion` described below. Class description: Lets the robot look at a point Method signatures and docstrings: - def __init__(self, target: Optional[Pose]=None, object: Optional[ObjectDesignatorDescription.Object]=None, resolver: Optional[Callable]=None): Moves the head of the robot s...
Implement the Python class `LookingMotion` described below. Class description: Lets the robot look at a point Method signatures and docstrings: - def __init__(self, target: Optional[Pose]=None, object: Optional[ObjectDesignatorDescription.Object]=None, resolver: Optional[Callable]=None): Moves the head of the robot s...
f9ef666d6d4685660c9517652f2c568ed2c9367c
<|skeleton|> class LookingMotion: """Lets the robot look at a point""" def __init__(self, target: Optional[Pose]=None, object: Optional[ObjectDesignatorDescription.Object]=None, resolver: Optional[Callable]=None): """Moves the head of the robot such that the camera points towards the given location. If...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LookingMotion: """Lets the robot look at a point""" def __init__(self, target: Optional[Pose]=None, object: Optional[ObjectDesignatorDescription.Object]=None, resolver: Optional[Callable]=None): """Moves the head of the robot such that the camera points towards the given location. If ``target`` a...
the_stack_v2_python_sparse
src/pycram/designators/motion_designator.py
cram2/pycram
train
12
69f55097bce684431e8e28900284848681d35c54
[ "boxes = self.data\nsx, sy = factor if ub.iterable(factor) else (factor, factor)\nif torch.is_tensor(boxes):\n new_data = boxes.float().clone()\nelif boxes.dtype.kind != 'f':\n new_data = boxes.astype(np.float)\nelse:\n new_data = boxes.copy()\nnew_data[..., 0:4:2] *= sx\nnew_data[..., 1:4:2] *= sy\nreturn...
<|body_start_0|> boxes = self.data sx, sy = factor if ub.iterable(factor) else (factor, factor) if torch.is_tensor(boxes): new_data = boxes.float().clone() elif boxes.dtype.kind != 'f': new_data = boxes.astype(np.float) else: new_data = boxes.c...
methods for transforming bounding boxes
_BoxTransformMixins
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _BoxTransformMixins: """methods for transforming bounding boxes""" def scale(self, factor): """works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([...
stack_v2_sparse_classes_75kplus_train_009126
30,722
permissive
[ { "docstring": "works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([[1, 1, 10, 10]])).scale((2, .5)).data array([[ 2. , 0.5, 20. , 5. ]]) >>> Boxes(np.array([[10, 10]])).scale...
4
stack_v2_sparse_classes_30k_val_002429
Implement the Python class `_BoxTransformMixins` described below. Class description: methods for transforming bounding boxes Method signatures and docstrings: - def scale(self, factor): works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scal...
Implement the Python class `_BoxTransformMixins` described below. Class description: methods for transforming bounding boxes Method signatures and docstrings: - def scale(self, factor): works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scal...
facbc204c5c4596a07ba498883f3f7ffff002f67
<|skeleton|> class _BoxTransformMixins: """methods for transforming bounding boxes""" def scale(self, factor): """works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _BoxTransformMixins: """methods for transforming bounding boxes""" def scale(self, factor): """works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([[1, 1, 10, 10...
the_stack_v2_python_sparse
netharn/util/util_boxes.py
Cookt2/netharn
train
0
42f47c36e8ce68c911415fafc6efd72932181876
[ "session.query(DbFunction).filter_by(kb=db_kb).delete()\nfor func in func_manager.values():\n db_func = DbFunction(kb=db_kb, addr=func.addr, blob=func.serialize())\n session.add(db_func)", "funcs = FunctionManager(kb)\ndb_funcs = session.query(DbFunction).filter_by(kb=db_kb)\nall_func_addrs = set(map(lambda...
<|body_start_0|> session.query(DbFunction).filter_by(kb=db_kb).delete() for func in func_manager.values(): db_func = DbFunction(kb=db_kb, addr=func.addr, blob=func.serialize()) session.add(db_func) <|end_body_0|> <|body_start_1|> funcs = FunctionManager(kb) db_fu...
Serialize/unserialize a function manager and its functions.
FunctionManagerSerializer
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FunctionManagerSerializer: """Serialize/unserialize a function manager and its functions.""" def dump(session, db_kb, func_manager): """:param session: :param DbKnowledgeBase db_kb: :param FunctionManager func_manager: :return:""" <|body_0|> def load(session, db_kb, kb):...
stack_v2_sparse_classes_75kplus_train_009127
1,531
permissive
[ { "docstring": ":param session: :param DbKnowledgeBase db_kb: :param FunctionManager func_manager: :return:", "name": "dump", "signature": "def dump(session, db_kb, func_manager)" }, { "docstring": ":param session: :param DbKnowledgeBase db_kb: :param KnowledgeBase kb: :return: A loaded function...
2
stack_v2_sparse_classes_30k_train_019469
Implement the Python class `FunctionManagerSerializer` described below. Class description: Serialize/unserialize a function manager and its functions. Method signatures and docstrings: - def dump(session, db_kb, func_manager): :param session: :param DbKnowledgeBase db_kb: :param FunctionManager func_manager: :return:...
Implement the Python class `FunctionManagerSerializer` described below. Class description: Serialize/unserialize a function manager and its functions. Method signatures and docstrings: - def dump(session, db_kb, func_manager): :param session: :param DbKnowledgeBase db_kb: :param FunctionManager func_manager: :return:...
579c50afb11463fba656392e2c2944db6a279d18
<|skeleton|> class FunctionManagerSerializer: """Serialize/unserialize a function manager and its functions.""" def dump(session, db_kb, func_manager): """:param session: :param DbKnowledgeBase db_kb: :param FunctionManager func_manager: :return:""" <|body_0|> def load(session, db_kb, kb):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FunctionManagerSerializer: """Serialize/unserialize a function manager and its functions.""" def dump(session, db_kb, func_manager): """:param session: :param DbKnowledgeBase db_kb: :param FunctionManager func_manager: :return:""" session.query(DbFunction).filter_by(kb=db_kb).delete() ...
the_stack_v2_python_sparse
angr/angrdb/serializers/funcs.py
borzacchiello/angr
train
1
0d21f6d9d4ad53cfd9776e38469b832bc0736875
[ "self.estimated_monthly_base_pay = estimated_monthly_base_pay\nself.estimated_monthly_overtime_pay = estimated_monthly_overtime_pay\nself.estimated_monthly_bonus_pay = estimated_monthly_bonus_pay\nself.estimated_monthly_commission_pay = estimated_monthly_commission_pay\nself.additional_properties = additional_prope...
<|body_start_0|> self.estimated_monthly_base_pay = estimated_monthly_base_pay self.estimated_monthly_overtime_pay = estimated_monthly_overtime_pay self.estimated_monthly_bonus_pay = estimated_monthly_bonus_pay self.estimated_monthly_commission_pay = estimated_monthly_commission_pay ...
Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overtime_pay (float): The estimated monthly overtime pay am...
PaystubMonthlyIncomeRecord
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PaystubMonthlyIncomeRecord: """Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overt...
stack_v2_sparse_classes_75kplus_train_009128
3,514
permissive
[ { "docstring": "Constructor for the PaystubMonthlyIncomeRecord class", "name": "__init__", "signature": "def __init__(self, estimated_monthly_base_pay=None, estimated_monthly_overtime_pay=None, estimated_monthly_bonus_pay=None, estimated_monthly_commission_pay=None, additional_properties={})" }, { ...
2
stack_v2_sparse_classes_30k_train_024168
Implement the Python class `PaystubMonthlyIncomeRecord` described below. Class description: Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculat...
Implement the Python class `PaystubMonthlyIncomeRecord` described below. Class description: Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculat...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class PaystubMonthlyIncomeRecord: """Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overt...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PaystubMonthlyIncomeRecord: """Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overtime_pay (floa...
the_stack_v2_python_sparse
finicityapi/models/paystub_monthly_income_record.py
monarchmoney/finicity-python
train
0
d224de054a109824421b7cd2d6dd1af4e237f212
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cyyan_liuzirui_yjunchoi_yzhang71', 'cyyan_liuzirui_yjunchoi_yzhang71')\nurl = 'http://datamechanics.io/data/wuhaoyu_yiran123/MBTA_Bus_Stops.geojson'\nresponse = urllib.request.urlopen(url).read().decode(...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('cyyan_liuzirui_yjunchoi_yzhang71', 'cyyan_liuzirui_yjunchoi_yzhang71') url = 'http://datamechanics.io/data/wuhaoyu_yiran123/MBTA_Bus_Stops.geojson' ...
busstopCoordinates
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class busstopCoordinates: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing every...
stack_v2_sparse_classes_75kplus_train_009129
4,070
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
stack_v2_sparse_classes_30k_train_029525
Implement the Python class `busstopCoordinates` described below. Class description: Implement the busstopCoordinates class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTi...
Implement the Python class `busstopCoordinates` described below. Class description: Implement the busstopCoordinates class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTi...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class busstopCoordinates: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing every...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class busstopCoordinates: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('cyyan_liuzirui_yjunchoi_yzhang71...
the_stack_v2_python_sparse
cyyan_liuzirui_yjunchoi_yzhang71/busstopCoordinates.py
ROODAY/course-2017-fal-proj
train
3
46e4d8883b8a3cf9ea71825f7286740aa371176f
[ "if custom_migrations is None:\n custom_migrations = _global_custom_migrations\nself._signal_sender = signal_sender or self\nsuper(MigrationExecutor, self).__init__(connection=connection, progress_callback=self._on_progress)\nself.loader = MigrationLoader(connection=connection, custom_migrations=custom_migration...
<|body_start_0|> if custom_migrations is None: custom_migrations = _global_custom_migrations self._signal_sender = signal_sender or self super(MigrationExecutor, self).__init__(connection=connection, progress_callback=self._on_progress) self.loader = MigrationLoader(connectio...
Load and execute migrations. This is a specialization of Django's own :py:class:`~django.db.migrations.executor.MigrationExecutor` that allows for providing additional migrations not available on disk, and for emitting our own signals when processing migrations.
MigrationExecutor
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MigrationExecutor: """Load and execute migrations. This is a specialization of Django's own :py:class:`~django.db.migrations.executor.MigrationExecutor` that allows for providing additional migrations not available on disk, and for emitting our own signals when processing migrations.""" def ...
stack_v2_sparse_classes_75kplus_train_009130
35,220
permissive
[ { "docstring": "Initialize the executor. Version Changed: 2.2: ``custom_migrations`` now defaults to any globally-registered custom migrations set in :py:func:`register_global_custom_migrations`. Args: connection (django.db.backends.base.BaseDatabaseWrapper): The connection to load applied migrations from. cust...
3
stack_v2_sparse_classes_30k_train_043942
Implement the Python class `MigrationExecutor` described below. Class description: Load and execute migrations. This is a specialization of Django's own :py:class:`~django.db.migrations.executor.MigrationExecutor` that allows for providing additional migrations not available on disk, and for emitting our own signals w...
Implement the Python class `MigrationExecutor` described below. Class description: Load and execute migrations. This is a specialization of Django's own :py:class:`~django.db.migrations.executor.MigrationExecutor` that allows for providing additional migrations not available on disk, and for emitting our own signals w...
756eedeacc41f77111a557fc13dee559cb94f433
<|skeleton|> class MigrationExecutor: """Load and execute migrations. This is a specialization of Django's own :py:class:`~django.db.migrations.executor.MigrationExecutor` that allows for providing additional migrations not available on disk, and for emitting our own signals when processing migrations.""" def ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MigrationExecutor: """Load and execute migrations. This is a specialization of Django's own :py:class:`~django.db.migrations.executor.MigrationExecutor` that allows for providing additional migrations not available on disk, and for emitting our own signals when processing migrations.""" def __init__(self...
the_stack_v2_python_sparse
django_evolution/utils/migrations.py
beanbaginc/django-evolution
train
22
03e2ee771f16934cf8231060dd62e6dd4615276c
[ "self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))", "t = np.exp(z - np.max(z))\nsf = t / t.sum(axis=1, keepdims=True)\nreturn sf", "tanh_input = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.dot(tanh_input, ...
<|body_start_0|> self.Wh = np.random.normal(size=(i + h, h)) self.Wy = np.random.normal(size=(h, o)) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) <|end_body_0|> <|body_start_1|> t = np.exp(z - np.max(z)) sf = t / t.sum(axis=1, keepdims=True) return sf <|...
the class RNNCell
RNNCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNCell: """the class RNNCell""" def __init__(self, i, h, o): """function constructor""" <|body_0|> def softmax(self, z): """SOFTMAX FUNCTION""" <|body_1|> def forward(self, h_prev, x_t): """forward function""" <|body_2|> <|end_skele...
stack_v2_sparse_classes_75kplus_train_009131
832
no_license
[ { "docstring": "function constructor", "name": "__init__", "signature": "def __init__(self, i, h, o)" }, { "docstring": "SOFTMAX FUNCTION", "name": "softmax", "signature": "def softmax(self, z)" }, { "docstring": "forward function", "name": "forward", "signature": "def fo...
3
stack_v2_sparse_classes_30k_train_002318
Implement the Python class `RNNCell` described below. Class description: the class RNNCell Method signatures and docstrings: - def __init__(self, i, h, o): function constructor - def softmax(self, z): SOFTMAX FUNCTION - def forward(self, h_prev, x_t): forward function
Implement the Python class `RNNCell` described below. Class description: the class RNNCell Method signatures and docstrings: - def __init__(self, i, h, o): function constructor - def softmax(self, z): SOFTMAX FUNCTION - def forward(self, h_prev, x_t): forward function <|skeleton|> class RNNCell: """the class RNN...
f887cfd48bb44bc4ac440e27014c82390994f04d
<|skeleton|> class RNNCell: """the class RNNCell""" def __init__(self, i, h, o): """function constructor""" <|body_0|> def softmax(self, z): """SOFTMAX FUNCTION""" <|body_1|> def forward(self, h_prev, x_t): """forward function""" <|body_2|> <|end_skele...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RNNCell: """the class RNNCell""" def __init__(self, i, h, o): """function constructor""" self.Wh = np.random.normal(size=(i + h, h)) self.Wy = np.random.normal(size=(h, o)) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) def softmax(self, z): """...
the_stack_v2_python_sparse
supervised_learning/0x0D-RNNs/0-rnn_cell.py
AhmedOmi/holbertonschool-machine_learning
train
0
17b3668fb6ab4ac7fb17c82f5516402cbe4ba89b
[ "super(SeqPostProcessor, self).__init__()\nself.word_vocab = word_vocab\nself.tk = tokenizer\nself.dtk = detokenizer\nself.ss = sent_splitter\nself.tc = tcaser\nself.retain_end_token = retain_end_token", "if self.word_vocab is not None:\n seq = format_seq(seq, start=self.word_vocab[START].id, end=self.word_voc...
<|body_start_0|> super(SeqPostProcessor, self).__init__() self.word_vocab = word_vocab self.tk = tokenizer self.dtk = detokenizer self.ss = sent_splitter self.tc = tcaser self.retain_end_token = retain_end_token <|end_body_0|> <|body_start_1|> if self.wor...
Post-processes sequences generated by the model to make them human readable.
SeqPostProcessor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeqPostProcessor: """Post-processes sequences generated by the model to make them human readable.""" def __init__(self, word_vocab=None, tokenizer=None, detokenizer=None, sent_splitter=None, tcaser=None, retain_end_token=True): """Args: word_vocab: self-explanatory. tokenizer: if pro...
stack_v2_sparse_classes_75kplus_train_009132
2,428
permissive
[ { "docstring": "Args: word_vocab: self-explanatory. tokenizer: if provided will tokenize and concatenate input tokens. detokenizer: used to make the sequence look more like human written. sent_splitter: a function that splits a string to sentences. Used for capitalisation of first words if provided. tcaser: a t...
2
stack_v2_sparse_classes_30k_train_038948
Implement the Python class `SeqPostProcessor` described below. Class description: Post-processes sequences generated by the model to make them human readable. Method signatures and docstrings: - def __init__(self, word_vocab=None, tokenizer=None, detokenizer=None, sent_splitter=None, tcaser=None, retain_end_token=Tru...
Implement the Python class `SeqPostProcessor` described below. Class description: Post-processes sequences generated by the model to make them human readable. Method signatures and docstrings: - def __init__(self, word_vocab=None, tokenizer=None, detokenizer=None, sent_splitter=None, tcaser=None, retain_end_token=Tru...
ca20e6eb8f93d21f9215a9cbf5a171b56600e3c1
<|skeleton|> class SeqPostProcessor: """Post-processes sequences generated by the model to make them human readable.""" def __init__(self, word_vocab=None, tokenizer=None, detokenizer=None, sent_splitter=None, tcaser=None, retain_end_token=True): """Args: word_vocab: self-explanatory. tokenizer: if pro...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SeqPostProcessor: """Post-processes sequences generated by the model to make them human readable.""" def __init__(self, word_vocab=None, tokenizer=None, detokenizer=None, sent_splitter=None, tcaser=None, retain_end_token=True): """Args: word_vocab: self-explanatory. tokenizer: if provided will to...
the_stack_v2_python_sparse
fewsum/utils/tools/seq_post_processor.py
developerdrone/FewSum
train
0
6c6dba21768d084e1deb7462e433b0489d0210f2
[ "self._key_proj = ContextProjection(bottleneck_dimension)\nself._val_proj = ContextProjection(bottleneck_dimension)\nself._query_proj = ContextProjection(bottleneck_dimension)\nself._feature_proj = None\nself._attention_temperature = attention_temperature\nself._bottleneck_dimension = bottleneck_dimension\nself._is...
<|body_start_0|> self._key_proj = ContextProjection(bottleneck_dimension) self._val_proj = ContextProjection(bottleneck_dimension) self._query_proj = ContextProjection(bottleneck_dimension) self._feature_proj = None self._attention_temperature = attention_temperature self...
Custom layer to perform all attention.
AttentionBlock
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentionBlock: """Custom layer to perform all attention.""" def __init__(self, bottleneck_dimension, attention_temperature, output_dimension=None, is_training=False, name='AttentionBlock', max_num_proposals=100, **kwargs): """Constructs an attention block. Args: bottleneck_dimension...
stack_v2_sparse_classes_75kplus_train_009133
10,274
permissive
[ { "docstring": "Constructs an attention block. Args: bottleneck_dimension: A int32 Tensor representing the bottleneck dimension for intermediate projections. attention_temperature: A float Tensor. It controls the temperature of the softmax for weights calculation. The formula for calculation as follows: weights...
3
stack_v2_sparse_classes_30k_train_041312
Implement the Python class `AttentionBlock` described below. Class description: Custom layer to perform all attention. Method signatures and docstrings: - def __init__(self, bottleneck_dimension, attention_temperature, output_dimension=None, is_training=False, name='AttentionBlock', max_num_proposals=100, **kwargs): ...
Implement the Python class `AttentionBlock` described below. Class description: Custom layer to perform all attention. Method signatures and docstrings: - def __init__(self, bottleneck_dimension, attention_temperature, output_dimension=None, is_training=False, name='AttentionBlock', max_num_proposals=100, **kwargs): ...
6fc53292b1d3ce3c0340ce724c2c11c77e663d27
<|skeleton|> class AttentionBlock: """Custom layer to perform all attention.""" def __init__(self, bottleneck_dimension, attention_temperature, output_dimension=None, is_training=False, name='AttentionBlock', max_num_proposals=100, **kwargs): """Constructs an attention block. Args: bottleneck_dimension...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AttentionBlock: """Custom layer to perform all attention.""" def __init__(self, bottleneck_dimension, attention_temperature, output_dimension=None, is_training=False, name='AttentionBlock', max_num_proposals=100, **kwargs): """Constructs an attention block. Args: bottleneck_dimension: A int32 Ten...
the_stack_v2_python_sparse
models/research/object_detection/meta_architectures/context_rcnn_lib_tf2.py
aboerzel/German_License_Plate_Recognition
train
34
77a05df04ddd22f5c609b32ceda10e6d7b02046a
[ "user = User.objects.create(username='testuser', password='qwerty12345Q!')\nrecruiter = User.objects.create(username='recruiter3', first_name='first_recruiter', last_name='last_recruiter', email='recruiter@mail.com')\ncandidate = User.objects.create(username='candidate3', first_name='first_candidate', last_name='la...
<|body_start_0|> user = User.objects.create(username='testuser', password='qwerty12345Q!') recruiter = User.objects.create(username='recruiter3', first_name='first_recruiter', last_name='last_recruiter', email='recruiter@mail.com') candidate = User.objects.create(username='candidate3', first_nam...
Test POST request Answers app
AnswersPostTestCases
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnswersPostTestCases: """Test POST request Answers app""" def setUp(self): """Create new data in in linked tables""" <|body_0|> def test_post_create_answers(self): """Test for POST Answers""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = U...
stack_v2_sparse_classes_75kplus_train_009134
13,494
no_license
[ { "docstring": "Create new data in in linked tables", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test for POST Answers", "name": "test_post_create_answers", "signature": "def test_post_create_answers(self)" } ]
2
stack_v2_sparse_classes_30k_train_043630
Implement the Python class `AnswersPostTestCases` described below. Class description: Test POST request Answers app Method signatures and docstrings: - def setUp(self): Create new data in in linked tables - def test_post_create_answers(self): Test for POST Answers
Implement the Python class `AnswersPostTestCases` described below. Class description: Test POST request Answers app Method signatures and docstrings: - def setUp(self): Create new data in in linked tables - def test_post_create_answers(self): Test for POST Answers <|skeleton|> class AnswersPostTestCases: """Test...
f448ec0453818d55c5c9d30aaa4f19e1d7ca5867
<|skeleton|> class AnswersPostTestCases: """Test POST request Answers app""" def setUp(self): """Create new data in in linked tables""" <|body_0|> def test_post_create_answers(self): """Test for POST Answers""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AnswersPostTestCases: """Test POST request Answers app""" def setUp(self): """Create new data in in linked tables""" user = User.objects.create(username='testuser', password='qwerty12345Q!') recruiter = User.objects.create(username='recruiter3', first_name='first_recruiter', last_...
the_stack_v2_python_sparse
Portfolio/tech-interview/techinterview/feedback/test_feedback.py
HeCToR74/Python
train
1
04295c02a91de6178cb7dbea7dd23c3ae98b3991
[ "if not root:\n return []\nqueue = [root]\nres = []\nwhile queue:\n child = []\n node = []\n for q in queue:\n if q:\n child.append(q.val)\n if q.left:\n node.append(q.left)\n if q.right:\n node.append(q.right)\n queue = node\n ...
<|body_start_0|> if not root: return [] queue = [root] res = [] while queue: child = [] node = [] for q in queue: if q: child.append(q.val) if q.left: node.appe...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: """bfs""" <|body_0|> def levelOrder(self, root: TreeNode) -> List[List[int]]: """dfs :param root: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: ...
stack_v2_sparse_classes_75kplus_train_009135
1,746
no_license
[ { "docstring": "bfs", "name": "levelOrderBfs", "signature": "def levelOrderBfs(self, root: TreeNode) -> List[List[int]]" }, { "docstring": "dfs :param root: :return:", "name": "levelOrder", "signature": "def levelOrder(self, root: TreeNode) -> List[List[int]]" } ]
2
stack_v2_sparse_classes_30k_train_028246
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: bfs - def levelOrder(self, root: TreeNode) -> List[List[int]]: dfs :param root: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: bfs - def levelOrder(self, root: TreeNode) -> List[List[int]]: dfs :param root: :return: <|skeleton|> class Solution:...
1a1abf5aabdd23755769efaa6c33579bc5b0917b
<|skeleton|> class Solution: def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: """bfs""" <|body_0|> def levelOrder(self, root: TreeNode) -> List[List[int]]: """dfs :param root: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: """bfs""" if not root: return [] queue = [root] res = [] while queue: child = [] node = [] for q in queue: if q: chi...
the_stack_v2_python_sparse
Week_03/G20190343020041/LeetCode_102_0041.py
algorithm005-class02/algorithm005-class02
train
45
321811d8aa35a3d729bad9bde4ccdd04d1a0c8e1
[ "id = range(N + 1)\nsize = [1] * (N + 1)\n\ndef union(a, b):\n i, j = (root(a), root(b))\n if i == j:\n return False\n if size[i] < size[j]:\n size[j] += size[i]\n id[i] = j\n else:\n size[i] += size[j]\n id[j] = i\n return True\n\ndef root(a):\n while id[a] != a...
<|body_start_0|> id = range(N + 1) size = [1] * (N + 1) def union(a, b): i, j = (root(a), root(b)) if i == j: return False if size[i] < size[j]: size[j] += size[i] id[i] = j else: siz...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumCost_union_find(self, N, connections): """:type N: int :type connections: List[List[int]] :rtype: int""" <|body_0|> def minimumCost_bfs(self, N, connections): """:type N: int :type connections: List[List[int]] :rtype: int""" <|body_1|> <...
stack_v2_sparse_classes_75kplus_train_009136
2,038
no_license
[ { "docstring": ":type N: int :type connections: List[List[int]] :rtype: int", "name": "minimumCost_union_find", "signature": "def minimumCost_union_find(self, N, connections)" }, { "docstring": ":type N: int :type connections: List[List[int]] :rtype: int", "name": "minimumCost_bfs", "sig...
2
stack_v2_sparse_classes_30k_train_027015
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumCost_union_find(self, N, connections): :type N: int :type connections: List[List[int]] :rtype: int - def minimumCost_bfs(self, N, connections): :type N: int :type conn...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumCost_union_find(self, N, connections): :type N: int :type connections: List[List[int]] :rtype: int - def minimumCost_bfs(self, N, connections): :type N: int :type conn...
3a7f20f79281fcaedb10696723dcb39c816ce258
<|skeleton|> class Solution: def minimumCost_union_find(self, N, connections): """:type N: int :type connections: List[List[int]] :rtype: int""" <|body_0|> def minimumCost_bfs(self, N, connections): """:type N: int :type connections: List[List[int]] :rtype: int""" <|body_1|> <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minimumCost_union_find(self, N, connections): """:type N: int :type connections: List[List[int]] :rtype: int""" id = range(N + 1) size = [1] * (N + 1) def union(a, b): i, j = (root(a), root(b)) if i == j: return False ...
the_stack_v2_python_sparse
1135_min_spanning_tree_union_find_bfs.py
haohanz/Leetcode-Solution
train
1
dec7b8b0df1bdf347c8639c86fae03eeffc2e5ec
[ "user = create_user('foo', 'bar')\nblog = create_blog('BlogTest', user)\nresponse = self.client.get(reverse('blogs:blog', args=[blog.id, blog.slug]))\nself.assertQuerysetEqual(response.context['posts'], [])", "_user = create_user('fo', 'bar')\n_blog = create_blog('blog', _user)\npost1 = create_post(_blog, 'Post1'...
<|body_start_0|> user = create_user('foo', 'bar') blog = create_blog('BlogTest', user) response = self.client.get(reverse('blogs:blog', args=[blog.id, blog.slug])) self.assertQuerysetEqual(response.context['posts'], []) <|end_body_0|> <|body_start_1|> _user = create_user('fo', '...
BlogsPostsTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BlogsPostsTests: def test_no_posts(self): """Jeśli użytkownika nie dodał żadnego posta, lista zwróconych postów będzie pusta.""" <|body_0|> def test_two_last_posts(self): """Po dodaniu dwóch postów przez użytkownika, zostaną one przypisane do ostatnich postów.""" ...
stack_v2_sparse_classes_75kplus_train_009137
3,948
no_license
[ { "docstring": "Jeśli użytkownika nie dodał żadnego posta, lista zwróconych postów będzie pusta.", "name": "test_no_posts", "signature": "def test_no_posts(self)" }, { "docstring": "Po dodaniu dwóch postów przez użytkownika, zostaną one przypisane do ostatnich postów.", "name": "test_two_las...
5
stack_v2_sparse_classes_30k_val_002468
Implement the Python class `BlogsPostsTests` described below. Class description: Implement the BlogsPostsTests class. Method signatures and docstrings: - def test_no_posts(self): Jeśli użytkownika nie dodał żadnego posta, lista zwróconych postów będzie pusta. - def test_two_last_posts(self): Po dodaniu dwóch postów p...
Implement the Python class `BlogsPostsTests` described below. Class description: Implement the BlogsPostsTests class. Method signatures and docstrings: - def test_no_posts(self): Jeśli użytkownika nie dodał żadnego posta, lista zwróconych postów będzie pusta. - def test_two_last_posts(self): Po dodaniu dwóch postów p...
707bb9ae84aa5d4e60425569c79ec8cf2fe98c25
<|skeleton|> class BlogsPostsTests: def test_no_posts(self): """Jeśli użytkownika nie dodał żadnego posta, lista zwróconych postów będzie pusta.""" <|body_0|> def test_two_last_posts(self): """Po dodaniu dwóch postów przez użytkownika, zostaną one przypisane do ostatnich postów.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BlogsPostsTests: def test_no_posts(self): """Jeśli użytkownika nie dodał żadnego posta, lista zwróconych postów będzie pusta.""" user = create_user('foo', 'bar') blog = create_blog('BlogTest', user) response = self.client.get(reverse('blogs:blog', args=[blog.id, blog.slug])) ...
the_stack_v2_python_sparse
blogs/tests.py
arn3th/naszblog
train
0
0e0a7b91f0b1f93449c49c571683a8e9ba91b281
[ "super().__init__(session_maker)\nself.coin_category = 'ETH'\nself.chain_api = ERC20Token()", "now = datetime.datetime.now()\nfilename = '{}_{}_{}_{}'.format(self.coin_category, now.strftime('%Y%m%d'), cnt, now.timestamp())\npassword = '{}_{}'.format(config.passwd_prefix, filename)\nfn = '{}/{}'.format(config.pri...
<|body_start_0|> super().__init__(session_maker) self.coin_category = 'ETH' self.chain_api = ERC20Token() <|end_body_0|> <|body_start_1|> now = datetime.datetime.now() filename = '{}_{}_{}_{}'.format(self.coin_category, now.strftime('%Y%m%d'), cnt, now.timestamp()) passw...
ErcManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ErcManager: def __init__(self, session_maker): """:param session_maker: mysql的session_maker""" <|body_0|> def generate_address(self, cnt: int) -> dict: """产生erc20地址账户 :param cnt: 编号 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__...
stack_v2_sparse_classes_75kplus_train_009138
1,454
no_license
[ { "docstring": ":param session_maker: mysql的session_maker", "name": "__init__", "signature": "def __init__(self, session_maker)" }, { "docstring": "产生erc20地址账户 :param cnt: 编号 :return:", "name": "generate_address", "signature": "def generate_address(self, cnt: int) -> dict" } ]
2
stack_v2_sparse_classes_30k_train_031190
Implement the Python class `ErcManager` described below. Class description: Implement the ErcManager class. Method signatures and docstrings: - def __init__(self, session_maker): :param session_maker: mysql的session_maker - def generate_address(self, cnt: int) -> dict: 产生erc20地址账户 :param cnt: 编号 :return:
Implement the Python class `ErcManager` described below. Class description: Implement the ErcManager class. Method signatures and docstrings: - def __init__(self, session_maker): :param session_maker: mysql的session_maker - def generate_address(self, cnt: int) -> dict: 产生erc20地址账户 :param cnt: 编号 :return: <|skeleton|>...
4ddca9c77c2361a8b9f0a708353809449094137d
<|skeleton|> class ErcManager: def __init__(self, session_maker): """:param session_maker: mysql的session_maker""" <|body_0|> def generate_address(self, cnt: int) -> dict: """产生erc20地址账户 :param cnt: 编号 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ErcManager: def __init__(self, session_maker): """:param session_maker: mysql的session_maker""" super().__init__(session_maker) self.coin_category = 'ETH' self.chain_api = ERC20Token() def generate_address(self, cnt: int) -> dict: """产生erc20地址账户 :param cnt: 编号 :retu...
the_stack_v2_python_sparse
source/common/address_manager/erc_20.py
buyongji/wallet
train
1
3200557ebf59ad6098e523817ad78e68e9bbbb2a
[ "assert self.steps_per_batch > -1 or self.episodes_per_batch > -1, 'You must define how many timesteps or episodes will be in each batch'\nassert not (self.steps_per_batch > -1 and self.episodes_per_batch > -1), 'You must define either steps or episodes per batch'\nif self.steps_per_batch > -1:\n trajs = self.en...
<|body_start_0|> assert self.steps_per_batch > -1 or self.episodes_per_batch > -1, 'You must define how many timesteps or episodes will be in each batch' assert not (self.steps_per_batch > -1 and self.episodes_per_batch > -1), 'You must define either steps or episodes per batch' if self.steps_pe...
An agent that has methods for collecting a collection of trajectories.
BatchAgent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BatchAgent: """An agent that has methods for collecting a collection of trajectories.""" def generate_trajectories(self): """Generate a collection of trajectories, limited by ``timesteps_per_batch`` or ``episodes_per_batch``. Returns ------- trajectories: list A list containing all s...
stack_v2_sparse_classes_75kplus_train_009139
2,018
permissive
[ { "docstring": "Generate a collection of trajectories, limited by ``timesteps_per_batch`` or ``episodes_per_batch``. Returns ------- trajectories: list A list containing all sampled trajectories.", "name": "generate_trajectories", "signature": "def generate_trajectories(self)" }, { "docstring": ...
2
stack_v2_sparse_classes_30k_train_024669
Implement the Python class `BatchAgent` described below. Class description: An agent that has methods for collecting a collection of trajectories. Method signatures and docstrings: - def generate_trajectories(self): Generate a collection of trajectories, limited by ``timesteps_per_batch`` or ``episodes_per_batch``. R...
Implement the Python class `BatchAgent` described below. Class description: An agent that has methods for collecting a collection of trajectories. Method signatures and docstrings: - def generate_trajectories(self): Generate a collection of trajectories, limited by ``timesteps_per_batch`` or ``episodes_per_batch``. R...
ed898e4bc0fc57d25c2349a9178fdc485e232661
<|skeleton|> class BatchAgent: """An agent that has methods for collecting a collection of trajectories.""" def generate_trajectories(self): """Generate a collection of trajectories, limited by ``timesteps_per_batch`` or ``episodes_per_batch``. Returns ------- trajectories: list A list containing all s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BatchAgent: """An agent that has methods for collecting a collection of trajectories.""" def generate_trajectories(self): """Generate a collection of trajectories, limited by ``timesteps_per_batch`` or ``episodes_per_batch``. Returns ------- trajectories: list A list containing all sampled trajec...
the_stack_v2_python_sparse
torchrl/agents/batch_agent.py
MahdiKarimian/torchrl
train
0
8f1cb251047bc0f41c858c9af34575fb5203e192
[ "instanceA = Enum()\ninstanceB = Enum()\nself.assertEqual(instanceA, instanceB)", "instance = Enum()\nHORIZONTAL = instance.getNextId('orientation')\nVERTICAL = instance.getNextId('orientation')\nself.assertTrue(HORIZONTAL < VERTICAL)", "class Direction:\n TOP = enum('direction')\n LEFT = enum('direction'...
<|body_start_0|> instanceA = Enum() instanceB = Enum() self.assertEqual(instanceA, instanceB) <|end_body_0|> <|body_start_1|> instance = Enum() HORIZONTAL = instance.getNextId('orientation') VERTICAL = instance.getNextId('orientation') self.assertTrue(HORIZONTAL ...
testing of class Enum
EnumTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnumTestCase: """testing of class Enum""" def testSingleton(self): """testing the singleton mechanism""" <|body_0|> def testGetNextId(self): """example of creating two constants""" <|body_1|> def testEnumFunctionWithStringContext(self): """ex...
stack_v2_sparse_classes_75kplus_train_009140
4,176
permissive
[ { "docstring": "testing the singleton mechanism", "name": "testSingleton", "signature": "def testSingleton(self)" }, { "docstring": "example of creating two constants", "name": "testGetNextId", "signature": "def testGetNextId(self)" }, { "docstring": "example of creating four con...
4
stack_v2_sparse_classes_30k_train_032934
Implement the Python class `EnumTestCase` described below. Class description: testing of class Enum Method signatures and docstrings: - def testSingleton(self): testing the singleton mechanism - def testGetNextId(self): example of creating two constants - def testEnumFunctionWithStringContext(self): example of creati...
Implement the Python class `EnumTestCase` described below. Class description: testing of class Enum Method signatures and docstrings: - def testSingleton(self): testing the singleton mechanism - def testGetNextId(self): example of creating two constants - def testEnumFunctionWithStringContext(self): example of creati...
d097ca0ad6a6aee2180d32dce6a3322621f655fd
<|skeleton|> class EnumTestCase: """testing of class Enum""" def testSingleton(self): """testing the singleton mechanism""" <|body_0|> def testGetNextId(self): """example of creating two constants""" <|body_1|> def testEnumFunctionWithStringContext(self): """ex...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EnumTestCase: """testing of class Enum""" def testSingleton(self): """testing the singleton mechanism""" instanceA = Enum() instanceB = Enum() self.assertEqual(instanceA, instanceB) def testGetNextId(self): """example of creating two constants""" insta...
the_stack_v2_python_sparse
recipes/Python/578015_Simple_enum_mechanism/recipe-578015.py
betty29/code-1
train
0
f271fac2a7e2970aab769f19532029b6064b9a9e
[ "obs, exp = ((4, 2), (6, 1))\nanswer = (4 - 6) / np.sqrt(5)\nz = statfunc.calc_z(obs, exp)\nassert z == answer", "obs, exp = ((4, 2), (6, 0))\nz = statfunc.calc_z(obs, exp)\nassert z == -1", "obs, exp = ((8, 0), (9, 0))\nz = statfunc.calc_z(obs, exp)\nassert z == np.inf" ]
<|body_start_0|> obs, exp = ((4, 2), (6, 1)) answer = (4 - 6) / np.sqrt(5) z = statfunc.calc_z(obs, exp) assert z == answer <|end_body_0|> <|body_start_1|> obs, exp = ((4, 2), (6, 0)) z = statfunc.calc_z(obs, exp) assert z == -1 <|end_body_1|> <|body_start_2|> ...
Tests the calc_z function
TestCalcZ
[ "WTFPL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCalcZ: """Tests the calc_z function""" def test_zcalc(self): """Tests the calculation with all nonzero values""" <|body_0|> def test_zcalc_zero_se_sided(self): """Tests to make sure that one zero does not error out""" <|body_1|> def test_zcalc_ze...
stack_v2_sparse_classes_75kplus_train_009141
4,777
permissive
[ { "docstring": "Tests the calculation with all nonzero values", "name": "test_zcalc", "signature": "def test_zcalc(self)" }, { "docstring": "Tests to make sure that one zero does not error out", "name": "test_zcalc_zero_se_sided", "signature": "def test_zcalc_zero_se_sided(self)" }, ...
3
null
Implement the Python class `TestCalcZ` described below. Class description: Tests the calc_z function Method signatures and docstrings: - def test_zcalc(self): Tests the calculation with all nonzero values - def test_zcalc_zero_se_sided(self): Tests to make sure that one zero does not error out - def test_zcalc_zero_s...
Implement the Python class `TestCalcZ` described below. Class description: Tests the calc_z function Method signatures and docstrings: - def test_zcalc(self): Tests the calculation with all nonzero values - def test_zcalc_zero_se_sided(self): Tests to make sure that one zero does not error out - def test_zcalc_zero_s...
94ab2613c5d53ea471f664a75c7d780a2689302f
<|skeleton|> class TestCalcZ: """Tests the calc_z function""" def test_zcalc(self): """Tests the calculation with all nonzero values""" <|body_0|> def test_zcalc_zero_se_sided(self): """Tests to make sure that one zero does not error out""" <|body_1|> def test_zcalc_ze...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestCalcZ: """Tests the calc_z function""" def test_zcalc(self): """Tests the calculation with all nonzero values""" obs, exp = ((4, 2), (6, 1)) answer = (4 - 6) / np.sqrt(5) z = statfunc.calc_z(obs, exp) assert z == answer def test_zcalc_zero_se_sided(self): ...
the_stack_v2_python_sparse
gale/stats/test_functions.py
adamrpah/GALE
train
0
d8d1db1c6308975cf5314ef81198c3b3c82bd6b9
[ "super().__init__()\nself._dates_cache: Optional[pd.DataFrame] = None\nself._cache_lock = asyncio.Lock()", "name = self._log_and_validate_group(table_name, outer.TRADING_DATES)\nif name != outer.TRADING_DATES:\n raise outer.DataError(f'Некорректное имя таблицы для обновления {table_name}')\nasync with self._ca...
<|body_start_0|> super().__init__() self._dates_cache: Optional[pd.DataFrame] = None self._cache_lock = asyncio.Lock() <|end_body_0|> <|body_start_1|> name = self._log_and_validate_group(table_name, outer.TRADING_DATES) if name != outer.TRADING_DATES: raise outer.Dat...
Обновление для таблиц с диапазоном доступных торговых дат.
TradingDatesLoader
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TradingDatesLoader: """Обновление для таблиц с диапазоном доступных торговых дат.""" def __init__(self) -> None: """Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.""" <|body_0|> async def get(self, table_name: outer.TableName) -> pd.DataFrame: ...
stack_v2_sparse_classes_75kplus_train_009142
1,823
permissive
[ { "docstring": "Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Получение обновленных данных о доступном диапазоне торговых дат.", "name": "get", "signature": "async def get(self, t...
2
stack_v2_sparse_classes_30k_train_012126
Implement the Python class `TradingDatesLoader` described below. Class description: Обновление для таблиц с диапазоном доступных торговых дат. Method signatures and docstrings: - def __init__(self) -> None: Кэшируются данные, чтобы сократить количество обращений к серверу MOEX. - async def get(self, table_name: outer...
Implement the Python class `TradingDatesLoader` described below. Class description: Обновление для таблиц с диапазоном доступных торговых дат. Method signatures and docstrings: - def __init__(self) -> None: Кэшируются данные, чтобы сократить количество обращений к серверу MOEX. - async def get(self, table_name: outer...
e5d0f2c28de25568e4515b63aaad4aa337e2e522
<|skeleton|> class TradingDatesLoader: """Обновление для таблиц с диапазоном доступных торговых дат.""" def __init__(self) -> None: """Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.""" <|body_0|> async def get(self, table_name: outer.TableName) -> pd.DataFrame: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TradingDatesLoader: """Обновление для таблиц с диапазоном доступных торговых дат.""" def __init__(self) -> None: """Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.""" super().__init__() self._dates_cache: Optional[pd.DataFrame] = None self._cache_lo...
the_stack_v2_python_sparse
poptimizer/data/adapters/loaders/trading_dates.py
chekanskiy/poptimizer
train
0
d0bd5c9412adc47bd92b2e671466afcb46fc738b
[ "self.track = track\nself.channel = channel\nself.time = time\nself.duration = duration\nself.tempo = tempo\nself.volume = volume", "output_MIDI_file = MIDIFile(1)\noutput_MIDI_file.addTempo(self.track, self.time, self.tempo)\nfor i, pitch in enumerate(midi_number_list):\n self.volume = int((pitch - 50) / (90 ...
<|body_start_0|> self.track = track self.channel = channel self.time = time self.duration = duration self.tempo = tempo self.volume = volume <|end_body_0|> <|body_start_1|> output_MIDI_file = MIDIFile(1) output_MIDI_file.addTempo(self.track, self.time, se...
PostProcessing
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PostProcessing: def __init__(self, track=0, channel=0, time=0, duration=1, tempo=60, volume=100): """Constructor of the class Parameters: - track (int) : - channel (int) : - time (int) : - duration (int) : - tempo (int) : - volume (int) : Returns: - An object of type Postprocessing""" ...
stack_v2_sparse_classes_75kplus_train_009143
1,341
permissive
[ { "docstring": "Constructor of the class Parameters: - track (int) : - channel (int) : - time (int) : - duration (int) : - tempo (int) : - volume (int) : Returns: - An object of type Postprocessing", "name": "__init__", "signature": "def __init__(self, track=0, channel=0, time=0, duration=1, tempo=60, v...
2
stack_v2_sparse_classes_30k_train_050537
Implement the Python class `PostProcessing` described below. Class description: Implement the PostProcessing class. Method signatures and docstrings: - def __init__(self, track=0, channel=0, time=0, duration=1, tempo=60, volume=100): Constructor of the class Parameters: - track (int) : - channel (int) : - time (int) ...
Implement the Python class `PostProcessing` described below. Class description: Implement the PostProcessing class. Method signatures and docstrings: - def __init__(self, track=0, channel=0, time=0, duration=1, tempo=60, volume=100): Constructor of the class Parameters: - track (int) : - channel (int) : - time (int) ...
a0917e785c35aa5fadcbb258e938c58071b4e482
<|skeleton|> class PostProcessing: def __init__(self, track=0, channel=0, time=0, duration=1, tempo=60, volume=100): """Constructor of the class Parameters: - track (int) : - channel (int) : - time (int) : - duration (int) : - tempo (int) : - volume (int) : Returns: - An object of type Postprocessing""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PostProcessing: def __init__(self, track=0, channel=0, time=0, duration=1, tempo=60, volume=100): """Constructor of the class Parameters: - track (int) : - channel (int) : - time (int) : - duration (int) : - tempo (int) : - volume (int) : Returns: - An object of type Postprocessing""" self.tra...
the_stack_v2_python_sparse
Pitch-Based Approach/postprocessing/postprocessing.py
pkaplish20/UAlberta-Multimedia-Masters-Program-Music-is-all-you-need-to-analyze-data
train
0
ee2a500d2de82fe9593a8b3981d4df780c8f9f01
[ "self.backup_source_inode_id = backup_source_inode_id\nself.mtime_usecs = mtime_usecs\nself.size = size\nself.mtype = mtype", "if dictionary is None:\n return None\nbackup_source_inode_id = dictionary.get('backupSourceInodeId')\nmtime_usecs = dictionary.get('mtimeUsecs')\nsize = dictionary.get('size')\nmtype =...
<|body_start_0|> self.backup_source_inode_id = backup_source_inode_id self.mtime_usecs = mtime_usecs self.size = size self.mtype = mtype <|end_body_0|> <|body_start_1|> if dictionary is None: return None backup_source_inode_id = dictionary.get('backupSourceIn...
Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is a file, the size of the file as returne...
FileStatInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileStatInfo: """Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is...
stack_v2_sparse_classes_75kplus_train_009144
2,281
permissive
[ { "docstring": "Constructor for the FileStatInfo class", "name": "__init__", "signature": "def __init__(self, backup_source_inode_id=None, mtime_usecs=None, size=None, mtype=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary ...
2
stack_v2_sparse_classes_30k_train_049014
Implement the Python class `FileStatInfo` described below. Class description: Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as return...
Implement the Python class `FileStatInfo` described below. Class description: Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as return...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class FileStatInfo: """Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileStatInfo: """Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is a file, the ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/file_stat_info.py
cohesity/management-sdk-python
train
24
2b64e35c62cf86cf6d7af1214ec8f9e22c3ca8fc
[ "assert len(hidden_layers_sizes) > 0\nself.n_layers = len(hidden_layers_sizes)\nself.layers = []\nself.rbm_layers = []\nself.params = []\nself.x = tf.placeholder(tf.float32, shape=[None, n_in])\nself.y = tf.placeholder(tf.float32, shape=[None, n_out])\nfor i in range(self.n_layers):\n if i == 0:\n layer_i...
<|body_start_0|> assert len(hidden_layers_sizes) > 0 self.n_layers = len(hidden_layers_sizes) self.layers = [] self.rbm_layers = [] self.params = [] self.x = tf.placeholder(tf.float32, shape=[None, n_in]) self.y = tf.placeholder(tf.float32, shape=[None, n_out]) ...
An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer.
DBN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBN: """An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer.""" def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]): """:param n_in: int, the dimension of input :param n_o...
stack_v2_sparse_classes_75kplus_train_009145
5,942
no_license
[ { "docstring": ":param n_in: int, the dimension of input :param n_out: int, the dimension of output :param hidden_layers_sizes: list or tuple, the hidden layer sizes", "name": "__init__", "signature": "def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500])" }, { "docstring": "Pre...
3
stack_v2_sparse_classes_30k_train_004441
Implement the Python class `DBN` described below. Class description: An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer. Method signatures and docstrings: - def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 5...
Implement the Python class `DBN` described below. Class description: An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer. Method signatures and docstrings: - def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 5...
a9b356636988ee920be5933155cd3d7c7559e201
<|skeleton|> class DBN: """An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer.""" def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]): """:param n_in: int, the dimension of input :param n_o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DBN: """An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer.""" def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]): """:param n_in: int, the dimension of input :param n_out: int, the ...
the_stack_v2_python_sparse
deepLearning/08_dbn.py
robot-Yang/Ewenwan_vision
train
11
a81157a174c6ce9b98d8916364616039bfc41689
[ "self._feature_store_id = feature_store_id\nself._feature_group_id = feature_group_id\nself._expectation_suite_id = expectation_suite_id", "_client = client.get_instance()\npath_params = ['project', _client._project_id, 'featurestores', self._feature_store_id, 'featuregroups', self._feature_group_id, 'expectation...
<|body_start_0|> self._feature_store_id = feature_store_id self._feature_group_id = feature_group_id self._expectation_suite_id = expectation_suite_id <|end_body_0|> <|body_start_1|> _client = client.get_instance() path_params = ['project', _client._project_id, 'featurestores', ...
ExpectationApi
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpectationApi: def __init__(self, feature_store_id: int, feature_group_id: int, expectation_suite_id: int): """Expectation Suite endpoints for the featuregroup resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id o...
stack_v2_sparse_classes_75kplus_train_009146
5,396
permissive
[ { "docstring": "Expectation Suite endpoints for the featuregroup resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id of the respective Feature Group :type feature_group_id: int :param expectation_suite_id: id of the respective Expectation...
6
stack_v2_sparse_classes_30k_train_027611
Implement the Python class `ExpectationApi` described below. Class description: Implement the ExpectationApi class. Method signatures and docstrings: - def __init__(self, feature_store_id: int, feature_group_id: int, expectation_suite_id: int): Expectation Suite endpoints for the featuregroup resource. :param feature...
Implement the Python class `ExpectationApi` described below. Class description: Implement the ExpectationApi class. Method signatures and docstrings: - def __init__(self, feature_store_id: int, feature_group_id: int, expectation_suite_id: int): Expectation Suite endpoints for the featuregroup resource. :param feature...
3e67b26271e43b1ce38bd1e872bfb4c9212bb372
<|skeleton|> class ExpectationApi: def __init__(self, feature_store_id: int, feature_group_id: int, expectation_suite_id: int): """Expectation Suite endpoints for the featuregroup resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExpectationApi: def __init__(self, feature_store_id: int, feature_group_id: int, expectation_suite_id: int): """Expectation Suite endpoints for the featuregroup resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id of the respecti...
the_stack_v2_python_sparse
python/hsfs/core/expectation_api.py
logicalclocks/feature-store-api
train
59
7a4f9e756ffdae61a7787dee2cfa71f298d7f6af
[ "self.config = vae_config.VAEConfiguration()\nself.device = torch.device('cuda')\nmodel_path = f'{self.config.MODEL_DIR}\\\\{model_name}.pt'\nself.model = VAE(self.config).to(self.device)\nprint(f'model[{model_name}] is specified ({os.path.exists(model_path)})')\nif os.path.exists(model_path):\n self.model.load_...
<|body_start_0|> self.config = vae_config.VAEConfiguration() self.device = torch.device('cuda') model_path = f'{self.config.MODEL_DIR}\\{model_name}.pt' self.model = VAE(self.config).to(self.device) print(f'model[{model_name}] is specified ({os.path.exists(model_path)})') ...
BSSRDF class with VAE
BSSRDF
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSSRDF: """BSSRDF class with VAE""" def __init__(self, model_name): """Instanciation the VAE class and load a trained model""" <|body_0|> def estimate(self, in_pos, im, props, sigma_n, active): """Estimate output position and absorption with VAE Notice that the t...
stack_v2_sparse_classes_75kplus_train_009147
6,365
permissive
[ { "docstring": "Instanciation the VAE class and load a trained model", "name": "__init__", "signature": "def __init__(self, model_name)" }, { "docstring": "Estimate output position and absorption with VAE Notice that the types of arguments are in pytorch (tensor) except sigma_n, but the ones of ...
3
stack_v2_sparse_classes_30k_train_042511
Implement the Python class `BSSRDF` described below. Class description: BSSRDF class with VAE Method signatures and docstrings: - def __init__(self, model_name): Instanciation the VAE class and load a trained model - def estimate(self, in_pos, im, props, sigma_n, active): Estimate output position and absorption with ...
Implement the Python class `BSSRDF` described below. Class description: BSSRDF class with VAE Method signatures and docstrings: - def __init__(self, model_name): Instanciation the VAE class and load a trained model - def estimate(self, in_pos, im, props, sigma_n, active): Estimate output position and absorption with ...
2ddb05c9bf30bfaa4aca404fa4fa7e15afef6a0c
<|skeleton|> class BSSRDF: """BSSRDF class with VAE""" def __init__(self, model_name): """Instanciation the VAE class and load a trained model""" <|body_0|> def estimate(self, in_pos, im, props, sigma_n, active): """Estimate output position and absorption with VAE Notice that the t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BSSRDF: """BSSRDF class with VAE""" def __init__(self, model_name): """Instanciation the VAE class and load a trained model""" self.config = vae_config.VAEConfiguration() self.device = torch.device('cuda') model_path = f'{self.config.MODEL_DIR}\\{model_name}.pt' se...
the_stack_v2_python_sparse
myscripts/render/bssrdf.py
Mine-525/mitsuba2
train
0
be670a0cbe6848da2e381e443bf3727077765354
[ "super().__init__(*args, **kwargs)\nself.min_sent_len = min_sent_len\nself.max_sent_len = max_sent_len\nself.punct_chars = punct_chars\nself.uniform_weight = uniform_weight\nself.logger = JinaLogger(self.__class__.__name__)\nself.traversal_paths = traversal_paths\nif not punct_chars:\n self.punct_chars = ['!', '...
<|body_start_0|> super().__init__(*args, **kwargs) self.min_sent_len = min_sent_len self.max_sent_len = max_sent_len self.punct_chars = punct_chars self.uniform_weight = uniform_weight self.logger = JinaLogger(self.__class__.__name__) self.traversal_paths = traver...
:class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_len`` or longer than the ``max_sent_len`` after stripping will be discarded.
Sentencizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sentencizer: """:class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_len`` or longer than the ``max_sent_len``...
stack_v2_sparse_classes_75kplus_train_009148
4,230
permissive
[ { "docstring": ":param min_sent_len: the minimal number of characters, (including white spaces) of the sentence, by default 1. :param max_sent_len: the maximal number of characters, (including white spaces) of the sentence, by default 512. :param punct_chars: the punctuation characters to split on, whatever is ...
2
stack_v2_sparse_classes_30k_train_019878
Implement the Python class `Sentencizer` described below. Class description: :class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_le...
Implement the Python class `Sentencizer` described below. Class description: :class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_le...
3b025b6106fca9dba3c2569b0e60da050273fa6e
<|skeleton|> class Sentencizer: """:class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_len`` or longer than the ``max_sent_len``...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Sentencizer: """:class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_len`` or longer than the ``max_sent_len`` after stripp...
the_stack_v2_python_sparse
jinahub/segmenters/Sentencizer/sentencizer.py
albertocarpentieri/executors
train
0
6bec5d96402ec19c298a694c329911e4904b5018
[ "super(WindowDecorator, self).__init__(data_holding_element, as_iterator)\nself._windowsize = windowsize\nself._stride = stride", "use_default_stride = False\nif self._stride is None:\n use_default_stride = True\nfor container in datalist:\n if use_default_stride:\n self._stride = 1 / container.frequ...
<|body_start_0|> super(WindowDecorator, self).__init__(data_holding_element, as_iterator) self._windowsize = windowsize self._stride = stride <|end_body_0|> <|body_start_1|> use_default_stride = False if self._stride is None: use_default_stride = True for con...
Windowfies each trial. Attributes: element (DataHoldingElement): Element inheriting from ``DataHoldingElement`` or providing function ``get_data`` is_iterator (bool): Indicates whether decorator is a generator or returns a list. windowsize (float): Duration of window in seconds stride (float): Time between consecutive ...
WindowDecorator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowDecorator: """Windowfies each trial. Attributes: element (DataHoldingElement): Element inheriting from ``DataHoldingElement`` or providing function ``get_data`` is_iterator (bool): Indicates whether decorator is a generator or returns a list. windowsize (float): Duration of window in second...
stack_v2_sparse_classes_75kplus_train_009149
25,032
no_license
[ { "docstring": "Args: windowsize (float): Size of window in seconds data_holding_element (DataHoldingElement): Data source as_iterator (bool): Whether to act as decorator stride (float): Size of stride in seconds", "name": "__init__", "signature": "def __init__(self, windowsize, data_holding_element, st...
4
stack_v2_sparse_classes_30k_train_047554
Implement the Python class `WindowDecorator` described below. Class description: Windowfies each trial. Attributes: element (DataHoldingElement): Element inheriting from ``DataHoldingElement`` or providing function ``get_data`` is_iterator (bool): Indicates whether decorator is a generator or returns a list. windowsiz...
Implement the Python class `WindowDecorator` described below. Class description: Windowfies each trial. Attributes: element (DataHoldingElement): Element inheriting from ``DataHoldingElement`` or providing function ``get_data`` is_iterator (bool): Indicates whether decorator is a generator or returns a list. windowsiz...
ccf575e250e8e1acabfd41c2b3fdff949193e4e4
<|skeleton|> class WindowDecorator: """Windowfies each trial. Attributes: element (DataHoldingElement): Element inheriting from ``DataHoldingElement`` or providing function ``get_data`` is_iterator (bool): Indicates whether decorator is a generator or returns a list. windowsize (float): Duration of window in second...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WindowDecorator: """Windowfies each trial. Attributes: element (DataHoldingElement): Element inheriting from ``DataHoldingElement`` or providing function ``get_data`` is_iterator (bool): Indicates whether decorator is a generator or returns a list. windowsize (float): Duration of window in seconds stride (flo...
the_stack_v2_python_sparse
biosi/emg/datadecorators.py
PaddyK/biosi
train
0
d7ca47caf1c5c67796d2045324eedab13b968f3d
[ "if isinstance(key, int):\n return DITypes(key)\nif key not in DITypes._member_map_:\n return extend_enum(DITypes, key, default)\nreturn DITypes[key]", "if not (isinstance(value, int) and 0 <= value <= 15):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 3 <= value <= 15:\n retu...
<|body_start_0|> if isinstance(key, int): return DITypes(key) if key not in DITypes._member_map_: return extend_enum(DITypes, key, default) return DITypes[key] <|end_body_0|> <|body_start_1|> if not (isinstance(value, int) and 0 <= value <= 15): raise...
[DITypes] DI-Types
DITypes
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DITypes: """[DITypes] DI-Types""" def get(key: 'int | str', default: 'int'=-1) -> 'DITypes': """Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""" <|body_0|> def _missing_(cls, value: 'int') -> 'DI...
stack_v2_sparse_classes_75kplus_train_009150
1,555
permissive
[ { "docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:", "name": "get", "signature": "def get(key: 'int | str', default: 'int'=-1) -> 'DITypes'" }, { "docstring": "Lookup function used when value is not found. Arg...
2
null
Implement the Python class `DITypes` described below. Class description: [DITypes] DI-Types Method signatures and docstrings: - def get(key: 'int | str', default: 'int'=-1) -> 'DITypes': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private: - def _mi...
Implement the Python class `DITypes` described below. Class description: [DITypes] DI-Types Method signatures and docstrings: - def get(key: 'int | str', default: 'int'=-1) -> 'DITypes': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private: - def _mi...
a6fe49ec58f09e105bec5a00fb66d9b3f22730d9
<|skeleton|> class DITypes: """[DITypes] DI-Types""" def get(key: 'int | str', default: 'int'=-1) -> 'DITypes': """Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""" <|body_0|> def _missing_(cls, value: 'int') -> 'DI...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DITypes: """[DITypes] DI-Types""" def get(key: 'int | str', default: 'int'=-1) -> 'DITypes': """Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""" if isinstance(key, int): return DITypes(key) if ...
the_stack_v2_python_sparse
pcapkit/const/hip/di.py
JarryShaw/PyPCAPKit
train
204
0ed346d39221be0f76f8dd95dcca40752e8cbcca
[ "data = {ApiField.TAG_ID: tag_meta_id, ApiField.FIGURE_ID: figure_id}\nif value is not None:\n data[ApiField.VALUE] = value\nresp = self._api.post('object-tags.add-to-object', data)\nreturn resp.json()", "data = {ApiField.TAG_ID: tag_meta_id, ApiField.FIGURE_ID: figure_id, ApiField.ID: tag_id}\nresp = self._ap...
<|body_start_0|> data = {ApiField.TAG_ID: tag_meta_id, ApiField.FIGURE_ID: figure_id} if value is not None: data[ApiField.VALUE] = value resp = self._api.post('object-tags.add-to-object', data) return resp.json() <|end_body_0|> <|body_start_1|> data = {ApiField.TAG_I...
class AdvancedApi
AdvancedApi
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdvancedApi: """class AdvancedApi""" def add_tag_to_object(self, tag_meta_id: int, figure_id: int, value: Optional[str or int]=None) -> Dict: """add_tag_to_object""" <|body_0|> def remove_tag_from_object(self, tag_meta_id: int, figure_id: int, tag_id: int) -> Dict: ...
stack_v2_sparse_classes_75kplus_train_009151
2,049
permissive
[ { "docstring": "add_tag_to_object", "name": "add_tag_to_object", "signature": "def add_tag_to_object(self, tag_meta_id: int, figure_id: int, value: Optional[str or int]=None) -> Dict" }, { "docstring": "remove_tag_from_object", "name": "remove_tag_from_object", "signature": "def remove_t...
5
null
Implement the Python class `AdvancedApi` described below. Class description: class AdvancedApi Method signatures and docstrings: - def add_tag_to_object(self, tag_meta_id: int, figure_id: int, value: Optional[str or int]=None) -> Dict: add_tag_to_object - def remove_tag_from_object(self, tag_meta_id: int, figure_id: ...
Implement the Python class `AdvancedApi` described below. Class description: class AdvancedApi Method signatures and docstrings: - def add_tag_to_object(self, tag_meta_id: int, figure_id: int, value: Optional[str or int]=None) -> Dict: add_tag_to_object - def remove_tag_from_object(self, tag_meta_id: int, figure_id: ...
f0df756b8fb89364202fde54e6ef5fe89fca089d
<|skeleton|> class AdvancedApi: """class AdvancedApi""" def add_tag_to_object(self, tag_meta_id: int, figure_id: int, value: Optional[str or int]=None) -> Dict: """add_tag_to_object""" <|body_0|> def remove_tag_from_object(self, tag_meta_id: int, figure_id: int, tag_id: int) -> Dict: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdvancedApi: """class AdvancedApi""" def add_tag_to_object(self, tag_meta_id: int, figure_id: int, value: Optional[str or int]=None) -> Dict: """add_tag_to_object""" data = {ApiField.TAG_ID: tag_meta_id, ApiField.FIGURE_ID: figure_id} if value is not None: data[ApiFiel...
the_stack_v2_python_sparse
supervisely/api/advanced_api.py
supervisely/supervisely
train
447
4ccc9d6311c7e260f20f92ac3fef347145856e89
[ "self.input = cStringIO.StringIO()\nself.input.write(character)\nself.elementNode = elementNode", "if character == '=':\n return ValueMonad(self.elementNode, self.input.getvalue().strip())\nself.input.write(character)\nreturn self" ]
<|body_start_0|> self.input = cStringIO.StringIO() self.input.write(character) self.elementNode = elementNode <|end_body_0|> <|body_start_1|> if character == '=': return ValueMonad(self.elementNode, self.input.getvalue().strip()) self.input.write(character) r...
A monad to set the key of an attribute of an ElementNode.
KeyMonad
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeyMonad: """A monad to set the key of an attribute of an ElementNode.""" def __init__(self, character, elementNode): """Initialize.""" <|body_0|> def getNextMonad(self, character): """Get the next monad.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_009152
26,101
no_license
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, character, elementNode)" }, { "docstring": "Get the next monad.", "name": "getNextMonad", "signature": "def getNextMonad(self, character)" } ]
2
null
Implement the Python class `KeyMonad` described below. Class description: A monad to set the key of an attribute of an ElementNode. Method signatures and docstrings: - def __init__(self, character, elementNode): Initialize. - def getNextMonad(self, character): Get the next monad.
Implement the Python class `KeyMonad` described below. Class description: A monad to set the key of an attribute of an ElementNode. Method signatures and docstrings: - def __init__(self, character, elementNode): Initialize. - def getNextMonad(self, character): Get the next monad. <|skeleton|> class KeyMonad: """...
ef1732ade7b1ae3c676e5321333c7ca88c9db514
<|skeleton|> class KeyMonad: """A monad to set the key of an attribute of an ElementNode.""" def __init__(self, character, elementNode): """Initialize.""" <|body_0|> def getNextMonad(self, character): """Get the next monad.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KeyMonad: """A monad to set the key of an attribute of an ElementNode.""" def __init__(self, character, elementNode): """Initialize.""" self.input = cStringIO.StringIO() self.input.write(character) self.elementNode = elementNode def getNextMonad(self, character): ...
the_stack_v2_python_sparse
fabmetheus_utilities/xml_simple_reader.py
joewalnes/SFACT
train
1
74e7d22fba18875c289e3f217632b8e459bf4229
[ "self.unknownVal = 'arbitraryValue'\nself.dataFrame = dataFrame\nself.dataClass = dataClass\nself.separatedClasses = self.seperateDataByClass()\nself.classPriors = self.calculateClassPriors()\nself.d = len(next(iter(self.separatedClasses.values())).columns)\nself.trainedCalculation = self.train()", "classProbs = ...
<|body_start_0|> self.unknownVal = 'arbitraryValue' self.dataFrame = dataFrame self.dataClass = dataClass self.separatedClasses = self.seperateDataByClass() self.classPriors = self.calculateClassPriors() self.d = len(next(iter(self.separatedClasses.values())).columns) ...
NaiveBayes
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NaiveBayes: def __init__(self, dataFrame, dataClass): """Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set""" <|body_0|> def test(self, tes...
stack_v2_sparse_classes_75kplus_train_009153
3,359
no_license
[ { "docstring": "Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set", "name": "__init__", "signature": "def __init__(self, dataFrame, dataClass)" }, { "docstring"...
5
stack_v2_sparse_classes_30k_train_034456
Implement the Python class `NaiveBayes` described below. Class description: Implement the NaiveBayes class. Method signatures and docstrings: - def __init__(self, dataFrame, dataClass): Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataCla...
Implement the Python class `NaiveBayes` described below. Class description: Implement the NaiveBayes class. Method signatures and docstrings: - def __init__(self, dataFrame, dataClass): Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataCla...
ee1dd50f2d01fe3b651d095a9dd25b1e0d3047a5
<|skeleton|> class NaiveBayes: def __init__(self, dataFrame, dataClass): """Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set""" <|body_0|> def test(self, tes...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NaiveBayes: def __init__(self, dataFrame, dataClass): """Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set""" self.unknownVal = 'arbitraryValue' self....
the_stack_v2_python_sparse
MLAlgorithms/NaiveBayes/naiveBayes.py
lineranch/CSCI-447
train
0
e0dc03abb80a8d591ff19cfbeaff2829ea092717
[ "click_but_login(self.driver)\nlogin_button(self.driver)\ntext = GetErrorText(self.driver)\nself.assertEqual(text, '请输入用户名/手机号')", "input_username(self.driver, '18513600235')\nlogin_button(self.driver)\ntext = GetErrorText(self.driver)\nself.assertEqual(text, '请输入密码')", "input_username(self.driver, '18513600235...
<|body_start_0|> click_but_login(self.driver) login_button(self.driver) text = GetErrorText(self.driver) self.assertEqual(text, '请输入用户名/手机号') <|end_body_0|> <|body_start_1|> input_username(self.driver, '18513600235') login_button(self.driver) text = GetErrorText(...
Gjs
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Gjs: def test_login_null(self): """登录测试:测试用户名和密码为空""" <|body_0|> def test_login_passwd_null(self): """登录测试:测试用户名不为空,密码为空""" <|body_1|> def test_login_success(self): """登录测试:测试用户名和密码正确;验证用户名""" <|body_2|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_75kplus_train_009154
1,068
no_license
[ { "docstring": "登录测试:测试用户名和密码为空", "name": "test_login_null", "signature": "def test_login_null(self)" }, { "docstring": "登录测试:测试用户名不为空,密码为空", "name": "test_login_passwd_null", "signature": "def test_login_passwd_null(self)" }, { "docstring": "登录测试:测试用户名和密码正确;验证用户名", "name": "...
3
stack_v2_sparse_classes_30k_train_004484
Implement the Python class `Gjs` described below. Class description: Implement the Gjs class. Method signatures and docstrings: - def test_login_null(self): 登录测试:测试用户名和密码为空 - def test_login_passwd_null(self): 登录测试:测试用户名不为空,密码为空 - def test_login_success(self): 登录测试:测试用户名和密码正确;验证用户名
Implement the Python class `Gjs` described below. Class description: Implement the Gjs class. Method signatures and docstrings: - def test_login_null(self): 登录测试:测试用户名和密码为空 - def test_login_passwd_null(self): 登录测试:测试用户名不为空,密码为空 - def test_login_success(self): 登录测试:测试用户名和密码正确;验证用户名 <|skeleton|> class Gjs: def te...
46acedadd225b07fe73f43feebd5c66d19c7eeac
<|skeleton|> class Gjs: def test_login_null(self): """登录测试:测试用户名和密码为空""" <|body_0|> def test_login_passwd_null(self): """登录测试:测试用户名不为空,密码为空""" <|body_1|> def test_login_success(self): """登录测试:测试用户名和密码正确;验证用户名""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Gjs: def test_login_null(self): """登录测试:测试用户名和密码为空""" click_but_login(self.driver) login_button(self.driver) text = GetErrorText(self.driver) self.assertEqual(text, '请输入用户名/手机号') def test_login_passwd_null(self): """登录测试:测试用户名不为空,密码为空""" input_usern...
the_stack_v2_python_sparse
Gjs_Po/testcase/Gjs_login_unittest.py
kuangtao94/TestHome
train
0
6c90a2de82f2a282ec7417b1974ab998e7d4e8d5
[ "if ':' in data['ip']:\n data['type'] = 'ipv6'\n data['addr_byte'], data['mask_byte'] = eptSubnet.get_prefix_array('ipv6', data['ip'])\nelse:\n data['type'] = 'ipv4'\n data['addr_byte'], data['mask_byte'] = eptSubnet.get_prefix_array('ipv4', data['ip'])\nreturn data", "if prefix_type == 'ipv4':\n a...
<|body_start_0|> if ':' in data['ip']: data['type'] = 'ipv6' data['addr_byte'], data['mask_byte'] = eptSubnet.get_prefix_array('ipv6', data['ip']) else: data['type'] = 'ipv4' data['addr_byte'], data['mask_byte'] = eptSubnet.get_prefix_array('ipv4', data['i...
provide subnet to BD vnid mapping for configured subnets
eptSubnet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class eptSubnet: """provide subnet to BD vnid mapping for configured subnets""" def before_subnet_create(cls, data): """before create auto-detect type and update integer value for addr and mask list""" <|body_0|> def get_prefix_array(prefix_type, prefix): """for ipv4 o...
stack_v2_sparse_classes_75kplus_train_009155
4,138
permissive
[ { "docstring": "before create auto-detect type and update integer value for addr and mask list", "name": "before_subnet_create", "signature": "def before_subnet_create(cls, data)" }, { "docstring": "for ipv4 or ipv6 prefix, return tuple (addr_byte list, mask_byte list)", "name": "get_prefix_...
3
stack_v2_sparse_classes_30k_train_054112
Implement the Python class `eptSubnet` described below. Class description: provide subnet to BD vnid mapping for configured subnets Method signatures and docstrings: - def before_subnet_create(cls, data): before create auto-detect type and update integer value for addr and mask list - def get_prefix_array(prefix_type...
Implement the Python class `eptSubnet` described below. Class description: provide subnet to BD vnid mapping for configured subnets Method signatures and docstrings: - def before_subnet_create(cls, data): before create auto-detect type and update integer value for addr and mask list - def get_prefix_array(prefix_type...
a4de84c5fc00549e6539dbc1d8d927c74a704dcc
<|skeleton|> class eptSubnet: """provide subnet to BD vnid mapping for configured subnets""" def before_subnet_create(cls, data): """before create auto-detect type and update integer value for addr and mask list""" <|body_0|> def get_prefix_array(prefix_type, prefix): """for ipv4 o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class eptSubnet: """provide subnet to BD vnid mapping for configured subnets""" def before_subnet_create(cls, data): """before create auto-detect type and update integer value for addr and mask list""" if ':' in data['ip']: data['type'] = 'ipv6' data['addr_byte'], data['...
the_stack_v2_python_sparse
Service/app/models/aci/ept/ept_subnet.py
Hrishi5/ACI-EnhancedEndpointTracker
train
0
d3111d02f3125363910728882b638b3e4223b11b
[ "if id_genero is None:\n error = {'error': 'parametros_faltantes', 'mensaje': 'Los siguientes parametros faltan en tu solicitud: <id>'}\n return error", "try:\n id_genero = int(id_genero)\n genero = Genero.obtener_genero_por_id(id_genero)\n if genero is None:\n error = {'error': 'genero_no_e...
<|body_start_0|> if id_genero is None: error = {'error': 'parametros_faltantes', 'mensaje': 'Los siguientes parametros faltan en tu solicitud: <id>'} return error <|end_body_0|> <|body_start_1|> try: id_genero = int(id_genero) genero = Genero.obtener_gene...
ValidacionGenero
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidacionGenero: def _validar_campos_requeridos(id_genero): """Valida si el id_genero no es None :param id_genero: El campo a validar :return: None si el campo no es None o un diccionario con el error y mensaje si el campo es None""" <|body_0|> def validar_existe_genero(id_...
stack_v2_sparse_classes_75kplus_train_009156
2,006
no_license
[ { "docstring": "Valida si el id_genero no es None :param id_genero: El campo a validar :return: None si el campo no es None o un diccionario con el error y mensaje si el campo es None", "name": "_validar_campos_requeridos", "signature": "def _validar_campos_requeridos(id_genero)" }, { "docstring...
3
stack_v2_sparse_classes_30k_val_002170
Implement the Python class `ValidacionGenero` described below. Class description: Implement the ValidacionGenero class. Method signatures and docstrings: - def _validar_campos_requeridos(id_genero): Valida si el id_genero no es None :param id_genero: El campo a validar :return: None si el campo no es None o un diccio...
Implement the Python class `ValidacionGenero` described below. Class description: Implement the ValidacionGenero class. Method signatures and docstrings: - def _validar_campos_requeridos(id_genero): Valida si el id_genero no es None :param id_genero: El campo a validar :return: None si el campo no es None o un diccio...
49bbaaf0bd4d1bec2d81eb35882e5f073b1c149f
<|skeleton|> class ValidacionGenero: def _validar_campos_requeridos(id_genero): """Valida si el id_genero no es None :param id_genero: El campo a validar :return: None si el campo no es None o un diccionario con el error y mensaje si el campo es None""" <|body_0|> def validar_existe_genero(id_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ValidacionGenero: def _validar_campos_requeridos(id_genero): """Valida si el id_genero no es None :param id_genero: El campo a validar :return: None si el campo no es None o un diccionario con el error y mensaje si el campo es None""" if id_genero is None: error = {'error': 'parame...
the_stack_v2_python_sparse
app/util/validaciones/modelos/ValidacionGenero.py
codeChinoUV/EspotifeiAPI
train
0
bc10e9eacb2d563140cf7f234e651f8f373a9352
[ "email = self.cleaned_data['email']\nself.users_cache = User.objects.filter(email__iexact=email, is_active=True)\nif not len(self.users_cache):\n raise forms.ValidationError(self.error_messages['unknown'])\nif any((user.password == UNUSABLE_PASSWORD for user in self.users_cache)):\n raise forms.ValidationErro...
<|body_start_0|> email = self.cleaned_data['email'] self.users_cache = User.objects.filter(email__iexact=email, is_active=True) if not len(self.users_cache): raise forms.ValidationError(self.error_messages['unknown']) if any((user.password == UNUSABLE_PASSWORD for user in sel...
PasswordResetForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordResetForm: def clean_email(self): """Validates that an active user exists with the given email address.""" <|body_0|> def save(self, project, subject_template_name='password_reset_subject.txt', email_template_name='password_reset_email.html', use_https=False, token_g...
stack_v2_sparse_classes_75kplus_train_009157
11,762
no_license
[ { "docstring": "Validates that an active user exists with the given email address.", "name": "clean_email", "signature": "def clean_email(self)" }, { "docstring": "Generates a one-use only link for resetting password and sends to the user.", "name": "save", "signature": "def save(self, p...
2
stack_v2_sparse_classes_30k_train_033214
Implement the Python class `PasswordResetForm` described below. Class description: Implement the PasswordResetForm class. Method signatures and docstrings: - def clean_email(self): Validates that an active user exists with the given email address. - def save(self, project, subject_template_name='password_reset_subjec...
Implement the Python class `PasswordResetForm` described below. Class description: Implement the PasswordResetForm class. Method signatures and docstrings: - def clean_email(self): Validates that an active user exists with the given email address. - def save(self, project, subject_template_name='password_reset_subjec...
5633b8c777ffa04e3372c7c5af4a86f672724d71
<|skeleton|> class PasswordResetForm: def clean_email(self): """Validates that an active user exists with the given email address.""" <|body_0|> def save(self, project, subject_template_name='password_reset_subject.txt', email_template_name='password_reset_email.html', use_https=False, token_g...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PasswordResetForm: def clean_email(self): """Validates that an active user exists with the given email address.""" email = self.cleaned_data['email'] self.users_cache = User.objects.filter(email__iexact=email, is_active=True) if not len(self.users_cache): raise form...
the_stack_v2_python_sparse
invites/forms.py
fabiosussetto/holiday
train
1
463e6f400ba1d499867ba06d1418083f1adb1e76
[ "self.resultfile = Utils.config_Utils.resultfile\nself.datafile = Utils.config_Utils.datafile\nself.logsdir = Utils.config_Utils.logsdir\nself.filename = Utils.config_Utils.filename\nself.logfile = Utils.config_Utils.logfile\nself.diag = Diag()", "wdesc = 'ping to destination system'\nUtils.testcase_Utils.pSubSt...
<|body_start_0|> self.resultfile = Utils.config_Utils.resultfile self.datafile = Utils.config_Utils.datafile self.logsdir = Utils.config_Utils.logsdir self.filename = Utils.config_Utils.filename self.logfile = Utils.config_Utils.logfile self.diag = Diag() <|end_body_0|> ...
Diagnostics keyword class
DiagActions
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiagActions: """Diagnostics keyword class""" def __init__(self): """Constructor""" <|body_0|> def ping_from_remotehost(self, system_name, session_name=None, dest_system=None, ip_type='ip', count='5'): """This keyword will use connection session available in sourc...
stack_v2_sparse_classes_75kplus_train_009158
7,482
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This keyword will use connection session available in source system (provided in system name) and will ping from source system to destination system :Datafile usuage: Tags or attributes to be u...
3
stack_v2_sparse_classes_30k_train_001745
Implement the Python class `DiagActions` described below. Class description: Diagnostics keyword class Method signatures and docstrings: - def __init__(self): Constructor - def ping_from_remotehost(self, system_name, session_name=None, dest_system=None, ip_type='ip', count='5'): This keyword will use connection sessi...
Implement the Python class `DiagActions` described below. Class description: Diagnostics keyword class Method signatures and docstrings: - def __init__(self): Constructor - def ping_from_remotehost(self, system_name, session_name=None, dest_system=None, ip_type='ip', count='5'): This keyword will use connection sessi...
685761cf044182ec88ce86a942d4be1e150a1256
<|skeleton|> class DiagActions: """Diagnostics keyword class""" def __init__(self): """Constructor""" <|body_0|> def ping_from_remotehost(self, system_name, session_name=None, dest_system=None, ip_type='ip', count='5'): """This keyword will use connection session available in sourc...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DiagActions: """Diagnostics keyword class""" def __init__(self): """Constructor""" self.resultfile = Utils.config_Utils.resultfile self.datafile = Utils.config_Utils.datafile self.logsdir = Utils.config_Utils.logsdir self.filename = Utils.config_Utils.filename ...
the_stack_v2_python_sparse
warrior/Actions/NetworkActions/Diagnostics/diagnostics_actions.py
warriorframework/warriorframework
train
25
2753cbbcde78ea49914cbc535c13f006c7c25ba3
[ "self.readfile = FileReader(config_file)\nvalue_level = self.readfile.read_dificult_level()\nif value_level == 'NoneType':\n self.level = ''\nelse:\n self.level = self.readfile.read_dificult_level().lower()", "if not self.level:\n return 'No Setting'\nelif self.level.strip() == 'easier':\n self.files ...
<|body_start_0|> self.readfile = FileReader(config_file) value_level = self.readfile.read_dificult_level() if value_level == 'NoneType': self.level = '' else: self.level = self.readfile.read_dificult_level().lower() <|end_body_0|> <|body_start_1|> if not ...
Generator class will create new sudoku games, based on already stored files
SudokuGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SudokuGenerator: """Generator class will create new sudoku games, based on already stored files""" def __init__(self, config_file): """Constructor: define which is the difficult level set by the user at config.ini file""" <|body_0|> def retrieve_file_names(self): ...
stack_v2_sparse_classes_75kplus_train_009159
3,413
no_license
[ { "docstring": "Constructor: define which is the difficult level set by the user at config.ini file", "name": "__init__", "signature": "def __init__(self, config_file)" }, { "docstring": "retrieve_file_names method retrieves all file names stored based on difficult level", "name": "retrieve_...
4
stack_v2_sparse_classes_30k_train_024511
Implement the Python class `SudokuGenerator` described below. Class description: Generator class will create new sudoku games, based on already stored files Method signatures and docstrings: - def __init__(self, config_file): Constructor: define which is the difficult level set by the user at config.ini file - def re...
Implement the Python class `SudokuGenerator` described below. Class description: Generator class will create new sudoku games, based on already stored files Method signatures and docstrings: - def __init__(self, config_file): Constructor: define which is the difficult level set by the user at config.ini file - def re...
de6c23378ea9b5280d820cc6459761823c596b58
<|skeleton|> class SudokuGenerator: """Generator class will create new sudoku games, based on already stored files""" def __init__(self, config_file): """Constructor: define which is the difficult level set by the user at config.ini file""" <|body_0|> def retrieve_file_names(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SudokuGenerator: """Generator class will create new sudoku games, based on already stored files""" def __init__(self, config_file): """Constructor: define which is the difficult level set by the user at config.ini file""" self.readfile = FileReader(config_file) value_level = self....
the_stack_v2_python_sparse
src/Player/generators.py
asalinasv/sudoku_python
train
0
63d22c51c4672aa3a749280c75c1df311d6ab1c3
[ "if User.objects.filter(email__iexact=value).exists():\n raise serializers.ValidationError(_('EMAIL.IN_USE'))\nreturn value.lower()", "user = User(**data)\npassword = data.get('password')\nerrors = dict()\ntry:\n validators.validate_password(password=password, user=User)\nexcept exceptions.ValidationError a...
<|body_start_0|> if User.objects.filter(email__iexact=value).exists(): raise serializers.ValidationError(_('EMAIL.IN_USE')) return value.lower() <|end_body_0|> <|body_start_1|> user = User(**data) password = data.get('password') errors = dict() try: ...
Profile serializer for creating a user instance
ProfileCreateSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileCreateSerializer: """Profile serializer for creating a user instance""" def validate_email(self, value): """Check if email is already in use""" <|body_0|> def validate(self, data): """Validate Password""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_75kplus_train_009160
6,076
permissive
[ { "docstring": "Check if email is already in use", "name": "validate_email", "signature": "def validate_email(self, value)" }, { "docstring": "Validate Password", "name": "validate", "signature": "def validate(self, data)" } ]
2
stack_v2_sparse_classes_30k_test_002908
Implement the Python class `ProfileCreateSerializer` described below. Class description: Profile serializer for creating a user instance Method signatures and docstrings: - def validate_email(self, value): Check if email is already in use - def validate(self, data): Validate Password
Implement the Python class `ProfileCreateSerializer` described below. Class description: Profile serializer for creating a user instance Method signatures and docstrings: - def validate_email(self, value): Check if email is already in use - def validate(self, data): Validate Password <|skeleton|> class ProfileCreate...
5e1a2b51aee87eb79443e0489d13f976b0e6bae8
<|skeleton|> class ProfileCreateSerializer: """Profile serializer for creating a user instance""" def validate_email(self, value): """Check if email is already in use""" <|body_0|> def validate(self, data): """Validate Password""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileCreateSerializer: """Profile serializer for creating a user instance""" def validate_email(self, value): """Check if email is already in use""" if User.objects.filter(email__iexact=value).exists(): raise serializers.ValidationError(_('EMAIL.IN_USE')) return valu...
the_stack_v2_python_sparse
api/api_v1/profiles/serializers.py
ehsanghaffar/djangoware
train
1
83ed12139ab57f61824f81ee8c14c3edb4b06bdb
[ "stack, rslt = (root and [root], [])\nwhile stack:\n currNode = stack.pop()\n rslt.append(currNode.val)\n stack.extend(reversed(currNode.children or []))\nreturn rslt", "rslt = []\nif root:\n rslt.append(root.val)\n for child in root.children:\n rslt.extend(self.preorder2(child))\nreturn rsl...
<|body_start_0|> stack, rslt = (root and [root], []) while stack: currNode = stack.pop() rslt.append(currNode.val) stack.extend(reversed(currNode.children or [])) return rslt <|end_body_0|> <|body_start_1|> rslt = [] if root: rslt....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def preorder(self, root: NaryTreeNode) -> List[int]: """Use iteration.""" <|body_0|> def preorder2(self, root: NaryTreeNode) -> List[int]: """Use recursion.""" <|body_1|> <|end_skeleton|> <|body_start_0|> stack, rslt = (root and [root], []...
stack_v2_sparse_classes_75kplus_train_009161
760
no_license
[ { "docstring": "Use iteration.", "name": "preorder", "signature": "def preorder(self, root: NaryTreeNode) -> List[int]" }, { "docstring": "Use recursion.", "name": "preorder2", "signature": "def preorder2(self, root: NaryTreeNode) -> List[int]" } ]
2
stack_v2_sparse_classes_30k_train_032511
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorder(self, root: NaryTreeNode) -> List[int]: Use iteration. - def preorder2(self, root: NaryTreeNode) -> List[int]: Use recursion.
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorder(self, root: NaryTreeNode) -> List[int]: Use iteration. - def preorder2(self, root: NaryTreeNode) -> List[int]: Use recursion. <|skeleton|> class Solution: def ...
edb870f83f0c4568cce0cacec04ee70cf6b545bf
<|skeleton|> class Solution: def preorder(self, root: NaryTreeNode) -> List[int]: """Use iteration.""" <|body_0|> def preorder2(self, root: NaryTreeNode) -> List[int]: """Use recursion.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def preorder(self, root: NaryTreeNode) -> List[int]: """Use iteration.""" stack, rslt = (root and [root], []) while stack: currNode = stack.pop() rslt.append(currNode.val) stack.extend(reversed(currNode.children or [])) return rslt ...
the_stack_v2_python_sparse
2020/n_ary_tree_preorder_traversal.py
eronekogin/leetcode
train
0
8f6e1d5da62393878c40893030382110d052af80
[ "argvalidate('can_create_update_request', [{'arg': account, 'instance': models.Account, 'allow_none': False, 'arg_name': 'account'}, {'arg': journal, 'instance': models.Journal, 'allow_none': False, 'arg_name': 'journal'}], exceptions.ArgumentException)\nif account.is_super:\n return True\nif not account.has_rol...
<|body_start_0|> argvalidate('can_create_update_request', [{'arg': account, 'instance': models.Account, 'allow_none': False, 'arg_name': 'account'}, {'arg': journal, 'instance': models.Journal, 'allow_none': False, 'arg_name': 'journal'}], exceptions.ArgumentException) if account.is_super: r...
~~AuthNZ:Service->AuthNZ:Feature~~
AuthorisationService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthorisationService: """~~AuthNZ:Service->AuthNZ:Feature~~""" def can_create_update_request(self, account, journal): """Is the given account allowed to create an update request from the given journal :param account: the account doing the action :param journal: the journal the accoun...
stack_v2_sparse_classes_75kplus_train_009162
5,958
permissive
[ { "docstring": "Is the given account allowed to create an update request from the given journal :param account: the account doing the action :param journal: the journal the account wants to create an update request from :return:", "name": "can_create_update_request", "signature": "def can_create_update_...
4
stack_v2_sparse_classes_30k_val_002980
Implement the Python class `AuthorisationService` described below. Class description: ~~AuthNZ:Service->AuthNZ:Feature~~ Method signatures and docstrings: - def can_create_update_request(self, account, journal): Is the given account allowed to create an update request from the given journal :param account: the accoun...
Implement the Python class `AuthorisationService` described below. Class description: ~~AuthNZ:Service->AuthNZ:Feature~~ Method signatures and docstrings: - def can_create_update_request(self, account, journal): Is the given account allowed to create an update request from the given journal :param account: the accoun...
b441932e93a114129539abe4ce79221bd4c7e970
<|skeleton|> class AuthorisationService: """~~AuthNZ:Service->AuthNZ:Feature~~""" def can_create_update_request(self, account, journal): """Is the given account allowed to create an update request from the given journal :param account: the account doing the action :param journal: the journal the accoun...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AuthorisationService: """~~AuthNZ:Service->AuthNZ:Feature~~""" def can_create_update_request(self, account, journal): """Is the given account allowed to create an update request from the given journal :param account: the account doing the action :param journal: the journal the account wants to cr...
the_stack_v2_python_sparse
portality/bll/services/authorisation.py
DOAJ/doaj
train
56
245114bbaabffadf744952c4284b4fbbcdd42a72
[ "super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, 'Sprite Fright')\nself.player_list = None\nself.coin_list = None\nself.gem_list = None\nself.player_sprite = None\nself.score = 0\nself.set_mouse_visible(False)\nself.game_over = False\nself.length_of_play = 0\narcade.set_background_color(arcade.color.AMAZON)\nself.bad...
<|body_start_0|> super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, 'Sprite Fright') self.player_list = None self.coin_list = None self.gem_list = None self.player_sprite = None self.score = 0 self.set_mouse_visible(False) self.game_over = False self.le...
Our custom Window Class
MyGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyGame: """Our custom Window Class""" def __init__(self): """Initializer""" <|body_0|> def setup(self): """Set up the game and initialize the variables.""" <|body_1|> def on_draw(self): """Draw everything""" <|body_2|> def on_key...
stack_v2_sparse_classes_75kplus_train_009163
7,022
no_license
[ { "docstring": "Initializer", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Set up the game and initialize the variables.", "name": "setup", "signature": "def setup(self)" }, { "docstring": "Draw everything", "name": "on_draw", "signature": "def...
6
stack_v2_sparse_classes_30k_train_010552
Implement the Python class `MyGame` described below. Class description: Our custom Window Class Method signatures and docstrings: - def __init__(self): Initializer - def setup(self): Set up the game and initialize the variables. - def on_draw(self): Draw everything - def on_key_press(self, key, modifiers): Called whe...
Implement the Python class `MyGame` described below. Class description: Our custom Window Class Method signatures and docstrings: - def __init__(self): Initializer - def setup(self): Set up the game and initialize the variables. - def on_draw(self): Draw everything - def on_key_press(self, key, modifiers): Called whe...
693f642db301863bedcd77ee98eea405ee794043
<|skeleton|> class MyGame: """Our custom Window Class""" def __init__(self): """Initializer""" <|body_0|> def setup(self): """Set up the game and initialize the variables.""" <|body_1|> def on_draw(self): """Draw everything""" <|body_2|> def on_key...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyGame: """Our custom Window Class""" def __init__(self): """Initializer""" super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, 'Sprite Fright') self.player_list = None self.coin_list = None self.gem_list = None self.player_sprite = None self.score = 0 ...
the_stack_v2_python_sparse
Lab 08 - Sprites/lab_08.py
TylerErdman/learn-arcade-work
train
0
0a1a023e88e4ea6742fa0ed7791e517e3065cb0e
[ "logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('h1.bookinfo-title').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_author = soup.select_one('span', {'itemprop': 'creator'}).text.strip()\nlogger.info('Novel author: %s...
<|body_start_0|> logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_title = soup.select_one('h1.bookinfo-title').text.strip() logger.info('Novel title: %s', self.novel_title) self.novel_author = soup.select_one('span', {'itemprop': 'creato...
NovelCool
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NovelCool: def read_novel_info(self): """Get novel title, autor, cover etc""" <|body_0|> def download_chapter_body(self, chapter): """Download body of a single chapter and return as clean html format.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_009164
2,362
permissive
[ { "docstring": "Get novel title, autor, cover etc", "name": "read_novel_info", "signature": "def read_novel_info(self)" }, { "docstring": "Download body of a single chapter and return as clean html format.", "name": "download_chapter_body", "signature": "def download_chapter_body(self, c...
2
stack_v2_sparse_classes_30k_train_022448
Implement the Python class `NovelCool` described below. Class description: Implement the NovelCool class. Method signatures and docstrings: - def read_novel_info(self): Get novel title, autor, cover etc - def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html format.
Implement the Python class `NovelCool` described below. Class description: Implement the NovelCool class. Method signatures and docstrings: - def read_novel_info(self): Get novel title, autor, cover etc - def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html format. <|s...
451e816ab03c8466be90f6f0b3eaa52d799140ce
<|skeleton|> class NovelCool: def read_novel_info(self): """Get novel title, autor, cover etc""" <|body_0|> def download_chapter_body(self, chapter): """Download body of a single chapter and return as clean html format.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NovelCool: def read_novel_info(self): """Get novel title, autor, cover etc""" logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_title = soup.select_one('h1.bookinfo-title').text.strip() logger.info('Novel title: %s', self.novel_...
the_stack_v2_python_sparse
lncrawl/sources/novelcool.py
NNTin/lightnovel-crawler
train
2
71795bc4c543f47a7e8ffdcb44671cb9e6937f00
[ "self.bert_model = BertModel.from_pretrained(pretrained_name, output_hidden_states=False, output_attentions=False).to(device)\nself.bert_model.eval()\nself.bert_tokenizer = BertTokenizer.from_pretrained(pretrained_name)\nself.max_len = max_len\nself.device = device", "if not len(texts):\n return {'cls': np.arr...
<|body_start_0|> self.bert_model = BertModel.from_pretrained(pretrained_name, output_hidden_states=False, output_attentions=False).to(device) self.bert_model.eval() self.bert_tokenizer = BertTokenizer.from_pretrained(pretrained_name) self.max_len = max_len self.device = device <|...
BertWordVectorizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BertWordVectorizer: def __init__(self, pretrained_name: str='bert-base-uncased', max_len: int=10, device: str='cpu') -> None: """Class for encoding texts with pretrained BERT model :param pretrained_name: str, path to checkpoints. Default: 'bert-base-uncased' :param max_len: int, max seq...
stack_v2_sparse_classes_75kplus_train_009165
6,020
no_license
[ { "docstring": "Class for encoding texts with pretrained BERT model :param pretrained_name: str, path to checkpoints. Default: 'bert-base-uncased' :param max_len: int, max seq length to use. All sequences, that are longer than max_len, will cut to this length. Ones, that are <= max_len - will be padded with 0 :...
3
null
Implement the Python class `BertWordVectorizer` described below. Class description: Implement the BertWordVectorizer class. Method signatures and docstrings: - def __init__(self, pretrained_name: str='bert-base-uncased', max_len: int=10, device: str='cpu') -> None: Class for encoding texts with pretrained BERT model ...
Implement the Python class `BertWordVectorizer` described below. Class description: Implement the BertWordVectorizer class. Method signatures and docstrings: - def __init__(self, pretrained_name: str='bert-base-uncased', max_len: int=10, device: str='cpu') -> None: Class for encoding texts with pretrained BERT model ...
9641b25df59c976f15375f115154dcae74b49600
<|skeleton|> class BertWordVectorizer: def __init__(self, pretrained_name: str='bert-base-uncased', max_len: int=10, device: str='cpu') -> None: """Class for encoding texts with pretrained BERT model :param pretrained_name: str, path to checkpoints. Default: 'bert-base-uncased' :param max_len: int, max seq...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BertWordVectorizer: def __init__(self, pretrained_name: str='bert-base-uncased', max_len: int=10, device: str='cpu') -> None: """Class for encoding texts with pretrained BERT model :param pretrained_name: str, path to checkpoints. Default: 'bert-base-uncased' :param max_len: int, max seq length to use...
the_stack_v2_python_sparse
vectorization_utils.py
YevhenKost/SemPrimsDetectionGA
train
1
5f23adc2fa2958a5cc398f410c0d860db1b0e76c
[ "embeddings = tf.get_variable(name='embeddings', dtype=tf.float32, shape=[params.vocab_size, params.embedding_size])\nsentence = tf.nn.embedding_lookup(embeddings, sentence)\nconv = tf.layers.conv1d(sentence, params.num_filters, params.kernel_size, name='conv')\ngmp = tf.reduce_mean(conv, reduction_indices=[1], nam...
<|body_start_0|> embeddings = tf.get_variable(name='embeddings', dtype=tf.float32, shape=[params.vocab_size, params.embedding_size]) sentence = tf.nn.embedding_lookup(embeddings, sentence) conv = tf.layers.conv1d(sentence, params.num_filters, params.kernel_size, name='conv') gmp = tf.red...
Define Deep Models, here we only define two function `inference()` and `loss()`, why design like this,as we want to use tensorflow high level api when training and evalute like tf.data.dataset api,but it difficult to use when inference with single sample. `inference`: get network outputs(logits), used in train and eval...
MyModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyModel: """Define Deep Models, here we only define two function `inference()` and `loss()`, why design like this,as we want to use tensorflow high level api when training and evalute like tf.data.dataset api,but it difficult to use when inference with single sample. `inference`: get network outp...
stack_v2_sparse_classes_75kplus_train_009166
2,197
no_license
[ { "docstring": "Portion of the compute graph that takes as input and converts it to a Y output(logit) :param sentence: input tensor, shape=[batch_size, dim] :param params: (Object)Param, a dictionary of parameters :return:", "name": "inference", "signature": "def inference(sentence, params, is_training=...
2
stack_v2_sparse_classes_30k_train_041775
Implement the Python class `MyModel` described below. Class description: Define Deep Models, here we only define two function `inference()` and `loss()`, why design like this,as we want to use tensorflow high level api when training and evalute like tf.data.dataset api,but it difficult to use when inference with singl...
Implement the Python class `MyModel` described below. Class description: Define Deep Models, here we only define two function `inference()` and `loss()`, why design like this,as we want to use tensorflow high level api when training and evalute like tf.data.dataset api,but it difficult to use when inference with singl...
7dcedd0b39eb4ce9404529d0d1a1146f4f3a92d3
<|skeleton|> class MyModel: """Define Deep Models, here we only define two function `inference()` and `loss()`, why design like this,as we want to use tensorflow high level api when training and evalute like tf.data.dataset api,but it difficult to use when inference with single sample. `inference`: get network outp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyModel: """Define Deep Models, here we only define two function `inference()` and `loss()`, why design like this,as we want to use tensorflow high level api when training and evalute like tf.data.dataset api,but it difficult to use when inference with single sample. `inference`: get network outputs(logits), ...
the_stack_v2_python_sparse
modules/pipeline_demo/model.py
syw2014/Practice4Tensorflow
train
0
e9b6bf2dd1eb7ddd3c48b9f328ed2be0afecd239
[ "queryset = self.filter_queryset(self.get_queryset())\nuid = force_text(urlsafe_base64_decode(self.kwargs['uid']))\ntoken = self.kwargs['token']\nobj = get_object_or_404(queryset, pk=uid)\nself.check_object_permissions(self.request, obj)\nif not default_token_generator.check_token(user=obj, token=token):\n raise...
<|body_start_0|> queryset = self.filter_queryset(self.get_queryset()) uid = force_text(urlsafe_base64_decode(self.kwargs['uid'])) token = self.kwargs['token'] obj = get_object_or_404(queryset, pk=uid) self.check_object_permissions(self.request, obj) if not default_token_g...
User activate view.
UserActivation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserActivation: """User activate view.""" def get_object(self) -> User: """Get user by uid and check permissions. :return: User.""" <|body_0|> def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response: """Activate user. :param request: :return:"""...
stack_v2_sparse_classes_75kplus_train_009167
5,061
no_license
[ { "docstring": "Get user by uid and check permissions. :return: User.", "name": "get_object", "signature": "def get_object(self) -> User" }, { "docstring": "Activate user. :param request: :return:", "name": "get", "signature": "def get(self, request: Request, *args: tuple, **kwargs: dict...
2
stack_v2_sparse_classes_30k_train_042791
Implement the Python class `UserActivation` described below. Class description: User activate view. Method signatures and docstrings: - def get_object(self) -> User: Get user by uid and check permissions. :return: User. - def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Activate user. :param...
Implement the Python class `UserActivation` described below. Class description: User activate view. Method signatures and docstrings: - def get_object(self) -> User: Get user by uid and check permissions. :return: User. - def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Activate user. :param...
713b9d84ac70d964d46f189ab1f9c7b944b9684b
<|skeleton|> class UserActivation: """User activate view.""" def get_object(self) -> User: """Get user by uid and check permissions. :return: User.""" <|body_0|> def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response: """Activate user. :param request: :return:"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserActivation: """User activate view.""" def get_object(self) -> User: """Get user by uid and check permissions. :return: User.""" queryset = self.filter_queryset(self.get_queryset()) uid = force_text(urlsafe_base64_decode(self.kwargs['uid'])) token = self.kwargs['token']...
the_stack_v2_python_sparse
jobadvisor/users/views/registration.py
ewgen19892/jobadvisor
train
0
9386662bd14635c1430e84fa95349c87a7e023bc
[ "if dtype not in DATA_TYPES:\n msg = \"unknown data type '{}'\"\n raise err.InvalidTemplateError(msg.format(dtype))\nself.column_id = column_id\nself.name = name\nself.dtype = dtype\nself.path = path\nself.required = required if required is not None else True", "if self.dtype == PARA_INT:\n return int(va...
<|body_start_0|> if dtype not in DATA_TYPES: msg = "unknown data type '{}'" raise err.InvalidTemplateError(msg.format(dtype)) self.column_id = column_id self.name = name self.dtype = dtype self.path = path self.required = required if required is no...
Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from nested result files.
ResultColumn
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResultColumn: """Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from ...
stack_v2_sparse_classes_75kplus_train_009168
11,903
permissive
[ { "docstring": "Initialize the unique column identifier, name, and the data type. If the value of dtype is not in the list of supported data types an error is raised. The optional path element references the column value in nested result files. If no path is given the column identifier is used instead. Paramete...
5
stack_v2_sparse_classes_30k_train_035712
Implement the Python class `ResultColumn` described below. Class description: Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is...
Implement the Python class `ResultColumn` described below. Class description: Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is...
7116b7060aa68ab36bf08e6393be166dc5db955f
<|skeleton|> class ResultColumn: """Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResultColumn: """Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from nested result...
the_stack_v2_python_sparse
flowserv/model/template/schema.py
anrunw/flowserv-core-1
train
0
cf0bf8ecf962cec11a35a563aa67f1b038a1709d
[ "ExecutionElement.__init__(self, uid)\nself.action = action\nself._args_api, self._data_in_api = get_filter_api(self.action)\nif isinstance(args, list):\n args = {arg['name']: arg['value'] for arg in args}\nelif isinstance(args, dict):\n args = args\nelse:\n args = {}\nself.args = validate_filter_parameter...
<|body_start_0|> ExecutionElement.__init__(self, uid) self.action = action self._args_api, self._data_in_api = get_filter_api(self.action) if isinstance(args, list): args = {arg['name']: arg['value'] for arg in args} elif isinstance(args, dict): args = arg...
Filter
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Filter: def __init__(self, action, args=None, uid=None): """Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument...
stack_v2_sparse_classes_75kplus_train_009169
2,894
permissive
[ { "docstring": "Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument keys to Argument values. This dictionary will be converted to a dic...
2
stack_v2_sparse_classes_30k_train_053456
Implement the Python class `Filter` described below. Class description: Implement the Filter class. Method signatures and docstrings: - def __init__(self, action, args=None, uid=None): Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for ...
Implement the Python class `Filter` described below. Class description: Implement the Filter class. Method signatures and docstrings: - def __init__(self, action, args=None, uid=None): Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for ...
18cd8b6d10241955bea5422947af9cf67f73aead
<|skeleton|> class Filter: def __init__(self, action, args=None, uid=None): """Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Filter: def __init__(self, action, args=None, uid=None): """Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument keys to Argum...
the_stack_v2_python_sparse
core/executionelements/filter.py
JustinTervala/WALKOFF
train
0
5e23c50159cb217655453245f7a577fa35986f91
[ "super().__init__()\nillegal_args = [(k, a) for k, a in locals().items() if isinstance(a, tuple) and len(a) != n_blocks]\nif illegal_args:\n raise ValueError(f'All the tuple-arg lengths need to be equal to `n_blocks`={n_blocks}. Illegal args: {illegal_args}')\nself.tr_blocks = nn.ModuleList()\nself.layer_scales ...
<|body_start_0|> super().__init__() illegal_args = [(k, a) for k, a in locals().items() if isinstance(a, tuple) and len(a) != n_blocks] if illegal_args: raise ValueError(f'All the tuple-arg lengths need to be equal to `n_blocks`={n_blocks}. Illegal args: {illegal_args}') self...
TransformerLayer
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransformerLayer: def __init__(self, query_dim: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, activation: str='star_relu', n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact'), computation_types: Tuple[str, ...]=('basic', 'basic'), dropouts: Tuple[float, ......
stack_v2_sparse_classes_75kplus_train_009170
12,584
permissive
[ { "docstring": "Chain transformer blocks to compose a full generic transformer. NOTE: For 2D image like data: - Forward input shape: (B, H*W, head_dim*num_heads) - Forward output sahpe: (B, H*W, head_dim*num_heads) Parameters ---------- query_dim : int The length/dim of the query. Typically: num_heads*head_dim ...
2
stack_v2_sparse_classes_30k_train_049067
Implement the Python class `TransformerLayer` described below. Class description: Implement the TransformerLayer class. Method signatures and docstrings: - def __init__(self, query_dim: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, activation: str='star_relu', n_blocks: int=2, block_types: T...
Implement the Python class `TransformerLayer` described below. Class description: Implement the TransformerLayer class. Method signatures and docstrings: - def __init__(self, query_dim: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, activation: str='star_relu', n_blocks: int=2, block_types: T...
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class TransformerLayer: def __init__(self, query_dim: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, activation: str='star_relu', n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact'), computation_types: Tuple[str, ...]=('basic', 'basic'), dropouts: Tuple[float, ......
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TransformerLayer: def __init__(self, query_dim: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, activation: str='star_relu', n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact'), computation_types: Tuple[str, ...]=('basic', 'basic'), dropouts: Tuple[float, ...]=(0.0, 0.0), ...
the_stack_v2_python_sparse
cellseg_models_pytorch/modules/transformers.py
okunator/cellseg_models.pytorch
train
43
26af818019ff22cb49061189c0e08b4fdc34af2f
[ "self.capacity = capacity\nself.size = 1\nself.head = LinkedList(0, -1)\nself.tail = self.head\nself.hash_table = {-1: self.head}", "if key in self.hash_table:\n if self.hash_table[key] is not self.tail:\n new_tail = LinkedList(self.hash_table[key].val, key)\n self.tail.next = new_tail\n s...
<|body_start_0|> self.capacity = capacity self.size = 1 self.head = LinkedList(0, -1) self.tail = self.head self.hash_table = {-1: self.head} <|end_body_0|> <|body_start_1|> if key in self.hash_table: if self.hash_table[key] is not self.tail: ...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_009171
2,028
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
stack_v2_sparse_classes_30k_train_022616
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
d09f56d4fef859ca4749dc753d869828f5de901f
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.size = 1 self.head = LinkedList(0, -1) self.tail = self.head self.hash_table = {-1: self.head} def get(self, key): """:type key: int :rtype: int""" ...
the_stack_v2_python_sparse
146/LRU Cache.py
ArrayZoneYour/LeetCode
train
0
0f2e7250a1bc8f22cae53a5da3e149b24f8010b9
[ "gen_params, disc_params = model_params\nself.num_steps = gen_params[-1]\nif gen_params[1] == 784:\n self.dis_network = convnet28(disc_params)\n self.gen_network = RecGenI28(gen_params)\nelif gen_params[1] == 64 * 64 * 3:\n self.dis_network = convnet64(disc_params)\n self.gen_network = RecGenI64(gen_par...
<|body_start_0|> gen_params, disc_params = model_params self.num_steps = gen_params[-1] if gen_params[1] == 784: self.dis_network = convnet28(disc_params) self.gen_network = RecGenI28(gen_params) elif gen_params[1] == 64 * 64 * 3: self.dis_network = co...
GRAN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GRAN: def __init__(self, model_params): """Initializes discriminator and generator for 64x64/128x128/MNIST""" <|body_0|> def cost_dis(self, X, num_examples): """compute cost of the discriminator""" <|body_1|> def cost_gen(self, num_examples): """...
stack_v2_sparse_classes_75kplus_train_009172
3,692
no_license
[ { "docstring": "Initializes discriminator and generator for 64x64/128x128/MNIST", "name": "__init__", "signature": "def __init__(self, model_params)" }, { "docstring": "compute cost of the discriminator", "name": "cost_dis", "signature": "def cost_dis(self, X, num_examples)" }, { ...
5
null
Implement the Python class `GRAN` described below. Class description: Implement the GRAN class. Method signatures and docstrings: - def __init__(self, model_params): Initializes discriminator and generator for 64x64/128x128/MNIST - def cost_dis(self, X, num_examples): compute cost of the discriminator - def cost_gen(...
Implement the Python class `GRAN` described below. Class description: Implement the GRAN class. Method signatures and docstrings: - def __init__(self, model_params): Initializes discriminator and generator for 64x64/128x128/MNIST - def cost_dis(self, X, num_examples): compute cost of the discriminator - def cost_gen(...
d494b3041069d377d6a7a9c296a14334f2fa5acc
<|skeleton|> class GRAN: def __init__(self, model_params): """Initializes discriminator and generator for 64x64/128x128/MNIST""" <|body_0|> def cost_dis(self, X, num_examples): """compute cost of the discriminator""" <|body_1|> def cost_gen(self, num_examples): """...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GRAN: def __init__(self, model_params): """Initializes discriminator and generator for 64x64/128x128/MNIST""" gen_params, disc_params = model_params self.num_steps = gen_params[-1] if gen_params[1] == 784: self.dis_network = convnet28(disc_params) self.g...
the_stack_v2_python_sparse
python/jiwoongim_GRAN/GRAN-master/gran.py
LiuFang816/SALSTM_py_data
train
10
a40e07cf86d5e5e9fcaf2ad6b159c90d02679ccc
[ "buildingCount = len(buildings)\nif buildingCount == 0:\n return []\ncorners = [[L, H, R] for L, R, H in buildings]\ncorners += [[R, None, 0] for L, R, H in buildings]\ncorners.sort()\nskyline = []\nshift = corners[0][0] - 1\nskylineheight = -1\nh = [[0, float('inf')]]\nfor c in corners:\n if c[0] > shift:\n ...
<|body_start_0|> buildingCount = len(buildings) if buildingCount == 0: return [] corners = [[L, H, R] for L, R, H in buildings] corners += [[R, None, 0] for L, R, H in buildings] corners.sort() skyline = [] shift = corners[0][0] - 1 skylineheig...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getSkyline(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def _getSkyline(self, buildings): """https://discuss.leetcode.com/topic/34119/10-line-python-solution-104-ms/2 credit : kitt""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus_train_009173
2,450
no_license
[ { "docstring": ":type buildings: List[List[int]] :rtype: List[List[int]]", "name": "getSkyline", "signature": "def getSkyline(self, buildings)" }, { "docstring": "https://discuss.leetcode.com/topic/34119/10-line-python-solution-104-ms/2 credit : kitt", "name": "_getSkyline", "signature":...
2
stack_v2_sparse_classes_30k_train_010966
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSkyline(self, buildings): :type buildings: List[List[int]] :rtype: List[List[int]] - def _getSkyline(self, buildings): https://discuss.leetcode.com/topic/34119/10-line-pyt...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSkyline(self, buildings): :type buildings: List[List[int]] :rtype: List[List[int]] - def _getSkyline(self, buildings): https://discuss.leetcode.com/topic/34119/10-line-pyt...
a2841fdb624548fdc6ef430e23ca46f3300e0558
<|skeleton|> class Solution: def getSkyline(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def _getSkyline(self, buildings): """https://discuss.leetcode.com/topic/34119/10-line-python-solution-104-ms/2 credit : kitt""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getSkyline(self, buildings): """:type buildings: List[List[int]] :rtype: List[List[int]]""" buildingCount = len(buildings) if buildingCount == 0: return [] corners = [[L, H, R] for L, R, H in buildings] corners += [[R, None, 0] for L, R, H in b...
the_stack_v2_python_sparse
getSkyLine.py
sfeng77/myleetcode
train
1
cf9b9168df5cea71b329f5f0b32f437032dd6087
[ "super(FGSM, self).__init__(model, device)\nself.loss = nn.CrossEntropyLoss()\nself.device = device\nself.eps = eps\nself.flag_target = flag_target", "xs = xs.to(self.device)\nxs.requires_grad = True\noutput = self.model_forward(xs)\nself.model_zero_grad()\nloss_val = self.loss(output, ys)\nloss_val.backward()\nx...
<|body_start_0|> super(FGSM, self).__init__(model, device) self.loss = nn.CrossEntropyLoss() self.device = device self.eps = eps self.flag_target = flag_target <|end_body_0|> <|body_start_1|> xs = xs.to(self.device) xs.requires_grad = True output = self.m...
FGSM
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FGSM: def __init__(self, model, device, eps=0.001, flag_target=False): """Initializing the FGSM class. Args: model: torch model device: torch.device eps: float, epsilon flag_target: bool, target flag""" <|body_0|> def attack(self, xs: torch.tensor, ys: torch.tensor): ...
stack_v2_sparse_classes_75kplus_train_009174
2,818
permissive
[ { "docstring": "Initializing the FGSM class. Args: model: torch model device: torch.device eps: float, epsilon flag_target: bool, target flag", "name": "__init__", "signature": "def __init__(self, model, device, eps=0.001, flag_target=False)" }, { "docstring": "Attacking the victim model by addi...
2
stack_v2_sparse_classes_30k_train_023157
Implement the Python class `FGSM` described below. Class description: Implement the FGSM class. Method signatures and docstrings: - def __init__(self, model, device, eps=0.001, flag_target=False): Initializing the FGSM class. Args: model: torch model device: torch.device eps: float, epsilon flag_target: bool, target ...
Implement the Python class `FGSM` described below. Class description: Implement the FGSM class. Method signatures and docstrings: - def __init__(self, model, device, eps=0.001, flag_target=False): Initializing the FGSM class. Args: model: torch model device: torch.device eps: float, epsilon flag_target: bool, target ...
3230044473614d2dd931d96cbd6a3bc974eff926
<|skeleton|> class FGSM: def __init__(self, model, device, eps=0.001, flag_target=False): """Initializing the FGSM class. Args: model: torch model device: torch.device eps: float, epsilon flag_target: bool, target flag""" <|body_0|> def attack(self, xs: torch.tensor, ys: torch.tensor): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FGSM: def __init__(self, model, device, eps=0.001, flag_target=False): """Initializing the FGSM class. Args: model: torch model device: torch.device eps: float, epsilon flag_target: bool, target flag""" super(FGSM, self).__init__(model, device) self.loss = nn.CrossEntropyLoss() ...
the_stack_v2_python_sparse
advt/attack/fgsm.py
WindFantasy98/ADVT
train
0
3c88f93df22dfcd613ae198b0733b3e1a3c96890
[ "self.d = {}\nfor i, elem in enumerate(arr):\n if self.d.has_key(elem):\n self.d[elem].append(i)\n else:\n self.d[elem] = [i]", "if value not in self.d.keys():\n return 0\nres = 0\nfor ind in self.d[value]:\n if left <= ind <= right:\n res += 1\nreturn res" ]
<|body_start_0|> self.d = {} for i, elem in enumerate(arr): if self.d.has_key(elem): self.d[elem].append(i) else: self.d[elem] = [i] <|end_body_0|> <|body_start_1|> if value not in self.d.keys(): return 0 res = 0 ...
RangeFreqQuery
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RangeFreqQuery: def __init__(self, arr): """:type arr: List[int]""" <|body_0|> def query(self, left, right, value): """:type left: int :type right: int :type value: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.d = {} ...
stack_v2_sparse_classes_75kplus_train_009175
1,037
no_license
[ { "docstring": ":type arr: List[int]", "name": "__init__", "signature": "def __init__(self, arr)" }, { "docstring": ":type left: int :type right: int :type value: int :rtype: int", "name": "query", "signature": "def query(self, left, right, value)" } ]
2
stack_v2_sparse_classes_30k_train_026500
Implement the Python class `RangeFreqQuery` described below. Class description: Implement the RangeFreqQuery class. Method signatures and docstrings: - def __init__(self, arr): :type arr: List[int] - def query(self, left, right, value): :type left: int :type right: int :type value: int :rtype: int
Implement the Python class `RangeFreqQuery` described below. Class description: Implement the RangeFreqQuery class. Method signatures and docstrings: - def __init__(self, arr): :type arr: List[int] - def query(self, left, right, value): :type left: int :type right: int :type value: int :rtype: int <|skeleton|> class...
ee59b82125f100970c842d5e1245287c484d6649
<|skeleton|> class RangeFreqQuery: def __init__(self, arr): """:type arr: List[int]""" <|body_0|> def query(self, left, right, value): """:type left: int :type right: int :type value: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RangeFreqQuery: def __init__(self, arr): """:type arr: List[int]""" self.d = {} for i, elem in enumerate(arr): if self.d.has_key(elem): self.d[elem].append(i) else: self.d[elem] = [i] def query(self, left, right, value): ...
the_stack_v2_python_sparse
_CodeTopics/LeetCode_contest/weekly/weekly2021/268/TLE--268_3.py
BIAOXYZ/variousCodes
train
0
376c55a34075e257de161999c5c7ab687de3f257
[ "self.prior = prior\nself.posterior = posterior\nself.true_observation = true_observation", "parameters = next(iter(parameters_dict.values()))\npotential = -self.posterior.log_prob(inputs=parameters, context=self.true_observation)\nif isinstance(self.prior, distributions.Uniform):\n log_prob_prior = self.prior...
<|body_start_0|> self.prior = prior self.posterior = posterior self.true_observation = true_observation <|end_body_0|> <|body_start_1|> parameters = next(iter(parameters_dict.values())) potential = -self.posterior.log_prob(inputs=parameters, context=self.true_observation) ...
Implementation of a potential function for Pyro MCMC which uses a classifier to evaluate a quantity proportional to the likelihood.
NeuralPotentialFunction
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeuralPotentialFunction: """Implementation of a potential function for Pyro MCMC which uses a classifier to evaluate a quantity proportional to the likelihood.""" def __init__(self, posterior, prior, true_observation): """:param neural_likelihood: Binary classifier which has learned ...
stack_v2_sparse_classes_75kplus_train_009176
32,145
no_license
[ { "docstring": ":param neural_likelihood: Binary classifier which has learned an approximation to the likelihood up to a constant. :param prior: Distribution object with 'log_prob' method. :param true_observation: torch.Tensor containing true observation x0.", "name": "__init__", "signature": "def __ini...
2
stack_v2_sparse_classes_30k_test_001467
Implement the Python class `NeuralPotentialFunction` described below. Class description: Implementation of a potential function for Pyro MCMC which uses a classifier to evaluate a quantity proportional to the likelihood. Method signatures and docstrings: - def __init__(self, posterior, prior, true_observation): :para...
Implement the Python class `NeuralPotentialFunction` described below. Class description: Implementation of a potential function for Pyro MCMC which uses a classifier to evaluate a quantity proportional to the likelihood. Method signatures and docstrings: - def __init__(self, posterior, prior, true_observation): :para...
c3919c251084763e305f99df3923497a130371a2
<|skeleton|> class NeuralPotentialFunction: """Implementation of a potential function for Pyro MCMC which uses a classifier to evaluate a quantity proportional to the likelihood.""" def __init__(self, posterior, prior, true_observation): """:param neural_likelihood: Binary classifier which has learned ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NeuralPotentialFunction: """Implementation of a potential function for Pyro MCMC which uses a classifier to evaluate a quantity proportional to the likelihood.""" def __init__(self, posterior, prior, true_observation): """:param neural_likelihood: Binary classifier which has learned an approximat...
the_stack_v2_python_sparse
src/inference/apt.py
conormdurkan/lfi
train
41
5f87a34a957465945b1fb0a41931b57ae316adea
[ "if data is None:\n if n <= 0:\n raise ValueError('n must be a positive value')\n if p <= 0 or 1 <= p:\n raise ValueError('p must be greater than 0 and less than 1')\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise Value...
<|body_start_0|> if data is None: if n <= 0: raise ValueError('n must be a positive value') if p <= 0 or 1 <= p: raise ValueError('p must be greater than 0 and less than 1') else: if type(data) is not list: raise TypeErr...
represents a binomial distribution
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """represents a binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”""" <|body_0|> def pmf(self, k):...
stack_v2_sparse_classes_75kplus_train_009177
2,297
no_license
[ { "docstring": "Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5)" }, { "docstring": "Calculates the value of the PMF (probab...
3
stack_v2_sparse_classes_30k_train_018043
Implement the Python class `Binomial` described below. Class description: represents a binomial distribution Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of...
Implement the Python class `Binomial` described below. Class description: represents a binomial distribution Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of...
c20d4dc396f53f2adf73ab9b360977ecf8834af4
<|skeleton|> class Binomial: """represents a binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”""" <|body_0|> def pmf(self, k):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Binomial: """represents a binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”""" if data is None: if n <= 0: ...
the_stack_v2_python_sparse
math/0x03-probability/binomial.py
afarizap/holbertonschool-machine_learning
train
0
afd3b4b572894d77aa5ec7660491ba44a2ff907e
[ "N = len(jobs)\nif k >= N:\n return max(jobs)\nassign = [0] * k\nself.res = inf\nself.depth = -1\n\ndef dfs(index):\n self.depth += 1\n if index == N:\n self.res = min(self.res, max(assign))\n return\n seen = set()\n for i in range(self.depth, self.depth + k):\n i = i % k\n ...
<|body_start_0|> N = len(jobs) if k >= N: return max(jobs) assign = [0] * k self.res = inf self.depth = -1 def dfs(index): self.depth += 1 if index == N: self.res = min(self.res, max(assign)) return ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumTimeRequired(self, jobs: List[int], k: int) -> int: """similar to 698,473 dfs solution""" <|body_0|> def minimumTimeRequired_BS(self, jobs: List[int], k: int) -> int: """DFS+BS(binary search) defined workers first and check with jobs assign""" ...
stack_v2_sparse_classes_75kplus_train_009178
2,411
no_license
[ { "docstring": "similar to 698,473 dfs solution", "name": "minimumTimeRequired", "signature": "def minimumTimeRequired(self, jobs: List[int], k: int) -> int" }, { "docstring": "DFS+BS(binary search) defined workers first and check with jobs assign", "name": "minimumTimeRequired_BS", "sig...
2
stack_v2_sparse_classes_30k_train_024631
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTimeRequired(self, jobs: List[int], k: int) -> int: similar to 698,473 dfs solution - def minimumTimeRequired_BS(self, jobs: List[int], k: int) -> int: DFS+BS(binary s...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTimeRequired(self, jobs: List[int], k: int) -> int: similar to 698,473 dfs solution - def minimumTimeRequired_BS(self, jobs: List[int], k: int) -> int: DFS+BS(binary s...
511a0ad0f5648275493345c6ce44c05c43d58aae
<|skeleton|> class Solution: def minimumTimeRequired(self, jobs: List[int], k: int) -> int: """similar to 698,473 dfs solution""" <|body_0|> def minimumTimeRequired_BS(self, jobs: List[int], k: int) -> int: """DFS+BS(binary search) defined workers first and check with jobs assign""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minimumTimeRequired(self, jobs: List[int], k: int) -> int: """similar to 698,473 dfs solution""" N = len(jobs) if k >= N: return max(jobs) assign = [0] * k self.res = inf self.depth = -1 def dfs(index): self.depth +...
the_stack_v2_python_sparse
code/1723.py
Samuel1043/leetcode
train
0
27ad550673add818c5c6b6dc3c6c66c77669957a
[ "if hasattr(self, '_ellipse_width'):\n return\nself._ellipse_width = Int(0)", "from apysc.type import value_util\nself._initialize_ellipse_width_if_not_initialized()\nreturn value_util.get_copy(value=self._ellipse_width)", "from apysc.validation import number_validation\nnumber_validation.validate_integer(in...
<|body_start_0|> if hasattr(self, '_ellipse_width'): return self._ellipse_width = Int(0) <|end_body_0|> <|body_start_1|> from apysc.type import value_util self._initialize_ellipse_width_if_not_initialized() return value_util.get_copy(value=self._ellipse_width) <|end_...
EllipseWidthInterface
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EllipseWidthInterface: def _initialize_ellipse_width_if_not_initialized(self) -> None: """Initialize _ellipse_width attribute if it is not initialized yet.""" <|body_0|> def ellipse_width(self) -> Int: """Get ellipse width value. Returns ------- ellipse_width : Int E...
stack_v2_sparse_classes_75kplus_train_009179
3,581
permissive
[ { "docstring": "Initialize _ellipse_width attribute if it is not initialized yet.", "name": "_initialize_ellipse_width_if_not_initialized", "signature": "def _initialize_ellipse_width_if_not_initialized(self) -> None" }, { "docstring": "Get ellipse width value. Returns ------- ellipse_width : In...
6
stack_v2_sparse_classes_30k_train_000667
Implement the Python class `EllipseWidthInterface` described below. Class description: Implement the EllipseWidthInterface class. Method signatures and docstrings: - def _initialize_ellipse_width_if_not_initialized(self) -> None: Initialize _ellipse_width attribute if it is not initialized yet. - def ellipse_width(se...
Implement the Python class `EllipseWidthInterface` described below. Class description: Implement the EllipseWidthInterface class. Method signatures and docstrings: - def _initialize_ellipse_width_if_not_initialized(self) -> None: Initialize _ellipse_width attribute if it is not initialized yet. - def ellipse_width(se...
5c6a4674e2e9684cb2cb1325dc9b070879d4d355
<|skeleton|> class EllipseWidthInterface: def _initialize_ellipse_width_if_not_initialized(self) -> None: """Initialize _ellipse_width attribute if it is not initialized yet.""" <|body_0|> def ellipse_width(self) -> Int: """Get ellipse width value. Returns ------- ellipse_width : Int E...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EllipseWidthInterface: def _initialize_ellipse_width_if_not_initialized(self) -> None: """Initialize _ellipse_width attribute if it is not initialized yet.""" if hasattr(self, '_ellipse_width'): return self._ellipse_width = Int(0) def ellipse_width(self) -> Int: ...
the_stack_v2_python_sparse
apysc/display/ellipse_width_interface.py
TrendingTechnology/apysc
train
0
7e2644aa394c9744343a1fce66c4d5ab53c6542b
[ "if name is None:\n name = Path.cwd().name\nself.name = name\nlog = self.log = logging.getLogger(name)\nlog.setLevel(logging.DEBUG)\nself.mylog = self.log_class(self)\nif len(log.handlers) > 0:\n log.warning(f'log={log!r} already has log.handlers={log.handlers!r}')\n for handler in log.handlers:\n i...
<|body_start_0|> if name is None: name = Path.cwd().name self.name = name log = self.log = logging.getLogger(name) log.setLevel(logging.DEBUG) self.mylog = self.log_class(self) if len(log.handlers) > 0: log.warning(f'log={log!r} already has log.han...
Log helper class. name: Name of logger parent: where to put the actual logging data To change logging levels at console: log_root.con.setLevel(logging.DEBUG) log_root.con.setLevel(logging.INFO) To change logging levels at file output log_root.fh.setLevel(logging.DEBUG) log_root.fh.setLevel(logging.INFO) Logging setting...
Log
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Log: """Log helper class. name: Name of logger parent: where to put the actual logging data To change logging levels at console: log_root.con.setLevel(logging.DEBUG) log_root.con.setLevel(logging.INFO) To change logging levels at file output log_root.fh.setLevel(logging.DEBUG) log_root.fh.setLeve...
stack_v2_sparse_classes_75kplus_train_009180
5,462
no_license
[ { "docstring": "Initialize Log. Creates a logger and then sets output to file and output to console at different levels with the root name `name`. If no name passed, then use the name of the current directory.", "name": "__init__", "signature": "def __init__(self, name: Optional[str]=None, parent=None)"...
4
stack_v2_sparse_classes_30k_train_009073
Implement the Python class `Log` described below. Class description: Log helper class. name: Name of logger parent: where to put the actual logging data To change logging levels at console: log_root.con.setLevel(logging.DEBUG) log_root.con.setLevel(logging.INFO) To change logging levels at file output log_root.fh.setL...
Implement the Python class `Log` described below. Class description: Log helper class. name: Name of logger parent: where to put the actual logging data To change logging levels at console: log_root.con.setLevel(logging.DEBUG) log_root.con.setLevel(logging.INFO) To change logging levels at file output log_root.fh.setL...
93b0ddddd872f953feec46025aef80a990e6bbeb
<|skeleton|> class Log: """Log helper class. name: Name of logger parent: where to put the actual logging data To change logging levels at console: log_root.con.setLevel(logging.DEBUG) log_root.con.setLevel(logging.INFO) To change logging levels at file output log_root.fh.setLevel(logging.DEBUG) log_root.fh.setLeve...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Log: """Log helper class. name: Name of logger parent: where to put the actual logging data To change logging levels at console: log_root.con.setLevel(logging.DEBUG) log_root.con.setLevel(logging.INFO) To change logging levels at file output log_root.fh.setLevel(logging.DEBUG) log_root.fh.setLevel(logging.INF...
the_stack_v2_python_sparse
restart/log.py
dcaseykc/restart
train
0
f29a0f5fd2f8e95fbb5f27bb78c2083693748ace
[ "self.sagemaker_session = sagemaker_session\nself.trial_component_name = trial_component_name\nself.artifact_bucket = artifact_bucket\nself.artifact_prefix = artifact_prefix\nself._s3_client = self.sagemaker_session.boto_session.client('s3')", "file_path = os.path.expanduser(file_path)\nif not os.path.isfile(file...
<|body_start_0|> self.sagemaker_session = sagemaker_session self.trial_component_name = trial_component_name self.artifact_bucket = artifact_bucket self.artifact_prefix = artifact_prefix self._s3_client = self.sagemaker_session.boto_session.client('s3') <|end_body_0|> <|body_sta...
Artifact uploader
_ArtifactUploader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _ArtifactUploader: """Artifact uploader""" def __init__(self, trial_component_name, sagemaker_session, artifact_bucket=None, artifact_prefix=_DEFAULT_ARTIFACT_PREFIX): """Initialize a `_ArtifactUploader` instance. Args: trial_component_name (str): The name of the trial component, whi...
stack_v2_sparse_classes_75kplus_train_009181
11,821
permissive
[ { "docstring": "Initialize a `_ArtifactUploader` instance. Args: trial_component_name (str): The name of the trial component, which is used to generate the S3 path to upload the artifact to. sagemaker_session (sagemaker.session.Session): Session object which manages interactions with Amazon SageMaker APIs and a...
4
stack_v2_sparse_classes_30k_train_037081
Implement the Python class `_ArtifactUploader` described below. Class description: Artifact uploader Method signatures and docstrings: - def __init__(self, trial_component_name, sagemaker_session, artifact_bucket=None, artifact_prefix=_DEFAULT_ARTIFACT_PREFIX): Initialize a `_ArtifactUploader` instance. Args: trial_c...
Implement the Python class `_ArtifactUploader` described below. Class description: Artifact uploader Method signatures and docstrings: - def __init__(self, trial_component_name, sagemaker_session, artifact_bucket=None, artifact_prefix=_DEFAULT_ARTIFACT_PREFIX): Initialize a `_ArtifactUploader` instance. Args: trial_c...
8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85
<|skeleton|> class _ArtifactUploader: """Artifact uploader""" def __init__(self, trial_component_name, sagemaker_session, artifact_bucket=None, artifact_prefix=_DEFAULT_ARTIFACT_PREFIX): """Initialize a `_ArtifactUploader` instance. Args: trial_component_name (str): The name of the trial component, whi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _ArtifactUploader: """Artifact uploader""" def __init__(self, trial_component_name, sagemaker_session, artifact_bucket=None, artifact_prefix=_DEFAULT_ARTIFACT_PREFIX): """Initialize a `_ArtifactUploader` instance. Args: trial_component_name (str): The name of the trial component, which is used to...
the_stack_v2_python_sparse
src/sagemaker/experiments/_helper.py
aws/sagemaker-python-sdk
train
2,050
0b96698f108e36feba88af61b8ce6b592d5e8d72
[ "error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError}\nerror_map.update(kwargs.pop('error_map', {}) or {})\n_headers = kwargs.pop('headers', {}) or {}\n_params = kwargs.pop('params', {}) or {}\ncls: ClsType[JSON] = kwargs.pop('cls', None)\...
<|body_start_0|> error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError} error_map.update(kwargs.pop('error_map', {}) or {}) _headers = kwargs.pop('headers', {}) or {} _params = kwargs.pop('params', {}) or {} ...
ServiceBusManagementClientOperationsMixin
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceBusManagementClientOperationsMixin: async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: """Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type top...
stack_v2_sparse_classes_75kplus_train_009182
37,944
permissive
[ { "docstring": "Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type topic_name: str :keyword skip: Default value is 0. :paramtype skip: int :keyword top: Default value is 100. :paramtype top: int :return: JSON :rtype: JSON :raises ...
3
stack_v2_sparse_classes_30k_test_000528
Implement the Python class `ServiceBusManagementClientOperationsMixin` described below. Class description: Implement the ServiceBusManagementClientOperationsMixin class. Method signatures and docstrings: - async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: Get su...
Implement the Python class `ServiceBusManagementClientOperationsMixin` described below. Class description: Implement the ServiceBusManagementClientOperationsMixin class. Method signatures and docstrings: - async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: Get su...
c2ca191e736bb06bfbbbc9493e8325763ba990bb
<|skeleton|> class ServiceBusManagementClientOperationsMixin: async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: """Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type top...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServiceBusManagementClientOperationsMixin: async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: """Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type topic_name: str :...
the_stack_v2_python_sparse
sdk/servicebus/azure-servicebus/azure/servicebus/management/_generated/aio/operations/_operations.py
Azure/azure-sdk-for-python
train
4,046
b8256f95c39afc197ce2f01e2848aea49fd8a021
[ "converted_value: Any = value\nif type_ == IconNetworkValueType.MAX_STEP_LIMITS:\n converted_value: dict = {}\n for key, value in value.items():\n if isinstance(key, str):\n if key == 'invoke':\n converted_value[IconScoreContextType.INVOKE] = value\n elif key == 'qu...
<|body_start_0|> converted_value: Any = value if type_ == IconNetworkValueType.MAX_STEP_LIMITS: converted_value: dict = {} for key, value in value.items(): if isinstance(key, str): if key == 'invoke': converted_value[Ico...
ValueConverter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValueConverter: def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': """Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:""" <|body_0|> def conver...
stack_v2_sparse_classes_75kplus_train_009183
8,639
permissive
[ { "docstring": "Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:", "name": "convert_for_icon_service", "signature": "def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value'" },...
2
stack_v2_sparse_classes_30k_train_008707
Implement the Python class `ValueConverter` described below. Class description: Implement the ValueConverter class. Method signatures and docstrings: - def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': Convert IconNetwork value data type for icon service. Some data need to be convert...
Implement the Python class `ValueConverter` described below. Class description: Implement the ValueConverter class. Method signatures and docstrings: - def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': Convert IconNetwork value data type for icon service. Some data need to be convert...
dfa61fcc42425390a0398ada42ce2121278eec08
<|skeleton|> class ValueConverter: def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': """Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:""" <|body_0|> def conver...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ValueConverter: def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': """Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:""" converted_value: Any = value if ...
the_stack_v2_python_sparse
iconservice/inv/container.py
icon-project/icon-service
train
53
792b55a311a8f9e4b5194bd2b1961f15428f1647
[ "res = 0\nfor i in nums:\n res ^= i\nreturn res", "x, y = (0, 0)\nfor z in nums:\n x = ~y & (z ^ x)\n y = ~x & (z ^ y)\nprint(x, y)\nreturn x", "res = 0\nfor i in nums:\n res ^= i\nn = res & -res\na = 0\nfor i in nums:\n if i & n:\n a ^= i\nb = a ^ res\nreturn [a, b]", "length = len(nums...
<|body_start_0|> res = 0 for i in nums: res ^= i return res <|end_body_0|> <|body_start_1|> x, y = (0, 0) for z in nums: x = ~y & (z ^ x) y = ~x & (z ^ y) print(x, y) return x <|end_body_1|> <|body_start_2|> res = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def singleNumber(self, nums: List[int]) -> int: """136. 只出现一次的数字 其它元素出现2次 顺序异或""" <|body_0|> def singleNumber_137(self, nums: List[int]) -> int: """137. 只出现一次的数字 II 其他元素出现3次 在每一位上出现3次就可以变成0 用有限状态机,写逻辑表达式""" <|body_1|> def singleNumber_260(self,...
stack_v2_sparse_classes_75kplus_train_009184
2,731
no_license
[ { "docstring": "136. 只出现一次的数字 其它元素出现2次 顺序异或", "name": "singleNumber", "signature": "def singleNumber(self, nums: List[int]) -> int" }, { "docstring": "137. 只出现一次的数字 II 其他元素出现3次 在每一位上出现3次就可以变成0 用有限状态机,写逻辑表达式", "name": "singleNumber_137", "signature": "def singleNumber_137(self, nums: List...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums: List[int]) -> int: 136. 只出现一次的数字 其它元素出现2次 顺序异或 - def singleNumber_137(self, nums: List[int]) -> int: 137. 只出现一次的数字 II 其他元素出现3次 在每一位上出现3次就可以变成0 用有限状态机...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums: List[int]) -> int: 136. 只出现一次的数字 其它元素出现2次 顺序异或 - def singleNumber_137(self, nums: List[int]) -> int: 137. 只出现一次的数字 II 其他元素出现3次 在每一位上出现3次就可以变成0 用有限状态机...
3fd69b85f52af861ff7e2c74d8aacc515b192615
<|skeleton|> class Solution: def singleNumber(self, nums: List[int]) -> int: """136. 只出现一次的数字 其它元素出现2次 顺序异或""" <|body_0|> def singleNumber_137(self, nums: List[int]) -> int: """137. 只出现一次的数字 II 其他元素出现3次 在每一位上出现3次就可以变成0 用有限状态机,写逻辑表达式""" <|body_1|> def singleNumber_260(self,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def singleNumber(self, nums: List[int]) -> int: """136. 只出现一次的数字 其它元素出现2次 顺序异或""" res = 0 for i in nums: res ^= i return res def singleNumber_137(self, nums: List[int]) -> int: """137. 只出现一次的数字 II 其他元素出现3次 在每一位上出现3次就可以变成0 用有限状态机,写逻辑表达式""" ...
the_stack_v2_python_sparse
Array/136_137_260_singleNumber.py
helloprogram6/leetcode_Cookbook_python
train
0
47136e7f2cefb379a4bce939d371d98ccf55f6c5
[ "self.terms = GetText(node.getElementsByTagName('Q')[0])\nparams = node.getElementsByTagName('PARAM')\nfor param in params:\n name = param.getAttribute('name')\n if name == 'num':\n self.size = param.getAttribute('value')\n elif name == 'start':\n self.start = param.getAttribute('value')\nele...
<|body_start_0|> self.terms = GetText(node.getElementsByTagName('Q')[0]) params = node.getElementsByTagName('PARAM') for param in params: name = param.getAttribute('name') if name == 'num': self.size = param.getAttribute('value') elif name == '...
A wrapper around the XML of a search response
Response
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Response: """A wrapper around the XML of a search response""" def __init__(self, node): """Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start i...
stack_v2_sparse_classes_75kplus_train_009185
20,975
no_license
[ { "docstring": "Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start index (offset 0) first: the index (offset 1) of the first result in the response last: the index (offset...
2
stack_v2_sparse_classes_30k_test_001331
Implement the Python class `Response` described below. Class description: A wrapper around the XML of a search response Method signatures and docstrings: - def __init__(self, node): Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the reques...
Implement the Python class `Response` described below. Class description: A wrapper around the XML of a search response Method signatures and docstrings: - def __init__(self, node): Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the reques...
99ad033be03779e9680ce8024cdd7a4bdc5a58bd
<|skeleton|> class Response: """A wrapper around the XML of a search response""" def __init__(self, node): """Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Response: """A wrapper around the XML of a search response""" def __init__(self, node): """Construct a wrapper around an XML search response. Exposes the following properties: terms : the requested search terms size: the requested number of search results start: the requested start index (offset ...
the_stack_v2_python_sparse
pubConvGoogle
maximilianh/pubMunch
train
43
f2ee7f09cd7883b0a77fa7228113203c47f4fb27
[ "limit = df[CLOSE].max()\nif limit > 0:\n return cls.__get_max_limit_tm(df[CLOSE], limit)", "limit = df[DIF].max()\nif limit > 0:\n return cls.__get_max_limit_tm(df[DIF], limit)", "limit = df[MACD].max()\nif limit > 0:\n return cls.__get_max_limit_tm(df[MACD], limit)", "limits = series[series >= limi...
<|body_start_0|> limit = df[CLOSE].max() if limit > 0: return cls.__get_max_limit_tm(df[CLOSE], limit) <|end_body_0|> <|body_start_1|> limit = df[DIF].max() if limit > 0: return cls.__get_max_limit_tm(df[DIF], limit) <|end_body_1|> <|body_start_2|> limit...
检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD
MaxLimitDetect
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaxLimitDetect: """检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD""" def get_close_limit_tm_in(cls, df): """获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:""" <|body_0|> def get_dif_limit_tm_in(cls, df): """获取区间内DIF最大值对应的...
stack_v2_sparse_classes_75kplus_train_009186
36,499
no_license
[ { "docstring": "获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:", "name": "get_close_limit_tm_in", "signature": "def get_close_limit_tm_in(cls, df)" }, { "docstring": "获取区间内DIF最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return...
4
stack_v2_sparse_classes_30k_train_009051
Implement the Python class `MaxLimitDetect` described below. Class description: 检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD Method signatures and docstrings: - def get_close_limit_tm_in(cls, df): 获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return: - def get_dif_limit_tm_in(cls...
Implement the Python class `MaxLimitDetect` described below. Class description: 检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD Method signatures and docstrings: - def get_close_limit_tm_in(cls, df): 获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return: - def get_dif_limit_tm_in(cls...
9446d33c0978c325c8b24a876ac2c42fe323dbe6
<|skeleton|> class MaxLimitDetect: """检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD""" def get_close_limit_tm_in(cls, df): """获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:""" <|body_0|> def get_dif_limit_tm_in(cls, df): """获取区间内DIF最大值对应的...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MaxLimitDetect: """检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD""" def get_close_limit_tm_in(cls, df): """获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:""" limit = df[CLOSE].max() if limit > 0: return cls.__get_max_limit_tm(...
the_stack_v2_python_sparse
back_forecast/learn_quant/MACD/jukuan_macd_signal.py
lnkyzhang/wayToFreedomOfWealth
train
3
ad6d42d53bef09c03f42de185cbce3d17cf8165f
[ "self.window = window\nself.window_rect = self.window.get_rect()\nself.bomb_number = 3\nself.bomb_image = pygame.image.load('images/bomb.png')\nself.bomb_rect_list = []\nfor i in range(self.bomb_number):\n bomb_rect = self.bomb_image.get_rect()\n bomb_rect.bottom = self.window_rect.height - constants.MARGIN\n...
<|body_start_0|> self.window = window self.window_rect = self.window.get_rect() self.bomb_number = 3 self.bomb_image = pygame.image.load('images/bomb.png') self.bomb_rect_list = [] for i in range(self.bomb_number): bomb_rect = self.bomb_image.get_rect() ...
可视化炸弹组
VisualBombGroup
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VisualBombGroup: """可视化炸弹组""" def __init__(self, window): """初始化可视化炸弹组""" <|body_0|> def play_explode_sound(self): """播放炸弹爆炸的声音""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.window = window self.window_rect = self.window.get_rect(...
stack_v2_sparse_classes_75kplus_train_009187
1,643
no_license
[ { "docstring": "初始化可视化炸弹组", "name": "__init__", "signature": "def __init__(self, window)" }, { "docstring": "播放炸弹爆炸的声音", "name": "play_explode_sound", "signature": "def play_explode_sound(self)" } ]
2
stack_v2_sparse_classes_30k_train_054625
Implement the Python class `VisualBombGroup` described below. Class description: 可视化炸弹组 Method signatures and docstrings: - def __init__(self, window): 初始化可视化炸弹组 - def play_explode_sound(self): 播放炸弹爆炸的声音
Implement the Python class `VisualBombGroup` described below. Class description: 可视化炸弹组 Method signatures and docstrings: - def __init__(self, window): 初始化可视化炸弹组 - def play_explode_sound(self): 播放炸弹爆炸的声音 <|skeleton|> class VisualBombGroup: """可视化炸弹组""" def __init__(self, window): """初始化可视化炸弹组""" ...
66f7f801e1395207778484e1543ea26309d4b354
<|skeleton|> class VisualBombGroup: """可视化炸弹组""" def __init__(self, window): """初始化可视化炸弹组""" <|body_0|> def play_explode_sound(self): """播放炸弹爆炸的声音""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VisualBombGroup: """可视化炸弹组""" def __init__(self, window): """初始化可视化炸弹组""" self.window = window self.window_rect = self.window.get_rect() self.bomb_number = 3 self.bomb_image = pygame.image.load('images/bomb.png') self.bomb_rect_list = [] for i in ra...
the_stack_v2_python_sparse
python/practise/PlaneWar/visual_bomb_group.py
anzhihe/learning
train
1,443
b3b1b4266cafe7327db1f305385e010c22976a5b
[ "logger.info('Processing BS Filter')\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)", "output_results_files = {}\noutput_metadata = {}\nlogger.info('BS-Filter')\nfrt = filterReadsTool(self.configuration)\nlogger.progress('BSseeker2 Filter', status='RUNNING')\nfastq1f,...
<|body_start_0|> logger.info('Processing BS Filter') if configuration is None: configuration = {} self.configuration.update(configuration) <|end_body_0|> <|body_start_1|> output_results_files = {} output_metadata = {} logger.info('BS-Filter') frt = fi...
Functions for filtering FASTQ files. Files are filtered for removal of duplicate reads. Low quality reads in qseq file can also be filtered.
process_bsFilter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class process_bsFilter: """Functions for filtering FASTQ files. Files are filtered for removal of duplicate reads. Low quality reads in qseq file can also be filtered.""" def __init__(self, configuration=None): """Initialise the class Parameters ---------- configuration : dict a dictionary...
stack_v2_sparse_classes_75kplus_train_009188
6,373
permissive
[ { "docstring": "Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.", "name": "__init__", "signature": "def __init__(self, configuration=None)" }, { "docstring": "...
2
stack_v2_sparse_classes_30k_train_037371
Implement the Python class `process_bsFilter` described below. Class description: Functions for filtering FASTQ files. Files are filtered for removal of duplicate reads. Low quality reads in qseq file can also be filtered. Method signatures and docstrings: - def __init__(self, configuration=None): Initialise the clas...
Implement the Python class `process_bsFilter` described below. Class description: Functions for filtering FASTQ files. Files are filtered for removal of duplicate reads. Low quality reads in qseq file can also be filtered. Method signatures and docstrings: - def __init__(self, configuration=None): Initialise the clas...
50c7115c0c1a6af48dc34f275e469d1b9eb02999
<|skeleton|> class process_bsFilter: """Functions for filtering FASTQ files. Files are filtered for removal of duplicate reads. Low quality reads in qseq file can also be filtered.""" def __init__(self, configuration=None): """Initialise the class Parameters ---------- configuration : dict a dictionary...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class process_bsFilter: """Functions for filtering FASTQ files. Files are filtered for removal of duplicate reads. Low quality reads in qseq file can also be filtered.""" def __init__(self, configuration=None): """Initialise the class Parameters ---------- configuration : dict a dictionary containing p...
the_stack_v2_python_sparse
process_bs_seeker_filter.py
Multiscale-Genomics/mg-process-fastq
train
2
b12a6c127f9c13c4864193a68b06a441843e9d1a
[ "if c in first:\n return 1\nelif c in second:\n return 2\nelse:\n return 3", "if len(word) < 2:\n return True\nrow = self.checkRow(word[0].lower())\nfor c in word:\n if row == 1 and c.lower() not in first:\n return False\n elif row == 2 and c.lower() not in second:\n return False\n...
<|body_start_0|> if c in first: return 1 elif c in second: return 2 else: return 3 <|end_body_0|> <|body_start_1|> if len(word) < 2: return True row = self.checkRow(word[0].lower()) for c in word: if row == 1 an...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def checkRow(self, c): """this function will determine the row of c""" <|body_0|> def canType(self, word): """this function will check if this word can be typed from a row""" <|body_1|> def findWords(self, words): """:type words: List[s...
stack_v2_sparse_classes_75kplus_train_009189
1,553
no_license
[ { "docstring": "this function will determine the row of c", "name": "checkRow", "signature": "def checkRow(self, c)" }, { "docstring": "this function will check if this word can be typed from a row", "name": "canType", "signature": "def canType(self, word)" }, { "docstring": ":ty...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkRow(self, c): this function will determine the row of c - def canType(self, word): this function will check if this word can be typed from a row - def findWords(self, wo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkRow(self, c): this function will determine the row of c - def canType(self, word): this function will check if this word can be typed from a row - def findWords(self, wo...
c01002206fcc1b3ed35d1ba1e83dffdff5fc16a5
<|skeleton|> class Solution: def checkRow(self, c): """this function will determine the row of c""" <|body_0|> def canType(self, word): """this function will check if this word can be typed from a row""" <|body_1|> def findWords(self, words): """:type words: List[s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def checkRow(self, c): """this function will determine the row of c""" if c in first: return 1 elif c in second: return 2 else: return 3 def canType(self, word): """this function will check if this word can be typed fro...
the_stack_v2_python_sparse
Keyboard Row/solution.py
kimjaspermui/LeetCode
train
0
e7b45ce0c4bac0ca43d10941381097144f23af2c
[ "for module, obs in observations.items():\n if module == 'raw':\n continue\n print(f\"{module.message_name()}\\n{'-' * 80}\\n{obs.get('prompt')}\\n{'-' * 80}\\n{'-' * 80}\")", "print('=' * 80)\nprint(f\"{'-' * 20} DISPLAYING ACT FIELDS {'-' * 20}\")\nprint('=' * 80)\nfor key, val in act.items():\n ...
<|body_start_0|> for module, obs in observations.items(): if module == 'raw': continue print(f"{module.message_name()}\n{'-' * 80}\n{obs.get('prompt')}\n{'-' * 80}\n{'-' * 80}") <|end_body_0|> <|body_start_1|> print('=' * 80) print(f"{'-' * 20} DISPLAYING...
DisplayUtils
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DisplayUtils: def display_observations(observations: Dict[Module, Dict[str, Any]]): """Print the observations nicely.""" <|body_0|> def display_act(act: Message): """Print the observations nicely.""" <|body_1|> <|end_skeleton|> <|body_start_0|> for ...
stack_v2_sparse_classes_75kplus_train_009190
22,847
permissive
[ { "docstring": "Print the observations nicely.", "name": "display_observations", "signature": "def display_observations(observations: Dict[Module, Dict[str, Any]])" }, { "docstring": "Print the observations nicely.", "name": "display_act", "signature": "def display_act(act: Message)" }...
2
null
Implement the Python class `DisplayUtils` described below. Class description: Implement the DisplayUtils class. Method signatures and docstrings: - def display_observations(observations: Dict[Module, Dict[str, Any]]): Print the observations nicely. - def display_act(act: Message): Print the observations nicely.
Implement the Python class `DisplayUtils` described below. Class description: Implement the DisplayUtils class. Method signatures and docstrings: - def display_observations(observations: Dict[Module, Dict[str, Any]]): Print the observations nicely. - def display_act(act: Message): Print the observations nicely. <|sk...
e1d899edfb92471552bae153f59ad30aa7fca468
<|skeleton|> class DisplayUtils: def display_observations(observations: Dict[Module, Dict[str, Any]]): """Print the observations nicely.""" <|body_0|> def display_act(act: Message): """Print the observations nicely.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DisplayUtils: def display_observations(observations: Dict[Module, Dict[str, Any]]): """Print the observations nicely.""" for module, obs in observations.items(): if module == 'raw': continue print(f"{module.message_name()}\n{'-' * 80}\n{obs.get('prompt')...
the_stack_v2_python_sparse
projects/bb3/agents/utils.py
facebookresearch/ParlAI
train
10,943
77ffe5203c68b6bd7286d5c8980e3dd369169989
[ "context = pecan.request.context\npolicy.enforce(context, 'network:create', action='network:create')\nnew_network = pecan.request.compute_api.network_create(context, network_dict['neutron_net_id'])\nreturn view.format_network(pecan.request.host_url, new_network)", "context = pecan.request.context\npolicy.enforce(...
<|body_start_0|> context = pecan.request.context policy.enforce(context, 'network:create', action='network:create') new_network = pecan.request.compute_api.network_create(context, network_dict['neutron_net_id']) return view.format_network(pecan.request.host_url, new_network) <|end_body_0...
Controller for Network
NetworkController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkController: """Controller for Network""" def post(self, **network_dict): """Create a new network. :param network_dict: a network within the request body.""" <|body_0|> def delete(self, network_ident, **kwargs): """Delete a network. :param network_ident: UU...
stack_v2_sparse_classes_75kplus_train_009191
3,260
permissive
[ { "docstring": "Create a new network. :param network_dict: a network within the request body.", "name": "post", "signature": "def post(self, **network_dict)" }, { "docstring": "Delete a network. :param network_ident: UUID of the network.", "name": "delete", "signature": "def delete(self,...
2
stack_v2_sparse_classes_30k_test_002073
Implement the Python class `NetworkController` described below. Class description: Controller for Network Method signatures and docstrings: - def post(self, **network_dict): Create a new network. :param network_dict: a network within the request body. - def delete(self, network_ident, **kwargs): Delete a network. :pa...
Implement the Python class `NetworkController` described below. Class description: Controller for Network Method signatures and docstrings: - def post(self, **network_dict): Create a new network. :param network_dict: a network within the request body. - def delete(self, network_ident, **kwargs): Delete a network. :pa...
4fa358474ee337f27bfaf8b98e886cc8d10ada50
<|skeleton|> class NetworkController: """Controller for Network""" def post(self, **network_dict): """Create a new network. :param network_dict: a network within the request body.""" <|body_0|> def delete(self, network_ident, **kwargs): """Delete a network. :param network_ident: UU...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NetworkController: """Controller for Network""" def post(self, **network_dict): """Create a new network. :param network_dict: a network within the request body.""" context = pecan.request.context policy.enforce(context, 'network:create', action='network:create') new_networ...
the_stack_v2_python_sparse
zun/api/controllers/v1/networks.py
openstack/zun
train
89
d07faf1a9a9d92d1fb1f0a2746fd7e3e07f4adf2
[ "def _get_hosts():\n zone = waiting.wait(lambda: self._client.find(zoneName=zone_name), timeout_seconds=config.NOVA_AVAILABILITY_TIMEOUT, expected_exceptions=nova_exceptions.ClientException)\n for hosts_dict in zone.hosts.values():\n for host in hosts_dict.values():\n host['updated_at'] = pa...
<|body_start_0|> def _get_hosts(): zone = waiting.wait(lambda: self._client.find(zoneName=zone_name), timeout_seconds=config.NOVA_AVAILABILITY_TIMEOUT, expected_exceptions=nova_exceptions.ClientException) for hosts_dict in zone.hosts.values(): for host in hosts_dict.value...
Availability zone steps.
AvailabilityZoneSteps
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AvailabilityZoneSteps: """Availability zone steps.""" def check_all_active_hosts_available(self, zone_name='nova'): """Checks that all active nova hosts for zone are available. Nova checks hosts status with some interval. To prevent checking on outdated hosts data this method wait fo...
stack_v2_sparse_classes_75kplus_train_009192
3,576
no_license
[ { "docstring": "Checks that all active nova hosts for zone are available. Nova checks hosts status with some interval. To prevent checking on outdated hosts data this method wait for `updated_at` host's attribute to be changed. Args: zone_name (str): zone name Raises: AssertionError: if not all hosts are active...
3
stack_v2_sparse_classes_30k_val_002498
Implement the Python class `AvailabilityZoneSteps` described below. Class description: Availability zone steps. Method signatures and docstrings: - def check_all_active_hosts_available(self, zone_name='nova'): Checks that all active nova hosts for zone are available. Nova checks hosts status with some interval. To pr...
Implement the Python class `AvailabilityZoneSteps` described below. Class description: Availability zone steps. Method signatures and docstrings: - def check_all_active_hosts_available(self, zone_name='nova'): Checks that all active nova hosts for zone are available. Nova checks hosts status with some interval. To pr...
e7583444cd24893ec6ae237b47db7c605b99b0c5
<|skeleton|> class AvailabilityZoneSteps: """Availability zone steps.""" def check_all_active_hosts_available(self, zone_name='nova'): """Checks that all active nova hosts for zone are available. Nova checks hosts status with some interval. To prevent checking on outdated hosts data this method wait fo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AvailabilityZoneSteps: """Availability zone steps.""" def check_all_active_hosts_available(self, zone_name='nova'): """Checks that all active nova hosts for zone are available. Nova checks hosts status with some interval. To prevent checking on outdated hosts data this method wait for `updated_at...
the_stack_v2_python_sparse
stepler/nova/steps/availability_zones.py
Mirantis/stepler
train
16
0f94febad3196146faaf287bf8870b439dd4f3b5
[ "print('In bl | User | create User method')\ntry:\n is_user_exists = FacadeAdmin.is_exist_by_login(entity['login'])\nexcept Exception as e:\n raise ServiceException('ADMIN_USER_DATABASE_QUERY_FAIL', 'Fail to verify if the user already exist.', str(e))\nif is_user_exists:\n raise ServiceException('ADMIN_USE...
<|body_start_0|> print('In bl | User | create User method') try: is_user_exists = FacadeAdmin.is_exist_by_login(entity['login']) except Exception as e: raise ServiceException('ADMIN_USER_DATABASE_QUERY_FAIL', 'Fail to verify if the user already exist.', str(e)) if...
Allow user management systems
Admin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Admin: """Allow user management systems""" def create_user(entity): """Create a new admin user :param entity: A Entity object with required values email: The email associated to this user [String, Required] password: The password associated to this user [String, Required] email: The ...
stack_v2_sparse_classes_75kplus_train_009193
5,356
no_license
[ { "docstring": "Create a new admin user :param entity: A Entity object with required values email: The email associated to this user [String, Required] password: The password associated to this user [String, Required] email: The email associated to this user [String, Required] firstname: The first name of the u...
3
stack_v2_sparse_classes_30k_train_012261
Implement the Python class `Admin` described below. Class description: Allow user management systems Method signatures and docstrings: - def create_user(entity): Create a new admin user :param entity: A Entity object with required values email: The email associated to this user [String, Required] password: The passwo...
Implement the Python class `Admin` described below. Class description: Allow user management systems Method signatures and docstrings: - def create_user(entity): Create a new admin user :param entity: A Entity object with required values email: The email associated to this user [String, Required] password: The passwo...
8dd3118eab24ee3992bc345573f4bb427930b30c
<|skeleton|> class Admin: """Allow user management systems""" def create_user(entity): """Create a new admin user :param entity: A Entity object with required values email: The email associated to this user [String, Required] password: The password associated to this user [String, Required] email: The ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Admin: """Allow user management systems""" def create_user(entity): """Create a new admin user :param entity: A Entity object with required values email: The email associated to this user [String, Required] password: The password associated to this user [String, Required] email: The email associa...
the_stack_v2_python_sparse
admin/bl/admin_user.py
amityadav17/catalog
train
0
9d8b8c19de5f3e7b31c576ea386b1a8b3a3c74f3
[ "odd = filter(lambda x: x % 2, A)\neven = filter(lambda x: not x % 2, A)\nresult = []\nwhile odd and even:\n result.append(even.pop())\n result.append(odd.pop())\nreturn result", "if not A:\n return A\neven = 0\nodd = 1\nwhile even < len(A) and odd < len(A):\n while not A[even] % 2:\n even += 2...
<|body_start_0|> odd = filter(lambda x: x % 2, A) even = filter(lambda x: not x % 2, A) result = [] while odd and even: result.append(even.pop()) result.append(odd.pop()) return result <|end_body_0|> <|body_start_1|> if not A: return A...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _sortArrayByParityII(self, A): """:type A: List[int] :rtype: List[int]""" <|body_0|> def sortArrayByParityII(self, A): """:type A: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> odd = filter(lambda x: x % 2...
stack_v2_sparse_classes_75kplus_train_009194
1,846
permissive
[ { "docstring": ":type A: List[int] :rtype: List[int]", "name": "_sortArrayByParityII", "signature": "def _sortArrayByParityII(self, A)" }, { "docstring": ":type A: List[int] :rtype: List[int]", "name": "sortArrayByParityII", "signature": "def sortArrayByParityII(self, A)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _sortArrayByParityII(self, A): :type A: List[int] :rtype: List[int] - def sortArrayByParityII(self, A): :type A: List[int] :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _sortArrayByParityII(self, A): :type A: List[int] :rtype: List[int] - def sortArrayByParityII(self, A): :type A: List[int] :rtype: List[int] <|skeleton|> class Solution: ...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _sortArrayByParityII(self, A): """:type A: List[int] :rtype: List[int]""" <|body_0|> def sortArrayByParityII(self, A): """:type A: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def _sortArrayByParityII(self, A): """:type A: List[int] :rtype: List[int]""" odd = filter(lambda x: x % 2, A) even = filter(lambda x: not x % 2, A) result = [] while odd and even: result.append(even.pop()) result.append(odd.pop()) ...
the_stack_v2_python_sparse
922.sort-array-by-parity-ii.py
windard/leeeeee
train
0
d569010915f16bffb181603d475c676527c5631e
[ "super(ConformalDeformationFlowNetwork, self).__init__()\nself.dim = dim\nself.latent_size = latent_size\nself.nlayers = nlayers\nself.width = width\nself.nonlinearity = nonlinearity\nself.output_scalar = output_scalar\nself.scale = nn.Parameter(torch.ones(1) * 0.1)\nnlin = NONLINEARITIES[nonlinearity]\nmodules = [...
<|body_start_0|> super(ConformalDeformationFlowNetwork, self).__init__() self.dim = dim self.latent_size = latent_size self.nlayers = nlayers self.width = width self.nonlinearity = nonlinearity self.output_scalar = output_scalar self.scale = nn.Parameter(t...
ConformalDeformationFlowNetwork
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConformalDeformationFlowNetwork: def __init__(self, dim=3, latent_size=1, nlayers=4, width=50, nonlinearity='softplus', output_scalar=False, arch='imnet'): """Intialize conformal deformation flow network w/ irrotational flow. The network produces a scalar field Phi(x,y,z,t), and the velo...
stack_v2_sparse_classes_75kplus_train_009195
23,339
permissive
[ { "docstring": "Intialize conformal deformation flow network w/ irrotational flow. The network produces a scalar field Phi(x,y,z,t), and the velocity field is represented as the gradient of Phi. v = abla\\\\Phi # noqa: W605 The gradients can be efficiently computed as the Jacobian through backprop. Args: dim: i...
2
null
Implement the Python class `ConformalDeformationFlowNetwork` described below. Class description: Implement the ConformalDeformationFlowNetwork class. Method signatures and docstrings: - def __init__(self, dim=3, latent_size=1, nlayers=4, width=50, nonlinearity='softplus', output_scalar=False, arch='imnet'): Intialize...
Implement the Python class `ConformalDeformationFlowNetwork` described below. Class description: Implement the ConformalDeformationFlowNetwork class. Method signatures and docstrings: - def __init__(self, dim=3, latent_size=1, nlayers=4, width=50, nonlinearity='softplus', output_scalar=False, arch='imnet'): Intialize...
bf152f60f287a728cc782aa53f2930154f18b2a3
<|skeleton|> class ConformalDeformationFlowNetwork: def __init__(self, dim=3, latent_size=1, nlayers=4, width=50, nonlinearity='softplus', output_scalar=False, arch='imnet'): """Intialize conformal deformation flow network w/ irrotational flow. The network produces a scalar field Phi(x,y,z,t), and the velo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConformalDeformationFlowNetwork: def __init__(self, dim=3, latent_size=1, nlayers=4, width=50, nonlinearity='softplus', output_scalar=False, arch='imnet'): """Intialize conformal deformation flow network w/ irrotational flow. The network produces a scalar field Phi(x,y,z,t), and the velocity field is ...
the_stack_v2_python_sparse
ShapeFlow/shapeflow/layers/deformation_layer.py
vikasTmz/SP-GAN
train
0
a8e50982c1776966b621ddde4ab8d7844365cceb
[ "if self.__dict__.get('verbose', False):\n print('generating anagrams')\nself.anagrams = build_anagrams(jobs)\nfor job in jobs:\n try:\n remaining_letters = alphabetize(char_filter(self.word, job, 1))\n if remaining_letters in self.anagrams:\n for second_job in self.anagrams[remaining...
<|body_start_0|> if self.__dict__.get('verbose', False): print('generating anagrams') self.anagrams = build_anagrams(jobs) for job in jobs: try: remaining_letters = alphabetize(char_filter(self.word, job, 1)) if remaining_letters in self.an...
MySolver is an example solver which is a child of the solver class.
MySolver
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MySolver: """MySolver is an example solver which is a child of the solver class.""" def try_list(self, list_name, jobs): """Takes a list job titles, and trys to find whether any of them together match merchant raider alphabetized.""" <|body_0|> def get_candidates(self): ...
stack_v2_sparse_classes_75kplus_train_009196
3,609
permissive
[ { "docstring": "Takes a list job titles, and trys to find whether any of them together match merchant raider alphabetized.", "name": "try_list", "signature": "def try_list(self, list_name, jobs)" }, { "docstring": "prints the current list of candidates", "name": "get_candidates", "signat...
2
stack_v2_sparse_classes_30k_train_003212
Implement the Python class `MySolver` described below. Class description: MySolver is an example solver which is a child of the solver class. Method signatures and docstrings: - def try_list(self, list_name, jobs): Takes a list job titles, and trys to find whether any of them together match merchant raider alphabetiz...
Implement the Python class `MySolver` described below. Class description: MySolver is an example solver which is a child of the solver class. Method signatures and docstrings: - def try_list(self, list_name, jobs): Takes a list job titles, and trys to find whether any of them together match merchant raider alphabetiz...
c84c1b51d83c7e780430175e41588632441aa180
<|skeleton|> class MySolver: """MySolver is an example solver which is a child of the solver class.""" def try_list(self, list_name, jobs): """Takes a list job titles, and trys to find whether any of them together match merchant raider alphabetized.""" <|body_0|> def get_candidates(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MySolver: """MySolver is an example solver which is a child of the solver class.""" def try_list(self, list_name, jobs): """Takes a list job titles, and trys to find whether any of them together match merchant raider alphabetized.""" if self.__dict__.get('verbose', False): pri...
the_stack_v2_python_sparse
solutions/20150524/merchant_raider.py
johnobrien/pyshortz
train
0
1886a0e1996e1e4538c02e00aed4aa6f5ef99889
[ "super(Transformer, self).__init__()\nself.encoder = encoder\nself.decoder = decoder\nself.linear = tf.keras.layers.Dense(units=target_vocab, input_shape=([None], [None]))", "print('============================')\nprint(inputs)\nprint(target)\nprint('============================')\ndec_output = self.decoder.decod...
<|body_start_0|> super(Transformer, self).__init__() self.encoder = encoder self.decoder = decoder self.linear = tf.keras.layers.Dense(units=target_vocab, input_shape=([None], [None])) <|end_body_0|> <|body_start_1|> print('============================') print(inputs) ...
The Transformer model class
Transformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Transformer: """The Transformer model class""" def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): """init of transformer""" <|body_0|> def call(self, inputs, target, training, encoder_mask, loo...
stack_v2_sparse_classes_75kplus_train_009197
1,488
no_license
[ { "docstring": "init of transformer", "name": "__init__", "signature": "def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1)" }, { "docstring": "Calls the transformer", "name": "call", "signature": "def call(self,...
2
stack_v2_sparse_classes_30k_train_003553
Implement the Python class `Transformer` described below. Class description: The Transformer model class Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): init of transformer - def call(self, inputs, tar...
Implement the Python class `Transformer` described below. Class description: The Transformer model class Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): init of transformer - def call(self, inputs, tar...
4200798bdbbe828db94e5585b62a595e3a96c3e6
<|skeleton|> class Transformer: """The Transformer model class""" def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): """init of transformer""" <|body_0|> def call(self, inputs, target, training, encoder_mask, loo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Transformer: """The Transformer model class""" def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): """init of transformer""" super(Transformer, self).__init__() self.encoder = encoder self.decoder...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-transformer.py
JohnCook17/holbertonschool-machine_learning
train
3
5d70d3035717d2baf5b39fdd614d8512f2d1e2bd
[ "self.phase_change_level_data = np.array([[1.0, 1.0, 2.0], [1.0, np.nan, 2.0], [1.0, 2.0, 2.0]])\nself.phase_change_data_no_interp = np.array([[np.nan, np.nan, np.nan], [1.0, np.nan, 2.0], [1.0, 2.0, np.nan]])\nself.orog = np.ones((3, 3))\nself.highest_wb_int = np.ones((3, 3))\nself.highest_height = 300.0", "plug...
<|body_start_0|> self.phase_change_level_data = np.array([[1.0, 1.0, 2.0], [1.0, np.nan, 2.0], [1.0, 2.0, 2.0]]) self.phase_change_data_no_interp = np.array([[np.nan, np.nan, np.nan], [1.0, np.nan, 2.0], [1.0, 2.0, np.nan]]) self.orog = np.ones((3, 3)) self.highest_wb_int = np.ones((3, 3...
Test the fill_in_high_phase_change_falling_levels method.
Test_fill_in_high_phase_change_falling_levels
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_fill_in_high_phase_change_falling_levels: """Test the fill_in_high_phase_change_falling_levels method.""" def setUp(self): """Set up arrays for testing.""" <|body_0|> def test_basic(self): """Test fills in missing data with orography + highest height""" ...
stack_v2_sparse_classes_75kplus_train_009198
37,344
permissive
[ { "docstring": "Set up arrays for testing.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test fills in missing data with orography + highest height", "name": "test_basic", "signature": "def test_basic(self)" }, { "docstring": "Test it doesn't fill in NaN if...
3
stack_v2_sparse_classes_30k_train_052164
Implement the Python class `Test_fill_in_high_phase_change_falling_levels` described below. Class description: Test the fill_in_high_phase_change_falling_levels method. Method signatures and docstrings: - def setUp(self): Set up arrays for testing. - def test_basic(self): Test fills in missing data with orography + h...
Implement the Python class `Test_fill_in_high_phase_change_falling_levels` described below. Class description: Test the fill_in_high_phase_change_falling_levels method. Method signatures and docstrings: - def setUp(self): Set up arrays for testing. - def test_basic(self): Test fills in missing data with orography + h...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_fill_in_high_phase_change_falling_levels: """Test the fill_in_high_phase_change_falling_levels method.""" def setUp(self): """Set up arrays for testing.""" <|body_0|> def test_basic(self): """Test fills in missing data with orography + highest height""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test_fill_in_high_phase_change_falling_levels: """Test the fill_in_high_phase_change_falling_levels method.""" def setUp(self): """Set up arrays for testing.""" self.phase_change_level_data = np.array([[1.0, 1.0, 2.0], [1.0, np.nan, 2.0], [1.0, 2.0, 2.0]]) self.phase_change_data_n...
the_stack_v2_python_sparse
improver_tests/psychrometric_calculations/test_PhaseChangeLevel.py
metoppv/improver
train
101
0989d3c5161c4e8f5a2ba914314692415b71a340
[ "for n in nodes:\n dict.__setitem__(self, n.i, n)\nfor e in edges:\n self[e.n1].connect(self[e.n2])\n self[e.n2].connect(self[e.n1])", "r = dict()\nr[-1] = 0\nr[0] = 0\nfor k in self:\n if r.get(self[k].s) == None:\n r[self[k].s] = 1.0 / float(len(self))\n else:\n r[self[k].s] = r[sel...
<|body_start_0|> for n in nodes: dict.__setitem__(self, n.i, n) for e in edges: self[e.n1].connect(self[e.n2]) self[e.n2].connect(self[e.n1]) <|end_body_0|> <|body_start_1|> r = dict() r[-1] = 0 r[0] = 0 for k in self: if r...
A graph object
Graph
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Graph: """A graph object""" def __init__(self, nodes=[], edges=[]): """Constructor nodes: a list of Node objects edges: a list of Edge objects""" <|body_0|> def ratio(self): """Pseudo-property: get the ratio of each player's occupied nodes""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_009199
24,726
no_license
[ { "docstring": "Constructor nodes: a list of Node objects edges: a list of Edge objects", "name": "__init__", "signature": "def __init__(self, nodes=[], edges=[])" }, { "docstring": "Pseudo-property: get the ratio of each player's occupied nodes", "name": "ratio", "signature": "def ratio...
5
stack_v2_sparse_classes_30k_train_023237
Implement the Python class `Graph` described below. Class description: A graph object Method signatures and docstrings: - def __init__(self, nodes=[], edges=[]): Constructor nodes: a list of Node objects edges: a list of Edge objects - def ratio(self): Pseudo-property: get the ratio of each player's occupied nodes - ...
Implement the Python class `Graph` described below. Class description: A graph object Method signatures and docstrings: - def __init__(self, nodes=[], edges=[]): Constructor nodes: a list of Node objects edges: a list of Edge objects - def ratio(self): Pseudo-property: get the ratio of each player's occupied nodes - ...
34d1387524d969e36fe13689edfcb43891c262e0
<|skeleton|> class Graph: """A graph object""" def __init__(self, nodes=[], edges=[]): """Constructor nodes: a list of Node objects edges: a list of Edge objects""" <|body_0|> def ratio(self): """Pseudo-property: get the ratio of each player's occupied nodes""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Graph: """A graph object""" def __init__(self, nodes=[], edges=[]): """Constructor nodes: a list of Node objects edges: a list of Edge objects""" for n in nodes: dict.__setitem__(self, n.i, n) for e in edges: self[e.n1].connect(self[e.n2]) self[...
the_stack_v2_python_sparse
NoUpload/shaqal/Nanomunchers/nano.py
designreuse/HeuristicProblemSolving
train
0