blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
d1adea77ae57d3868dbe4b890712420fb8cda2cd
[ "self.max_proba = max_proba\nself.confident_threshold = confident_threshold\nself.top_n = top_n", "if self.confident_threshold:\n return [list(np.where(np.array(d) > self.confident_threshold)[0]) for d in data]\nelif self.max_proba:\n return [np.argmax(d) for d in data]\nelif self.top_n:\n return [np.arg...
<|body_start_0|> self.max_proba = max_proba self.confident_threshold = confident_threshold self.top_n = top_n <|end_body_0|> <|body_start_1|> if self.confident_threshold: return [list(np.where(np.array(d) > self.confident_threshold)[0]) for d in data] elif self.max_p...
Class implements probability to labels processing using the following ways: choosing one or top_n indices with maximal probability or choosing any number of indices which probabilities to belong with are higher than given confident threshold Args: max_proba: whether to choose label with maximal probability confident_th...
Proba2Labels
[ "Python-2.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Proba2Labels: """Class implements probability to labels processing using the following ways: choosing one or top_n indices with maximal probability or choosing any number of indices which probabilities to belong with are higher than given confident threshold Args: max_proba: whether to choose lab...
stack_v2_sparse_classes_36k_train_011700
3,194
permissive
[ { "docstring": "Initialize class with given parameters", "name": "__init__", "signature": "def __init__(self, max_proba: bool=None, confident_threshold: float=None, top_n: int=None, **kwargs) -> None" }, { "docstring": "Process probabilities to labels Args: data: list of vectors with probability...
2
null
Implement the Python class `Proba2Labels` described below. Class description: Class implements probability to labels processing using the following ways: choosing one or top_n indices with maximal probability or choosing any number of indices which probabilities to belong with are higher than given confident threshold...
Implement the Python class `Proba2Labels` described below. Class description: Class implements probability to labels processing using the following ways: choosing one or top_n indices with maximal probability or choosing any number of indices which probabilities to belong with are higher than given confident threshold...
65f69dfb898f5444cc2c98ae03ec7b3f44266df2
<|skeleton|> class Proba2Labels: """Class implements probability to labels processing using the following ways: choosing one or top_n indices with maximal probability or choosing any number of indices which probabilities to belong with are higher than given confident threshold Args: max_proba: whether to choose lab...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Proba2Labels: """Class implements probability to labels processing using the following ways: choosing one or top_n indices with maximal probability or choosing any number of indices which probabilities to belong with are higher than given confident threshold Args: max_proba: whether to choose label with maxim...
the_stack_v2_python_sparse
deeppavlov/models/classifiers/proba2labels.py
vintagexav/DeepPavlov
train
2
86aa0e1deb3e9da53c5a98ddff2aa1239f867ae2
[ "super().__init__()\nself._logger = logging.getLogger(__name__)\nif not hasattr(sa_exc, 'orig') or not hasattr(sa_exc.orig, 'pgcode'):\n self.msg = 'A value entered is in wrong format.'\n return\nmsg_match = re.match('^.*»(.*)«.*$', sa_exc.orig.diag.message_primary)\ntry:\n value = msg_match.group(1)\nexce...
<|body_start_0|> super().__init__() self._logger = logging.getLogger(__name__) if not hasattr(sa_exc, 'orig') or not hasattr(sa_exc.orig, 'pgcode'): self.msg = 'A value entered is in wrong format.' return msg_match = re.match('^.*»(.*)«.*$', sa_exc.orig.diag.messa...
Define a exception in potion's hierarchy to deal with the data type error in database.
DataError
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataError: """Define a exception in potion's hierarchy to deal with the data type error in database.""" def __init__(self, sa_exc): """Constructors, extract message from sa's exception object Args: sa_exc (DataError): sa's exception""" <|body_0|> def as_dict(self): ...
stack_v2_sparse_classes_36k_train_011701
10,585
permissive
[ { "docstring": "Constructors, extract message from sa's exception object Args: sa_exc (DataError): sa's exception", "name": "__init__", "signature": "def __init__(self, sa_exc)" }, { "docstring": "Wraps original as_dict to return customized message", "name": "as_dict", "signature": "def ...
2
null
Implement the Python class `DataError` described below. Class description: Define a exception in potion's hierarchy to deal with the data type error in database. Method signatures and docstrings: - def __init__(self, sa_exc): Constructors, extract message from sa's exception object Args: sa_exc (DataError): sa's exce...
Implement the Python class `DataError` described below. Class description: Define a exception in potion's hierarchy to deal with the data type error in database. Method signatures and docstrings: - def __init__(self, sa_exc): Constructors, extract message from sa's exception object Args: sa_exc (DataError): sa's exce...
9c9040f6a173af5c495f5447889e9349fa56f234
<|skeleton|> class DataError: """Define a exception in potion's hierarchy to deal with the data type error in database.""" def __init__(self, sa_exc): """Constructors, extract message from sa's exception object Args: sa_exc (DataError): sa's exception""" <|body_0|> def as_dict(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataError: """Define a exception in potion's hierarchy to deal with the data type error in database.""" def __init__(self, sa_exc): """Constructors, extract message from sa's exception object Args: sa_exc (DataError): sa's exception""" super().__init__() self._logger = logging.get...
the_stack_v2_python_sparse
tessia/server/api/manager.py
tessia-project/tessia
train
10
a9d63308f84fbc79bc1e70d02fa05242063f12ba
[ "self.ports = in_node.ports\nself.in_node_loc = in_node.loc\nself.op_nodes = op_nodes\nself.out_node = out_node\nself.in_node = in_node", "local_in_node = self.in_node.clone()\nlocal_in_node.change_operands(operands)\nreturn CommandManager(local_in_node, self.out_node, self.op_nodes)", "cm = self.test(operands)...
<|body_start_0|> self.ports = in_node.ports self.in_node_loc = in_node.loc self.op_nodes = op_nodes self.out_node = out_node self.in_node = in_node <|end_body_0|> <|body_start_1|> local_in_node = self.in_node.clone() local_in_node.change_operands(operands) ...
CommandTester
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommandTester: def __init__(self, in_node: InNode, out_node: OutNode, op_nodes: list): """Initializes CommandTester. :param ports: List of ports that each shape should go in. :param out_node: Node where all operands should meet. :param op_nodes: List of all known operator nodes in the st...
stack_v2_sparse_classes_36k_train_011702
2,173
no_license
[ { "docstring": "Initializes CommandTester. :param ports: List of ports that each shape should go in. :param out_node: Node where all operands should meet. :param op_nodes: List of all known operator nodes in the stage.", "name": "__init__", "signature": "def __init__(self, in_node: InNode, out_node: Out...
3
stack_v2_sparse_classes_30k_train_018282
Implement the Python class `CommandTester` described below. Class description: Implement the CommandTester class. Method signatures and docstrings: - def __init__(self, in_node: InNode, out_node: OutNode, op_nodes: list): Initializes CommandTester. :param ports: List of ports that each shape should go in. :param out_...
Implement the Python class `CommandTester` described below. Class description: Implement the CommandTester class. Method signatures and docstrings: - def __init__(self, in_node: InNode, out_node: OutNode, op_nodes: list): Initializes CommandTester. :param ports: List of ports that each shape should go in. :param out_...
3435f802b3b5f26853e6d5301f4576875dc7fdf2
<|skeleton|> class CommandTester: def __init__(self, in_node: InNode, out_node: OutNode, op_nodes: list): """Initializes CommandTester. :param ports: List of ports that each shape should go in. :param out_node: Node where all operands should meet. :param op_nodes: List of all known operator nodes in the st...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommandTester: def __init__(self, in_node: InNode, out_node: OutNode, op_nodes: list): """Initializes CommandTester. :param ports: List of ports that each shape should go in. :param out_node: Node where all operands should meet. :param op_nodes: List of all known operator nodes in the stage.""" ...
the_stack_v2_python_sparse
components/commands/CommandTester.py
Iris-0829/LunarBlocks
train
0
2d61b14020fe0588895285604de3887d1aa116a3
[ "super().__init__()\nif all((var is None for var in (hidden_conv_layers, n_filters, kernel_sizes, strides, paddings))):\n hidden_conv_layers = HamiltonianNet.DEFAULT_PARAMS['hidden_conv_layers']\n n_filters = HamiltonianNet.DEFAULT_PARAMS['n_filters']\n kernel_sizes = HamiltonianNet.DEFAULT_PARAMS['kernel_...
<|body_start_0|> super().__init__() if all((var is None for var in (hidden_conv_layers, n_filters, kernel_sizes, strides, paddings))): hidden_conv_layers = HamiltonianNet.DEFAULT_PARAMS['hidden_conv_layers'] n_filters = HamiltonianNet.DEFAULT_PARAMS['n_filters'] kerne...
The Hamiltonian network, composed of 6 convolutional layers and a final linear layer.
HamiltonianNet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HamiltonianNet: """The Hamiltonian network, composed of 6 convolutional layers and a final linear layer.""" def __init__(self, in_shape, hidden_conv_layers=None, n_filters=None, kernel_sizes=None, strides=None, paddings=None, act_func=nn.Softplus(), dtype=torch.float): """Create the ...
stack_v2_sparse_classes_36k_train_011703
5,737
permissive
[ { "docstring": "Create the layers of the Hamiltonian network. If K is the total number of convolutional layers, then hidden_conv_layers = K - 2. The length of n_filters, kernel_sizes, and strides must be K. If all of them are None, HamiltonianNet.DEFAULT_PARAMS will be used. Args: in_shape (tuple): Shape of inp...
2
stack_v2_sparse_classes_30k_train_015668
Implement the Python class `HamiltonianNet` described below. Class description: The Hamiltonian network, composed of 6 convolutional layers and a final linear layer. Method signatures and docstrings: - def __init__(self, in_shape, hidden_conv_layers=None, n_filters=None, kernel_sizes=None, strides=None, paddings=None...
Implement the Python class `HamiltonianNet` described below. Class description: The Hamiltonian network, composed of 6 convolutional layers and a final linear layer. Method signatures and docstrings: - def __init__(self, in_shape, hidden_conv_layers=None, n_filters=None, kernel_sizes=None, strides=None, paddings=None...
702d3ff3aec40eba20e17c5a1612b5b0b1e2f831
<|skeleton|> class HamiltonianNet: """The Hamiltonian network, composed of 6 convolutional layers and a final linear layer.""" def __init__(self, in_shape, hidden_conv_layers=None, n_filters=None, kernel_sizes=None, strides=None, paddings=None, act_func=nn.Softplus(), dtype=torch.float): """Create the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HamiltonianNet: """The Hamiltonian network, composed of 6 convolutional layers and a final linear layer.""" def __init__(self, in_shape, hidden_conv_layers=None, n_filters=None, kernel_sizes=None, strides=None, paddings=None, act_func=nn.Softplus(), dtype=torch.float): """Create the layers of the...
the_stack_v2_python_sparse
networks/hamiltonian_net.py
CampusAI/Hamiltonian-Generative-Networks
train
35
ff8ece3607fc902cfea168fba8283dce281f53f0
[ "if request.method != 'POST':\n return None\nif 'HTTP_X_APPENGINE_CRON' in os.environ or 'HTTP_X_APPENGINE_QUEUENAME' in os.environ:\n return None\npost_token = request.POST.get('xsrf_token')\nif not post_token:\n logging.warn('Missing XSRF token for post data %s', request.POST)\n return http.HttpRespon...
<|body_start_0|> if request.method != 'POST': return None if 'HTTP_X_APPENGINE_CRON' in os.environ or 'HTTP_X_APPENGINE_QUEUENAME' in os.environ: return None post_token = request.POST.get('xsrf_token') if not post_token: logging.warn('Missing XSRF toke...
Middleware for preventing cross-site request forgery attacks. This class implements the specification defined at https://docs.djangoproject.com/en/dev/topics/http/middleware/.
XsrfMiddleware
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XsrfMiddleware: """Middleware for preventing cross-site request forgery attacks. This class implements the specification defined at https://docs.djangoproject.com/en/dev/topics/http/middleware/.""" def process_request(self, request): """Requires a valid XSRF token on POST requests.""...
stack_v2_sparse_classes_36k_train_011704
3,853
permissive
[ { "docstring": "Requires a valid XSRF token on POST requests.", "name": "process_request", "signature": "def process_request(self, request)" }, { "docstring": "Alters HTML responses containing <form> tags to embed the XSRF token.", "name": "process_response", "signature": "def process_re...
2
null
Implement the Python class `XsrfMiddleware` described below. Class description: Middleware for preventing cross-site request forgery attacks. This class implements the specification defined at https://docs.djangoproject.com/en/dev/topics/http/middleware/. Method signatures and docstrings: - def process_request(self, ...
Implement the Python class `XsrfMiddleware` described below. Class description: Middleware for preventing cross-site request forgery attacks. This class implements the specification defined at https://docs.djangoproject.com/en/dev/topics/http/middleware/. Method signatures and docstrings: - def process_request(self, ...
f581989f168189fa3a58c028eff327a16c03e438
<|skeleton|> class XsrfMiddleware: """Middleware for preventing cross-site request forgery attacks. This class implements the specification defined at https://docs.djangoproject.com/en/dev/topics/http/middleware/.""" def process_request(self, request): """Requires a valid XSRF token on POST requests.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XsrfMiddleware: """Middleware for preventing cross-site request forgery attacks. This class implements the specification defined at https://docs.djangoproject.com/en/dev/topics/http/middleware/.""" def process_request(self, request): """Requires a valid XSRF token on POST requests.""" if ...
the_stack_v2_python_sparse
app/soc/middleware/xsrf.py
sambitgaan/nupic.son
train
0
3ac608bfd94df299e5db69490b343ffb65b62e61
[ "dp = [float('inf')] * (n + 1)\ndp[0] = 0\nfor i in range(1, n + 1):\n for j in range(1, int(i ** 0.5) + 1):\n dp[i] = min(dp[i], dp[i - j * j] + 1)\nreturn dp[n]", "queue = [node(n)]\nvisited = set([node(n).value])\nwhile queue:\n vertex = queue.pop(0)\n residuals = [vertex.value - n * n for n in...
<|body_start_0|> dp = [float('inf')] * (n + 1) dp[0] = 0 for i in range(1, n + 1): for j in range(1, int(i ** 0.5) + 1): dp[i] = min(dp[i], dp[i - j * j] + 1) return dp[n] <|end_body_0|> <|body_start_1|> queue = [node(n)] visited = set([node(n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numSquares_dp(self, n): """:type n: int :rtype: int dp[i]代表到数字i组成最少完全平方个数 动态转移方程:dp[i] = min(dp[i], dp[i - j * j] + 1), j <= sqrt{i} + 1""" <|body_0|> def numSquares_bfs(self, n): """:type n: int :rtype: int BFS 其实是很简单的基础算法,抓住如下几点即可轻松写出不易错的 baseline: BF...
stack_v2_sparse_classes_36k_train_011705
2,613
no_license
[ { "docstring": ":type n: int :rtype: int dp[i]代表到数字i组成最少完全平方个数 动态转移方程:dp[i] = min(dp[i], dp[i - j * j] + 1), j <= sqrt{i} + 1", "name": "numSquares_dp", "signature": "def numSquares_dp(self, n)" }, { "docstring": ":type n: int :rtype: int BFS 其实是很简单的基础算法,抓住如下几点即可轻松写出不易错的 baseline: BFS 算法组成的 3 元素...
2
stack_v2_sparse_classes_30k_train_004897
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSquares_dp(self, n): :type n: int :rtype: int dp[i]代表到数字i组成最少完全平方个数 动态转移方程:dp[i] = min(dp[i], dp[i - j * j] + 1), j <= sqrt{i} + 1 - def numSquares_bfs(self, n): :type n: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSquares_dp(self, n): :type n: int :rtype: int dp[i]代表到数字i组成最少完全平方个数 动态转移方程:dp[i] = min(dp[i], dp[i - j * j] + 1), j <= sqrt{i} + 1 - def numSquares_bfs(self, n): :type n: ...
3f4284330f9771037ca59e2e6a94122e51e58540
<|skeleton|> class Solution: def numSquares_dp(self, n): """:type n: int :rtype: int dp[i]代表到数字i组成最少完全平方个数 动态转移方程:dp[i] = min(dp[i], dp[i - j * j] + 1), j <= sqrt{i} + 1""" <|body_0|> def numSquares_bfs(self, n): """:type n: int :rtype: int BFS 其实是很简单的基础算法,抓住如下几点即可轻松写出不易错的 baseline: BF...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numSquares_dp(self, n): """:type n: int :rtype: int dp[i]代表到数字i组成最少完全平方个数 动态转移方程:dp[i] = min(dp[i], dp[i - j * j] + 1), j <= sqrt{i} + 1""" dp = [float('inf')] * (n + 1) dp[0] = 0 for i in range(1, n + 1): for j in range(1, int(i ** 0.5) + 1): ...
the_stack_v2_python_sparse
Leetcode/279.完全平方数.py
myf-algorithm/Leetcode
train
1
5dc65ce1ef8529270a1b5058f28bb92636c85147
[ "super(NCC_model, self).__init__()\nself.c1 = th.nn.Conv1d(2, n_hiddens, 1)\nself.c2 = th.nn.Conv1d(n_hiddens, n_hiddens, 1)\nself.batch_norm = th.nn.BatchNorm1d(n_hiddens, affine=False)\nself.l1 = th.nn.Linear(n_hiddens, n_hiddens)\nself.l2 = th.nn.Linear(n_hiddens, 1)", "act = th.nn.ReLU()\nout = act(self.c1(x)...
<|body_start_0|> super(NCC_model, self).__init__() self.c1 = th.nn.Conv1d(2, n_hiddens, 1) self.c2 = th.nn.Conv1d(n_hiddens, n_hiddens, 1) self.batch_norm = th.nn.BatchNorm1d(n_hiddens, affine=False) self.l1 = th.nn.Linear(n_hiddens, n_hiddens) self.l2 = th.nn.Linear(n_hi...
NCC model structure.
NCC_model
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NCC_model: """NCC model structure.""" def __init__(self, n_hiddens=20): """Init the NCC structure with the number of hidden units. :param n_hiddens: Number of hidden units :type n_hiddens: int""" <|body_0|> def forward(self, x): """Passing data through the networ...
stack_v2_sparse_classes_36k_train_011706
3,373
permissive
[ { "docstring": "Init the NCC structure with the number of hidden units. :param n_hiddens: Number of hidden units :type n_hiddens: int", "name": "__init__", "signature": "def __init__(self, n_hiddens=20)" }, { "docstring": "Passing data through the network. :param x: 2d tensor containing both (x,...
2
null
Implement the Python class `NCC_model` described below. Class description: NCC model structure. Method signatures and docstrings: - def __init__(self, n_hiddens=20): Init the NCC structure with the number of hidden units. :param n_hiddens: Number of hidden units :type n_hiddens: int - def forward(self, x): Passing da...
Implement the Python class `NCC_model` described below. Class description: NCC model structure. Method signatures and docstrings: - def __init__(self, n_hiddens=20): Init the NCC structure with the number of hidden units. :param n_hiddens: Number of hidden units :type n_hiddens: int - def forward(self, x): Passing da...
0b15fd6f424074e369c03e0e6015c80dbf6f708e
<|skeleton|> class NCC_model: """NCC model structure.""" def __init__(self, n_hiddens=20): """Init the NCC structure with the number of hidden units. :param n_hiddens: Number of hidden units :type n_hiddens: int""" <|body_0|> def forward(self, x): """Passing data through the networ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NCC_model: """NCC model structure.""" def __init__(self, n_hiddens=20): """Init the NCC structure with the number of hidden units. :param n_hiddens: Number of hidden units :type n_hiddens: int""" super(NCC_model, self).__init__() self.c1 = th.nn.Conv1d(2, n_hiddens, 1) sel...
the_stack_v2_python_sparse
Causal Inference/Experiments/CausalDiscoveryToolbox-master/cdt/causality/pairwise/NCC.py
afcarl/techniques
train
0
cb45201393807138cd6afb8704970b72f6b2267a
[ "super(CDMStringIOWrapper, self).__init__()\nself._source = source\nself._is_error = is_error\nself._callback = callback", "for line in s.split('\\n'):\n if line != '':\n self._callback(self._source, line, self._is_error)\nreturn super(CDMStringIOWrapper, self).write(s)" ]
<|body_start_0|> super(CDMStringIOWrapper, self).__init__() self._source = source self._is_error = is_error self._callback = callback <|end_body_0|> <|body_start_1|> for line in s.split('\n'): if line != '': self._callback(self._source, line, self._is...
Subclass of io.StringIO, adds a callback to write(). This wrapped IO class will send lines it receives via write() to the callback, intended to be EnqueueMessage of a CDM instance.
CDMStringIOWrapper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CDMStringIOWrapper: """Subclass of io.StringIO, adds a callback to write(). This wrapped IO class will send lines it receives via write() to the callback, intended to be EnqueueMessage of a CDM instance.""" def __init__(self, source: str, is_error: bool, callback: Callable[[str, str, bool], ...
stack_v2_sparse_classes_36k_train_011707
17,020
permissive
[ { "docstring": "Initialise the object.", "name": "__init__", "signature": "def __init__(self, source: str, is_error: bool, callback: Callable[[str, str, bool], None]) -> None" }, { "docstring": "Writes the bytes to the internal buffer, and uses the callback on any lines received.", "name": "...
2
stack_v2_sparse_classes_30k_train_015295
Implement the Python class `CDMStringIOWrapper` described below. Class description: Subclass of io.StringIO, adds a callback to write(). This wrapped IO class will send lines it receives via write() to the callback, intended to be EnqueueMessage of a CDM instance. Method signatures and docstrings: - def __init__(self...
Implement the Python class `CDMStringIOWrapper` described below. Class description: Subclass of io.StringIO, adds a callback to write(). This wrapped IO class will send lines it receives via write() to the callback, intended to be EnqueueMessage of a CDM instance. Method signatures and docstrings: - def __init__(self...
bcea85b1ce7a0feb2aa28b5be4fc6ae124e8ca3c
<|skeleton|> class CDMStringIOWrapper: """Subclass of io.StringIO, adds a callback to write(). This wrapped IO class will send lines it receives via write() to the callback, intended to be EnqueueMessage of a CDM instance.""" def __init__(self, source: str, is_error: bool, callback: Callable[[str, str, bool], ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CDMStringIOWrapper: """Subclass of io.StringIO, adds a callback to write(). This wrapped IO class will send lines it receives via write() to the callback, intended to be EnqueueMessage of a CDM instance.""" def __init__(self, source: str, is_error: bool, callback: Callable[[str, str, bool], None]) -> Non...
the_stack_v2_python_sparse
dftimewolf/cli/curses_display_manager.py
log2timeline/dftimewolf
train
248
207b93e58cf13852fde826ed26f8c3c6d8c73424
[ "if not re.match('1[3-9]\\\\d{9}$', value):\n raise serializers.ValidationError('手机号有误')\nreturn value", "if value != 'true':\n raise serializers.ValidationError('请先同意使用协议')\nreturn value", "if attr.get('password') != attr.get('password2'):\n raise serializers.ValidationError('两个密码不一致')\nredis_conn = g...
<|body_start_0|> if not re.match('1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号有误') return value <|end_body_0|> <|body_start_1|> if value != 'true': raise serializers.ValidationError('请先同意使用协议') return value <|end_body_1|> <|body_start_2|> ...
注册序列化器
CreateUserSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateUserSerializer: """注册序列化器""" def validate_mobile(self, value): """单独校验手机号""" <|body_0|> def validate_allow(self, value): """校验是否同意协议""" <|body_1|> def validate(self, attr): """校验两次密码是否相同""" <|body_2|> def create(self, valid...
stack_v2_sparse_classes_36k_train_011708
8,653
no_license
[ { "docstring": "单独校验手机号", "name": "validate_mobile", "signature": "def validate_mobile(self, value)" }, { "docstring": "校验是否同意协议", "name": "validate_allow", "signature": "def validate_allow(self, value)" }, { "docstring": "校验两次密码是否相同", "name": "validate", "signature": "de...
4
stack_v2_sparse_classes_30k_val_000664
Implement the Python class `CreateUserSerializer` described below. Class description: 注册序列化器 Method signatures and docstrings: - def validate_mobile(self, value): 单独校验手机号 - def validate_allow(self, value): 校验是否同意协议 - def validate(self, attr): 校验两次密码是否相同 - def create(self, validated_data): 重写create方法
Implement the Python class `CreateUserSerializer` described below. Class description: 注册序列化器 Method signatures and docstrings: - def validate_mobile(self, value): 单独校验手机号 - def validate_allow(self, value): 校验是否同意协议 - def validate(self, attr): 校验两次密码是否相同 - def create(self, validated_data): 重写create方法 <|skeleton|> cla...
a8fb0fc2352e0c71bab756a06c5a8babd8c350da
<|skeleton|> class CreateUserSerializer: """注册序列化器""" def validate_mobile(self, value): """单独校验手机号""" <|body_0|> def validate_allow(self, value): """校验是否同意协议""" <|body_1|> def validate(self, attr): """校验两次密码是否相同""" <|body_2|> def create(self, valid...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateUserSerializer: """注册序列化器""" def validate_mobile(self, value): """单独校验手机号""" if not re.match('1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号有误') return value def validate_allow(self, value): """校验是否同意协议""" if value != 'true': ...
the_stack_v2_python_sparse
meiduo_mall/meiduo_mall/apps/users/serializers.py
zhangjian-ai/meiduo
train
22
7d9810ea4d21b6a6becb8acb1572f7495b048e6b
[ "self.m = collections.defaultdict(list)\nfor i, word in enumerate(words):\n self.m[word].append(i)", "idx1, idx2 = (self.m[word1], self.m[word2])\nres = float('inf')\ni = j = 0\nwhile i < len(idx1) and j < len(idx2):\n res = min(res, abs(idx1[i] - idx2[j]))\n if idx1[i] < idx2[j]:\n i += 1\n el...
<|body_start_0|> self.m = collections.defaultdict(list) for i, word in enumerate(words): self.m[word].append(i) <|end_body_0|> <|body_start_1|> idx1, idx2 = (self.m[word1], self.m[word2]) res = float('inf') i = j = 0 while i < len(idx1) and j < len(idx2): ...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.m = collections.defaultdict(list...
stack_v2_sparse_classes_36k_train_011709
785
no_license
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortest(self, word1, word2)" } ]
2
stack_v2_sparse_classes_30k_train_017411
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int <|skeleton|> class WordDistance: ...
5b14b6f42baf59b04cbcc8e115df4272029b64c8
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordDistance: def __init__(self, words): """:type words: List[str]""" self.m = collections.defaultdict(list) for i, word in enumerate(words): self.m[word].append(i) def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" id...
the_stack_v2_python_sparse
LeetCode/0244.Shortest-Word-Distance-Ii/Shortest-Word-Distance-Ii.py
htingwang/HandsOnAlgoDS
train
12
976402db022bf67f63dfed5157ba4f203c6a85e9
[ "super().__init__(netatmo_device.data_handler)\nself.entity_description = BATTERY_SENSOR_DESCRIPTION\nself._module = cast(pyatmo.modules.NRV, netatmo_device.device)\nself._id = netatmo_device.parent_id\nself._publishers.extend([{'name': HOME, 'home_id': netatmo_device.device.home.entity_id, SIGNAL_NAME: netatmo_dev...
<|body_start_0|> super().__init__(netatmo_device.data_handler) self.entity_description = BATTERY_SENSOR_DESCRIPTION self._module = cast(pyatmo.modules.NRV, netatmo_device.device) self._id = netatmo_device.parent_id self._publishers.extend([{'name': HOME, 'home_id': netatmo_device...
Implementation of a Netatmo sensor.
NetatmoClimateBatterySensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetatmoClimateBatterySensor: """Implementation of a Netatmo sensor.""" def __init__(self, netatmo_device: NetatmoDevice) -> None: """Initialize the sensor.""" <|body_0|> def async_update_callback(self) -> None: """Update the entity's state.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_011710
25,750
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, netatmo_device: NetatmoDevice) -> None" }, { "docstring": "Update the entity's state.", "name": "async_update_callback", "signature": "def async_update_callback(self) -> None" } ]
2
null
Implement the Python class `NetatmoClimateBatterySensor` described below. Class description: Implementation of a Netatmo sensor. Method signatures and docstrings: - def __init__(self, netatmo_device: NetatmoDevice) -> None: Initialize the sensor. - def async_update_callback(self) -> None: Update the entity's state.
Implement the Python class `NetatmoClimateBatterySensor` described below. Class description: Implementation of a Netatmo sensor. Method signatures and docstrings: - def __init__(self, netatmo_device: NetatmoDevice) -> None: Initialize the sensor. - def async_update_callback(self) -> None: Update the entity's state. ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class NetatmoClimateBatterySensor: """Implementation of a Netatmo sensor.""" def __init__(self, netatmo_device: NetatmoDevice) -> None: """Initialize the sensor.""" <|body_0|> def async_update_callback(self) -> None: """Update the entity's state.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetatmoClimateBatterySensor: """Implementation of a Netatmo sensor.""" def __init__(self, netatmo_device: NetatmoDevice) -> None: """Initialize the sensor.""" super().__init__(netatmo_device.data_handler) self.entity_description = BATTERY_SENSOR_DESCRIPTION self._module = ...
the_stack_v2_python_sparse
homeassistant/components/netatmo/sensor.py
home-assistant/core
train
35,501
e125e655a8febcb816ca069eaaa3bbd2076ae4e7
[ "super(Spectrogram, self).__init__()\nself.n_fft = n_fft\nself.hop = hop\nself.mels = mels\nself.sr = sr\nself.window = nn.Parameter(torch.hann_window(n_fft), requires_grad=False)\nstft_size = n_fft // 2 + 1\nself.mel_transform = nn.Conv1d(stft_size, mels, kernel_size=1, stride=1, padding=0, bias=True)\nself.mean =...
<|body_start_0|> super(Spectrogram, self).__init__() self.n_fft = n_fft self.hop = hop self.mels = mels self.sr = sr self.window = nn.Parameter(torch.hann_window(n_fft), requires_grad=False) stft_size = n_fft // 2 + 1 self.mel_transform = nn.Conv1d(stft_si...
Calculate the mel spectrogram as an additional input for the encoder
Spectrogram
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Spectrogram: """Calculate the mel spectrogram as an additional input for the encoder""" def __init__(self, n_fft, hop, mels, sr): """Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate...
stack_v2_sparse_classes_36k_train_011711
37,269
no_license
[ { "docstring": "Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate of the signal", "name": "__init__", "signature": "def __init__(self, n_fft, hop, mels, sr)" }, { "docstring": "Arguments: audio_...
4
stack_v2_sparse_classes_30k_test_000688
Implement the Python class `Spectrogram` described below. Class description: Calculate the mel spectrogram as an additional input for the encoder Method signatures and docstrings: - def __init__(self, n_fft, hop, mels, sr): Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {in...
Implement the Python class `Spectrogram` described below. Class description: Calculate the mel spectrogram as an additional input for the encoder Method signatures and docstrings: - def __init__(self, n_fft, hop, mels, sr): Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {in...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class Spectrogram: """Calculate the mel spectrogram as an additional input for the encoder""" def __init__(self, n_fft, hop, mels, sr): """Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Spectrogram: """Calculate the mel spectrogram as an additional input for the encoder""" def __init__(self, n_fft, hop, mels, sr): """Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate of the signa...
the_stack_v2_python_sparse
generated/test_pfnet_research_meta_tasnet.py
jansel/pytorch-jit-paritybench
train
35
290e8cd268006000cee9af28736b19d9a4ad31e6
[ "super(LightSource, self).at_object_creation()\nself.db.tutorial_info = 'This object can be turned on off and has a timed script controlling it.'\nself.db.is_active = False\nself.db.burntime = 60 * 3\nself.db.desc = 'A splinter of wood with remnants of resin on it, enough for burning.'\nself.cmdset.add_default(CmdS...
<|body_start_0|> super(LightSource, self).at_object_creation() self.db.tutorial_info = 'This object can be turned on off and has a timed script controlling it.' self.db.is_active = False self.db.burntime = 60 * 3 self.db.desc = 'A splinter of wood with remnants of resin on it, en...
This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at.
LightSource
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LightSource: """This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at.""" def at_object_creation(self): """Called when object is first created.""" <|body_0|> def reset(self...
stack_v2_sparse_classes_36k_train_011712
36,948
permissive
[ { "docstring": "Called when object is first created.", "name": "at_object_creation", "signature": "def at_object_creation(self)" }, { "docstring": "Can be called by tutorial world runner, or by the script when the lightsource has burned out.", "name": "reset", "signature": "def reset(sel...
2
stack_v2_sparse_classes_30k_train_006864
Implement the Python class `LightSource` described below. Class description: This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at. Method signatures and docstrings: - def at_object_creation(self): Called when object is...
Implement the Python class `LightSource` described below. Class description: This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at. Method signatures and docstrings: - def at_object_creation(self): Called when object is...
4515b6b569f919b18223ff2b241ea70f3e787e1e
<|skeleton|> class LightSource: """This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at.""" def at_object_creation(self): """Called when object is first created.""" <|body_0|> def reset(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LightSource: """This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at.""" def at_object_creation(self): """Called when object is first created.""" super(LightSource, self).at_object_creation...
the_stack_v2_python_sparse
contrib/tutorial_world/objects.py
mergederg/deuterium
train
1
e9433dda7638aade544bd5e12915d806c35cff27
[ "error_messages = {'incomplete': _('Must fill all coordinates')}\ndimensions = kwargs.get('dimensions', self.DIMENSIONS)\nfields = [forms.FloatField() for i in range(dimensions)]\nfor field in fields:\n field.error_messages = {}\nkwargs['widget'] = VectorWidget(attrs={'dimensions': dimensions})\nif 'max_length' ...
<|body_start_0|> error_messages = {'incomplete': _('Must fill all coordinates')} dimensions = kwargs.get('dimensions', self.DIMENSIONS) fields = [forms.FloatField() for i in range(dimensions)] for field in fields: field.error_messages = {} kwargs['widget'] = VectorWid...
N dimensional vector field
VectorFormField
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VectorFormField: """N dimensional vector field""" def __init__(self, *args, **kwargs): """Class initialization method""" <|body_0|> def compress(self, data_list): """Data compression method""" <|body_1|> <|end_skeleton|> <|body_start_0|> error_m...
stack_v2_sparse_classes_36k_train_011713
6,288
permissive
[ { "docstring": "Class initialization method", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Data compression method", "name": "compress", "signature": "def compress(self, data_list)" } ]
2
stack_v2_sparse_classes_30k_train_013761
Implement the Python class `VectorFormField` described below. Class description: N dimensional vector field Method signatures and docstrings: - def __init__(self, *args, **kwargs): Class initialization method - def compress(self, data_list): Data compression method
Implement the Python class `VectorFormField` described below. Class description: N dimensional vector field Method signatures and docstrings: - def __init__(self, *args, **kwargs): Class initialization method - def compress(self, data_list): Data compression method <|skeleton|> class VectorFormField: """N dimens...
be9d747b8ca4c5d18f9725b2dad08dba6119d810
<|skeleton|> class VectorFormField: """N dimensional vector field""" def __init__(self, *args, **kwargs): """Class initialization method""" <|body_0|> def compress(self, data_list): """Data compression method""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VectorFormField: """N dimensional vector field""" def __init__(self, *args, **kwargs): """Class initialization method""" error_messages = {'incomplete': _('Must fill all coordinates')} dimensions = kwargs.get('dimensions', self.DIMENSIONS) fields = [forms.FloatField() for ...
the_stack_v2_python_sparse
sitetools/forms/fields.py
olivergs/django-sitetools
train
0
5ac04510aeb31a2036521eca074e395b3d98cd2c
[ "self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(5, 0.1)\nself.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OFF': self.pump.PUMP_OFF}\nself.controller = Controller(self.sensor, self.pump, self.decider)", "self.sensor.measure = ...
<|body_start_0|> self.sensor = Sensor('127.0.0.1', 8000) self.pump = Pump('127.0.0.1', 8000) self.decider = Decider(5, 0.1) self.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OFF': self.pump.PUMP_OFF} self.controller = Controller(self.sensor, self...
Unit tests for the Controller class
ControllerTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ControllerTests: """Unit tests for the Controller class""" def setUp(self): """setUp method for running each test.""" <|body_0|> def test_determine_next_state_true(self): """Test that tick returns true when given mocked data to yield a response of True.""" ...
stack_v2_sparse_classes_36k_train_011714
5,252
no_license
[ { "docstring": "setUp method for running each test.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that tick returns true when given mocked data to yield a response of True.", "name": "test_determine_next_state_true", "signature": "def test_determine_next_state...
3
null
Implement the Python class `ControllerTests` described below. Class description: Unit tests for the Controller class Method signatures and docstrings: - def setUp(self): setUp method for running each test. - def test_determine_next_state_true(self): Test that tick returns true when given mocked data to yield a respon...
Implement the Python class `ControllerTests` described below. Class description: Unit tests for the Controller class Method signatures and docstrings: - def setUp(self): setUp method for running each test. - def test_determine_next_state_true(self): Test that tick returns true when given mocked data to yield a respon...
263685ca90110609bfd05d621516727f8cd0028f
<|skeleton|> class ControllerTests: """Unit tests for the Controller class""" def setUp(self): """setUp method for running each test.""" <|body_0|> def test_determine_next_state_true(self): """Test that tick returns true when given mocked data to yield a response of True.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ControllerTests: """Unit tests for the Controller class""" def setUp(self): """setUp method for running each test.""" self.sensor = Sensor('127.0.0.1', 8000) self.pump = Pump('127.0.0.1', 8000) self.decider = Decider(5, 0.1) self.actions = {'PUMP_IN': self.pump.PUM...
the_stack_v2_python_sparse
students/david_russo/lesson06/waterregulation/waterregulation/test.py
aurel1212/Sp2018-Online
train
0
3cb877ac1c346cf7ad85b1103d2c75f7af15cbb1
[ "test_group, created = PointGroup.objects.get_or_create(name=kwargs.get('pointGroupName', 'Test points'))\npt_group, created = PricingTierGroup.objects.get_or_create(group=test_group, pricingTier=self.defaultPricing, points=kwargs.get('pricingTierGroupPoints', 5))\ntest_combo = DiscountCombo(name=kwargs.get('name',...
<|body_start_0|> test_group, created = PointGroup.objects.get_or_create(name=kwargs.get('pointGroupName', 'Test points')) pt_group, created = PricingTierGroup.objects.get_or_create(group=test_group, pricingTier=self.defaultPricing, points=kwargs.get('pricingTierGroupPoints', 5)) test_combo = Dis...
BaseDiscountsTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseDiscountsTest: def create_discount(self, **kwargs): """This method just creates the necessary objects to create a simple discount with a single required component.""" <|body_0|> def register_to_check_discount(self, series, expected_amount=None): """This method ma...
stack_v2_sparse_classes_36k_train_011715
20,249
permissive
[ { "docstring": "This method just creates the necessary objects to create a simple discount with a single required component.", "name": "create_discount", "signature": "def create_discount(self, **kwargs)" }, { "docstring": "This method makes it easy to determine whether discounts are working cor...
2
null
Implement the Python class `BaseDiscountsTest` described below. Class description: Implement the BaseDiscountsTest class. Method signatures and docstrings: - def create_discount(self, **kwargs): This method just creates the necessary objects to create a simple discount with a single required component. - def register...
Implement the Python class `BaseDiscountsTest` described below. Class description: Implement the BaseDiscountsTest class. Method signatures and docstrings: - def create_discount(self, **kwargs): This method just creates the necessary objects to create a simple discount with a single required component. - def register...
19db3e83e76ea2002ee841989410d12d1e601023
<|skeleton|> class BaseDiscountsTest: def create_discount(self, **kwargs): """This method just creates the necessary objects to create a simple discount with a single required component.""" <|body_0|> def register_to_check_discount(self, series, expected_amount=None): """This method ma...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseDiscountsTest: def create_discount(self, **kwargs): """This method just creates the necessary objects to create a simple discount with a single required component.""" test_group, created = PointGroup.objects.get_or_create(name=kwargs.get('pointGroupName', 'Test points')) pt_group, ...
the_stack_v2_python_sparse
danceschool/discounts/tests.py
django-danceschool/django-danceschool
train
40
a99f82655c676f4e8b30b2b00a3c005ded995c4f
[ "try:\n sets = oai_provider_set_api.get_all()\n serializer = serializers.OaiProviderSetSerializer(sets, many=True, context={'request': request})\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Exception as exception:\n content = OaiPmhMessage.get_message_labelled(str(exception))\n ...
<|body_start_0|> try: sets = oai_provider_set_api.get_all() serializer = serializers.OaiProviderSetSerializer(sets, many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as exception: content ...
Sets List
SetsList
[ "BSD-3-Clause", "Apache-2.0", "MIT", "NIST-Software" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SetsList: """Sets List""" def get(self, request): """Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error""" <|body_0|> def post(self, request): """Create a OaiProviderS...
stack_v2_sparse_classes_36k_train_011716
7,772
permissive
[ { "docstring": "Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a OaiProviderSet Parameters: { \"set_spec\": \"value...
2
stack_v2_sparse_classes_30k_train_015076
Implement the Python class `SetsList` described below. Class description: Sets List Method signatures and docstrings: - def get(self, request): Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error - def post(self, request): ...
Implement the Python class `SetsList` described below. Class description: Sets List Method signatures and docstrings: - def get(self, request): Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error - def post(self, request): ...
1d2380d99c00c96a7c5ebdf8513b8ad5e8926d9f
<|skeleton|> class SetsList: """Sets List""" def get(self, request): """Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error""" <|body_0|> def post(self, request): """Create a OaiProviderS...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SetsList: """Sets List""" def get(self, request): """Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error""" try: sets = oai_provider_set_api.get_all() serializer = serial...
the_stack_v2_python_sparse
core_oaipmh_provider_app/rest/oai_provider_set/views.py
usnistgov/core_oaipmh_provider_app
train
0
ee26eb86a6a90c6b4badd59216bb48100934e49e
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('medinad', 'medinad')\npolice = repo.medinad.police\nneighborhoods = repo.medinad.neighbor\n\ndef product(R, S):\n return [(t, u) for t in R for u in S]\n\ndef project(R, p):\n return [p(t) for t in...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('medinad', 'medinad') police = repo.medinad.police neighborhoods = repo.medinad.neighbor def product(R, S): return [(t, u) for...
policeneighbors
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class policeneighbors: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everythi...
stack_v2_sparse_classes_36k_train_011717
5,402
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_017064
Implement the Python class `policeneighbors` described below. Class description: Implement the policeneighbors class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=Non...
Implement the Python class `policeneighbors` described below. Class description: Implement the policeneighbors class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=Non...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class policeneighbors: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everythi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class policeneighbors: 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('medinad', 'medinad') police...
the_stack_v2_python_sparse
jtbloom_rfballes_medinad/medinad/policeneighbors.py
ROODAY/course-2017-fal-proj
train
3
67fe38b17dbd876a0b4f42ac6af03fcb3f2144fc
[ "self.status_list.append(status)\nif len(self.status_list) >= 500:\n if not push_to_bigquery(self.status_list):\n print('Failed to send to bigquery', file=sys.stderr)\n return False\n self.num_imported += len(self.status_list)\n self.status_list = []\n print('Imported {0} rows'.format(self...
<|body_start_0|> self.status_list.append(status) if len(self.status_list) >= 500: if not push_to_bigquery(self.status_list): print('Failed to send to bigquery', file=sys.stderr) return False self.num_imported += len(self.status_list) se...
Streaming API로 추출한 트윗을 처리하기 위한 클래스
MyStreamListener
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyStreamListener: """Streaming API로 추출한 트윗을 처리하기 위한 클래스""" def on_status(self, status): """트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체""" <|body_0|> def push_to_bigquery(status_list): """트윗 리스트를 BigQuery에 임포트하는 메서드입니다.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_011718
4,338
no_license
[ { "docstring": "트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체", "name": "on_status", "signature": "def on_status(self, status)" }, { "docstring": "트윗 리스트를 BigQuery에 임포트하는 메서드입니다.", "name": "push_to_bigquery", "signature": "def push_to_bigquery(status_list)" } ]
2
stack_v2_sparse_classes_30k_train_019879
Implement the Python class `MyStreamListener` described below. Class description: Streaming API로 추출한 트윗을 처리하기 위한 클래스 Method signatures and docstrings: - def on_status(self, status): 트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체 - def push_to_bigquery(status_list): 트윗 리스트를 BigQuery에 임포트하는 메서드입니다.
Implement the Python class `MyStreamListener` described below. Class description: Streaming API로 추출한 트윗을 처리하기 위한 클래스 Method signatures and docstrings: - def on_status(self, status): 트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체 - def push_to_bigquery(status_list): 트윗 리스트를 BigQuery에 임포트하는 메서드입니다. <|skeleton|> class...
b64956e1250cc5d867b3d6d62e0b7d9506344993
<|skeleton|> class MyStreamListener: """Streaming API로 추출한 트윗을 처리하기 위한 클래스""" def on_status(self, status): """트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체""" <|body_0|> def push_to_bigquery(status_list): """트윗 리스트를 BigQuery에 임포트하는 메서드입니다.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyStreamListener: """Streaming API로 추출한 트윗을 처리하기 위한 클래스""" def on_status(self, status): """트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체""" self.status_list.append(status) if len(self.status_list) >= 500: if not push_to_bigquery(self.status_list): pri...
the_stack_v2_python_sparse
chapter_5/import_from_stream_api_to_bigquery.py
innerrace/crawl_images.py
train
0
ad29a7a2706ac1cc9c52a7c09ebadcc8163ae510
[ "self.strategy = strategy\nif opponents is None:\n self.opponents = [axl.Random(p) for p in np.linspace(0, 1, number_of_opponents)]\nelse:\n self.opponents = opponents", "if isinstance(self.strategy, axl.Player):\n players = [self.strategy] + self.opponents\nelse:\n players = [self.strategy()] + self....
<|body_start_0|> self.strategy = strategy if opponents is None: self.opponents = [axl.Random(p) for p in np.linspace(0, 1, number_of_opponents)] else: self.opponents = opponents <|end_body_0|> <|body_start_1|> if isinstance(self.strategy, axl.Player): ...
TransitiveFingerprint
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransitiveFingerprint: def __init__(self, strategy, opponents=None, number_of_opponents=50): """Parameters ---------- strategy : class or instance A class that must be descended from axelrod.Player or an instance of axelrod.Player. opponents : list of instances A list that contains a lis...
stack_v2_sparse_classes_36k_train_011719
20,808
permissive
[ { "docstring": "Parameters ---------- strategy : class or instance A class that must be descended from axelrod.Player or an instance of axelrod.Player. opponents : list of instances A list that contains a list of opponents Default: A spectrum of Random players number_of_opponents: int The number of Random oppon...
4
null
Implement the Python class `TransitiveFingerprint` described below. Class description: Implement the TransitiveFingerprint class. Method signatures and docstrings: - def __init__(self, strategy, opponents=None, number_of_opponents=50): Parameters ---------- strategy : class or instance A class that must be descended ...
Implement the Python class `TransitiveFingerprint` described below. Class description: Implement the TransitiveFingerprint class. Method signatures and docstrings: - def __init__(self, strategy, opponents=None, number_of_opponents=50): Parameters ---------- strategy : class or instance A class that must be descended ...
fa748627cd4f0333bb2dbfcb1454372a78a9098a
<|skeleton|> class TransitiveFingerprint: def __init__(self, strategy, opponents=None, number_of_opponents=50): """Parameters ---------- strategy : class or instance A class that must be descended from axelrod.Player or an instance of axelrod.Player. opponents : list of instances A list that contains a lis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransitiveFingerprint: def __init__(self, strategy, opponents=None, number_of_opponents=50): """Parameters ---------- strategy : class or instance A class that must be descended from axelrod.Player or an instance of axelrod.Player. opponents : list of instances A list that contains a list of opponents...
the_stack_v2_python_sparse
axelrod/fingerprint.py
Axelrod-Python/Axelrod
train
673
72fa46a74c5f57bdc4f3f2b89fb2ff302ca1f415
[ "if self._mode == common.FULL_COMMS_MODE:\n if struct_tree.IsValidElement(args[arg_idx]):\n return args[arg_idx].flags.status\n else:\n return None\nelif self._mode == common.SPARSE_COMMS_MODE:\n return self._GetTetherValue(args[0], self._node_labels[arg_idx], 'state')\nelse:\n assert Fals...
<|body_start_0|> if self._mode == common.FULL_COMMS_MODE: if struct_tree.IsValidElement(args[arg_idx]): return args[arg_idx].flags.status else: return None elif self._mode == common.SPARSE_COMMS_MODE: return self._GetTetherValue(args[0]...
Base indicator for servos' armed status.
BaseArmedIndicator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseArmedIndicator: """Base indicator for servos' armed status.""" def _GetSingleValue(self, arg_idx, *args): """Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicat...
stack_v2_sparse_classes_36k_train_011720
17,733
permissive
[ { "docstring": "Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicator. The attributes vary in different modes. For FULL_COMMS_MODE, it is the list of ServoStatus messages for each servo, so ar...
2
stack_v2_sparse_classes_30k_train_016877
Implement the Python class `BaseArmedIndicator` described below. Class description: Base indicator for servos' armed status. Method signatures and docstrings: - def _GetSingleValue(self, arg_idx, *args): Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the...
Implement the Python class `BaseArmedIndicator` described below. Class description: Base indicator for servos' armed status. Method signatures and docstrings: - def _GetSingleValue(self, arg_idx, *args): Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the...
818ae8b7119b200a28af6b3669a3045f30e0dc64
<|skeleton|> class BaseArmedIndicator: """Base indicator for servos' armed status.""" def _GetSingleValue(self, arg_idx, *args): """Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseArmedIndicator: """Base indicator for servos' armed status.""" def _GetSingleValue(self, arg_idx, *args): """Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicator. The attri...
the_stack_v2_python_sparse
gs/monitor2/apps/plugins/indicators/servo.py
ghomsy/makani
train
0
6c445198cfccb2e214c3bb7286632e461508d610
[ "if kwargs.get('instance'):\n kwargs.update(initial={'projects': kwargs['instance'].project_set.all()})\nsuper().__init__(*args, **kwargs)", "super()._save_m2m(*args, **kwargs)\nproject_ids = []\nif hasattr(self.data, 'getlist'):\n project_ids = self.data.getlist('projects')\nelif self.data.get('projects'):...
<|body_start_0|> if kwargs.get('instance'): kwargs.update(initial={'projects': kwargs['instance'].project_set.all()}) super().__init__(*args, **kwargs) <|end_body_0|> <|body_start_1|> super()._save_m2m(*args, **kwargs) project_ids = [] if hasattr(self.data, 'getlist'...
PowerPlantForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PowerPlantForm: def __init__(self, *args, **kwargs): """Display all of the PowerPlant's current projects as initial data.""" <|body_0|> def _save_m2m(self, *args, **kwargs): """Save the PowerPlant's Projects. All of the other uses of Django-Select2 are for Many-To-Ma...
stack_v2_sparse_classes_36k_train_011721
8,772
no_license
[ { "docstring": "Display all of the PowerPlant's current projects as initial data.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Save the PowerPlant's Projects. All of the other uses of Django-Select2 are for Many-To-Many fields, but since the project...
2
stack_v2_sparse_classes_30k_train_007284
Implement the Python class `PowerPlantForm` described below. Class description: Implement the PowerPlantForm class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Display all of the PowerPlant's current projects as initial data. - def _save_m2m(self, *args, **kwargs): Save the PowerPlant's P...
Implement the Python class `PowerPlantForm` described below. Class description: Implement the PowerPlantForm class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Display all of the PowerPlant's current projects as initial data. - def _save_m2m(self, *args, **kwargs): Save the PowerPlant's P...
f45fa2718ac8a0a852449fcb58cbcde20dd7a7ff
<|skeleton|> class PowerPlantForm: def __init__(self, *args, **kwargs): """Display all of the PowerPlant's current projects as initial data.""" <|body_0|> def _save_m2m(self, *args, **kwargs): """Save the PowerPlant's Projects. All of the other uses of Django-Select2 are for Many-To-Ma...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PowerPlantForm: def __init__(self, *args, **kwargs): """Display all of the PowerPlant's current projects as initial data.""" if kwargs.get('instance'): kwargs.update(initial={'projects': kwargs['instance'].project_set.all()}) super().__init__(*args, **kwargs) def _save...
the_stack_v2_python_sparse
infrastructure/forms.py
CSIS-iLab/new-silk-road
train
8
0cd5caff7f97ac51dd972604e7bc931c4ae90233
[ "mergeUnits = {}\nnewMergeUnit = {}\nfor mergeableFile in mergeableFiles:\n newMergeFile = {}\n for key in mergeableFile:\n newMergeFile[key] = mergeableFile[key]\n if newMergeFile['file_run'] not in mergeUnits:\n mergeUnits[newMergeFile['file_run']] = []\n for mergeUnit in mergeUnits[newM...
<|body_start_0|> mergeUnits = {} newMergeUnit = {} for mergeableFile in mergeableFiles: newMergeFile = {} for key in mergeableFile: newMergeFile[key] = mergeableFile[key] if newMergeFile['file_run'] not in mergeUnits: mergeUnits...
_SplitFileBased_ JobSplitting algorithm for creating jobs that run over the results of split processing jobs.
SplitFileBased
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SplitFileBased: """_SplitFileBased_ JobSplitting algorithm for creating jobs that run over the results of split processing jobs.""" def defineMergeUnits(self, mergeableFiles): """_defineMergeUnits_ Split all the mergeable files into merge units. A merge unit is a group of files that ...
stack_v2_sparse_classes_36k_train_011722
6,285
permissive
[ { "docstring": "_defineMergeUnits_ Split all the mergeable files into merge units. A merge unit is a group of files that must be merged together. For example, the files that result from event based splitting jobs need to be merged back together. This method will return a list of merge units. A merge unit is a d...
3
stack_v2_sparse_classes_30k_val_000881
Implement the Python class `SplitFileBased` described below. Class description: _SplitFileBased_ JobSplitting algorithm for creating jobs that run over the results of split processing jobs. Method signatures and docstrings: - def defineMergeUnits(self, mergeableFiles): _defineMergeUnits_ Split all the mergeable files...
Implement the Python class `SplitFileBased` described below. Class description: _SplitFileBased_ JobSplitting algorithm for creating jobs that run over the results of split processing jobs. Method signatures and docstrings: - def defineMergeUnits(self, mergeableFiles): _defineMergeUnits_ Split all the mergeable files...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class SplitFileBased: """_SplitFileBased_ JobSplitting algorithm for creating jobs that run over the results of split processing jobs.""" def defineMergeUnits(self, mergeableFiles): """_defineMergeUnits_ Split all the mergeable files into merge units. A merge unit is a group of files that ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SplitFileBased: """_SplitFileBased_ JobSplitting algorithm for creating jobs that run over the results of split processing jobs.""" def defineMergeUnits(self, mergeableFiles): """_defineMergeUnits_ Split all the mergeable files into merge units. A merge unit is a group of files that must be merge...
the_stack_v2_python_sparse
src/python/WMCore/JobSplitting/SplitFileBased.py
vkuznet/WMCore
train
0
6b43666e1543170ab30c957bb12edfc94a6f68b2
[ "rslt, N = (list(s), len(s))\nleftCnt = rightCnt = 0\nfor i in range(N):\n if rslt[i] == '(':\n leftCnt += 1\n elif rslt[i] == ')':\n rightCnt += 1\n if leftCnt < rightCnt:\n rslt[i] = ''\n rightCnt -= 1\nleftCnt = rightCnt = 0\nfor i in reversed(range(N)):\n if r...
<|body_start_0|> rslt, N = (list(s), len(s)) leftCnt = rightCnt = 0 for i in range(N): if rslt[i] == '(': leftCnt += 1 elif rslt[i] == ')': rightCnt += 1 if leftCnt < rightCnt: rslt[i] = '' ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minRemoveToMakeValid(self, s: str) -> str: """For any prefix in a valid string with parentheses, its left parentheses should be no less than its right parentheses, same as suffix. So we could scan from left to right to remove invalid right parentheses, then scan from right ...
stack_v2_sparse_classes_36k_train_011723
1,915
no_license
[ { "docstring": "For any prefix in a valid string with parentheses, its left parentheses should be no less than its right parentheses, same as suffix. So we could scan from left to right to remove invalid right parentheses, then scan from right to left to remove invalid left parentheses.", "name": "minRemove...
2
stack_v2_sparse_classes_30k_train_007652
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minRemoveToMakeValid(self, s: str) -> str: For any prefix in a valid string with parentheses, its left parentheses should be no less than its right parentheses, same as suffi...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minRemoveToMakeValid(self, s: str) -> str: For any prefix in a valid string with parentheses, its left parentheses should be no less than its right parentheses, same as suffi...
edb870f83f0c4568cce0cacec04ee70cf6b545bf
<|skeleton|> class Solution: def minRemoveToMakeValid(self, s: str) -> str: """For any prefix in a valid string with parentheses, its left parentheses should be no less than its right parentheses, same as suffix. So we could scan from left to right to remove invalid right parentheses, then scan from right ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minRemoveToMakeValid(self, s: str) -> str: """For any prefix in a valid string with parentheses, its left parentheses should be no less than its right parentheses, same as suffix. So we could scan from left to right to remove invalid right parentheses, then scan from right to left to rem...
the_stack_v2_python_sparse
2021/minimum_remove_to_make_valid_parentheses.py
eronekogin/leetcode
train
0
35a639c24caa744c935cb1666eb775426e6ebabe
[ "if not reservation.is_within_allowed_period() and (not (reservation.special or reservation.event)):\n num_days = reservation.FUTURE_LIMIT.days\n return ngettext('Reservations can only be made {num_days} day ahead of time', 'Reservations can only be made {num_days} days ahead of time', num_days).format(num_da...
<|body_start_0|> if not reservation.is_within_allowed_period() and (not (reservation.special or reservation.event)): num_days = reservation.FUTURE_LIMIT.days return ngettext('Reservations can only be made {num_days} day ahead of time', 'Reservations can only be made {num_days} days ahead...
Base abstract class for the reservation create or change view.
ReservationCreateOrUpdateView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReservationCreateOrUpdateView: """Base abstract class for the reservation create or change view.""" def get_error_message(self, form, reservation): """Generates the correct error message for the given form. :param reservation: The reservation to generate an error message for :param f...
stack_v2_sparse_classes_36k_train_011724
16,552
permissive
[ { "docstring": "Generates the correct error message for the given form. :param reservation: The reservation to generate an error message for :param form: The form to generate an error message for :return: The error message", "name": "get_error_message", "signature": "def get_error_message(self, form, re...
5
null
Implement the Python class `ReservationCreateOrUpdateView` described below. Class description: Base abstract class for the reservation create or change view. Method signatures and docstrings: - def get_error_message(self, form, reservation): Generates the correct error message for the given form. :param reservation: ...
Implement the Python class `ReservationCreateOrUpdateView` described below. Class description: Base abstract class for the reservation create or change view. Method signatures and docstrings: - def get_error_message(self, form, reservation): Generates the correct error message for the given form. :param reservation: ...
a90ac79f5756721c9a3864658a87fa62633dbc6c
<|skeleton|> class ReservationCreateOrUpdateView: """Base abstract class for the reservation create or change view.""" def get_error_message(self, form, reservation): """Generates the correct error message for the given form. :param reservation: The reservation to generate an error message for :param f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReservationCreateOrUpdateView: """Base abstract class for the reservation create or change view.""" def get_error_message(self, form, reservation): """Generates the correct error message for the given form. :param reservation: The reservation to generate an error message for :param form: The form...
the_stack_v2_python_sparse
src/make_queue/views/reservation.py
MAKENTNU/web
train
12
8b09716a2aa886b93b7002878d1d8558d790cf45
[ "self.id_nodo = id_nodo\nself.padre = padre\nself.valor = valor\nself.hijos = {}", "if self.id_nodo == id_nodo:\n return self\nfor hijo in self.hijos.values():\n nodo = hijo.obtener_nodo(id_nodo)\n if nodo is not None:\n return nodo\nreturn None", "padre = self.obtener_nodo(id_padre)\nif padre i...
<|body_start_0|> self.id_nodo = id_nodo self.padre = padre self.valor = valor self.hijos = {} <|end_body_0|> <|body_start_1|> if self.id_nodo == id_nodo: return self for hijo in self.hijos.values(): nodo = hijo.obtener_nodo(id_nodo) if...
Esta clase representa un árbol La estructura es recursiva, de manera que cada nodo es la raíz de un sub-árbol. Los nodos hijos pueden ser guardados en una estructura, como lista o diccionario. En este ejemplo, los nodos hijos serán guardados en un diccionario.
Arbol
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Arbol: """Esta clase representa un árbol La estructura es recursiva, de manera que cada nodo es la raíz de un sub-árbol. Los nodos hijos pueden ser guardados en una estructura, como lista o diccionario. En este ejemplo, los nodos hijos serán guardados en un diccionario.""" def __init__(self,...
stack_v2_sparse_classes_36k_train_011725
5,113
no_license
[ { "docstring": "Inicializa la estructura básica del árbol. Tiene un identificador propio, la referencia a su padre, el valor almacenado y una estructura con sus hijos.", "name": "__init__", "signature": "def __init__(self, id_nodo, valor=None, padre=None)" }, { "docstring": "Obtiene el nodo con ...
4
stack_v2_sparse_classes_30k_train_010177
Implement the Python class `Arbol` described below. Class description: Esta clase representa un árbol La estructura es recursiva, de manera que cada nodo es la raíz de un sub-árbol. Los nodos hijos pueden ser guardados en una estructura, como lista o diccionario. En este ejemplo, los nodos hijos serán guardados en un ...
Implement the Python class `Arbol` described below. Class description: Esta clase representa un árbol La estructura es recursiva, de manera que cada nodo es la raíz de un sub-árbol. Los nodos hijos pueden ser guardados en una estructura, como lista o diccionario. En este ejemplo, los nodos hijos serán guardados en un ...
54f55b9da9d0fa3f976466b3bef19e488c45bef8
<|skeleton|> class Arbol: """Esta clase representa un árbol La estructura es recursiva, de manera que cada nodo es la raíz de un sub-árbol. Los nodos hijos pueden ser guardados en una estructura, como lista o diccionario. En este ejemplo, los nodos hijos serán guardados en un diccionario.""" def __init__(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Arbol: """Esta clase representa un árbol La estructura es recursiva, de manera que cada nodo es la raíz de un sub-árbol. Los nodos hijos pueden ser guardados en una estructura, como lista o diccionario. En este ejemplo, los nodos hijos serán guardados en un diccionario.""" def __init__(self, id_nodo, val...
the_stack_v2_python_sparse
Semana 11/arboles.py
TMagini/Apuntes-Progra-Avanzada
train
0
54cbe225c4d9de7369dd4e457804faee0020c705
[ "super().__init__()\nself.queries = queries\nself.query_labels: IntTensor = tf.cast(tf.convert_to_tensor(query_labels), dtype='int32')\nself.targets = targets\nself.target_labels = target_labels\nself.distance = distance\nself.evaluator = MemoryEvaluator()\nself.metrics: List[ClassificationMetric] = [make_classific...
<|body_start_0|> super().__init__() self.queries = queries self.query_labels: IntTensor = tf.cast(tf.convert_to_tensor(query_labels), dtype='int32') self.targets = targets self.target_labels = target_labels self.distance = distance self.evaluator = MemoryEvaluator...
Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive.
EvalCallback
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EvalCallback: """Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive.""" def __init__(self, queries: Tensor, query_labels: Sequence[int], targets: Tensor, target_labels: Sequ...
stack_v2_sparse_classes_36k_train_011726
15,886
permissive
[ { "docstring": "Evaluate model matching quality against a validation dataset at epoch end. Args: queries: Test examples that will be tested against the built index. query_labels: Queries nearest neighbors expected labels. targets: Examples that are indexed. target_labels: Target examples labels. distance: Dista...
2
stack_v2_sparse_classes_30k_train_001229
Implement the Python class `EvalCallback` described below. Class description: Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive. Method signatures and docstrings: - def __init__(self, queries: Tenso...
Implement the Python class `EvalCallback` described below. Class description: Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive. Method signatures and docstrings: - def __init__(self, queries: Tenso...
99642bcd33c3e54dfef01a0f9d82823418c0e918
<|skeleton|> class EvalCallback: """Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive.""" def __init__(self, queries: Tensor, query_labels: Sequence[int], targets: Tensor, target_labels: Sequ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EvalCallback: """Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive.""" def __init__(self, queries: Tensor, query_labels: Sequence[int], targets: Tensor, target_labels: Sequence[int], di...
the_stack_v2_python_sparse
tensorflow_similarity/callbacks.py
aditigarg2810/similarity
train
0
599471fca4ccb4ca24191a09dc5ffa6db27b94f2
[ "if self._validate:\n if len(data.shape) <= 1:\n raise DataProcessorError('The data should be an array with at least two dimensions.')\nreturn data", "all_counts = []\nfor datum in data:\n counts = {}\n for bit_string in set(datum):\n counts[bit_string] = sum(datum == bit_string)\n all_c...
<|body_start_0|> if self._validate: if len(data.shape) <= 1: raise DataProcessorError('The data should be an array with at least two dimensions.') return data <|end_body_0|> <|body_start_1|> all_counts = [] for datum in data: counts = {} ...
A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array.
MemoryToCounts
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MemoryToCounts: """A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array.""" def _format_d...
stack_v2_sparse_classes_36k_train_011727
42,185
permissive
[ { "docstring": "Validate the input data.", "name": "_format_data", "signature": "def _format_data(self, data: np.ndarray) -> np.ndarray" }, { "docstring": "Args: data: The classified data to format into a counts dictionary. The first dimension is assumed to correspond to the different circuit ex...
2
stack_v2_sparse_classes_30k_train_004052
Implement the Python class `MemoryToCounts` described below. Class description: A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped ...
Implement the Python class `MemoryToCounts` described below. Class description: A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped ...
a387675a3fe817cef05b968bbf3e05799a09aaae
<|skeleton|> class MemoryToCounts: """A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array.""" def _format_d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MemoryToCounts: """A data action that takes discriminated data and transforms it into a counts dict. This node is intended to be used after the :class:`.DiscriminatorNode` node. It will convert the classified memory into a list of count dictionaries wrapped in a numpy array.""" def _format_data(self, dat...
the_stack_v2_python_sparse
qiskit_experiments/data_processing/nodes.py
oliverdial/qiskit-experiments
train
0
c0b879709e1cc761c4a4db22824405de09a147cf
[ "self.k = k\nself.nums = nums\nself.nums.append(float('-inf'))\nheapq.heapify(self.nums)\nwhile len(self.nums) > self.k:\n heapq.heappop(self.nums)", "if val > self.nums[0]:\n heapq.heappushpop(self.nums, val)\nreturn self.nums[0]" ]
<|body_start_0|> self.k = k self.nums = nums self.nums.append(float('-inf')) heapq.heapify(self.nums) while len(self.nums) > self.k: heapq.heappop(self.nums) <|end_body_0|> <|body_start_1|> if val > self.nums[0]: heapq.heappushpop(self.nums, val) ...
KthLargest5
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KthLargest5: def __init__(self, k: int, nums: List[int]): """Time complexity: O(N), where N is the number of elements in nums""" <|body_0|> def add(self, val: int) -> int: """Time complexity: O(logN), where N is the number of elements in nums""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_011728
6,443
no_license
[ { "docstring": "Time complexity: O(N), where N is the number of elements in nums", "name": "__init__", "signature": "def __init__(self, k: int, nums: List[int])" }, { "docstring": "Time complexity: O(logN), where N is the number of elements in nums", "name": "add", "signature": "def add(...
2
stack_v2_sparse_classes_30k_train_014372
Implement the Python class `KthLargest5` described below. Class description: Implement the KthLargest5 class. Method signatures and docstrings: - def __init__(self, k: int, nums: List[int]): Time complexity: O(N), where N is the number of elements in nums - def add(self, val: int) -> int: Time complexity: O(logN), wh...
Implement the Python class `KthLargest5` described below. Class description: Implement the KthLargest5 class. Method signatures and docstrings: - def __init__(self, k: int, nums: List[int]): Time complexity: O(N), where N is the number of elements in nums - def add(self, val: int) -> int: Time complexity: O(logN), wh...
642e6dd2c3cd65704c90d6e06a392bdae2ddd644
<|skeleton|> class KthLargest5: def __init__(self, k: int, nums: List[int]): """Time complexity: O(N), where N is the number of elements in nums""" <|body_0|> def add(self, val: int) -> int: """Time complexity: O(logN), where N is the number of elements in nums""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KthLargest5: def __init__(self, k: int, nums: List[int]): """Time complexity: O(N), where N is the number of elements in nums""" self.k = k self.nums = nums self.nums.append(float('-inf')) heapq.heapify(self.nums) while len(self.nums) > self.k: heapq...
the_stack_v2_python_sparse
LeetCode/703.Kth_Largest_Element_in_a_Stream.py
viiicky/Problem-Solving
train
0
149f757735d08168938bf3b0e641c18f292eb12c
[ "index = 'test_index'\nsketch_id = 1\nsessionizer = SSHSessionizerSketchPlugin(index, sketch_id)\nself.assertIsInstance(sessionizer, SSHSessionizerSketchPlugin)\nself.assertEqual(index, sessionizer.index_name)\nself.assertEqual(sketch_id, sessionizer.sketch.id)", "index = 'test_index'\nsketch_id = 1\nsessionizer ...
<|body_start_0|> index = 'test_index' sketch_id = 1 sessionizer = SSHSessionizerSketchPlugin(index, sketch_id) self.assertIsInstance(sessionizer, SSHSessionizerSketchPlugin) self.assertEqual(index, sessionizer.index_name) self.assertEqual(sketch_id, sessionizer.sketch.id)...
Tests the functionality of the ssh sessionizing sketch analyzer.
TestSSHSessionizerPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSSHSessionizerPlugin: """Tests the functionality of the ssh sessionizing sketch analyzer.""" def test_sessionizer(self): """Test basic ssh sessionizer functionality.""" <|body_0|> def test_session_starts_with_connection_event(self): """Test a session is creat...
stack_v2_sparse_classes_36k_train_011729
5,646
permissive
[ { "docstring": "Test basic ssh sessionizer functionality.", "name": "test_sessionizer", "signature": "def test_sessionizer(self)" }, { "docstring": "Test a session is created if it starts with SSH connection event.", "name": "test_session_starts_with_connection_event", "signature": "def ...
5
null
Implement the Python class `TestSSHSessionizerPlugin` described below. Class description: Tests the functionality of the ssh sessionizing sketch analyzer. Method signatures and docstrings: - def test_sessionizer(self): Test basic ssh sessionizer functionality. - def test_session_starts_with_connection_event(self): Te...
Implement the Python class `TestSSHSessionizerPlugin` described below. Class description: Tests the functionality of the ssh sessionizing sketch analyzer. Method signatures and docstrings: - def test_sessionizer(self): Test basic ssh sessionizer functionality. - def test_session_starts_with_connection_event(self): Te...
24f471b58ca4a87cb053961b5f05c07a544ca7b8
<|skeleton|> class TestSSHSessionizerPlugin: """Tests the functionality of the ssh sessionizing sketch analyzer.""" def test_sessionizer(self): """Test basic ssh sessionizer functionality.""" <|body_0|> def test_session_starts_with_connection_event(self): """Test a session is creat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSSHSessionizerPlugin: """Tests the functionality of the ssh sessionizing sketch analyzer.""" def test_sessionizer(self): """Test basic ssh sessionizer functionality.""" index = 'test_index' sketch_id = 1 sessionizer = SSHSessionizerSketchPlugin(index, sketch_id) ...
the_stack_v2_python_sparse
timesketch/lib/analyzers/ssh_sessionizer_test.py
google/timesketch
train
2,263
7b6bfea4bdd1d379164831142d04323c47aaf368
[ "l, r = (0, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n if nums[m] == target:\n return m\n if nums[m] < nums[r]:\n if nums[m] < target <= nums[r]:\n l = m + 1\n else:\n r = m - 1\n elif nums[l] <= target < nums[m]:\n r = m - 1\n else:\n ...
<|body_start_0|> l, r = (0, len(nums) - 1) while l <= r: m = (l + r) // 2 if nums[m] == target: return m if nums[m] < nums[r]: if nums[m] < target <= nums[r]: l = m + 1 else: r = m...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def search1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> l,...
stack_v2_sparse_classes_36k_train_011730
1,611
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "search1", "signature": "def search1(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "search", "signature": "def search(self, nums, target)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int <|skel...
763674fcbe271af3d21eed790c3968c4d33f7b09
<|skeleton|> class Solution: def search1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def search1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" l, r = (0, len(nums) - 1) while l <= r: m = (l + r) // 2 if nums[m] == target: return m if nums[m] < nums[r]: if nums...
the_stack_v2_python_sparse
33_search_in_rotated_sorted_array/33.py
guzhoudiaoke/leetcode_python3
train
0
daa07370bf88942b278ef091bf5ac645fcd3f1f5
[ "self.rb = rest_base\nself.members = []\nself.config = {'@odata.type': '#EventDestinationCollection.EventDestinationCollection', 'Name': 'Event Subscription Collection', 'Members': {}, 'Members@odata.count': 0}", "c = self.config.copy()\nc['Members@odata.count'] = len(self.members)\nc['Members'] = self.members\nr...
<|body_start_0|> self.rb = rest_base self.members = [] self.config = {'@odata.type': '#EventDestinationCollection.EventDestinationCollection', 'Name': 'Event Subscription Collection', 'Members': {}, 'Members@odata.count': 0} <|end_body_0|> <|body_start_1|> c = self.config.copy() ...
Event Subscriptions
Subscriptions
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subscriptions: """Event Subscriptions""" def __init__(self, rest_base): """Subscription collection constructor Arguments: rest_base - Base URL of the RESTful interface""" <|body_0|> def configuration(self): """Configuration property.""" <|body_1|> de...
stack_v2_sparse_classes_36k_train_011731
4,372
permissive
[ { "docstring": "Subscription collection constructor Arguments: rest_base - Base URL of the RESTful interface", "name": "__init__", "signature": "def __init__(self, rest_base)" }, { "docstring": "Configuration property.", "name": "configuration", "signature": "def configuration(self)" }...
3
null
Implement the Python class `Subscriptions` described below. Class description: Event Subscriptions Method signatures and docstrings: - def __init__(self, rest_base): Subscription collection constructor Arguments: rest_base - Base URL of the RESTful interface - def configuration(self): Configuration property. - def ad...
Implement the Python class `Subscriptions` described below. Class description: Event Subscriptions Method signatures and docstrings: - def __init__(self, rest_base): Subscription collection constructor Arguments: rest_base - Base URL of the RESTful interface - def configuration(self): Configuration property. - def ad...
32777c66a8410d767eae15baabf71c61a0bef13c
<|skeleton|> class Subscriptions: """Event Subscriptions""" def __init__(self, rest_base): """Subscription collection constructor Arguments: rest_base - Base URL of the RESTful interface""" <|body_0|> def configuration(self): """Configuration property.""" <|body_1|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Subscriptions: """Event Subscriptions""" def __init__(self, rest_base): """Subscription collection constructor Arguments: rest_base - Base URL of the RESTful interface""" self.rb = rest_base self.members = [] self.config = {'@odata.type': '#EventDestinationCollection.Event...
the_stack_v2_python_sparse
tools/Redfish-Interface-Emulator/api_emulator/redfish/event_service.py
facebook/openbmc
train
684
2dc8c67cdcbc8d5d2fe3ade3f4be0148ed938049
[ "total_val = sharadar.Institutions.slice(period_offset=0).TOTALVALUE\nfund_val = sharadar.Institutions.slice(period_offset=0).FNDVALUE\nzipline_sids_to_real_sids = {1: 'FI12345', 2: 'FI23456'}\nloader = SharadarInstitutionsPipelineLoader(zipline_sids_to_real_sids)\ndomain = total_val.domain\ncolumns = [total_val, f...
<|body_start_0|> total_val = sharadar.Institutions.slice(period_offset=0).TOTALVALUE fund_val = sharadar.Institutions.slice(period_offset=0).FNDVALUE zipline_sids_to_real_sids = {1: 'FI12345', 2: 'FI23456'} loader = SharadarInstitutionsPipelineLoader(zipline_sids_to_real_sids) do...
SharadarInstitutionsLoaderTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharadarInstitutionsLoaderTestCase: def test_institutions_data(self): """Tests loading data from get_sharadar_institutions_reindexed_like.""" <|body_0|> def test_no_data(self): """Tests handling when get_sharadar_institutions_reindexed_like returns no data.""" ...
stack_v2_sparse_classes_36k_train_011732
12,404
permissive
[ { "docstring": "Tests loading data from get_sharadar_institutions_reindexed_like.", "name": "test_institutions_data", "signature": "def test_institutions_data(self)" }, { "docstring": "Tests handling when get_sharadar_institutions_reindexed_like returns no data.", "name": "test_no_data", ...
2
stack_v2_sparse_classes_30k_train_015302
Implement the Python class `SharadarInstitutionsLoaderTestCase` described below. Class description: Implement the SharadarInstitutionsLoaderTestCase class. Method signatures and docstrings: - def test_institutions_data(self): Tests loading data from get_sharadar_institutions_reindexed_like. - def test_no_data(self): ...
Implement the Python class `SharadarInstitutionsLoaderTestCase` described below. Class description: Implement the SharadarInstitutionsLoaderTestCase class. Method signatures and docstrings: - def test_institutions_data(self): Tests loading data from get_sharadar_institutions_reindexed_like. - def test_no_data(self): ...
d08d1a9a343232e37d9e5767cae64af799067b45
<|skeleton|> class SharadarInstitutionsLoaderTestCase: def test_institutions_data(self): """Tests loading data from get_sharadar_institutions_reindexed_like.""" <|body_0|> def test_no_data(self): """Tests handling when get_sharadar_institutions_reindexed_like returns no data.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SharadarInstitutionsLoaderTestCase: def test_institutions_data(self): """Tests loading data from get_sharadar_institutions_reindexed_like.""" total_val = sharadar.Institutions.slice(period_offset=0).TOTALVALUE fund_val = sharadar.Institutions.slice(period_offset=0).FNDVALUE zip...
the_stack_v2_python_sparse
zipline/_tests/pipeline/test_sharadar_loader.py
quantrocket-llc/zipline
train
17
4a0521e733d7580ef3eba6519f3e26a369b68637
[ "super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.kernel_size = kernel_size\nself._conv = conv\nshape = (kernel_size, in_channels, out_channels)\nself.weight = torch.nn.Parameter(torch.Tensor(*shape))\nif bias:\n self.bias = torch.nn.Parameter(torch.Tensor(out_channels))...
<|body_start_0|> super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self._conv = conv shape = (kernel_size, in_channels, out_channels) self.weight = torch.nn.Parameter(torch.Tensor(*shape)) if ...
Graph convolutional layer.
ChebConv
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChebConv: """Graph convolutional layer.""" def __init__(self, in_channels, out_channels, kernel_size, bias=True, conv=cheb_conv): """Initialize the Chebyshev layer. Args: in_channels (int): Number of channels/features in the input graph. out_channels (int): Number of channels/feature...
stack_v2_sparse_classes_36k_train_011733
41,403
no_license
[ { "docstring": "Initialize the Chebyshev layer. Args: in_channels (int): Number of channels/features in the input graph. out_channels (int): Number of channels/features in the output graph. kernel_size (int): Number of trainable parameters per filter, which is also the size of the convolutional kernel. The orde...
3
stack_v2_sparse_classes_30k_train_010400
Implement the Python class `ChebConv` described below. Class description: Graph convolutional layer. Method signatures and docstrings: - def __init__(self, in_channels, out_channels, kernel_size, bias=True, conv=cheb_conv): Initialize the Chebyshev layer. Args: in_channels (int): Number of channels/features in the in...
Implement the Python class `ChebConv` described below. Class description: Graph convolutional layer. Method signatures and docstrings: - def __init__(self, in_channels, out_channels, kernel_size, bias=True, conv=cheb_conv): Initialize the Chebyshev layer. Args: in_channels (int): Number of channels/features in the in...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class ChebConv: """Graph convolutional layer.""" def __init__(self, in_channels, out_channels, kernel_size, bias=True, conv=cheb_conv): """Initialize the Chebyshev layer. Args: in_channels (int): Number of channels/features in the input graph. out_channels (int): Number of channels/feature...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChebConv: """Graph convolutional layer.""" def __init__(self, in_channels, out_channels, kernel_size, bias=True, conv=cheb_conv): """Initialize the Chebyshev layer. Args: in_channels (int): Number of channels/features in the input graph. out_channels (int): Number of channels/features in the outp...
the_stack_v2_python_sparse
generated/test_deepsphere_deepsphere_pytorch.py
jansel/pytorch-jit-paritybench
train
35
c2de35438ed0776f6aed9eb719a59bd0f7be6eaa
[ "self._async_abort_entries_match({CONF_HOST: data[CONF_HOST]})\ncamera = AqaraCamera(self.hass, data[CONF_HOST], data[CONF_MODEL], data[CONF_STREAM], verbose=False)\nret = await self.hass.async_add_executor_job(camera.connect)\nif not ret:\n raise CannotConnect\nconfig = {CONF_RTSP_AUTH: data.get(CONF_RTSP_AUTH,...
<|body_start_0|> self._async_abort_entries_match({CONF_HOST: data[CONF_HOST]}) camera = AqaraCamera(self.hass, data[CONF_HOST], data[CONF_MODEL], data[CONF_STREAM], verbose=False) ret = await self.hass.async_add_executor_job(camera.connect) if not ret: raise CannotConnect ...
Handle a config flow for Aqara Camera.
ConfigFlow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigFlow: """Handle a config flow for Aqara Camera.""" async def _validate_and_create(self, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.""" <|body_0|> async def async_step_user(self, user_i...
stack_v2_sparse_classes_36k_train_011734
3,371
no_license
[ { "docstring": "Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.", "name": "_validate_and_create", "signature": "async def _validate_and_create(self, data)" }, { "docstring": "Handle the initial step.", "name": "async_step_use...
2
stack_v2_sparse_classes_30k_train_014287
Implement the Python class `ConfigFlow` described below. Class description: Handle a config flow for Aqara Camera. Method signatures and docstrings: - async def _validate_and_create(self, data): Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. - async ...
Implement the Python class `ConfigFlow` described below. Class description: Handle a config flow for Aqara Camera. Method signatures and docstrings: - async def _validate_and_create(self, data): Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. - async ...
3988d204908478996fffa433faffa9ea20f42562
<|skeleton|> class ConfigFlow: """Handle a config flow for Aqara Camera.""" async def _validate_and_create(self, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.""" <|body_0|> async def async_step_user(self, user_i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigFlow: """Handle a config flow for Aqara Camera.""" async def _validate_and_create(self, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.""" self._async_abort_entries_match({CONF_HOST: data[CONF_HOST]}) ...
the_stack_v2_python_sparse
certificates/custom_components/aqara_camera/config_flow.py
hellad/hass-config
train
3
4375e2a1aeae290587b1884e656cf83b8cb82a82
[ "if not root:\n return 0\nreturn 1 + self.countNodes(root.left) + self.countNodes(root.right)", "if not root:\n return 0\nh = 0\nwhile root.left:\n h += 1\n root = root.left\nreturn 2 ** h - 1" ]
<|body_start_0|> if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right) <|end_body_0|> <|body_start_1|> if not root: return 0 h = 0 while root.left: h += 1 root = root.left return 2 ** h -...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countNodes(self, root) -> int: """完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。""" <|body_0|> def countFullNodes(self, root): """满二叉树,既每层都是满的二叉树 他的节点个数为 2^h -1 个 (h为层数)""" <|body_1|> <|end_skeleton|>...
stack_v2_sparse_classes_36k_train_011735
1,095
no_license
[ { "docstring": "完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。", "name": "countNodes", "signature": "def countNodes(self, root) -> int" }, { "docstring": "满二叉树,既每层都是满的二叉树 他的节点个数为 2^h -1 个 (h为层数)", "name": "countFullNodes", "signature": "def cou...
2
stack_v2_sparse_classes_30k_train_013202
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countNodes(self, root) -> int: 完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。 - def countFullNodes(self, root): 满二叉树,既每层都是满的二叉树 他的...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countNodes(self, root) -> int: 完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。 - def countFullNodes(self, root): 满二叉树,既每层都是满的二叉树 他的...
e0ad5e52829345dd2ce4bc578295336ca07b2662
<|skeleton|> class Solution: def countNodes(self, root) -> int: """完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。""" <|body_0|> def countFullNodes(self, root): """满二叉树,既每层都是满的二叉树 他的节点个数为 2^h -1 个 (h为层数)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countNodes(self, root) -> int: """完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。""" if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right) def countFullNodes(self, root): ...
the_stack_v2_python_sparse
labuladong/二叉树/222.完全二叉树的节点个数.py
Ehco1996/leetcode
train
7
1c9727f69402cfea8802be139db3ce7c04eabc10
[ "widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\nrequire_object_modify_permission(widget.dashboard, self.current_user)\nwidget_properties = request.get_json(force=True)\nwidget.text = widget_properties['text']\nwidget.options = json_dumps(widget_properties['options'])\nmodels.db.session.commi...
<|body_start_0|> widget = models.Widget.get_by_id_and_org(widget_id, self.current_org) require_object_modify_permission(widget.dashboard, self.current_user) widget_properties = request.get_json(force=True) widget.text = widget_properties['text'] widget.options = json_dumps(widget...
WidgetResource
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WidgetResource: def post(self, widget_id): """Updates a widget in a dashboard. This method currently handles Text Box widgets only. :param number widget_id: The ID of the widget to modify :<json string text: The new contents of the text box""" <|body_0|> def delete(self, wid...
stack_v2_sparse_classes_36k_train_011736
3,086
permissive
[ { "docstring": "Updates a widget in a dashboard. This method currently handles Text Box widgets only. :param number widget_id: The ID of the widget to modify :<json string text: The new contents of the text box", "name": "post", "signature": "def post(self, widget_id)" }, { "docstring": "Remove ...
2
stack_v2_sparse_classes_30k_train_009535
Implement the Python class `WidgetResource` described below. Class description: Implement the WidgetResource class. Method signatures and docstrings: - def post(self, widget_id): Updates a widget in a dashboard. This method currently handles Text Box widgets only. :param number widget_id: The ID of the widget to modi...
Implement the Python class `WidgetResource` described below. Class description: Implement the WidgetResource class. Method signatures and docstrings: - def post(self, widget_id): Updates a widget in a dashboard. This method currently handles Text Box widgets only. :param number widget_id: The ID of the widget to modi...
7b722a1067397a3ecb408b2c5df07d75250fb66a
<|skeleton|> class WidgetResource: def post(self, widget_id): """Updates a widget in a dashboard. This method currently handles Text Box widgets only. :param number widget_id: The ID of the widget to modify :<json string text: The new contents of the text box""" <|body_0|> def delete(self, wid...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WidgetResource: def post(self, widget_id): """Updates a widget in a dashboard. This method currently handles Text Box widgets only. :param number widget_id: The ID of the widget to modify :<json string text: The new contents of the text box""" widget = models.Widget.get_by_id_and_org(widget_id...
the_stack_v2_python_sparse
redash/handlers/widgets.py
getredash/redash
train
23,871
5c01fa12c58b23c8d7e33d8ac3440debb60e726c
[ "if len(strs) == 0:\n return unichr(258)\nreturn unichr(257).join((singleStr.encode('utf-8') for singleStr in strs))", "if s == unichr(258):\n return []\nreturn s.split(unichr(257))" ]
<|body_start_0|> if len(strs) == 0: return unichr(258) return unichr(257).join((singleStr.encode('utf-8') for singleStr in strs)) <|end_body_0|> <|body_start_1|> if s == unichr(258): return [] return s.split(unichr(257)) <|end_body_1|>
Codec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" <|body_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_011737
1,322
permissive
[ { "docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str", "name": "encode", "signature": "def encode(self, strs)" }, { "docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]", "name": "decode", "signature": "def ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str - def decode(self, s): Decodes a single string to a list of strings. :type s: st...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str - def decode(self, s): Decodes a single string to a list of strings. :type s: st...
20ae1a048eddbc9a32c819cf61258e2b57572f05
<|skeleton|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" <|body_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" if len(strs) == 0: return unichr(258) return unichr(257).join((singleStr.encode('utf-8') for singleStr in strs)) def decode(self, s): """Decodes...
the_stack_v2_python_sparse
leetcode.com/python/271_Encode_and_Decode_Strings.py
partho-maple/coding-interview-gym
train
862
658780d9ebb1c977ef19f7674ef2154869365f46
[ "anon = User.anonymous()\nif not g.security.has_access(artifact, 'read', user=anon):\n return\nif not g.security.has_access(c.project, 'read', user=anon):\n return\nif title is None:\n title = '%s modified by %s' % (artifact.title_s, c.user.get_pref('display_name'))\nif description is None:\n descriptio...
<|body_start_0|> anon = User.anonymous() if not g.security.has_access(artifact, 'read', user=anon): return if not g.security.has_access(c.project, 'read', user=anon): return if title is None: title = '%s modified by %s' % (artifact.title_s, c.user.get_...
Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection
Feed
[ "LicenseRef-scancode-other-permissive" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Feed: """Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection""" def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None): """Create a Feed item and returns the item. If anon doesn...
stack_v2_sparse_classes_36k_train_011738
39,694
permissive
[ { "docstring": "Create a Feed item and returns the item. If anon doesn't have read access, create does not happen and None is returned", "name": "post", "signature": "def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None)" }, { "docstring": "Produc...
2
null
Implement the Python class `Feed` described below. Class description: Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection Method signatures and docstrings: - def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None...
Implement the Python class `Feed` described below. Class description: Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection Method signatures and docstrings: - def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None...
a5ed73858f64b2d2296c55d174b4af79f8f81d41
<|skeleton|> class Feed: """Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection""" def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None): """Create a Feed item and returns the item. If anon doesn...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Feed: """Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection""" def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None): """Create a Feed item and returns the item. If anon doesn't have read ...
the_stack_v2_python_sparse
vulcanforge/artifact/model.py
vulcan-collaboration/vulcanforge
train
2
ca317eabfa3f0a5b00ceff03b256a9eab98cde77
[ "super(Decoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for __ in range(self.N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)"...
<|body_start_0|> super(Decoder, self).__init__() self.N = N self.dm = dm self.embedding = tf.keras.layers.Embedding(input_vocab, dm) self.positional_encoding = positional_encoding(max_seq_len, dm) self.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for __ in range(self....
Decoder for a transformer
Decoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decoder: """Decoder for a transformer""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Class constructor""" <|body_0|> def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): """Public instance method""" ...
stack_v2_sparse_classes_36k_train_011739
1,600
no_license
[ { "docstring": "Class constructor", "name": "__init__", "signature": "def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1)" }, { "docstring": "Public instance method", "name": "call", "signature": "def call(self, x, encoder_output, training, look_ahead_mask, padd...
2
null
Implement the Python class `Decoder` described below. Class description: Decoder for a transformer Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor - def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): Public i...
Implement the Python class `Decoder` described below. Class description: Decoder for a transformer Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor - def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): Public i...
c23deee331a71a089197547fcae4c1eefb8d24ef
<|skeleton|> class Decoder: """Decoder for a transformer""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Class constructor""" <|body_0|> def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): """Public instance method""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Decoder: """Decoder for a transformer""" def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): """Class constructor""" super(Decoder, self).__init__() self.N = N self.dm = dm self.embedding = tf.keras.layers.Embedding(input_vocab, dm) ...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/10-transformer_decoder.py
YosriGFX/holbertonschool-machine_learning
train
0
53b4a1cbbf1dd4744a57e15fb25741cbbf2c088d
[ "future_question = create_question('Question_1', 5)\nresponse = self.client.get(reverse('polls:detail', kwargs={'pk': future_question.id}))\nself.assertEqual(response.status_code, 404)", "past_question = create_question('Question_1', -5)\nresponse = self.client.get(reverse('polls:detail', kwargs={'pk': past_quest...
<|body_start_0|> future_question = create_question('Question_1', 5) response = self.client.get(reverse('polls:detail', kwargs={'pk': future_question.id})) self.assertEqual(response.status_code, 404) <|end_body_0|> <|body_start_1|> past_question = create_question('Question_1', -5) ...
QuestionDetailViewTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuestionDetailViewTests: def test_detail_view_with_future_questions(self): """A question in the future should not be visible on this view.""" <|body_0|> def test_detail_view_with_past_questions(self): """A question in the future should not be visible on this view."""...
stack_v2_sparse_classes_36k_train_011740
4,246
no_license
[ { "docstring": "A question in the future should not be visible on this view.", "name": "test_detail_view_with_future_questions", "signature": "def test_detail_view_with_future_questions(self)" }, { "docstring": "A question in the future should not be visible on this view.", "name": "test_det...
2
null
Implement the Python class `QuestionDetailViewTests` described below. Class description: Implement the QuestionDetailViewTests class. Method signatures and docstrings: - def test_detail_view_with_future_questions(self): A question in the future should not be visible on this view. - def test_detail_view_with_past_ques...
Implement the Python class `QuestionDetailViewTests` described below. Class description: Implement the QuestionDetailViewTests class. Method signatures and docstrings: - def test_detail_view_with_future_questions(self): A question in the future should not be visible on this view. - def test_detail_view_with_past_ques...
acbb6d21a8182feabcb3329e17c76ac3af375255
<|skeleton|> class QuestionDetailViewTests: def test_detail_view_with_future_questions(self): """A question in the future should not be visible on this view.""" <|body_0|> def test_detail_view_with_past_questions(self): """A question in the future should not be visible on this view."""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuestionDetailViewTests: def test_detail_view_with_future_questions(self): """A question in the future should not be visible on this view.""" future_question = create_question('Question_1', 5) response = self.client.get(reverse('polls:detail', kwargs={'pk': future_question.id})) ...
the_stack_v2_python_sparse
pythonTutorial/django/mysite/polls/tests.py
rajatgirotra/study
train
6
25c392f2dc096cd7ccdd8c8c7bfcdc3cb0003738
[ "self.log_file = log_file_path\nself.logger = logging.getLogger('DP')\nself._init_logging('DataPipeline Automation Framework')", "self.logger.setLevel(logging.INFO)\nformatter_fh = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')\nformatter_ch = logging.Formatter('[%(asctime)s] [%(levelname)s] %(mes...
<|body_start_0|> self.log_file = log_file_path self.logger = logging.getLogger('DP') self._init_logging('DataPipeline Automation Framework') <|end_body_0|> <|body_start_1|> self.logger.setLevel(logging.INFO) formatter_fh = logging.Formatter('[%(asctime)s] [%(levelname)s] %(messa...
请勿在其他类中生成该Logger对象,该Logger用作框架全局系统生产日志 所有脚本中需要记录的日志,请使用print() 框架执行过程中将会把控制台输出信息重定向到报告以及脚本日志文件中
DPLogger
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DPLogger: """请勿在其他类中生成该Logger对象,该Logger用作框架全局系统生产日志 所有脚本中需要记录的日志,请使用print() 框架执行过程中将会把控制台输出信息重定向到报告以及脚本日志文件中""" def __init__(self, log_file_path): """用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型""" <|body_0|> def _init_logging(self, welcome_str): """用于初始化自动化框架系统级别Log...
stack_v2_sparse_classes_36k_train_011741
15,306
no_license
[ { "docstring": "用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型", "name": "__init__", "signature": "def __init__(self, log_file_path)" }, { "docstring": "用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型 :param welcome_str: welcome_str", "name": "_init_logging", "signature": "def _init_logging(self, wel...
2
stack_v2_sparse_classes_30k_train_018595
Implement the Python class `DPLogger` described below. Class description: 请勿在其他类中生成该Logger对象,该Logger用作框架全局系统生产日志 所有脚本中需要记录的日志,请使用print() 框架执行过程中将会把控制台输出信息重定向到报告以及脚本日志文件中 Method signatures and docstrings: - def __init__(self, log_file_path): 用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型 - def _init_logging(self, welcome_st...
Implement the Python class `DPLogger` described below. Class description: 请勿在其他类中生成该Logger对象,该Logger用作框架全局系统生产日志 所有脚本中需要记录的日志,请使用print() 框架执行过程中将会把控制台输出信息重定向到报告以及脚本日志文件中 Method signatures and docstrings: - def __init__(self, log_file_path): 用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型 - def _init_logging(self, welcome_st...
e4798a1fb58a8dd72922fa653e6c801a8924c0ff
<|skeleton|> class DPLogger: """请勿在其他类中生成该Logger对象,该Logger用作框架全局系统生产日志 所有脚本中需要记录的日志,请使用print() 框架执行过程中将会把控制台输出信息重定向到报告以及脚本日志文件中""" def __init__(self, log_file_path): """用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型""" <|body_0|> def _init_logging(self, welcome_str): """用于初始化自动化框架系统级别Log...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DPLogger: """请勿在其他类中生成该Logger对象,该Logger用作框架全局系统生产日志 所有脚本中需要记录的日志,请使用print() 框架执行过程中将会把控制台输出信息重定向到报告以及脚本日志文件中""" def __init__(self, log_file_path): """用于初始化自动化框架系统级别Logging,请勿手动调用该函数或尝试初始化该类型""" self.log_file = log_file_path self.logger = logging.getLogger('DP') self._init_...
the_stack_v2_python_sparse
runner.py
qinzhen-DPL/DP-AUTO
train
0
0cc20dd7b864b1e8334fdce375f180eed04e4207
[ "extra_vars = dict(EasyBlock.extra_options(extra_vars))\nextra_vars.update({'configure_cmd_prefix': ['', 'Prefix to be glued before ./configure', CUSTOM], 'prefix_opt': ['--prefix=', 'Prefix command line option for configure script', CUSTOM], 'tar_config_opts': [False, 'Override tar settings as determined by config...
<|body_start_0|> extra_vars = dict(EasyBlock.extra_options(extra_vars)) extra_vars.update({'configure_cmd_prefix': ['', 'Prefix to be glued before ./configure', CUSTOM], 'prefix_opt': ['--prefix=', 'Prefix command line option for configure script', CUSTOM], 'tar_config_opts': [False, 'Override tar setti...
Support for building and installing applications with configure/make/make install
ConfigureMake
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigureMake: """Support for building and installing applications with configure/make/make install""" def extra_options(extra_vars=None): """Extra easyconfig parameters specific to ConfigureMake.""" <|body_0|> def configure_step(self, cmd_prefix=''): """Configur...
stack_v2_sparse_classes_36k_train_011742
4,867
no_license
[ { "docstring": "Extra easyconfig parameters specific to ConfigureMake.", "name": "extra_options", "signature": "def extra_options(extra_vars=None)" }, { "docstring": "Configure step - typically ./configure --prefix=/install/path style", "name": "configure_step", "signature": "def configu...
5
null
Implement the Python class `ConfigureMake` described below. Class description: Support for building and installing applications with configure/make/make install Method signatures and docstrings: - def extra_options(extra_vars=None): Extra easyconfig parameters specific to ConfigureMake. - def configure_step(self, cmd...
Implement the Python class `ConfigureMake` described below. Class description: Support for building and installing applications with configure/make/make install Method signatures and docstrings: - def extra_options(extra_vars=None): Extra easyconfig parameters specific to ConfigureMake. - def configure_step(self, cmd...
3c5434f9a4193fbe4cf8107327faadda83d798ae
<|skeleton|> class ConfigureMake: """Support for building and installing applications with configure/make/make install""" def extra_options(extra_vars=None): """Extra easyconfig parameters specific to ConfigureMake.""" <|body_0|> def configure_step(self, cmd_prefix=''): """Configur...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigureMake: """Support for building and installing applications with configure/make/make install""" def extra_options(extra_vars=None): """Extra easyconfig parameters specific to ConfigureMake.""" extra_vars = dict(EasyBlock.extra_options(extra_vars)) extra_vars.update({'config...
the_stack_v2_python_sparse
1.13.0/easyblock/easyblocks/generic/configuremake.py
lsuhpchelp/easybuild_smic
train
0
d0dbe20e7be354ff1c9a605d07b30f41a4ad3bd4
[ "\"\"\"\n #Extract data for existing products\n data_to_update = []\n for index, product in enumerate(validated_data):\n if \"id\" in product:\n data_to_update.append(validated_data.pop(index))\n\n #Update existing products with extracted data\n self.upda...
<|body_start_0|> """ #Extract data for existing products data_to_update = [] for index, product in enumerate(validated_data): if "id" in product: data_to_update.append(validated_data.pop(index)) #Update ...
ProductListSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProductListSerializer: def create(self, validated_data): """Override the 'create' method We separate the data with ids, which will be used to update existing products. After the existing products are updated or deleted, then new products are created for data without ids""" <|body...
stack_v2_sparse_classes_36k_train_011743
21,355
no_license
[ { "docstring": "Override the 'create' method We separate the data with ids, which will be used to update existing products. After the existing products are updated or deleted, then new products are created for data without ids", "name": "create", "signature": "def create(self, validated_data)" }, { ...
2
stack_v2_sparse_classes_30k_train_012678
Implement the Python class `ProductListSerializer` described below. Class description: Implement the ProductListSerializer class. Method signatures and docstrings: - def create(self, validated_data): Override the 'create' method We separate the data with ids, which will be used to update existing products. After the ...
Implement the Python class `ProductListSerializer` described below. Class description: Implement the ProductListSerializer class. Method signatures and docstrings: - def create(self, validated_data): Override the 'create' method We separate the data with ids, which will be used to update existing products. After the ...
bef520659a7316c861933f9609b6b9ca7d9f47ac
<|skeleton|> class ProductListSerializer: def create(self, validated_data): """Override the 'create' method We separate the data with ids, which will be used to update existing products. After the existing products are updated or deleted, then new products are created for data without ids""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProductListSerializer: def create(self, validated_data): """Override the 'create' method We separate the data with ids, which will be used to update existing products. After the existing products are updated or deleted, then new products are created for data without ids""" """ ...
the_stack_v2_python_sparse
supplies/serializers.py
charliephairoj/backend
train
0
3571fe525cc229d60ac2beecc85b12280658eea6
[ "site = models.SiteSettings.objects.get()\ndata = {'site_form': forms.SiteForm(instance=site)}\nreturn TemplateResponse(request, 'settings/site.html', data)", "site = models.SiteSettings.objects.get()\nform = forms.SiteForm(request.POST, request.FILES, instance=site)\nif not form.is_valid():\n data = {'site_fo...
<|body_start_0|> site = models.SiteSettings.objects.get() data = {'site_form': forms.SiteForm(instance=site)} return TemplateResponse(request, 'settings/site.html', data) <|end_body_0|> <|body_start_1|> site = models.SiteSettings.objects.get() form = forms.SiteForm(request.POST,...
manage things like the instance name
Site
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Site: """manage things like the instance name""" def get(self, request): """edit form""" <|body_0|> def post(self, request): """edit the site settings""" <|body_1|> <|end_skeleton|> <|body_start_0|> site = models.SiteSettings.objects.get() ...
stack_v2_sparse_classes_36k_train_011744
3,435
no_license
[ { "docstring": "edit form", "name": "get", "signature": "def get(self, request)" }, { "docstring": "edit the site settings", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_012980
Implement the Python class `Site` described below. Class description: manage things like the instance name Method signatures and docstrings: - def get(self, request): edit form - def post(self, request): edit the site settings
Implement the Python class `Site` described below. Class description: manage things like the instance name Method signatures and docstrings: - def get(self, request): edit form - def post(self, request): edit the site settings <|skeleton|> class Site: """manage things like the instance name""" def get(self,...
0f8da5b738047f3c34d60d93f59bdedd8f797224
<|skeleton|> class Site: """manage things like the instance name""" def get(self, request): """edit form""" <|body_0|> def post(self, request): """edit the site settings""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Site: """manage things like the instance name""" def get(self, request): """edit form""" site = models.SiteSettings.objects.get() data = {'site_form': forms.SiteForm(instance=site)} return TemplateResponse(request, 'settings/site.html', data) def post(self, request): ...
the_stack_v2_python_sparse
bookwyrm/views/admin/site.py
bookwyrm-social/bookwyrm
train
1,398
0d6e5ee3cc02ede6de613b9c96492372e087416d
[ "if not numBins:\n numBins = int(len(data) / 5)\nres = stats.cumfreq(data, numbins=numBins)\nself.cdistr = res.cumcount / len(data)\nself.loLim = res.lowerlimit\nself.upLim = res.lowerlimit + res.binsize * res.cumcount.size\nself.binWidth = res.binsize", "if value <= self.loLim:\n d = 0.0\nelif value >= sel...
<|body_start_0|> if not numBins: numBins = int(len(data) / 5) res = stats.cumfreq(data, numbins=numBins) self.cdistr = res.cumcount / len(data) self.loLim = res.lowerlimit self.upLim = res.lowerlimit + res.binsize * res.cumcount.size self.binWidth = res.binsiz...
cumulative distr
CumDistr
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CumDistr: """cumulative distr""" def __init__(self, data, numBins=None): """initializer Parameters data : array numBins : no of bins""" <|body_0|> def getDistr(self, value): """get cumulative distribution Parameters value : value""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_36k_train_011745
32,264
permissive
[ { "docstring": "initializer Parameters data : array numBins : no of bins", "name": "__init__", "signature": "def __init__(self, data, numBins=None)" }, { "docstring": "get cumulative distribution Parameters value : value", "name": "getDistr", "signature": "def getDistr(self, value)" } ...
2
stack_v2_sparse_classes_30k_train_007901
Implement the Python class `CumDistr` described below. Class description: cumulative distr Method signatures and docstrings: - def __init__(self, data, numBins=None): initializer Parameters data : array numBins : no of bins - def getDistr(self, value): get cumulative distribution Parameters value : value
Implement the Python class `CumDistr` described below. Class description: cumulative distr Method signatures and docstrings: - def __init__(self, data, numBins=None): initializer Parameters data : array numBins : no of bins - def getDistr(self, value): get cumulative distribution Parameters value : value <|skeleton|...
861fd06b6b7abaffe5e8ca795136ab0fbb2234b5
<|skeleton|> class CumDistr: """cumulative distr""" def __init__(self, data, numBins=None): """initializer Parameters data : array numBins : no of bins""" <|body_0|> def getDistr(self, value): """get cumulative distribution Parameters value : value""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CumDistr: """cumulative distr""" def __init__(self, data, numBins=None): """initializer Parameters data : array numBins : no of bins""" if not numBins: numBins = int(len(data) / 5) res = stats.cumfreq(data, numbins=numBins) self.cdistr = res.cumcount / len(data...
the_stack_v2_python_sparse
matumizi/matumizi/sampler.py
pranab/whakapai
train
18
9ceeaecd6eb28b8e2a803aeca3251367da63b365
[ "StaticPanel.__init__(self, container, *args, **kwargs)\nself.attributes.append(wx.TextCtrl(self, wx.ID_ANY))\nself.attributes.append(wx.TextCtrl(self, wx.ID_ANY))\nself.attributes.append(wx.lib.masked.TimeCtrl(self, wx.ID_ANY, format='24HHMM'))\nself._set_attributes(self.attributes)", "attributes = []\nfor atr i...
<|body_start_0|> StaticPanel.__init__(self, container, *args, **kwargs) self.attributes.append(wx.TextCtrl(self, wx.ID_ANY)) self.attributes.append(wx.TextCtrl(self, wx.ID_ANY)) self.attributes.append(wx.lib.masked.TimeCtrl(self, wx.ID_ANY, format='24HHMM')) self._set_attributes(...
StaticVacationPanel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StaticVacationPanel: def __init__(self, container, *args, **kwargs): """The default constructor container: a data container object""" <|body_0|> def get_attributes(self): """Return a list of all attributes. return: a list, that contains this panel's attribute values....
stack_v2_sparse_classes_36k_train_011746
11,497
no_license
[ { "docstring": "The default constructor container: a data container object", "name": "__init__", "signature": "def __init__(self, container, *args, **kwargs)" }, { "docstring": "Return a list of all attributes. return: a list, that contains this panel's attribute values.", "name": "get_attri...
3
null
Implement the Python class `StaticVacationPanel` described below. Class description: Implement the StaticVacationPanel class. Method signatures and docstrings: - def __init__(self, container, *args, **kwargs): The default constructor container: a data container object - def get_attributes(self): Return a list of all ...
Implement the Python class `StaticVacationPanel` described below. Class description: Implement the StaticVacationPanel class. Method signatures and docstrings: - def __init__(self, container, *args, **kwargs): The default constructor container: a data container object - def get_attributes(self): Return a list of all ...
781ce419b51b5bd99bbd1b155c03843cb434cb8c
<|skeleton|> class StaticVacationPanel: def __init__(self, container, *args, **kwargs): """The default constructor container: a data container object""" <|body_0|> def get_attributes(self): """Return a list of all attributes. return: a list, that contains this panel's attribute values....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StaticVacationPanel: def __init__(self, container, *args, **kwargs): """The default constructor container: a data container object""" StaticPanel.__init__(self, container, *args, **kwargs) self.attributes.append(wx.TextCtrl(self, wx.ID_ANY)) self.attributes.append(wx.TextCtrl(s...
the_stack_v2_python_sparse
gui/static_data.py
mcepar1/Scheduler
train
0
8a52c0796b09aa751af6632b2fa59a85d37cb274
[ "if not root:\n return 0\nleft_branch = self.maxDepth(root.left) + 1\nright_branch = self.maxDepth(root.right) + 1\nreturn max(left_branch, right_branch)", "if root.left is None and root.right is None:\n return 0\ndiameter = self.maxDepth(root.left) + self.maxDepth(root.right) + 2\ndiameter_left = self.diam...
<|body_start_0|> if not root: return 0 left_branch = self.maxDepth(root.left) + 1 right_branch = self.maxDepth(root.right) + 1 return max(left_branch, right_branch) <|end_body_0|> <|body_start_1|> if root.left is None and root.right is None: return 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def diameterOfBinaryTree(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: return 0 ...
stack_v2_sparse_classes_36k_train_011747
938
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "maxDepth", "signature": "def maxDepth(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "diameterOfBinaryTree", "signature": "def diameterOfBinaryTree(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root): :type root: TreeNode :rtype: int - def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root): :type root: TreeNode :rtype: int - def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: def maxDept...
85f71621c54f6b0029f3a2746f022f89dd7419d9
<|skeleton|> class Solution: def maxDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def diameterOfBinaryTree(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxDepth(self, root): """:type root: TreeNode :rtype: int""" if not root: return 0 left_branch = self.maxDepth(root.left) + 1 right_branch = self.maxDepth(root.right) + 1 return max(left_branch, right_branch) def diameterOfBinaryTree(self,...
the_stack_v2_python_sparse
LeetCode/30 days challenge/11_diameter_of_binary_tree.py
XyK0907/for_work
train
0
f975aeba676a086d3f21a56c6632978aab3212ea
[ "if not triangle:\n return\nfor i in range(len(triangle) - 2, -1, -1):\n for j in range(len(triangle[i])):\n triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])\nreturn triangle[0][0]", "if not triangle:\n return\npath = triangle[-1]\nfor i in range(len(triangle) - 2, -1, -1):\n f...
<|body_start_0|> if not triangle: return for i in range(len(triangle) - 2, -1, -1): for j in range(len(triangle[i])): triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]) return triangle[0][0] <|end_body_0|> <|body_start_1|> if not tr...
Triangle
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Triangle: def get_minimum_sum(self, triangle: List[List[int]]) -> int: """Approach: Bottom up :param triangle: :return:""" <|body_0|> def get_minimum_sum_(self, triangle: List[List[int]]) -> int: """Approach: Bottom up with O(n) space. :param triangle: :return:""" ...
stack_v2_sparse_classes_36k_train_011748
1,205
no_license
[ { "docstring": "Approach: Bottom up :param triangle: :return:", "name": "get_minimum_sum", "signature": "def get_minimum_sum(self, triangle: List[List[int]]) -> int" }, { "docstring": "Approach: Bottom up with O(n) space. :param triangle: :return:", "name": "get_minimum_sum_", "signature...
2
null
Implement the Python class `Triangle` described below. Class description: Implement the Triangle class. Method signatures and docstrings: - def get_minimum_sum(self, triangle: List[List[int]]) -> int: Approach: Bottom up :param triangle: :return: - def get_minimum_sum_(self, triangle: List[List[int]]) -> int: Approac...
Implement the Python class `Triangle` described below. Class description: Implement the Triangle class. Method signatures and docstrings: - def get_minimum_sum(self, triangle: List[List[int]]) -> int: Approach: Bottom up :param triangle: :return: - def get_minimum_sum_(self, triangle: List[List[int]]) -> int: Approac...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Triangle: def get_minimum_sum(self, triangle: List[List[int]]) -> int: """Approach: Bottom up :param triangle: :return:""" <|body_0|> def get_minimum_sum_(self, triangle: List[List[int]]) -> int: """Approach: Bottom up with O(n) space. :param triangle: :return:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Triangle: def get_minimum_sum(self, triangle: List[List[int]]) -> int: """Approach: Bottom up :param triangle: :return:""" if not triangle: return for i in range(len(triangle) - 2, -1, -1): for j in range(len(triangle[i])): triangle[i][j] += min(...
the_stack_v2_python_sparse
data_structures/triangle.py
Shiv2157k/leet_code
train
1
c971e8e50352a731549f84ade9cff29b11634640
[ "client = get_object_or_404(Client, id=pk)\nform = ClientForm(instance=client)\nreturn render(request, 'client/add-client.html', {'form': form, 'func': 'Update', 'client': client})", "client = get_object_or_404(Client, id=pk)\nmeasurements_exist = False\nif client.gender == 'M':\n measurements_exist = MaleMeas...
<|body_start_0|> client = get_object_or_404(Client, id=pk) form = ClientForm(instance=client) return render(request, 'client/add-client.html', {'form': form, 'func': 'Update', 'client': client}) <|end_body_0|> <|body_start_1|> client = get_object_or_404(Client, id=pk) measuremen...
Class based view for displaying client detail.
ClientUpdateView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientUpdateView: """Class based view for displaying client detail.""" def get(self, request, pk): """Return update client form.""" <|body_0|> def post(self, request, pk): """Update client by id .""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_011749
5,092
no_license
[ { "docstring": "Return update client form.", "name": "get", "signature": "def get(self, request, pk)" }, { "docstring": "Update client by id .", "name": "post", "signature": "def post(self, request, pk)" } ]
2
null
Implement the Python class `ClientUpdateView` described below. Class description: Class based view for displaying client detail. Method signatures and docstrings: - def get(self, request, pk): Return update client form. - def post(self, request, pk): Update client by id .
Implement the Python class `ClientUpdateView` described below. Class description: Class based view for displaying client detail. Method signatures and docstrings: - def get(self, request, pk): Return update client form. - def post(self, request, pk): Update client by id . <|skeleton|> class ClientUpdateView: """...
93c3106ab90fb9aed85658f93f51686ba4734091
<|skeleton|> class ClientUpdateView: """Class based view for displaying client detail.""" def get(self, request, pk): """Return update client form.""" <|body_0|> def post(self, request, pk): """Update client by id .""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClientUpdateView: """Class based view for displaying client detail.""" def get(self, request, pk): """Return update client form.""" client = get_object_or_404(Client, id=pk) form = ClientForm(instance=client) return render(request, 'client/add-client.html', {'form': form, ...
the_stack_v2_python_sparse
client/views/client_views.py
saadali5997/tms
train
0
0163054dd5e092f954f7f7bbfde502a0d55d41df
[ "def recur(i, j):\n if j == 0 or i == j:\n return 1\n else:\n return recur(i - 1, j - 1) + recur(i - 1, j)\nres = []\nfor i in range(numRows):\n tmp = []\n for j in range(i + 1):\n if j == 0 or i == j:\n tmp.append(1)\n else:\n tmp.append(recur(i - 1, j ...
<|body_start_0|> def recur(i, j): if j == 0 or i == j: return 1 else: return recur(i - 1, j - 1) + recur(i - 1, j) res = [] for i in range(numRows): tmp = [] for j in range(i + 1): if j == 0 or i == j...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generate_1(self, numRows: int) -> List[List[int]]: """递归 时间复杂度:O(numRows^3) 空间复杂度:O(numRows^2) :param numRows: :return:""" <|body_0|> def generate_2(self, numRows: int) -> List[List[int]]: """动态规划 时间复杂度:O(numRows^2) 空间复杂度:O(numRows^2) :param numRows: :r...
stack_v2_sparse_classes_36k_train_011750
1,669
no_license
[ { "docstring": "递归 时间复杂度:O(numRows^3) 空间复杂度:O(numRows^2) :param numRows: :return:", "name": "generate_1", "signature": "def generate_1(self, numRows: int) -> List[List[int]]" }, { "docstring": "动态规划 时间复杂度:O(numRows^2) 空间复杂度:O(numRows^2) :param numRows: :return:", "name": "generate_2", "s...
2
stack_v2_sparse_classes_30k_train_005330
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate_1(self, numRows: int) -> List[List[int]]: 递归 时间复杂度:O(numRows^3) 空间复杂度:O(numRows^2) :param numRows: :return: - def generate_2(self, numRows: int) -> List[List[int]]: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate_1(self, numRows: int) -> List[List[int]]: 递归 时间复杂度:O(numRows^3) 空间复杂度:O(numRows^2) :param numRows: :return: - def generate_2(self, numRows: int) -> List[List[int]]: ...
62419b49000e79962bcdc99cd98afd2fb82ea345
<|skeleton|> class Solution: def generate_1(self, numRows: int) -> List[List[int]]: """递归 时间复杂度:O(numRows^3) 空间复杂度:O(numRows^2) :param numRows: :return:""" <|body_0|> def generate_2(self, numRows: int) -> List[List[int]]: """动态规划 时间复杂度:O(numRows^2) 空间复杂度:O(numRows^2) :param numRows: :r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def generate_1(self, numRows: int) -> List[List[int]]: """递归 时间复杂度:O(numRows^3) 空间复杂度:O(numRows^2) :param numRows: :return:""" def recur(i, j): if j == 0 or i == j: return 1 else: return recur(i - 1, j - 1) + recur(i - 1, j) ...
the_stack_v2_python_sparse
软件开发岗刷题(华为笔试准备)/递归/generate.py
MaoningGuan/LeetCode
train
3
a214d2f29db2f663907d95ae4d73163f0414534a
[ "self.crypto = crypto\nself.liveness = liveness\nself.game_instance = game_instance\nself.mailbox = mailbox\nself.agent_name = agent_name", "tac_msg = TACMessage(tac_type=TACMessage.Type.GET_STATE_UPDATE)\ntac_bytes = TACSerializer().encode(tac_msg)\nself.mailbox.outbox.put_message(to=self.game_instance.controlle...
<|body_start_0|> self.crypto = crypto self.liveness = liveness self.game_instance = game_instance self.mailbox = mailbox self.agent_name = agent_name <|end_body_0|> <|body_start_1|> tac_msg = TACMessage(tac_type=TACMessage.Type.GET_STATE_UPDATE) tac_bytes = TACSe...
The ControllerActions class defines the actions of an agent towards the ControllerAgent.
ControllerActions
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ControllerActions: """The ControllerActions class defines the actions of an agent towards the ControllerAgent.""" def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_name: str) -> None: """Instantiate the ControllerActions. :par...
stack_v2_sparse_classes_36k_train_011751
12,389
permissive
[ { "docstring": "Instantiate the ControllerActions. :param crypto: the crypto module :param liveness: the liveness module :param game_instance: the game instance :param mailbox: the mailbox of the agent :param agent_name: the agent name :return: None", "name": "__init__", "signature": "def __init__(self,...
2
stack_v2_sparse_classes_30k_train_007813
Implement the Python class `ControllerActions` described below. Class description: The ControllerActions class defines the actions of an agent towards the ControllerAgent. Method signatures and docstrings: - def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_na...
Implement the Python class `ControllerActions` described below. Class description: The ControllerActions class defines the actions of an agent towards the ControllerAgent. Method signatures and docstrings: - def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_na...
33c4aa24ca8daf26f2c8f2d2fa38d7f4bf750cfa
<|skeleton|> class ControllerActions: """The ControllerActions class defines the actions of an agent towards the ControllerAgent.""" def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_name: str) -> None: """Instantiate the ControllerActions. :par...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ControllerActions: """The ControllerActions class defines the actions of an agent towards the ControllerAgent.""" def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_name: str) -> None: """Instantiate the ControllerActions. :param crypto: th...
the_stack_v2_python_sparse
tac/agents/participant/v1/base/actions.py
fetchai/agents-tac
train
30
631836f7da85434f1ae1fb81e3ebb35065638ca6
[ "binds = []\nfor jid, fid, run, lumi in jobFileRunLumis:\n binds.append({'jobid': jid, 'fileid': fid, 'run': run, 'lumi': lumi})\nreturn binds", "if jobFileRunLumis:\n binds = self.getBinds(jobFileRunLumis)\nelif jobid and fileid and run and lumi:\n binds = DBFormatter.getBinds(self, jobid=jobid, fileid=...
<|body_start_0|> binds = [] for jid, fid, run, lumi in jobFileRunLumis: binds.append({'jobid': jid, 'fileid': fid, 'run': run, 'lumi': lumi}) return binds <|end_body_0|> <|body_start_1|> if jobFileRunLumis: binds = self.getBinds(jobFileRunLumis) elif jobi...
Add WorkUnit associations to jobs
AddWorkUnits
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddWorkUnits: """Add WorkUnit associations to jobs""" def getBinds(self, jobFileRunLumis): """Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A""" <|body_0|> def execute(self,...
stack_v2_sparse_classes_36k_train_011752
2,035
permissive
[ { "docstring": "Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A", "name": "getBinds", "signature": "def getBinds(self, jobFileRunLumis)" }, { "docstring": "Args: jobid: The id of a single job fileid...
2
stack_v2_sparse_classes_30k_train_008656
Implement the Python class `AddWorkUnits` described below. Class description: Add WorkUnit associations to jobs Method signatures and docstrings: - def getBinds(self, jobFileRunLumis): Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] ...
Implement the Python class `AddWorkUnits` described below. Class description: Add WorkUnit associations to jobs Method signatures and docstrings: - def getBinds(self, jobFileRunLumis): Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] ...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class AddWorkUnits: """Add WorkUnit associations to jobs""" def getBinds(self, jobFileRunLumis): """Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A""" <|body_0|> def execute(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddWorkUnits: """Add WorkUnit associations to jobs""" def getBinds(self, jobFileRunLumis): """Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A""" binds = [] for jid, fid, run, lumi in ...
the_stack_v2_python_sparse
src/python/WMCore/WMBS/MySQL/Jobs/AddWorkUnits.py
vkuznet/WMCore
train
0
0bbf15f3c8623d96deaef7161dc9a8c071aa731e
[ "m, n = (len(grid), len(grid[0]))\nstart = None\ncnt = 0\nfor i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n cnt += 1\n elif grid[i][j] == 1:\n start = (i, j)\n\ndef dfs(i, j, c=0):\n if grid[i][j] == 2 and c == cnt + 1:\n return 1\n saved = grid[i][j...
<|body_start_0|> m, n = (len(grid), len(grid[0])) start = None cnt = 0 for i in range(m): for j in range(n): if grid[i][j] == 0: cnt += 1 elif grid[i][j] == 1: start = (i, j) def dfs(i, j, c=0): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: """Nov 13, 2021 10:23 DFS""" <|body_0|> def uniquePathsIII(self, grid: List[List[int]]) -> int: """Feb 19, 2023 22:45""" <|body_1|> <|end_skeleton|> <|body_start_0|> m, n = (len(grid)...
stack_v2_sparse_classes_36k_train_011753
3,805
no_license
[ { "docstring": "Nov 13, 2021 10:23 DFS", "name": "uniquePathsIII", "signature": "def uniquePathsIII(self, grid: List[List[int]]) -> int" }, { "docstring": "Feb 19, 2023 22:45", "name": "uniquePathsIII", "signature": "def uniquePathsIII(self, grid: List[List[int]]) -> int" } ]
2
stack_v2_sparse_classes_30k_train_001037
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePathsIII(self, grid: List[List[int]]) -> int: Nov 13, 2021 10:23 DFS - def uniquePathsIII(self, grid: List[List[int]]) -> int: Feb 19, 2023 22:45
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePathsIII(self, grid: List[List[int]]) -> int: Nov 13, 2021 10:23 DFS - def uniquePathsIII(self, grid: List[List[int]]) -> int: Feb 19, 2023 22:45 <|skeleton|> class So...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: """Nov 13, 2021 10:23 DFS""" <|body_0|> def uniquePathsIII(self, grid: List[List[int]]) -> int: """Feb 19, 2023 22:45""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: """Nov 13, 2021 10:23 DFS""" m, n = (len(grid), len(grid[0])) start = None cnt = 0 for i in range(m): for j in range(n): if grid[i][j] == 0: cnt += 1 ...
the_stack_v2_python_sparse
leetcode/solved/1022_Unique_Paths_III/solution.py
sungminoh/algorithms
train
0
839c4a99e88f806b5a193287d47e6d345229e947
[ "service = self.context['service']\nif service.is_active:\n raise serializers.ValidationError('You need to finish the Service after write a review.')\ndata['service'] = service\nreturn data", "user_bbs = data['service'].user_bbs.user_bbs\nreview = Review.objects.create(service_origin=data['service'], review=da...
<|body_start_0|> service = self.context['service'] if service.is_active: raise serializers.ValidationError('You need to finish the Service after write a review.') data['service'] = service return data <|end_body_0|> <|body_start_1|> user_bbs = data['service'].user_bb...
Create Review Serializer.
CreateReviewModelSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateReviewModelSerializer: """Create Review Serializer.""" def validate(self, data): """Validate if the service ends in the momento of the review.""" <|body_0|> def create(self, data): """Create the review.""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_011754
1,727
permissive
[ { "docstring": "Validate if the service ends in the momento of the review.", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Create the review.", "name": "create", "signature": "def create(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_014066
Implement the Python class `CreateReviewModelSerializer` described below. Class description: Create Review Serializer. Method signatures and docstrings: - def validate(self, data): Validate if the service ends in the momento of the review. - def create(self, data): Create the review.
Implement the Python class `CreateReviewModelSerializer` described below. Class description: Create Review Serializer. Method signatures and docstrings: - def validate(self, data): Validate if the service ends in the momento of the review. - def create(self, data): Create the review. <|skeleton|> class CreateReviewM...
5c37c6876ca13b5794ac44e0342b810426acbc76
<|skeleton|> class CreateReviewModelSerializer: """Create Review Serializer.""" def validate(self, data): """Validate if the service ends in the momento of the review.""" <|body_0|> def create(self, data): """Create the review.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateReviewModelSerializer: """Create Review Serializer.""" def validate(self, data): """Validate if the service ends in the momento of the review.""" service = self.context['service'] if service.is_active: raise serializers.ValidationError('You need to finish the Ser...
the_stack_v2_python_sparse
hisitter/reviews/serializers.py
babysitter-finder/backend
train
1
0597a2d0a0628f71426bdb55db6f9bd717e65c30
[ "if not (filename is None) ^ (maskobject is None):\n raise ValueError('You have to provide either a file name or a Mask object')\nelif not maskobject is None:\n if not isinstance(maskobject, Mask):\n raise ValueError('maskobject must be an instance of Mask')\n base_mask = maskobject.mask\n self._...
<|body_start_0|> if not (filename is None) ^ (maskobject is None): raise ValueError('You have to provide either a file name or a Mask object') elif not maskobject is None: if not isinstance(maskobject, Mask): raise ValueError('maskobject must be an instance of Mas...
Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object
ComposedSubMask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ComposedSubMask: """Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object""" def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmatvar='nav_lat', xlevelsmatvar='nav_lon', dzvarname='e3t'): ""...
stack_v2_sparse_classes_36k_train_011755
4,524
no_license
[ { "docstring": "ComposedSubMask constructor Args: - *basin*: a ComposedBasin object. - *filename*: the path to a NetCDF file. - *maskobject*: a Mask object. Caveats: - *filename* and *maskobject* are mutually exclusive.", "name": "__init__", "signature": "def __init__(self, basin, filename=None, maskobj...
2
stack_v2_sparse_classes_30k_test_000120
Implement the Python class `ComposedSubMask` described below. Class description: Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object Method signatures and docstrings: - def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmat...
Implement the Python class `ComposedSubMask` described below. Class description: Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object Method signatures and docstrings: - def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmat...
985f34c2214ea55cd4d324704847d5a0d2a9de1e
<|skeleton|> class ComposedSubMask: """Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object""" def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmatvar='nav_lat', xlevelsmatvar='nav_lon', dzvarname='e3t'): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ComposedSubMask: """Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object""" def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmatvar='nav_lat', xlevelsmatvar='nav_lon', dzvarname='e3t'): """ComposedSubM...
the_stack_v2_python_sparse
commons/composedsubmask.py
inogs/bit.sea
train
4
81b6f4e1c22093d23e46af50fe947a8d93a89e39
[ "A = solution1[:point].append(solution2[point:])\nB = solution2[:point].append(solution1[point:])\nreturn (A, B)", "A = solution1\nB = solution2\nfor p in points:\n A, B = Crossover.single_point_crossover(A, B, p)\nreturn (A, B)", "A = solution1\nB = solution2\nfor i in range(len(chances)):\n if chances[i...
<|body_start_0|> A = solution1[:point].append(solution2[point:]) B = solution2[:point].append(solution1[point:]) return (A, B) <|end_body_0|> <|body_start_1|> A = solution1 B = solution2 for p in points: A, B = Crossover.single_point_crossover(A, B, p) ...
Crossover
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Crossover: def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: """Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n ...
stack_v2_sparse_classes_36k_train_011756
19,927
no_license
[ { "docstring": "Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n being the solution size. Args: solution1: One solution to be used in crossover with size N. solution2: Another solution to be used in crossover with size N. point: An intege...
3
stack_v2_sparse_classes_30k_train_003061
Implement the Python class `Crossover` described below. Class description: Implement the Crossover class. Method signatures and docstrings: - def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: Returns two children solu...
Implement the Python class `Crossover` described below. Class description: Implement the Crossover class. Method signatures and docstrings: - def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: Returns two children solu...
f1e705a80f60d28d56f3a1c2e0b700438078496c
<|skeleton|> class Crossover: def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: """Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Crossover: def single_point_crossover(solution1: List[Tuple[str, int]], solution2: List[Tuple[str, int]], point: int) -> Tuple[Tuple[str, int], Tuple[str, int]]: """Returns two children solutions based on a single-point crossover between the two given solutions. Complexity: O(n), with n being the solu...
the_stack_v2_python_sparse
code/python/genetic.py
akahenry/INF05100_Problems
train
0
7024ebf9f75940fdd27ee55f36921a0b488fa1c4
[ "Serializable._init(self, locals())\nsuper().__init__(min_rollouts=min_rollouts, min_steps=min_steps)\nself.env = env\nself.policy = policy\nself.show_progress_bar = show_progress_bar\nif mp.get_start_method(allow_none=True) != 'spawn':\n mp.set_start_method('spawn', force=True)\nself.pool = SamplerPool(num_work...
<|body_start_0|> Serializable._init(self, locals()) super().__init__(min_rollouts=min_rollouts, min_steps=min_steps) self.env = env self.policy = policy self.show_progress_bar = show_progress_bar if mp.get_start_method(allow_none=True) != 'spawn': mp.set_start...
Class for sampling from multiple environments in parallel
ParallelRolloutSampler
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParallelRolloutSampler: """Class for sampling from multiple environments in parallel""" def __init__(self, env, policy, num_workers: int, *, min_rollouts: int=None, min_steps: int=None, show_progress_bar: bool=True, seed: int=NO_SEED_PASSED): """Constructor :param env: environment to...
stack_v2_sparse_classes_36k_train_011757
13,009
permissive
[ { "docstring": "Constructor :param env: environment to sample from :param policy: policy to act in the environment (can also be an exploration strategy) :param num_workers: number of parallel samplers :param min_rollouts: minimum number of complete rollouts to sample :param min_steps: minimum total number of st...
3
null
Implement the Python class `ParallelRolloutSampler` described below. Class description: Class for sampling from multiple environments in parallel Method signatures and docstrings: - def __init__(self, env, policy, num_workers: int, *, min_rollouts: int=None, min_steps: int=None, show_progress_bar: bool=True, seed: in...
Implement the Python class `ParallelRolloutSampler` described below. Class description: Class for sampling from multiple environments in parallel Method signatures and docstrings: - def __init__(self, env, policy, num_workers: int, *, min_rollouts: int=None, min_steps: int=None, show_progress_bar: bool=True, seed: in...
d7e9cd191ccb318d5f1e580babc2fc38b5b3675a
<|skeleton|> class ParallelRolloutSampler: """Class for sampling from multiple environments in parallel""" def __init__(self, env, policy, num_workers: int, *, min_rollouts: int=None, min_steps: int=None, show_progress_bar: bool=True, seed: int=NO_SEED_PASSED): """Constructor :param env: environment to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParallelRolloutSampler: """Class for sampling from multiple environments in parallel""" def __init__(self, env, policy, num_workers: int, *, min_rollouts: int=None, min_steps: int=None, show_progress_bar: bool=True, seed: int=NO_SEED_PASSED): """Constructor :param env: environment to sample from ...
the_stack_v2_python_sparse
Pyrado/pyrado/sampling/parallel_rollout_sampler.py
1abner1/SimuRLacra
train
0
36734cf3c512acf2f182a9646fa3739df805df66
[ "super().__init__(mt_constant)\nself.mt_namespace = get_namespace(mt_constant, command=True)\nself.mt_endpoint = get_command(mt_constant)\nself.channel = get_channel_from_connection(self.connection)\nself.publish_schema_types = get_schema_types_from_file(mt_constant['command_json_file'])\nself.event_consumer = self...
<|body_start_0|> super().__init__(mt_constant) self.mt_namespace = get_namespace(mt_constant, command=True) self.mt_endpoint = get_command(mt_constant) self.channel = get_channel_from_connection(self.connection) self.publish_schema_types = get_schema_types_from_file(mt_constant['...
Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages
MTPublisher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MTPublisher: """Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages""" def __init__(self, mt_constant): """Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces""" <|...
stack_v2_sparse_classes_36k_train_011758
14,450
permissive
[ { "docstring": "Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces", "name": "__init__", "signature": "def __init__(self, mt_constant)" }, { "docstring": "Method for publish message to MT listener exchange. Declare needed exchange, the...
2
stack_v2_sparse_classes_30k_test_000337
Implement the Python class `MTPublisher` described below. Class description: Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages Method signatures and docstrings: - def __init__(self, mt_constant): Method for define all needed for publishing variables. :param mt_con...
Implement the Python class `MTPublisher` described below. Class description: Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages Method signatures and docstrings: - def __init__(self, mt_constant): Method for define all needed for publishing variables. :param mt_con...
0c9beacc4a98c3f55ed56969a8b7eb84c4209c21
<|skeleton|> class MTPublisher: """Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages""" def __init__(self, mt_constant): """Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MTPublisher: """Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages""" def __init__(self, mt_constant): """Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces""" super().__init_...
the_stack_v2_python_sparse
Source/sds_tools/mass_transit/MTMessageProcessor.py
ArqiSoft/ml-services
train
0
dd43ce02f33278a95bd15939bedba4f5b814ce13
[ "defaults = {'decimal_places': 2, 'max_digits': 11}\ndefaults.update(kwargs)\nsuper().__init__(*args, **defaults)", "val = data.get(self.name)\nif isinstance(val, str):\n return decimal.Decimal(val)\nif val is not None:\n return val / decimal.Decimal('100')" ]
<|body_start_0|> defaults = {'decimal_places': 2, 'max_digits': 11} defaults.update(kwargs) super().__init__(*args, **defaults) <|end_body_0|> <|body_start_1|> val = data.get(self.name) if isinstance(val, str): return decimal.Decimal(val) if val is not None: ...
A legacy field to store currency amounts in dollars (etc). Stripe is always in cents. Historically djstripe stored everything in dollars. Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead. We're planning on migrating existing fields in dj-stripe 3.0, see https://github.com/dj-stripe/dj-s...
StripeDecimalCurrencyAmountField
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StripeDecimalCurrencyAmountField: """A legacy field to store currency amounts in dollars (etc). Stripe is always in cents. Historically djstripe stored everything in dollars. Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead. We're planning on migrating existing fi...
stack_v2_sparse_classes_36k_train_011759
6,138
permissive
[ { "docstring": "Assign default args to this field. By contacting stripe support, some accounts will have their limit raised to 11 digits", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Convert the raw value to decimal representation.", "name": "str...
2
stack_v2_sparse_classes_30k_train_008324
Implement the Python class `StripeDecimalCurrencyAmountField` described below. Class description: A legacy field to store currency amounts in dollars (etc). Stripe is always in cents. Historically djstripe stored everything in dollars. Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead. ...
Implement the Python class `StripeDecimalCurrencyAmountField` described below. Class description: A legacy field to store currency amounts in dollars (etc). Stripe is always in cents. Historically djstripe stored everything in dollars. Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead. ...
ee04b2ea6850e9bc5d8c382bd32cbf21e696c281
<|skeleton|> class StripeDecimalCurrencyAmountField: """A legacy field to store currency amounts in dollars (etc). Stripe is always in cents. Historically djstripe stored everything in dollars. Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead. We're planning on migrating existing fi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StripeDecimalCurrencyAmountField: """A legacy field to store currency amounts in dollars (etc). Stripe is always in cents. Historically djstripe stored everything in dollars. Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead. We're planning on migrating existing fields in dj-st...
the_stack_v2_python_sparse
djstripe/fields.py
dj-stripe/dj-stripe
train
1,178
204837e6365227f2b5c9259cee61720831530093
[ "f = self.RequiredForm()\np = f.as_p()\nself.assert_('<input type=\"file\" name=\"files[]\" id=\"id_files0\" />' in p)", "f = self.MultiForm()\np = f.as_p()\nself.assert_('<input type=\"file\" name=\"files[]\" id=\"id_files0\" />' in p)\nself.assert_('<input type=\"file\" name=\"files[]\" id=\"id_files1\" />' in ...
<|body_start_0|> f = self.RequiredForm() p = f.as_p() self.assert_('<input type="file" name="files[]" id="id_files0" />' in p) <|end_body_0|> <|body_start_1|> f = self.MultiForm() p = f.as_p() self.assert_('<input type="file" name="files[]" id="id_files0" />' in p) ...
Tests that MultiFileField field.
MultiFileFieldTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiFileFieldTest: """Tests that MultiFileField field.""" def testOneRender(self): """Test the rendering of a MultiFileField with 1 input box.""" <|body_0|> def testTwoRender(self): """Test the rendering of a MultiFileField with 2 input boxes.""" <|body_...
stack_v2_sparse_classes_36k_train_011760
3,598
no_license
[ { "docstring": "Test the rendering of a MultiFileField with 1 input box.", "name": "testOneRender", "signature": "def testOneRender(self)" }, { "docstring": "Test the rendering of a MultiFileField with 2 input boxes.", "name": "testTwoRender", "signature": "def testTwoRender(self)" }, ...
4
stack_v2_sparse_classes_30k_train_019007
Implement the Python class `MultiFileFieldTest` described below. Class description: Tests that MultiFileField field. Method signatures and docstrings: - def testOneRender(self): Test the rendering of a MultiFileField with 1 input box. - def testTwoRender(self): Test the rendering of a MultiFileField with 2 input boxe...
Implement the Python class `MultiFileFieldTest` described below. Class description: Tests that MultiFileField field. Method signatures and docstrings: - def testOneRender(self): Test the rendering of a MultiFileField with 1 input box. - def testTwoRender(self): Test the rendering of a MultiFileField with 2 input boxe...
2791145f62a7e296be859a400499812b394249e9
<|skeleton|> class MultiFileFieldTest: """Tests that MultiFileField field.""" def testOneRender(self): """Test the rendering of a MultiFileField with 1 input box.""" <|body_0|> def testTwoRender(self): """Test the rendering of a MultiFileField with 2 input boxes.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiFileFieldTest: """Tests that MultiFileField field.""" def testOneRender(self): """Test the rendering of a MultiFileField with 1 input box.""" f = self.RequiredForm() p = f.as_p() self.assert_('<input type="file" name="files[]" id="id_files0" />' in p) def testTwo...
the_stack_v2_python_sparse
combaragi/ccboard/tests.py
yonseics/yonseics
train
1
7f75d1b3bbc723b39b9583ca46207a30e61119d4
[ "def traverse(root):\n if root:\n data.append(str(root.val))\n traverse(root.left)\n traverse(root.right)\n else:\n data.append('#')\ndata = []\ntraverse(root)\nreturn ' '.join(data)", "def build():\n val = array.next()\n if val == '#':\n return None\n node = Tree...
<|body_start_0|> def traverse(root): if root: data.append(str(root.val)) traverse(root.left) traverse(root.right) else: data.append('#') data = [] traverse(root) return ' '.join(data) <|end_body_0|> ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_011761
1,307
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_val_000250
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
9dffc419af45709d95d2ab5dc163461d254140c4
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def traverse(root): if root: data.append(str(root.val)) traverse(root.left) traverse(root.right) else: ...
the_stack_v2_python_sparse
Trees/serialize_deserialize.py
TedWildenradt/CTCI-Python
train
0
1afa227e05651e0d3dcc5cb1be9521895a2ed293
[ "srcs = var_to_list(srcs)\ndeps = var_to_list(deps)\nextra_cppflags = var_to_list(extra_cppflags)\nextra_linkflags = var_to_list(extra_linkflags)\nCcTarget.__init__(self, name, target_type, srcs, deps, None, warning, defs, incs, [], [], extra_cppflags, extra_linkflags, blade, kwargs)", "nvcc_flags = []\nif self.d...
<|body_start_0|> srcs = var_to_list(srcs) deps = var_to_list(deps) extra_cppflags = var_to_list(extra_cppflags) extra_linkflags = var_to_list(extra_linkflags) CcTarget.__init__(self, name, target_type, srcs, deps, None, warning, defs, incs, [], [], extra_cppflags, extra_linkflags...
A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc.
CuTarget
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CuTarget: """A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc.""" def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs): """Init method. Init the...
stack_v2_sparse_classes_36k_train_011762
10,571
permissive
[ { "docstring": "Init method. Init the cu target.", "name": "__init__", "signature": "def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs)" }, { "docstring": "_get_cu_flags. Return the nvcc flags according to the BUILD file and oth...
3
stack_v2_sparse_classes_30k_val_001188
Implement the Python class `CuTarget` described below. Class description: A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc. Method signatures and docstrings: - def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflag...
Implement the Python class `CuTarget` described below. Class description: A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc. Method signatures and docstrings: - def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflag...
a7da427617885546c5b5e07aa7740b3dee690337
<|skeleton|> class CuTarget: """A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc.""" def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs): """Init method. Init the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CuTarget: """A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc.""" def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs): """Init method. Init the cu target.""...
the_stack_v2_python_sparse
build_tools/typhoon-blade/src/blade/cu_targets.py
algo-data-platform/PredictorService
train
3
5f36120cfe2eb3459e1c85f1ea1cf7fef8ad9bbf
[ "previous_index = 0\ntotal_profit = 0\nfor index in range(0, len(prices)):\n if previous_index == index:\n continue\n previous_price = prices[previous_index]\n current_price = prices[index]\n if previous_price < current_price:\n total_profit += current_price - previous_price\n previous_...
<|body_start_0|> previous_index = 0 total_profit = 0 for index in range(0, len(prices)): if previous_index == index: continue previous_price = prices[previous_index] current_price = prices[index] if previous_price < current_price: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> previous_index = 0 total_profi...
stack_v2_sparse_classes_36k_train_011763
1,420
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "removeDuplicates", "signature": "def removeDuplicates(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_002496
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def removeDuplicates(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def maxP...
dae0a5e6e688a34e6b870a93ecb210416a54d67a
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" previous_index = 0 total_profit = 0 for index in range(0, len(prices)): if previous_index == index: continue previous_price = prices[previous_index] ...
the_stack_v2_python_sparse
python/algorithms/arrays/max_profit.py
nathanle89/interview
train
0
0386f5ec419b6208473417122e44d6727a148020
[ "repository = self.object\ngh = self.gh\nif not gh:\n return\nrepository.check_hook(gh)\nreturn repository.hook_set", "if not result:\n CheckRepositoryEvents.add_job(self.identifier.hget())\nelse:\n for j in CheckRepositoryEvents.collection(queued=1, identifier=self.identifier.hget()).instances():\n ...
<|body_start_0|> repository = self.object gh = self.gh if not gh: return repository.check_hook(gh) return repository.hook_set <|end_body_0|> <|body_start_1|> if not result: CheckRepositoryEvents.add_job(self.identifier.hget()) else: ...
Every 15 minutes (+-2mn), check if the hook is set and if None and if there is no job to fetch events every minute, create one.
CheckRepositoryHook
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckRepositoryHook: """Every 15 minutes (+-2mn), check if the hook is set and if None and if there is no job to fetch events every minute, create one.""" def run(self, queue): """Check if the hook exist for this modele. If not, try to add a job to start checking events every minute ...
stack_v2_sparse_classes_36k_train_011764
3,018
no_license
[ { "docstring": "Check if the hook exist for this modele. If not, try to add a job to start checking events every minute (if one already exists, no new one will be added)", "name": "run", "signature": "def run(self, queue)" }, { "docstring": "If the repository hook is not set, add a job to fetch ...
2
stack_v2_sparse_classes_30k_train_009974
Implement the Python class `CheckRepositoryHook` described below. Class description: Every 15 minutes (+-2mn), check if the hook is set and if None and if there is no job to fetch events every minute, create one. Method signatures and docstrings: - def run(self, queue): Check if the hook exist for this modele. If not...
Implement the Python class `CheckRepositoryHook` described below. Class description: Every 15 minutes (+-2mn), check if the hook is set and if None and if there is no job to fetch events every minute, create one. Method signatures and docstrings: - def run(self, queue): Check if the hook exist for this modele. If not...
63a405b993e77f10b9c2b6d9790aae7576d9d84f
<|skeleton|> class CheckRepositoryHook: """Every 15 minutes (+-2mn), check if the hook is set and if None and if there is no job to fetch events every minute, create one.""" def run(self, queue): """Check if the hook exist for this modele. If not, try to add a job to start checking events every minute ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckRepositoryHook: """Every 15 minutes (+-2mn), check if the hook is set and if None and if there is no job to fetch events every minute, create one.""" def run(self, queue): """Check if the hook exist for this modele. If not, try to add a job to start checking events every minute (if one alrea...
the_stack_v2_python_sparse
gim/hooks/tasks.py
derekey/github-issues-manager
train
1
e79169cb4dd3e72ae82dc4ace9ff963f4bd274b8
[ "self.log_dev_name = device_name\nself.__driver_logger = logging.getLogger(__name__)\nself.__is_log_out = True\nif len(self.__driver_logger.handlers) == 0:\n self.__driver_logger.propagate = False\n if len(GlobalModule.EM_LOGGER.handlers) != 2:\n raise ValueError('not 2rotate handler')\n for i in ra...
<|body_start_0|> self.log_dev_name = device_name self.__driver_logger = logging.getLogger(__name__) self.__is_log_out = True if len(self.__driver_logger.handlers) == 0: self.__driver_logger.propagate = False if len(GlobalModule.EM_LOGGER.handlers) != 2: ...
Log output class for the individual section on the driver
EmDriverCommonUtilityLog
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmDriverCommonUtilityLog: """Log output class for the individual section on the driver""" def __init__(self, device_name=None): """Constructor""" <|body_0|> def logging(self, device_name=None, log_level=None, log_message=None, log_module=' '): """Log output (Indi...
stack_v2_sparse_classes_36k_train_011765
3,487
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, device_name=None)" }, { "docstring": "Log output (Individual section on the driver) Explanation about parameter: device_name: Device name log_level: Log level (DEBUG,INFO,WARN,ERROR) log_message: Log message log_m...
3
stack_v2_sparse_classes_30k_train_011745
Implement the Python class `EmDriverCommonUtilityLog` described below. Class description: Log output class for the individual section on the driver Method signatures and docstrings: - def __init__(self, device_name=None): Constructor - def logging(self, device_name=None, log_level=None, log_message=None, log_module='...
Implement the Python class `EmDriverCommonUtilityLog` described below. Class description: Log output class for the individual section on the driver Method signatures and docstrings: - def __init__(self, device_name=None): Constructor - def logging(self, device_name=None, log_level=None, log_message=None, log_module='...
e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f
<|skeleton|> class EmDriverCommonUtilityLog: """Log output class for the individual section on the driver""" def __init__(self, device_name=None): """Constructor""" <|body_0|> def logging(self, device_name=None, log_level=None, log_message=None, log_module=' '): """Log output (Indi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmDriverCommonUtilityLog: """Log output class for the individual section on the driver""" def __init__(self, device_name=None): """Constructor""" self.log_dev_name = device_name self.__driver_logger = logging.getLogger(__name__) self.__is_log_out = True if len(self...
the_stack_v2_python_sparse
lib/DriverUtility/EmDriverCommonUtilityLog.py
lixiaochun/element-manager
train
0
e18d5320abe75fc8ec7b1bb62af5d5d92d12368c
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jliang24_tpotye', 'jliang24_tpotye')\nrepo.dropPermanent('policeHospitalData')\nrepo.createPermanent('policeHospitalData')\nnumPolice = []\nnumHospital = []\nfor entry in repo.jliang24_tpotye.police.find...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('jliang24_tpotye', 'jliang24_tpotye') repo.dropPermanent('policeHospitalData') repo.createPermanent('policeHospitalData') numPolice = [] ...
policeHospital
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class policeHospital: 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 everythin...
stack_v2_sparse_classes_36k_train_011766
4,759
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_003696
Implement the Python class `policeHospital` described below. Class description: Implement the policeHospital class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None,...
Implement the Python class `policeHospital` described below. Class description: Implement the policeHospital class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None,...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class policeHospital: 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 everythin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class policeHospital: 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('jliang24_tpotye', 'jliang24_tpotye')...
the_stack_v2_python_sparse
jliang24_tpotye/policeHospital.py
ROODAY/course-2017-fal-proj
train
3
c7ad32e46f21e5ad482156cea5f101f6fb87e48a
[ "text_buffer = TextWriter.make_text(text, custom_text)\nwidth = len(text_buffer)\nheight = 0\nif width > 0:\n height = len(text_buffer[0])\nif surface != None:\n for x in range(0, len(text_buffer)):\n for y in range(0, len(text_buffer[x])):\n if text_buffer[x][y] == 1:\n if ty...
<|body_start_0|> text_buffer = TextWriter.make_text(text, custom_text) width = len(text_buffer) height = 0 if width > 0: height = len(text_buffer[0]) if surface != None: for x in range(0, len(text_buffer)): for y in range(0, len(text_buffer...
TextWriter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextWriter: def draw_text(surface, text, colour, x_pos, y_pos, custom_text=None): """Draws text in the specified place, in the appropriate colour""" <|body_0|> def make_text(string, custom_text=None): """Construct a buffer that contains which pixels to draw (=1) to m...
stack_v2_sparse_classes_36k_train_011767
6,876
permissive
[ { "docstring": "Draws text in the specified place, in the appropriate colour", "name": "draw_text", "signature": "def draw_text(surface, text, colour, x_pos, y_pos, custom_text=None)" }, { "docstring": "Construct a buffer that contains which pixels to draw (=1) to make text", "name": "make_t...
2
null
Implement the Python class `TextWriter` described below. Class description: Implement the TextWriter class. Method signatures and docstrings: - def draw_text(surface, text, colour, x_pos, y_pos, custom_text=None): Draws text in the specified place, in the appropriate colour - def make_text(string, custom_text=None): ...
Implement the Python class `TextWriter` described below. Class description: Implement the TextWriter class. Method signatures and docstrings: - def draw_text(surface, text, colour, x_pos, y_pos, custom_text=None): Draws text in the specified place, in the appropriate colour - def make_text(string, custom_text=None): ...
7780b5425883e2af88d28d73ec8f3d2f8bd624bf
<|skeleton|> class TextWriter: def draw_text(surface, text, colour, x_pos, y_pos, custom_text=None): """Draws text in the specified place, in the appropriate colour""" <|body_0|> def make_text(string, custom_text=None): """Construct a buffer that contains which pixels to draw (=1) to m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextWriter: def draw_text(surface, text, colour, x_pos, y_pos, custom_text=None): """Draws text in the specified place, in the appropriate colour""" text_buffer = TextWriter.make_text(text, custom_text) width = len(text_buffer) height = 0 if width > 0: heigh...
the_stack_v2_python_sparse
software/controller/lib/text.py
fraz3alpha/led-disco-dancefloor
train
0
c7b1f4ea8a523c6a5ca42c0e9f0173c80b430ef7
[ "res = super(account_invoice, self).create(cr, uid, vals, context=context)\nif 'calc_taxes_done' not in ['context']:\n self.button_reset_taxes(cr, uid, [res], context)\nreturn res", "res = super(account_invoice, self).write(cr, uid, ids, vals, context=context)\nif 'calc_taxes_done' not in ['context']:\n sel...
<|body_start_0|> res = super(account_invoice, self).create(cr, uid, vals, context=context) if 'calc_taxes_done' not in ['context']: self.button_reset_taxes(cr, uid, [res], context) return res <|end_body_0|> <|body_start_1|> res = super(account_invoice, self).write(cr, uid, i...
account_invoice
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class account_invoice: def create(self, cr, uid, vals, context=None): """Compute the taxes when the invoice is created""" <|body_0|> def write(self, cr, uid, ids, vals, context=None): """Compute the taxes when the invoice is saved""" <|body_1|> def button_rese...
stack_v2_sparse_classes_36k_train_011768
2,579
no_license
[ { "docstring": "Compute the taxes when the invoice is created", "name": "create", "signature": "def create(self, cr, uid, vals, context=None)" }, { "docstring": "Compute the taxes when the invoice is saved", "name": "write", "signature": "def write(self, cr, uid, ids, vals, context=None)...
3
stack_v2_sparse_classes_30k_train_002569
Implement the Python class `account_invoice` described below. Class description: Implement the account_invoice class. Method signatures and docstrings: - def create(self, cr, uid, vals, context=None): Compute the taxes when the invoice is created - def write(self, cr, uid, ids, vals, context=None): Compute the taxes ...
Implement the Python class `account_invoice` described below. Class description: Implement the account_invoice class. Method signatures and docstrings: - def create(self, cr, uid, vals, context=None): Compute the taxes when the invoice is created - def write(self, cr, uid, ids, vals, context=None): Compute the taxes ...
6eeb48468792e09d46d61b89499467a44d67bc79
<|skeleton|> class account_invoice: def create(self, cr, uid, vals, context=None): """Compute the taxes when the invoice is created""" <|body_0|> def write(self, cr, uid, ids, vals, context=None): """Compute the taxes when the invoice is saved""" <|body_1|> def button_rese...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class account_invoice: def create(self, cr, uid, vals, context=None): """Compute the taxes when the invoice is created""" res = super(account_invoice, self).create(cr, uid, vals, context=context) if 'calc_taxes_done' not in ['context']: self.button_reset_taxes(cr, uid, [res], con...
the_stack_v2_python_sparse
account_invoice_compute_taxes/account_invoice_compute_taxes.py
smart-solution/natuurpunt-finance
train
0
7fe80a38e380b7477140933718ba1a4e4ab8d501
[ "super(DMPNN, self).__init__()\nself.mode: str = mode\nself.n_classes: int = n_classes\nself.n_tasks: int = n_tasks\nself.encoder: nn.Module = layers.DMPNNEncoderLayer(use_default_fdim=use_default_fdim, atom_fdim=atom_fdim, bond_fdim=bond_fdim, d_hidden=enc_hidden, depth=depth, bias=bias, activation=enc_activation,...
<|body_start_0|> super(DMPNN, self).__init__() self.mode: str = mode self.n_classes: int = n_classes self.n_tasks: int = n_tasks self.encoder: nn.Module = layers.DMPNNEncoderLayer(use_default_fdim=use_default_fdim, atom_fdim=atom_fdim, bond_fdim=bond_fdim, d_hidden=enc_hidden, de...
Directed Message Passing Neural Network In this class, we define the various encoder layers and establish a sequential model for the Directed Message Passing Neural Network (D-MPNN) [1]_. We also define the forward call of this model in the forward function. Example ------- >>> import deepchem as dc >>> from torch_geom...
DMPNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DMPNN: """Directed Message Passing Neural Network In this class, we define the various encoder layers and establish a sequential model for the Directed Message Passing Neural Network (D-MPNN) [1]_. We also define the forward call of this model in the forward function. Example ------- >>> import d...
stack_v2_sparse_classes_36k_train_011769
31,166
permissive
[ { "docstring": "Initialize the DMPNN class. Parameters ---------- mode: str, default 'regression' The model type - classification or regression. n_classes: int, default 3 The number of classes to predict (used only in classification mode). n_tasks: int, default 1 The number of tasks. global_features_size: int, ...
2
null
Implement the Python class `DMPNN` described below. Class description: Directed Message Passing Neural Network In this class, we define the various encoder layers and establish a sequential model for the Directed Message Passing Neural Network (D-MPNN) [1]_. We also define the forward call of this model in the forward...
Implement the Python class `DMPNN` described below. Class description: Directed Message Passing Neural Network In this class, we define the various encoder layers and establish a sequential model for the Directed Message Passing Neural Network (D-MPNN) [1]_. We also define the forward call of this model in the forward...
ee6e67ebcf7bf04259cf13aff6388e2b791fea3d
<|skeleton|> class DMPNN: """Directed Message Passing Neural Network In this class, we define the various encoder layers and establish a sequential model for the Directed Message Passing Neural Network (D-MPNN) [1]_. We also define the forward call of this model in the forward function. Example ------- >>> import d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DMPNN: """Directed Message Passing Neural Network In this class, we define the various encoder layers and establish a sequential model for the Directed Message Passing Neural Network (D-MPNN) [1]_. We also define the forward call of this model in the forward function. Example ------- >>> import deepchem as dc...
the_stack_v2_python_sparse
deepchem/models/torch_models/dmpnn.py
deepchem/deepchem
train
4,876
b87f95828974a114651d6da3830cd65aca75cf03
[ "iris_prefix_found = re.search('^iris', self.metric_name, re.IGNORECASE)\nself.metric_name = self.metric_name if iris_prefix_found else 'iris_{}'.format(self.metric_name)\nself.help_str = '# HELP {} {}'.format(self.metric_name, self.help_str)\nself.type_str = '# TYPE {} {}'.format(self.metric_name, self.type_str)",...
<|body_start_0|> iris_prefix_found = re.search('^iris', self.metric_name, re.IGNORECASE) self.metric_name = self.metric_name if iris_prefix_found else 'iris_{}'.format(self.metric_name) self.help_str = '# HELP {} {}'.format(self.metric_name, self.help_str) self.type_str = '# TYPE {} {}'....
The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from :param help_str: the help string that desc...
PromStrBuilder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PromStrBuilder: """The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from ...
stack_v2_sparse_classes_36k_train_011770
5,963
no_license
[ { "docstring": "Add the iris_ prefix to the metric if it is not in the metric name. Create the help_str and type_str :return: None", "name": "__post_init__", "signature": "def __post_init__(self) -> None" }, { "docstring": "Create the prom string from the metric we executed :return: the metric r...
3
stack_v2_sparse_classes_30k_train_010876
Implement the Python class `PromStrBuilder` described below. Class description: The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metr...
Implement the Python class `PromStrBuilder` described below. Class description: The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metr...
e66651af2c4e106d8c05999ac1137a4b9a58f29f
<|skeleton|> class PromStrBuilder: """The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PromStrBuilder: """The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from :param help_s...
the_stack_v2_python_sparse
iris/utils/prom_helpers.py
dzhang30/Iris
train
0
411c31dd9eeb0e05a1c4bd281c2f27d8701be9a4
[ "qs = super().get_queryset(*args, **kwargs)\nqs = qs.annotate(camp_expenses_amount=Sum('credebtors__expenses__amount', filter=Q(credebtors__expenses__camp=self.camp), distinct=True), camp_expenses_count=Count('credebtors__expenses', filter=Q(credebtors__expenses__camp=self.camp), distinct=True), camp_revenues_amoun...
<|body_start_0|> qs = super().get_queryset(*args, **kwargs) qs = qs.annotate(camp_expenses_amount=Sum('credebtors__expenses__amount', filter=Q(credebtors__expenses__camp=self.camp), distinct=True), camp_expenses_count=Count('credebtors__expenses', filter=Q(credebtors__expenses__camp=self.camp), distinct...
ChainDetailView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChainDetailView: def get_queryset(self, *args, **kwargs): """Annotate the Chain object with the camp filtered expense and revenue info.""" <|body_0|> def get_context_data(self, *args, **kwargs): """Add credebtors, expenses and revenues to the context in camp-filtered...
stack_v2_sparse_classes_36k_train_011771
34,955
permissive
[ { "docstring": "Annotate the Chain object with the camp filtered expense and revenue info.", "name": "get_queryset", "signature": "def get_queryset(self, *args, **kwargs)" }, { "docstring": "Add credebtors, expenses and revenues to the context in camp-filtered versions.", "name": "get_contex...
2
null
Implement the Python class `ChainDetailView` described below. Class description: Implement the ChainDetailView class. Method signatures and docstrings: - def get_queryset(self, *args, **kwargs): Annotate the Chain object with the camp filtered expense and revenue info. - def get_context_data(self, *args, **kwargs): A...
Implement the Python class `ChainDetailView` described below. Class description: Implement the ChainDetailView class. Method signatures and docstrings: - def get_queryset(self, *args, **kwargs): Annotate the Chain object with the camp filtered expense and revenue info. - def get_context_data(self, *args, **kwargs): A...
767deb7f58429e9162e0c2ef79be9f0f38f37ce1
<|skeleton|> class ChainDetailView: def get_queryset(self, *args, **kwargs): """Annotate the Chain object with the camp filtered expense and revenue info.""" <|body_0|> def get_context_data(self, *args, **kwargs): """Add credebtors, expenses and revenues to the context in camp-filtered...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChainDetailView: def get_queryset(self, *args, **kwargs): """Annotate the Chain object with the camp filtered expense and revenue info.""" qs = super().get_queryset(*args, **kwargs) qs = qs.annotate(camp_expenses_amount=Sum('credebtors__expenses__amount', filter=Q(credebtors__expenses_...
the_stack_v2_python_sparse
src/backoffice/views/economy.py
bornhack/bornhack-website
train
9
1f4d2024b7947bc36e64f67048c304a826941225
[ "super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=30))\nself.device = device\nself.paired_device = paired_device", "try:\n async with asyncio.timeout(10):\n device_state_resp = await self.device.fetch_state()\n device_state = device_state_resp.data.get(ATTR_DEVICE_ST...
<|body_start_0|> super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=30)) self.device = device self.paired_device = paired_device <|end_body_0|> <|body_start_1|> try: async with asyncio.timeout(10): device_state_resp = await self.de...
YoLink DataUpdateCoordinator.
YoLinkCoordinator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YoLinkCoordinator: """YoLink DataUpdateCoordinator.""" def __init__(self, hass: HomeAssistant, device: YoLinkDevice, paired_device: YoLinkDevice | None=None) -> None: """Init YoLink DataUpdateCoordinator. fetch state every 30 minutes base on yolink device heartbeat interval data is N...
stack_v2_sparse_classes_36k_train_011772
2,414
permissive
[ { "docstring": "Init YoLink DataUpdateCoordinator. fetch state every 30 minutes base on yolink device heartbeat interval data is None before the first successful update, but we need to use data at first update", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, device: YoLinkDevi...
2
null
Implement the Python class `YoLinkCoordinator` described below. Class description: YoLink DataUpdateCoordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, device: YoLinkDevice, paired_device: YoLinkDevice | None=None) -> None: Init YoLink DataUpdateCoordinator. fetch state every 30 m...
Implement the Python class `YoLinkCoordinator` described below. Class description: YoLink DataUpdateCoordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, device: YoLinkDevice, paired_device: YoLinkDevice | None=None) -> None: Init YoLink DataUpdateCoordinator. fetch state every 30 m...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class YoLinkCoordinator: """YoLink DataUpdateCoordinator.""" def __init__(self, hass: HomeAssistant, device: YoLinkDevice, paired_device: YoLinkDevice | None=None) -> None: """Init YoLink DataUpdateCoordinator. fetch state every 30 minutes base on yolink device heartbeat interval data is N...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class YoLinkCoordinator: """YoLink DataUpdateCoordinator.""" def __init__(self, hass: HomeAssistant, device: YoLinkDevice, paired_device: YoLinkDevice | None=None) -> None: """Init YoLink DataUpdateCoordinator. fetch state every 30 minutes base on yolink device heartbeat interval data is None before th...
the_stack_v2_python_sparse
homeassistant/components/yolink/coordinator.py
home-assistant/core
train
35,501
f96f67e348bfb38cc7be3fbe27fb651be9cc8066
[ "assert 'variables' not in kwds, 'variables parameter is useless.'\nif 'method' not in kwds:\n import hysop.default_methods as default\n kwds['method'] = default.BAROCLINIC\nsuper(BaroclinicFromRHS, self).__init__(variables=[vorticity, rhs], **kwds)\nself.vorticity = vorticity\nself.rhs = rhs\nself.input = [s...
<|body_start_0|> assert 'variables' not in kwds, 'variables parameter is useless.' if 'method' not in kwds: import hysop.default_methods as default kwds['method'] = default.BAROCLINIC super(BaroclinicFromRHS, self).__init__(variables=[vorticity, rhs], **kwds) self...
TODO : describe this operator ...
BaroclinicFromRHS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaroclinicFromRHS: """TODO : describe this operator ...""" def __init__(self, vorticity, rhs, **kwds): """Constructor. Create the baroclinic term in the N.S. equations with a given -GradRho/rho x GradP/rho term as the rhs field. @param vorticity : discretization of the vorticity fiel...
stack_v2_sparse_classes_36k_train_011773
2,183
no_license
[ { "docstring": "Constructor. Create the baroclinic term in the N.S. equations with a given -GradRho/rho x GradP/rho term as the rhs field. @param vorticity : discretization of the vorticity field @param rhs : right hand side of the term", "name": "__init__", "signature": "def __init__(self, vorticity, r...
2
stack_v2_sparse_classes_30k_train_001218
Implement the Python class `BaroclinicFromRHS` described below. Class description: TODO : describe this operator ... Method signatures and docstrings: - def __init__(self, vorticity, rhs, **kwds): Constructor. Create the baroclinic term in the N.S. equations with a given -GradRho/rho x GradP/rho term as the rhs field...
Implement the Python class `BaroclinicFromRHS` described below. Class description: TODO : describe this operator ... Method signatures and docstrings: - def __init__(self, vorticity, rhs, **kwds): Constructor. Create the baroclinic term in the N.S. equations with a given -GradRho/rho x GradP/rho term as the rhs field...
60e9535ece75321367b19f1daf13e1ae014d6e81
<|skeleton|> class BaroclinicFromRHS: """TODO : describe this operator ...""" def __init__(self, vorticity, rhs, **kwds): """Constructor. Create the baroclinic term in the N.S. equations with a given -GradRho/rho x GradP/rho term as the rhs field. @param vorticity : discretization of the vorticity fiel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaroclinicFromRHS: """TODO : describe this operator ...""" def __init__(self, vorticity, rhs, **kwds): """Constructor. Create the baroclinic term in the N.S. equations with a given -GradRho/rho x GradP/rho term as the rhs field. @param vorticity : discretization of the vorticity field @param rhs ...
the_stack_v2_python_sparse
hysop/operator/discrete/baroclinic_from_rhs.py
ljktest/tmp-tests
train
0
dcad37a8101e1054ceb0404e5dcec42041a1f2a3
[ "BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise)\nself.veh_id = veh_id\nself.v_max = v_max\nself.adaptation = adaptation\nself.h_st = h_st", "this_vel = env.k.vehicle.get_speed(self.veh_id)\nh = env.k.vehicle.get_headway(self.veh_id)\nalpha = 1.689\n...
<|body_start_0|> BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise) self.veh_id = veh_id self.v_max = v_max self.adaptation = adaptation self.h_st = h_st <|end_body_0|> <|body_start_1|> this_vel = env.k.vehicle...
Linear OVM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class v_max : float max velocity (default: 30) adaptation : float adaptation constant (default: 0.65) h...
LinearOVM
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearOVM: """Linear OVM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class v_max : float max velocity (default: 30) adaptation : float ...
stack_v2_sparse_classes_36k_train_011774
17,548
permissive
[ { "docstring": "Instantiate a Linear OVM controller.", "name": "__init__", "signature": "def __init__(self, veh_id, car_following_params, v_max=30, adaptation=0.65, h_st=5, time_delay=0.0, noise=0, fail_safe=None)" }, { "docstring": "See parent class.", "name": "get_accel", "signature": ...
2
stack_v2_sparse_classes_30k_train_000013
Implement the Python class `LinearOVM` described below. Class description: Linear OVM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class v_max : float max vel...
Implement the Python class `LinearOVM` described below. Class description: Linear OVM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class v_max : float max vel...
badac3da17f04d8d8ae5691ee8ba2af9d56fac35
<|skeleton|> class LinearOVM: """Linear OVM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class v_max : float max velocity (default: 30) adaptation : float ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearOVM: """Linear OVM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class v_max : float max velocity (default: 30) adaptation : float adaptation co...
the_stack_v2_python_sparse
flow/controllers/car_following_models.py
parthjaggi/flow
train
6
e99fd102efb4cf06f571cf7ace677bb46a600cbc
[ "self.v1 = v1\nself.v2 = v2\nself.p1 = 0\nself.p2 = 0\nself.n1 = len(v1)\nself.n2 = len(v2)\nself.first = True", "if self.first and self.p1 < self.n1 or self.p2 >= self.n2:\n self.first = False\n res = self.v1[self.p1]\n self.p1 += 1\nelse:\n self.first = True\n res = self.v2[self.p2]\n self.p2 ...
<|body_start_0|> self.v1 = v1 self.v2 = v2 self.p1 = 0 self.p2 = 0 self.n1 = len(v1) self.n2 = len(v2) self.first = True <|end_body_0|> <|body_start_1|> if self.first and self.p1 < self.n1 or self.p2 >= self.n2: self.first = False ...
ZigzagIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end...
stack_v2_sparse_classes_36k_train_011775
1,045
no_license
[ { "docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]", "name": "__init__", "signature": "def __init__(self, v1, v2)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": ":rtype: bool", "name"...
3
stack_v2_sparse_classes_30k_train_016978
Implement the Python class `ZigzagIterator` described below. Class description: Implement the ZigzagIterator class. Method signatures and docstrings: - def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int] - def next(self): :rtype: int - def hasNext(self): :rtype: bo...
Implement the Python class `ZigzagIterator` described below. Class description: Implement the ZigzagIterator class. Method signatures and docstrings: - def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int] - def next(self): :rtype: int - def hasNext(self): :rtype: bo...
917bd000c2a055dfa2633440a61ca4ae2b665fe3
<|skeleton|> class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" self.v1 = v1 self.v2 = v2 self.p1 = 0 self.p2 = 0 self.n1 = len(v1) self.n2 = len(v2) self.first = True def next(s...
the_stack_v2_python_sparse
281_zigzag-iterator.py
Khrystynka/LeetCodeProblems
train
0
d78df71049cfb1e7e54845c62e33baf609c54001
[ "super(Semaphore, self).__init__()\nself.size = size\nself.semaphore = threading.BoundedSemaphore(size)\nreturn", "self.logger.debug('Acquiring the semaphore')\nself.semaphore.acquire()\nreturn", "self.logger.debug('releasing {n} times'.format(n=value))\nfor i in repeat(None, times=value):\n self.semaphore.r...
<|body_start_0|> super(Semaphore, self).__init__() self.size = size self.semaphore = threading.BoundedSemaphore(size) return <|end_body_0|> <|body_start_1|> self.logger.debug('Acquiring the semaphore') self.semaphore.acquire() return <|end_body_1|> <|body_start_...
Implements a Semaphore using Alan Downey's notation. This is an unbounded semaphore so it can release more than it has acquired
Semaphore
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Semaphore: """Implements a Semaphore using Alan Downey's notation. This is an unbounded semaphore so it can release more than it has acquired""" def __init__(self, size=1): """:param: - `size`: The number of threads to wait for.""" <|body_0|> def wait(self): """D...
stack_v2_sparse_classes_36k_train_011776
1,353
permissive
[ { "docstring": ":param: - `size`: The number of threads to wait for.", "name": "__init__", "signature": "def __init__(self, size=1)" }, { "docstring": "Decrements the semaphore if > 0, waits if it is 0", "name": "wait", "signature": "def wait(self)" }, { "docstring": "Increments ...
4
null
Implement the Python class `Semaphore` described below. Class description: Implements a Semaphore using Alan Downey's notation. This is an unbounded semaphore so it can release more than it has acquired Method signatures and docstrings: - def __init__(self, size=1): :param: - `size`: The number of threads to wait for...
Implement the Python class `Semaphore` described below. Class description: Implements a Semaphore using Alan Downey's notation. This is an unbounded semaphore so it can release more than it has acquired Method signatures and docstrings: - def __init__(self, size=1): :param: - `size`: The number of threads to wait for...
b4d1c77e1d611fe2b30768b42bdc7493afb0ea95
<|skeleton|> class Semaphore: """Implements a Semaphore using Alan Downey's notation. This is an unbounded semaphore so it can release more than it has acquired""" def __init__(self, size=1): """:param: - `size`: The number of threads to wait for.""" <|body_0|> def wait(self): """D...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Semaphore: """Implements a Semaphore using Alan Downey's notation. This is an unbounded semaphore so it can release more than it has acquired""" def __init__(self, size=1): """:param: - `size`: The number of threads to wait for.""" super(Semaphore, self).__init__() self.size = siz...
the_stack_v2_python_sparse
apetools/threads/semaphore.py
russell-n/oldape
train
0
14415d1bf0ecba1515660f051b621434cc25e66b
[ "self.price = price\nself.quantity = quantity\nself.total = total\nself.delay_start = delay_start\nself.id = id\nself.level_1 = level_1\nself.level_2 = level_2\nself.offer_to_affiliates = offer_to_affiliates\nself.owner = owner\nself.setup_fee = setup_fee\nself.setup_fee_date = setup_fee_date\nself.setup_fee_when =...
<|body_start_0|> self.price = price self.quantity = quantity self.total = total self.delay_start = delay_start self.id = id self.level_1 = level_1 self.level_2 = level_2 self.offer_to_affiliates = offer_to_affiliates self.owner = owner self...
Implementation of the 'Product' model. TODO: type model description here. Attributes: price (list of Price): TODO: type description here. quantity (int): How many of this product are being purchased? total (float): What is the total amount of this sale? delay_start (int): Days to delay start. id (int): This must be an ...
Product
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Product: """Implementation of the 'Product' model. TODO: type model description here. Attributes: price (list of Price): TODO: type description here. quantity (int): How many of this product are being purchased? total (float): What is the total amount of this sale? delay_start (int): Days to dela...
stack_v2_sparse_classes_36k_train_011777
7,834
permissive
[ { "docstring": "Constructor for the Product class", "name": "__init__", "signature": "def __init__(self, price=None, quantity=None, total=None, delay_start=None, id=None, level_1=None, level_2=None, offer_to_affiliates=False, owner=None, setup_fee=None, setup_fee_date=None, setup_fee_when=None, shipping...
2
stack_v2_sparse_classes_30k_train_012399
Implement the Python class `Product` described below. Class description: Implementation of the 'Product' model. TODO: type model description here. Attributes: price (list of Price): TODO: type description here. quantity (int): How many of this product are being purchased? total (float): What is the total amount of thi...
Implement the Python class `Product` described below. Class description: Implementation of the 'Product' model. TODO: type model description here. Attributes: price (list of Price): TODO: type description here. quantity (int): How many of this product are being purchased? total (float): What is the total amount of thi...
fb4834e89b897dce3475c89c7e6c34bf8756880e
<|skeleton|> class Product: """Implementation of the 'Product' model. TODO: type model description here. Attributes: price (list of Price): TODO: type description here. quantity (int): How many of this product are being purchased? total (float): What is the total amount of this sale? delay_start (int): Days to dela...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Product: """Implementation of the 'Product' model. TODO: type model description here. Attributes: price (list of Price): TODO: type description here. quantity (int): How many of this product are being purchased? total (float): What is the total amount of this sale? delay_start (int): Days to delay start. id (...
the_stack_v2_python_sparse
ontraportlib/models/product.py
LifePosts/ontraportlib
train
0
3400dbab0f9a3edb08d4b4528b4c878bc68bf906
[ "out_file = open(file_path, 'w')\njson.dump(data, out_file, indent=4)\nout_file.close()", "try:\n with open(file_path) as f:\n return json.load(f)\nexcept IOError as e:\n print('could not read ' + file_path)" ]
<|body_start_0|> out_file = open(file_path, 'w') json.dump(data, out_file, indent=4) out_file.close() <|end_body_0|> <|body_start_1|> try: with open(file_path) as f: return json.load(f) except IOError as e: print('could not read ' + file_p...
This class handles writing data objects to files and loading in data objects
MyJsonHandler
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyJsonHandler: """This class handles writing data objects to files and loading in data objects""" def save_data_to_json_file(data, file_path): """Store data as json in designated file_path""" <|body_0|> def get_data_from_json_file(file_path): """get data as json ...
stack_v2_sparse_classes_36k_train_011778
704
permissive
[ { "docstring": "Store data as json in designated file_path", "name": "save_data_to_json_file", "signature": "def save_data_to_json_file(data, file_path)" }, { "docstring": "get data as json in designated file_path and returns the loaded json", "name": "get_data_from_json_file", "signatur...
2
stack_v2_sparse_classes_30k_train_007111
Implement the Python class `MyJsonHandler` described below. Class description: This class handles writing data objects to files and loading in data objects Method signatures and docstrings: - def save_data_to_json_file(data, file_path): Store data as json in designated file_path - def get_data_from_json_file(file_pat...
Implement the Python class `MyJsonHandler` described below. Class description: This class handles writing data objects to files and loading in data objects Method signatures and docstrings: - def save_data_to_json_file(data, file_path): Store data as json in designated file_path - def get_data_from_json_file(file_pat...
20d8df6172906337f81583dabb841d66b8f31857
<|skeleton|> class MyJsonHandler: """This class handles writing data objects to files and loading in data objects""" def save_data_to_json_file(data, file_path): """Store data as json in designated file_path""" <|body_0|> def get_data_from_json_file(file_path): """get data as json ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyJsonHandler: """This class handles writing data objects to files and loading in data objects""" def save_data_to_json_file(data, file_path): """Store data as json in designated file_path""" out_file = open(file_path, 'w') json.dump(data, out_file, indent=4) out_file.clos...
the_stack_v2_python_sparse
new_algs/Number+theoretic+algorithms/Euclidean+algorithm/myjsonhandler.py
coolsnake/JupyterNotebook
train
0
f336cd96cf813ec8daa9f4ea73b96fa49779c260
[ "super(Interface, self).__init__(name, line_number)\nself.lines = lines\nself.source = source_file", "all_subroutines = []\nroutine_re = re.compile('^\\\\s*MODULE PROCEDURE ([A-Z0-9_]+)', re.IGNORECASE)\nvarying_string_re1 = re.compile('VSC*(Obj|Number|)[0-9]*$', re.IGNORECASE)\nvarying_string_re2 = re.compile('V...
<|body_start_0|> super(Interface, self).__init__(name, line_number) self.lines = lines self.source = source_file <|end_body_0|> <|body_start_1|> all_subroutines = [] routine_re = re.compile('^\\s*MODULE PROCEDURE ([A-Z0-9_]+)', re.IGNORECASE) varying_string_re1 = re.comp...
Information on an interface
Interface
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interface: """Information on an interface""" def __init__(self, name, line_number, lines, source_file): """Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines -- Contents of interface as a list of lines source_file -- ...
stack_v2_sparse_classes_36k_train_011779
28,119
no_license
[ { "docstring": "Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines -- Contents of interface as a list of lines source_file -- Source file containing the interface", "name": "__init__", "signature": "def __init__(self, name, line_number, ...
3
stack_v2_sparse_classes_30k_train_014538
Implement the Python class `Interface` described below. Class description: Information on an interface Method signatures and docstrings: - def __init__(self, name, line_number, lines, source_file): Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines --...
Implement the Python class `Interface` described below. Class description: Information on an interface Method signatures and docstrings: - def __init__(self, name, line_number, lines, source_file): Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines --...
38c0755396efea44feb87a4c01b5e956d6736691
<|skeleton|> class Interface: """Information on an interface""" def __init__(self, name, line_number, lines, source_file): """Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines -- Contents of interface as a list of lines source_file -- ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Interface: """Information on an interface""" def __init__(self, name, line_number, lines, source_file): """Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines -- Contents of interface as a list of lines source_file -- Source file c...
the_stack_v2_python_sparse
bindings/generate_bindings/parse.py
OpenCMISS/iron
train
10
21ed2d9ce79d50a07d917a02c99ea4a1e17ec838
[ "def walk(root, lower, upper):\n if not root:\n return True\n if root.val > lower and root.val < upper:\n return walk(root.left, lower, root.val) and walk(root.right, root.val, upper)\n else:\n return False\nreturn walk(root, float('-inf'), float('inf'))", "def isValid(root, smaller,...
<|body_start_0|> def walk(root, lower, upper): if not root: return True if root.val > lower and root.val < upper: return walk(root.left, lower, root.val) and walk(root.right, root.val, upper) else: return False return wa...
ValidBST
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidBST: def isValidBST(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isValidBST2(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> def walk(root, lower, upper): if n...
stack_v2_sparse_classes_36k_train_011780
942
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isValidBST", "signature": "def isValidBST(self, root)" }, { "docstring": ":type root: TreeNode :rtype: bool", "name": "isValidBST2", "signature": "def isValidBST2(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_001716
Implement the Python class `ValidBST` described below. Class description: Implement the ValidBST class. Method signatures and docstrings: - def isValidBST(self, root): :type root: TreeNode :rtype: bool - def isValidBST2(self, root): :type root: TreeNode :rtype: bool
Implement the Python class `ValidBST` described below. Class description: Implement the ValidBST class. Method signatures and docstrings: - def isValidBST(self, root): :type root: TreeNode :rtype: bool - def isValidBST2(self, root): :type root: TreeNode :rtype: bool <|skeleton|> class ValidBST: def isValidBST(s...
e7f486114df17918e49d6452c7047c9d90e8aef2
<|skeleton|> class ValidBST: def isValidBST(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isValidBST2(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidBST: def isValidBST(self, root): """:type root: TreeNode :rtype: bool""" def walk(root, lower, upper): if not root: return True if root.val > lower and root.val < upper: return walk(root.left, lower, root.val) and walk(root.right, ro...
the_stack_v2_python_sparse
tranquil-beach/tree/valid_bst.py
yokolet/tranquil-beach-python
train
0
63042da00f72c17ed5f78d701ddad9fc91cdcf7b
[ "\"\"\"\n 1) Get image schema\n 2) Verify the response status code is 200\n \"\"\"\nresponse = self.api_client.get_image_schema()\nimage_schema = response.entity\nself.assertEqual(200, response.status_code)", "\"\"\"\n 1) Get images schema\n 2) Verify the response status code is...
<|body_start_0|> """ 1) Get image schema 2) Verify the response status code is 200 """ response = self.api_client.get_image_schema() image_schema = response.entity self.assertEqual(200, response.status_code) <|end_body_0|> <|body_start_1|>...
Test the retrieval of schema details for images
GetImagesSchemaTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetImagesSchemaTest: """Test the retrieval of schema details for images""" def test_get_image_schema(self): """Get schema that represents an image entity.""" <|body_0|> def test_get_images_schema(self): """Get schema that represents an images entity.""" <...
stack_v2_sparse_classes_36k_train_011781
1,531
permissive
[ { "docstring": "Get schema that represents an image entity.", "name": "test_get_image_schema", "signature": "def test_get_image_schema(self)" }, { "docstring": "Get schema that represents an images entity.", "name": "test_get_images_schema", "signature": "def test_get_images_schema(self)...
2
stack_v2_sparse_classes_30k_test_000111
Implement the Python class `GetImagesSchemaTest` described below. Class description: Test the retrieval of schema details for images Method signatures and docstrings: - def test_get_image_schema(self): Get schema that represents an image entity. - def test_get_images_schema(self): Get schema that represents an images...
Implement the Python class `GetImagesSchemaTest` described below. Class description: Test the retrieval of schema details for images Method signatures and docstrings: - def test_get_image_schema(self): Get schema that represents an image entity. - def test_get_images_schema(self): Get schema that represents an images...
b2e69c7f5657ee1f1cc7f03c8af18effb3c41cb6
<|skeleton|> class GetImagesSchemaTest: """Test the retrieval of schema details for images""" def test_get_image_schema(self): """Get schema that represents an image entity.""" <|body_0|> def test_get_images_schema(self): """Get schema that represents an images entity.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetImagesSchemaTest: """Test the retrieval of schema details for images""" def test_get_image_schema(self): """Get schema that represents an image entity.""" """ 1) Get image schema 2) Verify the response status code is 200 """ respo...
the_stack_v2_python_sparse
cloudroast/images/v2/functional/test_get_images_schema.py
ProjectMeniscus/cloudroast
train
0
b42dd1c39c764de5bf8748cc1c6c64253337a8a9
[ "diff_file_blink_h = ['some diff']\ndiff_file_chromium_h = ['another diff']\ndiff_file_test_expectations = ['more diff']\nmock_input_api = MockInputApi()\nmock_python_file = MockAffectedFile('file_blink.py', ['lint me'])\nmock_input_api.files = [MockAffectedFile('file_blink.h', diff_file_blink_h), MockAffectedFile(...
<|body_start_0|> diff_file_blink_h = ['some diff'] diff_file_chromium_h = ['another diff'] diff_file_test_expectations = ['more diff'] mock_input_api = MockInputApi() mock_python_file = MockAffectedFile('file_blink.py', ['lint me']) mock_input_api.files = [MockAffectedFil...
PresubmitTest
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PresubmitTest: def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): """This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files.""" <|body_0|> def testCheckChangeOnUploadWithEmptyAffectedFileList(self, _)...
stack_v2_sparse_classes_36k_train_011782
10,881
permissive
[ { "docstring": "This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files.", "name": "testCheckChangeOnUploadWithBlinkAndChromiumFiles", "signature": "def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint)" }, { "docstring": "Thi...
5
stack_v2_sparse_classes_30k_train_006515
Implement the Python class `PresubmitTest` described below. Class description: Implement the PresubmitTest class. Method signatures and docstrings: - def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): This verifies that CheckChangeOnUpload will only call check_blink_style.py on no...
Implement the Python class `PresubmitTest` described below. Class description: Implement the PresubmitTest class. Method signatures and docstrings: - def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): This verifies that CheckChangeOnUpload will only call check_blink_style.py on no...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class PresubmitTest: def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): """This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files.""" <|body_0|> def testCheckChangeOnUploadWithEmptyAffectedFileList(self, _)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PresubmitTest: def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): """This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files.""" diff_file_blink_h = ['some diff'] diff_file_chromium_h = ['another diff'] d...
the_stack_v2_python_sparse
third_party/blink/PRESUBMIT_test.py
chromium/chromium
train
17,408
05fb71d0c6f5a87a89a792ee13d84accffdc2ace
[ "book_url = response.xpath(\"//*[@class='content']/h6/a/@href\").extract()\nbook_url = [url.replace('xxs', 'xxss') for url in book_url]\nend_flag = response.xpath(\"//*[@class='page']/a[last()-1]/text()\").extract_first()\nfor url in book_url:\n yield scrapy.Request(url=url, callback=self.middle_page)\nprint(f'h...
<|body_start_0|> book_url = response.xpath("//*[@class='content']/h6/a/@href").extract() book_url = [url.replace('xxs', 'xxss') for url in book_url] end_flag = response.xpath("//*[@class='page']/a[last()-1]/text()").extract_first() for url in book_url: yield scrapy.Request(ur...
M23swSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class M23swSpider: def parse(self, response): """书目录""" <|body_0|> def middle_page(self, response): """小说目录页""" <|body_1|> def content(self, response): """小说章节页的数据""" <|body_2|> <|end_skeleton|> <|body_start_0|> book_url = response.xp...
stack_v2_sparse_classes_36k_train_011783
2,871
no_license
[ { "docstring": "书目录", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "小说目录页", "name": "middle_page", "signature": "def middle_page(self, response)" }, { "docstring": "小说章节页的数据", "name": "content", "signature": "def content(self, response)" }...
3
stack_v2_sparse_classes_30k_test_000496
Implement the Python class `M23swSpider` described below. Class description: Implement the M23swSpider class. Method signatures and docstrings: - def parse(self, response): 书目录 - def middle_page(self, response): 小说目录页 - def content(self, response): 小说章节页的数据
Implement the Python class `M23swSpider` described below. Class description: Implement the M23swSpider class. Method signatures and docstrings: - def parse(self, response): 书目录 - def middle_page(self, response): 小说目录页 - def content(self, response): 小说章节页的数据 <|skeleton|> class M23swSpider: def parse(self, respon...
ba9a8dd9a62f60df7130d2240628b7969800c647
<|skeleton|> class M23swSpider: def parse(self, response): """书目录""" <|body_0|> def middle_page(self, response): """小说目录页""" <|body_1|> def content(self, response): """小说章节页的数据""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class M23swSpider: def parse(self, response): """书目录""" book_url = response.xpath("//*[@class='content']/h6/a/@href").extract() book_url = [url.replace('xxs', 'xxss') for url in book_url] end_flag = response.xpath("//*[@class='page']/a[last()-1]/text()").extract_first() for u...
the_stack_v2_python_sparse
SpiderPractice/m23sw_all/m23sw_all/spiders/m23sw.py
mafiadarm/Python-Practice
train
0
7ac5c4e35615c6a2f6efe675af93ca2ac42efe6d
[ "super().__init__(**kwargs)\nself.filename = filename\nself.site = site or pywikibot.Site()\nself.page_regex, self.title_regex = self._make_regexes()", "if self.opt.textonly:\n pattern = '^(.*)$'\nelse:\n pattern = re.escape(self.opt.begin) + '(.*?)' + re.escape(self.opt.end)\npage_regex = re.compile(patter...
<|body_start_0|> super().__init__(**kwargs) self.filename = filename self.site = site or pywikibot.Site() self.page_regex, self.title_regex = self._make_regexes() <|end_body_0|> <|body_start_1|> if self.opt.textonly: pattern = '^(.*)$' else: patte...
Generator class, responsible for reading the file. .. versionchanged:: 7.6 subclassed from :class:`pywikibot.tools.collections.GeneratorWrapper`
PageFromFileReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PageFromFileReader: """Generator class, responsible for reading the file. .. versionchanged:: 7.6 subclassed from :class:`pywikibot.tools.collections.GeneratorWrapper`""" def __init__(self, filename, site=None, **kwargs) -> None: """Initializer.""" <|body_0|> def _make_r...
stack_v2_sparse_classes_36k_train_011784
11,900
permissive
[ { "docstring": "Initializer.", "name": "__init__", "signature": "def __init__(self, filename, site=None, **kwargs) -> None" }, { "docstring": "Make regex from options.", "name": "_make_regexes", "signature": "def _make_regexes(self)" }, { "docstring": "Read file and yield a page ...
4
null
Implement the Python class `PageFromFileReader` described below. Class description: Generator class, responsible for reading the file. .. versionchanged:: 7.6 subclassed from :class:`pywikibot.tools.collections.GeneratorWrapper` Method signatures and docstrings: - def __init__(self, filename, site=None, **kwargs) -> ...
Implement the Python class `PageFromFileReader` described below. Class description: Generator class, responsible for reading the file. .. versionchanged:: 7.6 subclassed from :class:`pywikibot.tools.collections.GeneratorWrapper` Method signatures and docstrings: - def __init__(self, filename, site=None, **kwargs) -> ...
5c01e6bfcd328bc6eae643e661f1a0ae57612808
<|skeleton|> class PageFromFileReader: """Generator class, responsible for reading the file. .. versionchanged:: 7.6 subclassed from :class:`pywikibot.tools.collections.GeneratorWrapper`""" def __init__(self, filename, site=None, **kwargs) -> None: """Initializer.""" <|body_0|> def _make_r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PageFromFileReader: """Generator class, responsible for reading the file. .. versionchanged:: 7.6 subclassed from :class:`pywikibot.tools.collections.GeneratorWrapper`""" def __init__(self, filename, site=None, **kwargs) -> None: """Initializer.""" super().__init__(**kwargs) self....
the_stack_v2_python_sparse
scripts/pagefromfile.py
wikimedia/pywikibot
train
432
ff280ca47a570d71f3d240773b4776ff55a925c4
[ "bd = {'title': bundle.obj.minus.title, 'id': bundle.obj.minus.id, 'resource_uri': '/api/v1/minusrecord/%s/' % bundle.obj.minus.id, 'length': bundle.obj.minus.length, 'filesize': bundle.obj.minus.filesize, 'file': bundle.obj.minus.file.url}\nbd['author_name'] = bundle.obj.minus.author.name\nbd['filetype'] = str(bun...
<|body_start_0|> bd = {'title': bundle.obj.minus.title, 'id': bundle.obj.minus.id, 'resource_uri': '/api/v1/minusrecord/%s/' % bundle.obj.minus.id, 'length': bundle.obj.minus.length, 'filesize': bundle.obj.minus.filesize, 'file': bundle.obj.minus.file.url} bd['author_name'] = bundle.obj.minus.author.nam...
MinusWeekStatsResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MinusWeekStatsResource: def _dehydrate_short(self, bundle): """put foreignkey data into the serialized bundle""" <|body_0|> def _dehydrate_full(self, bundle): """put foreignkey data into the serialized bundle""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_011785
5,016
no_license
[ { "docstring": "put foreignkey data into the serialized bundle", "name": "_dehydrate_short", "signature": "def _dehydrate_short(self, bundle)" }, { "docstring": "put foreignkey data into the serialized bundle", "name": "_dehydrate_full", "signature": "def _dehydrate_full(self, bundle)" ...
2
null
Implement the Python class `MinusWeekStatsResource` described below. Class description: Implement the MinusWeekStatsResource class. Method signatures and docstrings: - def _dehydrate_short(self, bundle): put foreignkey data into the serialized bundle - def _dehydrate_full(self, bundle): put foreignkey data into the s...
Implement the Python class `MinusWeekStatsResource` described below. Class description: Implement the MinusWeekStatsResource class. Method signatures and docstrings: - def _dehydrate_short(self, bundle): put foreignkey data into the serialized bundle - def _dehydrate_full(self, bundle): put foreignkey data into the s...
c61267e5a19142c2b7030534b24a2b7f97d0deb2
<|skeleton|> class MinusWeekStatsResource: def _dehydrate_short(self, bundle): """put foreignkey data into the serialized bundle""" <|body_0|> def _dehydrate_full(self, bundle): """put foreignkey data into the serialized bundle""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MinusWeekStatsResource: def _dehydrate_short(self, bundle): """put foreignkey data into the serialized bundle""" bd = {'title': bundle.obj.minus.title, 'id': bundle.obj.minus.id, 'resource_uri': '/api/v1/minusrecord/%s/' % bundle.obj.minus.id, 'length': bundle.obj.minus.length, 'filesize': bun...
the_stack_v2_python_sparse
modules/minusstore/api.py
ibitprogress/minus-master
train
0
dc5062f9ae292324c6a6279004d2e86cb35dd55c
[ "self._filepath = filepath\nself._autofill = autofill\nself._sep = sep\nself._host = socket.gethostname()\nself._user = getpass.getuser()\nself._autotext = '%s%s%s%s' % (self._host, self._sep, self._user, self._sep) if self._autofill is True else ''\nif printheader is False and os.path.exists(self._filepath) is Fal...
<|body_start_0|> self._filepath = filepath self._autofill = autofill self._sep = sep self._host = socket.gethostname() self._user = getpass.getuser() self._autotext = '%s%s%s%s' % (self._host, self._sep, self._user, self._sep) if self._autofill is True else '' if ...
This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. (i.e.: printheader=True, headertext='some,header,text,here') On class instantiation, validation is performed to determine if the log file exists. If the log file d...
Log
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Log: """This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. (i.e.: printheader=True, headertext='some,header,text,here') On class instantiation, validation is performed to determine if the log...
stack_v2_sparse_classes_36k_train_011786
7,510
permissive
[ { "docstring": "Class initialiser.", "name": "__init__", "signature": "def __init__(self, filepath, autofill=True, printheader=False, headertext='', sep=',')" }, { "docstring": "Write text to the log file defined at instantiation. Args: text (str): Delimited text string to be written to the log....
3
stack_v2_sparse_classes_30k_train_010340
Implement the Python class `Log` described below. Class description: This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. (i.e.: printheader=True, headertext='some,header,text,here') On class instantiation, validati...
Implement the Python class `Log` described below. Class description: This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. (i.e.: printheader=True, headertext='some,header,text,here') On class instantiation, validati...
824bee75ecd756b9097581e5cf5929b389a74240
<|skeleton|> class Log: """This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. (i.e.: printheader=True, headertext='some,header,text,here') On class instantiation, validation is performed to determine if the log...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Log: """This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. (i.e.: printheader=True, headertext='some,header,text,here') On class instantiation, validation is performed to determine if the log file exists....
the_stack_v2_python_sparse
build/lib/utils3/log.py
S3DEV/utils3
train
0
92a26ea192637dcdf422b462a446a22806887140
[ "super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.num_filters = num_filters\nself.num_pool_layers = num_pool_layers\nself.dropout_probability = dropout_probability\nself.down_sample_layers = nn.ModuleList([MultiDomainConvBlock(forward_operator, backward_operator, in_channel...
<|body_start_0|> super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.num_filters = num_filters self.num_pool_layers = num_pool_layers self.dropout_probability = dropout_probability self.down_sample_layers = nn.ModuleList([MultiD...
Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge.
MultiDomainUnet2d
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiDomainUnet2d: """Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge.""" def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, num_filters: int, num_pool_layers: in...
stack_v2_sparse_classes_36k_train_011787
11,794
permissive
[ { "docstring": "Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_channels: int Number of input channels to the u-net. out_channels: int Number of output channels to the u-net. num_filters: int Number of output channels of the first convolutiona...
2
stack_v2_sparse_classes_30k_train_001868
Implement the Python class `MultiDomainUnet2d` described below. Class description: Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge. Method signatures and docstrings: - def __init__(self, forward_operator: Callable, backward_operator: Callable, in_cha...
Implement the Python class `MultiDomainUnet2d` described below. Class description: Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge. Method signatures and docstrings: - def __init__(self, forward_operator: Callable, backward_operator: Callable, in_cha...
2a4c29342bc52a404aae097bc2654fb4323e1ac8
<|skeleton|> class MultiDomainUnet2d: """Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge.""" def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, num_filters: int, num_pool_layers: in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiDomainUnet2d: """Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge.""" def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, num_filters: int, num_pool_layers: int, dropout_pr...
the_stack_v2_python_sparse
direct/nn/multidomainnet/multidomain.py
NKI-AI/direct
train
151
32d62d93df88ed9350aba218d19f3a16dbf707c7
[ "proc_mounts = 'rootfs / rootfs rw 0 0\\nnone /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0\\nnone /proc proc rw,nosuid,nodev,noexec,relatime 0 0\\nnone /dev devtmpfs rw,relatime,size=4056920k,nr_inodes=1014230,mode=755 0 0\\nnone /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0\\n/dev/map...
<|body_start_0|> proc_mounts = 'rootfs / rootfs rw 0 0\nnone /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0\nnone /proc proc rw,nosuid,nodev,noexec,relatime 0 0\nnone /dev devtmpfs rw,relatime,size=4056920k,nr_inodes=1014230,mode=755 0 0\nnone /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=00...
Test the linux client utils.
ClientUtilsLinuxTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientUtilsLinuxTest: """Test the linux client utils.""" def testLinuxGetRawDevice(self): """Test the parser for linux mounts.""" <|body_0|> def testLinuxTransactionLog(self): """Tests the linux transaction log.""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_011788
4,763
permissive
[ { "docstring": "Test the parser for linux mounts.", "name": "testLinuxGetRawDevice", "signature": "def testLinuxGetRawDevice(self)" }, { "docstring": "Tests the linux transaction log.", "name": "testLinuxTransactionLog", "signature": "def testLinuxTransactionLog(self)" } ]
2
stack_v2_sparse_classes_30k_train_012648
Implement the Python class `ClientUtilsLinuxTest` described below. Class description: Test the linux client utils. Method signatures and docstrings: - def testLinuxGetRawDevice(self): Test the parser for linux mounts. - def testLinuxTransactionLog(self): Tests the linux transaction log.
Implement the Python class `ClientUtilsLinuxTest` described below. Class description: Test the linux client utils. Method signatures and docstrings: - def testLinuxGetRawDevice(self): Test the parser for linux mounts. - def testLinuxTransactionLog(self): Tests the linux transaction log. <|skeleton|> class ClientUtil...
44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6
<|skeleton|> class ClientUtilsLinuxTest: """Test the linux client utils.""" def testLinuxGetRawDevice(self): """Test the parser for linux mounts.""" <|body_0|> def testLinuxTransactionLog(self): """Tests the linux transaction log.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClientUtilsLinuxTest: """Test the linux client utils.""" def testLinuxGetRawDevice(self): """Test the parser for linux mounts.""" proc_mounts = 'rootfs / rootfs rw 0 0\nnone /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0\nnone /proc proc rw,nosuid,nodev,noexec,relatime 0 0\nnone /dev devt...
the_stack_v2_python_sparse
grr/client/grr_response_client/linux/client_utils_linux_test.py
google/grr
train
4,683
3244bf8ea0d56d10eea595fbe67aa8ccbe21fafd
[ "super(OnSidewalkTest, self).__init__(name, actor, 0, None, optional)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._map = CarlaDataProvider.get_map()\nself._onsidewalk_active = False\nself.positive_shift = shapely.geometry.LineString([(0, 0), (0.0, 1.2)])\nself.negative_s...
<|body_start_0|> super(OnSidewalkTest, self).__init__(name, actor, 0, None, optional) self.logger.debug('%s.__init__()' % self.__class__.__name__) self._actor = actor self._map = CarlaDataProvider.get_map() self._onsidewalk_active = False self.positive_shift = shapely.geo...
This class contains an atomic test to detect sidewalk invasions. Important parameters: - actor: CARLA actor to be used for this test - optional [optional]: If True, the result is not considered for an overall pass/fail result
OnSidewalkTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OnSidewalkTest: """This class contains an atomic test to detect sidewalk invasions. Important parameters: - actor: CARLA actor to be used for this test - optional [optional]: If True, the result is not considered for an overall pass/fail result""" def __init__(self, actor, optional=False, na...
stack_v2_sparse_classes_36k_train_011789
44,616
permissive
[ { "docstring": "Construction with sensor setup", "name": "__init__", "signature": "def __init__(self, actor, optional=False, name='OnSidewalkTest')" }, { "docstring": "Check lane invasion count", "name": "update", "signature": "def update(self)" } ]
2
null
Implement the Python class `OnSidewalkTest` described below. Class description: This class contains an atomic test to detect sidewalk invasions. Important parameters: - actor: CARLA actor to be used for this test - optional [optional]: If True, the result is not considered for an overall pass/fail result Method signa...
Implement the Python class `OnSidewalkTest` described below. Class description: This class contains an atomic test to detect sidewalk invasions. Important parameters: - actor: CARLA actor to be used for this test - optional [optional]: If True, the result is not considered for an overall pass/fail result Method signa...
8ab0894b92e1f994802a218002021ee075c405bf
<|skeleton|> class OnSidewalkTest: """This class contains an atomic test to detect sidewalk invasions. Important parameters: - actor: CARLA actor to be used for this test - optional [optional]: If True, the result is not considered for an overall pass/fail result""" def __init__(self, actor, optional=False, na...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OnSidewalkTest: """This class contains an atomic test to detect sidewalk invasions. Important parameters: - actor: CARLA actor to be used for this test - optional [optional]: If True, the result is not considered for an overall pass/fail result""" def __init__(self, actor, optional=False, name='OnSidewal...
the_stack_v2_python_sparse
carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_criteria.py
TinaMenke/Deep-Reinforcement-Learning
train
9
f46989d4ad19be0294b5e48975f596d4f111f3b6
[ "if not process.is_active:\n raise serializers.ValidationError('Process {} is not active.'.format(process))\nreturn process", "if self.instance and self.instance.collection != collection:\n self.instance.validate_change_collection(collection)\nreturn collection", "update_collection = 'collection' in valid...
<|body_start_0|> if not process.is_active: raise serializers.ValidationError('Process {} is not active.'.format(process)) return process <|end_body_0|> <|body_start_1|> if self.instance and self.instance.collection != collection: self.instance.validate_change_collection(...
Serializer for Data objects.
DataSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataSerializer: """Serializer for Data objects.""" def validate_process(self, process): """Check that process is active.""" <|body_0|> def validate_collection(self, collection): """Verify that changing collection is done in the right place.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_011790
3,632
permissive
[ { "docstring": "Check that process is active.", "name": "validate_process", "signature": "def validate_process(self, process)" }, { "docstring": "Verify that changing collection is done in the right place.", "name": "validate_collection", "signature": "def validate_collection(self, colle...
3
stack_v2_sparse_classes_30k_train_013003
Implement the Python class `DataSerializer` described below. Class description: Serializer for Data objects. Method signatures and docstrings: - def validate_process(self, process): Check that process is active. - def validate_collection(self, collection): Verify that changing collection is done in the right place. -...
Implement the Python class `DataSerializer` described below. Class description: Serializer for Data objects. Method signatures and docstrings: - def validate_process(self, process): Check that process is active. - def validate_collection(self, collection): Verify that changing collection is done in the right place. -...
25c0c45235ef37beb45c1af4c917fbbae6282016
<|skeleton|> class DataSerializer: """Serializer for Data objects.""" def validate_process(self, process): """Check that process is active.""" <|body_0|> def validate_collection(self, collection): """Verify that changing collection is done in the right place.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataSerializer: """Serializer for Data objects.""" def validate_process(self, process): """Check that process is active.""" if not process.is_active: raise serializers.ValidationError('Process {} is not active.'.format(process)) return process def validate_collect...
the_stack_v2_python_sparse
resolwe/flow/serializers/data.py
genialis/resolwe
train
35
bb71e87b760f753c42a94c827740976d42b9be58
[ "if not numRows:\n return []\noutput = [[1]]\nfor i in range(1, numRows):\n row = []\n for j in range(i + 1):\n if j == 0:\n row.append(output[i - 1][0])\n elif j == i:\n row.append(output[i - 1][-1])\n else:\n row.append(output[i - 1][j - 1] + output[i...
<|body_start_0|> if not numRows: return [] output = [[1]] for i in range(1, numRows): row = [] for j in range(i + 1): if j == 0: row.append(output[i - 1][0]) elif j == i: row.append(output...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_0|> def generate_terse(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not numRows: ...
stack_v2_sparse_classes_36k_train_011791
1,574
no_license
[ { "docstring": ":type numRows: int :rtype: List[List[int]]", "name": "generate", "signature": "def generate(self, numRows)" }, { "docstring": ":type numRows: int :rtype: List[List[int]]", "name": "generate_terse", "signature": "def generate_terse(self, numRows)" } ]
2
stack_v2_sparse_classes_30k_train_020103
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate(self, numRows): :type numRows: int :rtype: List[List[int]] - def generate_terse(self, numRows): :type numRows: int :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate(self, numRows): :type numRows: int :rtype: List[List[int]] - def generate_terse(self, numRows): :type numRows: int :rtype: List[List[int]] <|skeleton|> class Soluti...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_0|> def generate_terse(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" if not numRows: return [] output = [[1]] for i in range(1, numRows): row = [] for j in range(i + 1): if j == 0: row.ap...
the_stack_v2_python_sparse
src/lt_118.py
oxhead/CodingYourWay
train
0
4098019b631071b929d9b152789846d53222acaa
[ "super().__init__(coordinator)\nself.entity_description = description\nself._device_id = device_id\nself._attr_unique_id = f'{device_id}_{description.key}'\nself._attr_name = sensor.display_name\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, device_id)}, name=device.name, hw_version=device.hardware_vers...
<|body_start_0|> super().__init__(coordinator) self.entity_description = description self._device_id = device_id self._attr_unique_id = f'{device_id}_{description.key}' self._attr_name = sensor.display_name self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, device_...
Representation of an Oncue entity.
OncueEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OncueEntity: """Representation of an Oncue entity.""" def __init__(self, coordinator: DataUpdateCoordinator[dict[str, OncueDevice]], device_id: str, device: OncueDevice, sensor: OncueSensor, description: EntityDescription) -> None: """Initialize the sensor.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_011792
3,156
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, coordinator: DataUpdateCoordinator[dict[str, OncueDevice]], device_id: str, device: OncueDevice, sensor: OncueSensor, description: EntityDescription) -> None" }, { "docstring": "Return the sensor value....
3
null
Implement the Python class `OncueEntity` described below. Class description: Representation of an Oncue entity. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator[dict[str, OncueDevice]], device_id: str, device: OncueDevice, sensor: OncueSensor, description: EntityDescription) -...
Implement the Python class `OncueEntity` described below. Class description: Representation of an Oncue entity. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator[dict[str, OncueDevice]], device_id: str, device: OncueDevice, sensor: OncueSensor, description: EntityDescription) -...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class OncueEntity: """Representation of an Oncue entity.""" def __init__(self, coordinator: DataUpdateCoordinator[dict[str, OncueDevice]], device_id: str, device: OncueDevice, sensor: OncueSensor, description: EntityDescription) -> None: """Initialize the sensor.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OncueEntity: """Representation of an Oncue entity.""" def __init__(self, coordinator: DataUpdateCoordinator[dict[str, OncueDevice]], device_id: str, device: OncueDevice, sensor: OncueSensor, description: EntityDescription) -> None: """Initialize the sensor.""" super().__init__(coordinator...
the_stack_v2_python_sparse
homeassistant/components/oncue/entity.py
home-assistant/core
train
35,501
122df3ae9a84ecd450297c5b04a97b349ea1bc6b
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceAndAppManagementRoleAssignment()", "from .role_assignment import RoleAssignment\nfrom .role_assignment import RoleAssignment\nfields: Dict[str, Callable[[Any], None]] = {'members': lambda n: setattr(self, 'members', n.get_collect...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return DeviceAndAppManagementRoleAssignment() <|end_body_0|> <|body_start_1|> from .role_assignment import RoleAssignment from .role_assignment import RoleAssignment fields: Dict[str, C...
The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles.
DeviceAndAppManagementRoleAssignment
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceAndAppManagementRoleAssignment: """The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles.""" def create_from_discriminator_value(parse_node: Op...
stack_v2_sparse_classes_36k_train_011793
2,440
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DeviceAndAppManagementRoleAssignment", "name": "create_from_discriminator_value", "signature": "def create_f...
3
null
Implement the Python class `DeviceAndAppManagementRoleAssignment` described below. Class description: The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles. Method signatures ...
Implement the Python class `DeviceAndAppManagementRoleAssignment` described below. Class description: The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles. Method signatures ...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class DeviceAndAppManagementRoleAssignment: """The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles.""" def create_from_discriminator_value(parse_node: Op...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeviceAndAppManagementRoleAssignment: """The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles.""" def create_from_discriminator_value(parse_node: Optional[ParseN...
the_stack_v2_python_sparse
msgraph/generated/models/device_and_app_management_role_assignment.py
microsoftgraph/msgraph-sdk-python
train
135
9aa80106342f775b26660553f7057706494b7e96
[ "super(UpBlock, self).__init__(in_channels, general_args.kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck)\nself.subpixel = SubPixel1D(in_channels=sum(channel_sizes), out_channels=sum(channel_sizes) // general_args.upscale_factor, upscale_factor=general_args.upscale_factor)\nself.dropout = nn.Dropou...
<|body_start_0|> super(UpBlock, self).__init__(in_channels, general_args.kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck) self.subpixel = SubPixel1D(in_channels=sum(channel_sizes), out_channels=sum(channel_sizes) // general_args.upscale_factor, upscale_factor=general_args.upscale_factor...
UpBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpBlock: def __init__(self, in_channels, channel_sizes, bottleneck_channels, use_bottleneck, general_args): """Initializes the class UpBlock that inherits its main properties from BaseBlock. UpBlock is the main ingredient of the decoding part of both the generator and the auto-encoder. :...
stack_v2_sparse_classes_36k_train_011794
1,951
no_license
[ { "docstring": "Initializes the class UpBlock that inherits its main properties from BaseBlock. UpBlock is the main ingredient of the decoding part of both the generator and the auto-encoder. :param in_channels: number of channels of the input tensor (scalar int). :param channel_sizes: number of filters for eac...
2
stack_v2_sparse_classes_30k_train_013938
Implement the Python class `UpBlock` described below. Class description: Implement the UpBlock class. Method signatures and docstrings: - def __init__(self, in_channels, channel_sizes, bottleneck_channels, use_bottleneck, general_args): Initializes the class UpBlock that inherits its main properties from BaseBlock. U...
Implement the Python class `UpBlock` described below. Class description: Implement the UpBlock class. Method signatures and docstrings: - def __init__(self, in_channels, channel_sizes, bottleneck_channels, use_bottleneck, general_args): Initializes the class UpBlock that inherits its main properties from BaseBlock. U...
76c4537d605bdf6f46586aa245c8bdec64fc4ec1
<|skeleton|> class UpBlock: def __init__(self, in_channels, channel_sizes, bottleneck_channels, use_bottleneck, general_args): """Initializes the class UpBlock that inherits its main properties from BaseBlock. UpBlock is the main ingredient of the decoding part of both the generator and the auto-encoder. :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpBlock: def __init__(self, in_channels, channel_sizes, bottleneck_channels, use_bottleneck, general_args): """Initializes the class UpBlock that inherits its main properties from BaseBlock. UpBlock is the main ingredient of the decoding part of both the generator and the auto-encoder. :param in_chann...
the_stack_v2_python_sparse
blocks/up_block.py
aosbro/audio-super-resolution
train
0
73e8babfd5e0e672e15a5b6968724ece0cf6a44c
[ "highlight = get_object_or_404(highlights, pk=pk)\nuser = request.user\nhighlight.highlightsvoters.remove(user)\nhighlight.save()\nserializer_context = {'request': request}\nserializer = self.serializer_class(highlight, context=serializer_context)\nreturn Response(serializer.data, status=status.HTTP_200_OK)", "hi...
<|body_start_0|> highlight = get_object_or_404(highlights, pk=pk) user = request.user highlight.highlightsvoters.remove(user) highlight.save() serializer_context = {'request': request} serializer = self.serializer_class(highlight, context=serializer_context) retur...
Allow users to add/remove a like to/from an answer instance.
HighlightsLikeAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HighlightsLikeAPIView: """Allow users to add/remove a like to/from an answer instance.""" def delete(self, request, pk): """Remove request.user from the voters queryset of an answer instance.""" <|body_0|> def post(self, request, pk): """Add request.user to the v...
stack_v2_sparse_classes_36k_train_011795
10,756
no_license
[ { "docstring": "Remove request.user from the voters queryset of an answer instance.", "name": "delete", "signature": "def delete(self, request, pk)" }, { "docstring": "Add request.user to the voters queryset of an answer instance.", "name": "post", "signature": "def post(self, request, p...
2
stack_v2_sparse_classes_30k_train_003339
Implement the Python class `HighlightsLikeAPIView` described below. Class description: Allow users to add/remove a like to/from an answer instance. Method signatures and docstrings: - def delete(self, request, pk): Remove request.user from the voters queryset of an answer instance. - def post(self, request, pk): Add ...
Implement the Python class `HighlightsLikeAPIView` described below. Class description: Allow users to add/remove a like to/from an answer instance. Method signatures and docstrings: - def delete(self, request, pk): Remove request.user from the voters queryset of an answer instance. - def post(self, request, pk): Add ...
e74237fd26226afa108d981c95e962c72ab4b11a
<|skeleton|> class HighlightsLikeAPIView: """Allow users to add/remove a like to/from an answer instance.""" def delete(self, request, pk): """Remove request.user from the voters queryset of an answer instance.""" <|body_0|> def post(self, request, pk): """Add request.user to the v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HighlightsLikeAPIView: """Allow users to add/remove a like to/from an answer instance.""" def delete(self, request, pk): """Remove request.user from the voters queryset of an answer instance.""" highlight = get_object_or_404(highlights, pk=pk) user = request.user highlight...
the_stack_v2_python_sparse
battlesoccer/app/api/views.py
battlesocce/tournament
train
0
60b2fba24c18be3fd65449e31e24574a42f9166d
[ "super(AnaphoraDocumentGraph, self).__init__()\nself.name = name if name else os.path.basename(anaphora_filepath)\nself.ns = namespace\nself.root = self.ns + ':root_node'\nself.tokens = []\nif anaphora_filepath:\n self.add_node(self.root, layers={self.ns})\n with open(anaphora_filepath, 'r') as anno_file:\n ...
<|body_start_0|> super(AnaphoraDocumentGraph, self).__init__() self.name = name if name else os.path.basename(anaphora_filepath) self.ns = namespace self.root = self.ns + ':root_node' self.tokens = [] if anaphora_filepath: self.add_node(self.root, layers={self...
represents a text in which abstract anaphora were annotated as a graph. Attributes ---------- ns : str the namespace of the graph (default: anaphoricity) tokens : list of int a list of node IDs (int) which represent the tokens in the order they occur in the text root : str name of the document root node ID (default: se...
AnaphoraDocumentGraph
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnaphoraDocumentGraph: """represents a text in which abstract anaphora were annotated as a graph. Attributes ---------- ns : str the namespace of the graph (default: anaphoricity) tokens : list of int a list of node IDs (int) which represent the tokens in the order they occur in the text root : s...
stack_v2_sparse_classes_36k_train_011796
7,148
permissive
[ { "docstring": "Reads an abstract anaphora annotation file, creates a directed graph and adds a node for each token, as well as an edge from the root node to each token. If a token is annotated, it will have a 'namespace:annotation' attribute, which maps to a dict with the keys 'anaphoricity' (str) and 'certain...
2
stack_v2_sparse_classes_30k_train_011029
Implement the Python class `AnaphoraDocumentGraph` described below. Class description: represents a text in which abstract anaphora were annotated as a graph. Attributes ---------- ns : str the namespace of the graph (default: anaphoricity) tokens : list of int a list of node IDs (int) which represent the tokens in th...
Implement the Python class `AnaphoraDocumentGraph` described below. Class description: represents a text in which abstract anaphora were annotated as a graph. Attributes ---------- ns : str the namespace of the graph (default: anaphoricity) tokens : list of int a list of node IDs (int) which represent the tokens in th...
108fea5a7f61030a9c11708296e06ee8ccfd7783
<|skeleton|> class AnaphoraDocumentGraph: """represents a text in which abstract anaphora were annotated as a graph. Attributes ---------- ns : str the namespace of the graph (default: anaphoricity) tokens : list of int a list of node IDs (int) which represent the tokens in the order they occur in the text root : s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnaphoraDocumentGraph: """represents a text in which abstract anaphora were annotated as a graph. Attributes ---------- ns : str the namespace of the graph (default: anaphoricity) tokens : list of int a list of node IDs (int) which represent the tokens in the order they occur in the text root : str name of th...
the_stack_v2_python_sparse
src/discoursegraphs/readwrite/anaphoricity.py
dav009/discoursegraphs
train
1
f72172eac2c6d21542d8b35978e52d69bbc8cf3e
[ "flask_config = config.flask_config[config.FLASK_ENV]\nlog_conf = flask_config.LOGGER_CONF\npath = os.path.join(config.BASEDIR, log_conf['path'])\nif not os.path.isdir(path):\n os.makedirs(path)\nlogger = logging.getLogger()\nlogger.setLevel(log_conf['level'])\nhandler = logging.StreamHandler()\nhandler.setForma...
<|body_start_0|> flask_config = config.flask_config[config.FLASK_ENV] log_conf = flask_config.LOGGER_CONF path = os.path.join(config.BASEDIR, log_conf['path']) if not os.path.isdir(path): os.makedirs(path) logger = logging.getLogger() logger.setLevel(log_conf[...
FlaskApp
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlaskApp: def init_logger(cls): """日志配置 :return:""" <|body_0|> def init_extensions(cls, _app): """初始化第三方插件 :param _app: :return:""" <|body_1|> def create_app(cls, service_name, config_name): """根据config name创建不同环境下的app :param service_name: 服务名称就是...
stack_v2_sparse_classes_36k_train_011797
3,975
no_license
[ { "docstring": "日志配置 :return:", "name": "init_logger", "signature": "def init_logger(cls)" }, { "docstring": "初始化第三方插件 :param _app: :return:", "name": "init_extensions", "signature": "def init_extensions(cls, _app)" }, { "docstring": "根据config name创建不同环境下的app :param service_name:...
3
null
Implement the Python class `FlaskApp` described below. Class description: Implement the FlaskApp class. Method signatures and docstrings: - def init_logger(cls): 日志配置 :return: - def init_extensions(cls, _app): 初始化第三方插件 :param _app: :return: - def create_app(cls, service_name, config_name): 根据config name创建不同环境下的app :p...
Implement the Python class `FlaskApp` described below. Class description: Implement the FlaskApp class. Method signatures and docstrings: - def init_logger(cls): 日志配置 :return: - def init_extensions(cls, _app): 初始化第三方插件 :param _app: :return: - def create_app(cls, service_name, config_name): 根据config name创建不同环境下的app :p...
ff36deb73e667de16a73b1666bbeaf28f993f944
<|skeleton|> class FlaskApp: def init_logger(cls): """日志配置 :return:""" <|body_0|> def init_extensions(cls, _app): """初始化第三方插件 :param _app: :return:""" <|body_1|> def create_app(cls, service_name, config_name): """根据config name创建不同环境下的app :param service_name: 服务名称就是...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlaskApp: def init_logger(cls): """日志配置 :return:""" flask_config = config.flask_config[config.FLASK_ENV] log_conf = flask_config.LOGGER_CONF path = os.path.join(config.BASEDIR, log_conf['path']) if not os.path.isdir(path): os.makedirs(path) logger = ...
the_stack_v2_python_sparse
backend/app/app.py
LyanJin/check-pay
train
0
5d48017fb1950f08a3b9488176dd2339e84ea943
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuthenticationStrengthPolicy()", "from .authentication_combination_configuration import AuthenticationCombinationConfiguration\nfrom .authentication_method_modes import AuthenticationMethodModes\nfrom .authentication_strength_policy_ty...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return AuthenticationStrengthPolicy() <|end_body_0|> <|body_start_1|> from .authentication_combination_configuration import AuthenticationCombinationConfiguration from .authentication_method_mo...
AuthenticationStrengthPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthenticationStrengthPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationStrengthPolicy: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value...
stack_v2_sparse_classes_36k_train_011798
5,616
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AuthenticationStrengthPolicy", "name": "create_from_discriminator_value", "signature": "def create_from_disc...
3
null
Implement the Python class `AuthenticationStrengthPolicy` described below. Class description: Implement the AuthenticationStrengthPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationStrengthPolicy: Creates a new instance of the a...
Implement the Python class `AuthenticationStrengthPolicy` described below. Class description: Implement the AuthenticationStrengthPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationStrengthPolicy: Creates a new instance of the a...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class AuthenticationStrengthPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationStrengthPolicy: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthenticationStrengthPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationStrengthPolicy: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th...
the_stack_v2_python_sparse
msgraph/generated/models/authentication_strength_policy.py
microsoftgraph/msgraph-sdk-python
train
135
bf85f25e540c2ec927089e40f668f0f160bca552
[ "super(Cell, self).__init__()\nself.desc = desc\nself.drop_path_prob = desc.get('drop_path_prob') or 0", "affine = True\nif isinstance(self.desc.genotype[0][0], list):\n affine = False\nif self.reduction_prev:\n self.preprocess0 = FactorizedReduce(self.C_prev_prev, self.C, affine)\nelse:\n self.preproces...
<|body_start_0|> super(Cell, self).__init__() self.desc = desc self.drop_path_prob = desc.get('drop_path_prob') or 0 <|end_body_0|> <|body_start_1|> affine = True if isinstance(self.desc.genotype[0][0], list): affine = False if self.reduction_prev: ...
Cell structure according to desc.
Cell
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cell: """Cell structure according to desc.""" def __init__(self, desc): """Init Cell.""" <|body_0|> def build(self): """Build Cell.""" <|body_1|> def _compile(self, C, op_names, indices_out, indices_inp, concat, reduction): """Compile the cel...
stack_v2_sparse_classes_36k_train_011799
6,558
permissive
[ { "docstring": "Init Cell.", "name": "__init__", "signature": "def __init__(self, desc)" }, { "docstring": "Build Cell.", "name": "build", "signature": "def build(self)" }, { "docstring": "Compile the cell. :param C: channels of this cell :type C: int :param op_names: list of all...
4
null
Implement the Python class `Cell` described below. Class description: Cell structure according to desc. Method signatures and docstrings: - def __init__(self, desc): Init Cell. - def build(self): Build Cell. - def _compile(self, C, op_names, indices_out, indices_inp, concat, reduction): Compile the cell. :param C: ch...
Implement the Python class `Cell` described below. Class description: Cell structure according to desc. Method signatures and docstrings: - def __init__(self, desc): Init Cell. - def build(self): Build Cell. - def _compile(self, C, op_names, indices_out, indices_inp, concat, reduction): Compile the cell. :param C: ch...
df51ed9c1d6dbde1deef63f2a037a369f8554406
<|skeleton|> class Cell: """Cell structure according to desc.""" def __init__(self, desc): """Init Cell.""" <|body_0|> def build(self): """Build Cell.""" <|body_1|> def _compile(self, C, op_names, indices_out, indices_inp, concat, reduction): """Compile the cel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cell: """Cell structure according to desc.""" def __init__(self, desc): """Init Cell.""" super(Cell, self).__init__() self.desc = desc self.drop_path_prob = desc.get('drop_path_prob') or 0 def build(self): """Build Cell.""" affine = True if isi...
the_stack_v2_python_sparse
built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/fine_grained_space/operators/darts.py
Huawei-Ascend/modelzoo
train
1