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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
796cfb8e71990ec8a252dc775aaff0e21be06e15 | [
"self.vocab = vocab\nself.unk_token = unk_token\nself.normalize_text = normalize_text",
"if self.normalize_text:\n text = unicodedata.normalize('NFKC', text)\noutput_tokens = []\nfor char in text:\n if char not in self.vocab:\n output_tokens.append(self.unk_token)\n continue\n output_tokens... | <|body_start_0|>
self.vocab = vocab
self.unk_token = unk_token
self.normalize_text = normalize_text
<|end_body_0|>
<|body_start_1|>
if self.normalize_text:
text = unicodedata.normalize('NFKC', text)
output_tokens = []
for char in text:
if char not... | Runs Character tokenization. | CharacterTokenizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharacterTokenizer:
"""Runs Character tokenization."""
def __init__(self, vocab, unk_token, normalize_text=True):
"""Constructs a CharacterTokenizer. Args: **vocab**: Vocabulary object. **unk_token**: str A special symbol for out-of-vocabulary token. **normalize_text**: (`optional`) ... | stack_v2_sparse_classes_36k_train_030300 | 40,187 | permissive | [
{
"docstring": "Constructs a CharacterTokenizer. Args: **vocab**: Vocabulary object. **unk_token**: str A special symbol for out-of-vocabulary token. **normalize_text**: (`optional`) boolean (default True) Whether to apply unicode normalization to text before tokenization.",
"name": "__init__",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_005879 | Implement the Python class `CharacterTokenizer` described below.
Class description:
Runs Character tokenization.
Method signatures and docstrings:
- def __init__(self, vocab, unk_token, normalize_text=True): Constructs a CharacterTokenizer. Args: **vocab**: Vocabulary object. **unk_token**: str A special symbol for o... | Implement the Python class `CharacterTokenizer` described below.
Class description:
Runs Character tokenization.
Method signatures and docstrings:
- def __init__(self, vocab, unk_token, normalize_text=True): Constructs a CharacterTokenizer. Args: **vocab**: Vocabulary object. **unk_token**: str A special symbol for o... | 4fa0aff21ee083d0197a898cdf17ff476fae2ac3 | <|skeleton|>
class CharacterTokenizer:
"""Runs Character tokenization."""
def __init__(self, vocab, unk_token, normalize_text=True):
"""Constructs a CharacterTokenizer. Args: **vocab**: Vocabulary object. **unk_token**: str A special symbol for out-of-vocabulary token. **normalize_text**: (`optional`) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharacterTokenizer:
"""Runs Character tokenization."""
def __init__(self, vocab, unk_token, normalize_text=True):
"""Constructs a CharacterTokenizer. Args: **vocab**: Vocabulary object. **unk_token**: str A special symbol for out-of-vocabulary token. **normalize_text**: (`optional`) boolean (defa... | the_stack_v2_python_sparse | src/transformers/models/bert_japanese/tokenization_bert_japanese.py | huggingface/transformers | train | 102,193 |
96647a534284a3a0c57ba511cb75f8bb8cd45ddb | [
"session = db_apis.get_session()\nwith session.begin():\n loadbalancer = self.loadbalancer_repo.get(session, id=loadbalancer_id)\nif loadbalancer:\n self.amphora_driver.update(loadbalancer)\nelse:\n LOG.error('Load balancer %s for listeners update not found. Skipping update.', loadbalancer_id)",
"LOG.war... | <|body_start_0|>
session = db_apis.get_session()
with session.begin():
loadbalancer = self.loadbalancer_repo.get(session, id=loadbalancer_id)
if loadbalancer:
self.amphora_driver.update(loadbalancer)
else:
LOG.error('Load balancer %s for listeners upda... | Task to update amphora with all specified listeners' configurations. | ListenersUpdate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListenersUpdate:
"""Task to update amphora with all specified listeners' configurations."""
def execute(self, loadbalancer_id):
"""Execute updates per listener for an amphora."""
<|body_0|>
def revert(self, loadbalancer_id, *args, **kwargs):
"""Handle failed list... | stack_v2_sparse_classes_36k_train_030301 | 28,773 | permissive | [
{
"docstring": "Execute updates per listener for an amphora.",
"name": "execute",
"signature": "def execute(self, loadbalancer_id)"
},
{
"docstring": "Handle failed listeners updates.",
"name": "revert",
"signature": "def revert(self, loadbalancer_id, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `ListenersUpdate` described below.
Class description:
Task to update amphora with all specified listeners' configurations.
Method signatures and docstrings:
- def execute(self, loadbalancer_id): Execute updates per listener for an amphora.
- def revert(self, loadbalancer_id, *args, **kwargs... | Implement the Python class `ListenersUpdate` described below.
Class description:
Task to update amphora with all specified listeners' configurations.
Method signatures and docstrings:
- def execute(self, loadbalancer_id): Execute updates per listener for an amphora.
- def revert(self, loadbalancer_id, *args, **kwargs... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class ListenersUpdate:
"""Task to update amphora with all specified listeners' configurations."""
def execute(self, loadbalancer_id):
"""Execute updates per listener for an amphora."""
<|body_0|>
def revert(self, loadbalancer_id, *args, **kwargs):
"""Handle failed list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListenersUpdate:
"""Task to update amphora with all specified listeners' configurations."""
def execute(self, loadbalancer_id):
"""Execute updates per listener for an amphora."""
session = db_apis.get_session()
with session.begin():
loadbalancer = self.loadbalancer_rep... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/amphora_driver_tasks.py | openstack/octavia | train | 147 |
5966fc65dc15b01fd857b743e91d49e4559a6bc3 | [
"self.method = method\nself.uri = uri\nself.propstats = []\nself.success_response = success_response",
"if type(what) is int:\n code = what\n error = None\n message = responsecode.RESPONSES[code]\nelif isinstance(what, Failure):\n code = statusForFailure(what)\n error = errorForFailure(what)\n m... | <|body_start_0|>
self.method = method
self.uri = uri
self.propstats = []
self.success_response = success_response
<|end_body_0|>
<|body_start_1|>
if type(what) is int:
code = what
error = None
message = responsecode.RESPONSES[code]
eli... | Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}. | PropertyStatusResponseQueue | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyStatusResponseQueue:
"""Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}."""
def __init__(self, method, uri, success_response):
"""@param method: the name of the method generating the queue. @param uri: the URI for the response. @param s... | stack_v2_sparse_classes_36k_train_030302 | 13,040 | permissive | [
{
"docstring": "@param method: the name of the method generating the queue. @param uri: the URI for the response. @param success_response: the status to return if no L{PropertyStatus} are added to this queue.",
"name": "__init__",
"signature": "def __init__(self, method, uri, success_response)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_000208 | Implement the Python class `PropertyStatusResponseQueue` described below.
Class description:
Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}.
Method signatures and docstrings:
- def __init__(self, method, uri, success_response): @param method: the name of the method generating ... | Implement the Python class `PropertyStatusResponseQueue` described below.
Class description:
Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}.
Method signatures and docstrings:
- def __init__(self, method, uri, success_response): @param method: the name of the method generating ... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class PropertyStatusResponseQueue:
"""Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}."""
def __init__(self, method, uri, success_response):
"""@param method: the name of the method generating the queue. @param uri: the URI for the response. @param s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertyStatusResponseQueue:
"""Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}."""
def __init__(self, method, uri, success_response):
"""@param method: the name of the method generating the queue. @param uri: the URI for the response. @param success_respon... | the_stack_v2_python_sparse | txweb2/dav/http.py | ass-a2s/ccs-calendarserver | train | 2 |
44ee63fa031f015a32b8a8d6083697416065d539 | [
"self.destination = destination\nself.from_user_id = from_user_id\nself.to_user_id = to_user_id\nself.project_id = project_id\nself.project_name = project_name\nself.auth_role = auth_role\nself.user_message = user_message\nself.share_user_ids = share_user_ids",
"item_id = self.get_existing_item_id(api)\nif not it... | <|body_start_0|>
self.destination = destination
self.from_user_id = from_user_id
self.to_user_id = to_user_id
self.project_id = project_id
self.project_name = project_name
self.auth_role = auth_role
self.user_message = user_message
self.share_user_ids = sh... | Contains data for processing either share or deliver. | D4S2Item | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class D4S2Item:
"""Contains data for processing either share or deliver."""
def __init__(self, destination, from_user_id, to_user_id, project_id, project_name, auth_role, user_message, share_user_ids):
"""Save data for use with send method. :param destination: str type of message we are se... | stack_v2_sparse_classes_36k_train_030303 | 21,979 | permissive | [
{
"docstring": "Save data for use with send method. :param destination: str type of message we are sending(SHARE_DESTINATION or DELIVER_DESTINATION) :param from_user_id: str uuid(duke-data-service) of the user who is sending the share/delivery :param to_user_id: str uuid(duke-data-service) of the user is receiv... | 4 | stack_v2_sparse_classes_30k_train_002645 | Implement the Python class `D4S2Item` described below.
Class description:
Contains data for processing either share or deliver.
Method signatures and docstrings:
- def __init__(self, destination, from_user_id, to_user_id, project_id, project_name, auth_role, user_message, share_user_ids): Save data for use with send ... | Implement the Python class `D4S2Item` described below.
Class description:
Contains data for processing either share or deliver.
Method signatures and docstrings:
- def __init__(self, destination, from_user_id, to_user_id, project_id, project_name, auth_role, user_message, share_user_ids): Save data for use with send ... | 0e9d058429de915b8da5afefb21186f6b69cc235 | <|skeleton|>
class D4S2Item:
"""Contains data for processing either share or deliver."""
def __init__(self, destination, from_user_id, to_user_id, project_id, project_name, auth_role, user_message, share_user_ids):
"""Save data for use with send method. :param destination: str type of message we are se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class D4S2Item:
"""Contains data for processing either share or deliver."""
def __init__(self, destination, from_user_id, to_user_id, project_id, project_name, auth_role, user_message, share_user_ids):
"""Save data for use with send method. :param destination: str type of message we are sending(SHARE_D... | the_stack_v2_python_sparse | ddsc/core/d4s2.py | Duke-GCB/DukeDSClient | train | 6 |
22f5b8072cda9e7986941d2d436d1bf605ebcaa5 | [
"self.center = copy.deepcopy(center)\nself.axis = copy.deepcopy(axis)\nself.A = copy.deepcopy(A)\nself.eta = copy.deepcopy(eta)\nself.n_dim = np.size(self.axis)\nself.coeffs = copy.deepcopy(coeffs)\nreturn",
"phi = np.zeros(self.n_dim)\nfor i in range(self.n_dim):\n phi[i] = (x[i] - self.center[i]) ** (2 * sel... | <|body_start_0|>
self.center = copy.deepcopy(center)
self.axis = copy.deepcopy(axis)
self.A = copy.deepcopy(A)
self.eta = copy.deepcopy(eta)
self.n_dim = np.size(self.axis)
self.coeffs = copy.deepcopy(coeffs)
return
<|end_body_0|>
<|body_start_1|>
phi = n... | Implementation of an obstacle for Dynamic Movement Primitives written as a general n-ellipsoid / x - x_c \\ 2n / y - y_c \\ 2n / z - z_c \\ 2n |---------| + |---------| + |---------| = 1 \\ a / \\ b / \\ c / | Obstacle_Static | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Obstacle_Static:
"""Implementation of an obstacle for Dynamic Movement Primitives written as a general n-ellipsoid / x - x_c \\ 2n / y - y_c \\ 2n / z - z_c \\ 2n |---------| + |---------| + |---------| = 1 \\ a / \\ b / \\ c /"""
def __init__(self, center=np.zeros(2), axis=np.ones(2), coeff... | stack_v2_sparse_classes_36k_train_030304 | 8,195 | no_license | [
{
"docstring": "n_dim int : dimension of the space (usually 2 or 3) center float : array containing the coordinates of the center of the ellipsoid axis float : array containing the lengths of the ais of the ellipsoid",
"name": "__init__",
"signature": "def __init__(self, center=np.zeros(2), axis=np.ones... | 4 | stack_v2_sparse_classes_30k_train_015956 | Implement the Python class `Obstacle_Static` described below.
Class description:
Implementation of an obstacle for Dynamic Movement Primitives written as a general n-ellipsoid / x - x_c \\ 2n / y - y_c \\ 2n / z - z_c \\ 2n |---------| + |---------| + |---------| = 1 \\ a / \\ b / \\ c /
Method signatures and docstri... | Implement the Python class `Obstacle_Static` described below.
Class description:
Implementation of an obstacle for Dynamic Movement Primitives written as a general n-ellipsoid / x - x_c \\ 2n / y - y_c \\ 2n / z - z_c \\ 2n |---------| + |---------| + |---------| = 1 \\ a / \\ b / \\ c /
Method signatures and docstri... | 41e353f91f78613cf7bea2ef2369f7589a091a01 | <|skeleton|>
class Obstacle_Static:
"""Implementation of an obstacle for Dynamic Movement Primitives written as a general n-ellipsoid / x - x_c \\ 2n / y - y_c \\ 2n / z - z_c \\ 2n |---------| + |---------| + |---------| = 1 \\ a / \\ b / \\ c /"""
def __init__(self, center=np.zeros(2), axis=np.ones(2), coeff... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Obstacle_Static:
"""Implementation of an obstacle for Dynamic Movement Primitives written as a general n-ellipsoid / x - x_c \\ 2n / y - y_c \\ 2n / z - z_c \\ 2n |---------| + |---------| + |---------| = 1 \\ a / \\ b / \\ c /"""
def __init__(self, center=np.zeros(2), axis=np.ones(2), coeffs=np.ones(2),... | the_stack_v2_python_sparse | dmp/obstacle_superquadric.py | mginesi/dmp_vol_obst | train | 23 |
cdb0315ea07083829df3bc9e6cbbcda9f7e14de8 | [
"if not root:\n return ''\nq = deque()\nq.append(root)\nret = []\nwhile q:\n cur = q.popleft()\n if cur == None:\n ret += ['#']\n continue\n ret += [cur.val]\n q.append(cur.left)\n q.append(cur.right)\nreturn ret",
"if not data:\n return None\nq = deque()\nroot = TreeNode(data[0... | <|body_start_0|>
if not root:
return ''
q = deque()
q.append(root)
ret = []
while q:
cur = q.popleft()
if cur == None:
ret += ['#']
continue
ret += [cur.val]
q.append(cur.left)
... | 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_030305 | 1,551 | 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 | null | 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:... | 6322be072e0f75e2da28b209c1dbb31593e5849f | <|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"""
if not root:
return ''
q = deque()
q.append(root)
ret = []
while q:
cur = q.popleft()
if cur == None:
... | the_stack_v2_python_sparse | solutions/0297_Serialize_and_Deserialize_Binary_Tree/bfs.py | zh-wang/leetcode | train | 0 | |
958988360ac67288121bb5501351a043ac22d0b1 | [
"PuckDetectorCore.__init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster)\nself.m_displayOutput = i_displayOutput\nself.xPosInPixels = 0\nself.yPosInPixels = 0\nself.xPosInMeters = 0\nself.yPosInMeters = 0\nself.newInfo = False\nself.m_dimensionsConverter = i_dimensionsConverter",
"if i_puck... | <|body_start_0|>
PuckDetectorCore.__init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster)
self.m_displayOutput = i_displayOutput
self.xPosInPixels = 0
self.yPosInPixels = 0
self.xPosInMeters = 0
self.yPosInMeters = 0
self.newInfo = False
... | PuckDetector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PuckDetector:
def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True):
"""PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the las... | stack_v2_sparse_classes_36k_train_030306 | 3,210 | permissive | [
{
"docstring": "PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the last known center of the puck Args: i_lowerColor: HSV values of the lower threshold used to identify the puck i_upperColor: HSV values of the Upper threshol... | 4 | null | Implement the Python class `PuckDetector` described below.
Class description:
Implement the PuckDetector class.
Method signatures and docstrings:
- def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True): PuckDetector class's constructor. Initiali... | Implement the Python class `PuckDetector` described below.
Class description:
Implement the PuckDetector class.
Method signatures and docstrings:
- def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True): PuckDetector class's constructor. Initiali... | 2130b462b0038a527061744ab7faf20c2996c04f | <|skeleton|>
class PuckDetector:
def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True):
"""PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the las... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PuckDetector:
def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True):
"""PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the last known center... | the_stack_v2_python_sparse | vision/src/VisionPuckDetector/PuckDetector.py | victoriapc/HockusPockus | train | 0 | |
9685f4071c28aa9857a00c4e55cd1bb34d658ed2 | [
"assert len(hidden_sizes) > 0\nself.layers = [FCLayer(input_size, hidden_sizes[0]), ReLU()]\nfor i in range(1, len(hidden_sizes)):\n self.layers.append(FCLayer(hidden_sizes[i - 1], hidden_sizes[i]))\n self.layers.append(ReLU())\nself.layers.append(FCLayer(hidden_sizes[-1], output_size))\nself.layers.append(So... | <|body_start_0|>
assert len(hidden_sizes) > 0
self.layers = [FCLayer(input_size, hidden_sizes[0]), ReLU()]
for i in range(1, len(hidden_sizes)):
self.layers.append(FCLayer(hidden_sizes[i - 1], hidden_sizes[i]))
self.layers.append(ReLU())
self.layers.append(FCLayer... | SimpleNeuralNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleNeuralNet:
def __init__(self, input_size: int, hidden_sizes: np.array, output_size: int):
"""Initialize network :param input_size: dimension of input data :param hidden_sizes: np.arrray of sizes of hidden layers :param output_size: dimensionality of output data"""
<|body_0|... | stack_v2_sparse_classes_36k_train_030307 | 6,674 | no_license | [
{
"docstring": "Initialize network :param input_size: dimension of input data :param hidden_sizes: np.arrray of sizes of hidden layers :param output_size: dimensionality of output data",
"name": "__init__",
"signature": "def __init__(self, input_size: int, hidden_sizes: np.array, output_size: int)"
},... | 6 | stack_v2_sparse_classes_30k_train_005169 | Implement the Python class `SimpleNeuralNet` described below.
Class description:
Implement the SimpleNeuralNet class.
Method signatures and docstrings:
- def __init__(self, input_size: int, hidden_sizes: np.array, output_size: int): Initialize network :param input_size: dimension of input data :param hidden_sizes: np... | Implement the Python class `SimpleNeuralNet` described below.
Class description:
Implement the SimpleNeuralNet class.
Method signatures and docstrings:
- def __init__(self, input_size: int, hidden_sizes: np.array, output_size: int): Initialize network :param input_size: dimension of input data :param hidden_sizes: np... | 4739b8bbb0fe01be19c0c2cc228b092790876edd | <|skeleton|>
class SimpleNeuralNet:
def __init__(self, input_size: int, hidden_sizes: np.array, output_size: int):
"""Initialize network :param input_size: dimension of input data :param hidden_sizes: np.arrray of sizes of hidden layers :param output_size: dimensionality of output data"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleNeuralNet:
def __init__(self, input_size: int, hidden_sizes: np.array, output_size: int):
"""Initialize network :param input_size: dimension of input data :param hidden_sizes: np.arrray of sizes of hidden layers :param output_size: dimensionality of output data"""
assert len(hidden_sizes... | the_stack_v2_python_sparse | models/simple_neural_net.py | mkozel92/ml_playground | train | 0 | |
6a978b0e7c90d560d37ba0deb75a929c826cb0f0 | [
"topic_movement = '/swarm/behaviour/movement'\ntopic_position = '/swarm/behaviour/position'\nself.pub_movement = rospy.Publisher(topic_movement, Movement, queue_size=10)\nself.pub_position = rospy.Publisher(topic_position, Position, queue_size=10)\nself.wanted_movement = Movement()\nself.wanted_position = Position(... | <|body_start_0|>
topic_movement = '/swarm/behaviour/movement'
topic_position = '/swarm/behaviour/position'
self.pub_movement = rospy.Publisher(topic_movement, Movement, queue_size=10)
self.pub_position = rospy.Publisher(topic_position, Position, queue_size=10)
self.wanted_movemen... | Helper class to let behaviour publish wanted movement to ROS | Talker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Talker:
"""Helper class to let behaviour publish wanted movement to ROS"""
def __init__(self):
"""Initialises ROS publishers"""
<|body_0|>
def __call__(self, data, typ='movement'):
"""Caller function to publish newest data Args: data: Either a Vector or GPS point... | stack_v2_sparse_classes_36k_train_030308 | 1,407 | permissive | [
{
"docstring": "Initialises ROS publishers",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Caller function to publish newest data Args: data: Either a Vector or GPS point containing wanted from behaviour",
"name": "__call__",
"signature": "def __call__(self, da... | 2 | null | Implement the Python class `Talker` described below.
Class description:
Helper class to let behaviour publish wanted movement to ROS
Method signatures and docstrings:
- def __init__(self): Initialises ROS publishers
- def __call__(self, data, typ='movement'): Caller function to publish newest data Args: data: Either ... | Implement the Python class `Talker` described below.
Class description:
Helper class to let behaviour publish wanted movement to ROS
Method signatures and docstrings:
- def __init__(self): Initialises ROS publishers
- def __call__(self, data, typ='movement'): Caller function to publish newest data Args: data: Either ... | 9487dd16b6ce0466f449944ae0e193358e19524d | <|skeleton|>
class Talker:
"""Helper class to let behaviour publish wanted movement to ROS"""
def __init__(self):
"""Initialises ROS publishers"""
<|body_0|>
def __call__(self, data, typ='movement'):
"""Caller function to publish newest data Args: data: Either a Vector or GPS point... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Talker:
"""Helper class to let behaviour publish wanted movement to ROS"""
def __init__(self):
"""Initialises ROS publishers"""
topic_movement = '/swarm/behaviour/movement'
topic_position = '/swarm/behaviour/position'
self.pub_movement = rospy.Publisher(topic_movement, Mov... | the_stack_v2_python_sparse | Behaviour/ROS_operators/Behaviour_talker.py | AnKIbach/swarm | train | 0 |
c6f9854962eb5ddb4b09549fe36000706a46141a | [
"self.factory = RequestFactory()\nself.anomimus = AnonymousUser()\nself.user = User.objects.filter(username='mgalindo1').first()\nself.client = Client(HTTP_USER_AGENT='Mozilla/5.0')\nself.client.login(username='mgalindo1', password=CONTRASENA)",
"request = self.factory.get('muestra-detail')\nrequest.user = self.a... | <|body_start_0|>
self.factory = RequestFactory()
self.anomimus = AnonymousUser()
self.user = User.objects.filter(username='mgalindo1').first()
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0')
self.client.login(username='mgalindo1', password=CONTRASENA)
<|end_body_0|>
<|body_s... | Hisotria de usuario desarrollada con TDD Se encarga de: * Comprobar que un asistente de laboratorio pueda listar y filtrar muestras * Comporbar que solo los autorizados vean las muestras. | DetalleMuestra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetalleMuestra:
"""Hisotria de usuario desarrollada con TDD Se encarga de: * Comprobar que un asistente de laboratorio pueda listar y filtrar muestras * Comporbar que solo los autorizados vean las muestras."""
def setUp(self):
"""Inicia el estado del test Se encarga de : * Loguearse ... | stack_v2_sparse_classes_36k_train_030309 | 4,271 | no_license | [
{
"docstring": "Inicia el estado del test Se encarga de : * Loguearse con un usario existente",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Comprueba que solo los usuarios autorizados puedan acceder a la lista de muestras",
"name": "test_IngresarURL",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_012325 | Implement the Python class `DetalleMuestra` described below.
Class description:
Hisotria de usuario desarrollada con TDD Se encarga de: * Comprobar que un asistente de laboratorio pueda listar y filtrar muestras * Comporbar que solo los autorizados vean las muestras.
Method signatures and docstrings:
- def setUp(self... | Implement the Python class `DetalleMuestra` described below.
Class description:
Hisotria de usuario desarrollada con TDD Se encarga de: * Comprobar que un asistente de laboratorio pueda listar y filtrar muestras * Comporbar que solo los autorizados vean las muestras.
Method signatures and docstrings:
- def setUp(self... | 76b35570a569c490d507de101f48817c1d0835e7 | <|skeleton|>
class DetalleMuestra:
"""Hisotria de usuario desarrollada con TDD Se encarga de: * Comprobar que un asistente de laboratorio pueda listar y filtrar muestras * Comporbar que solo los autorizados vean las muestras."""
def setUp(self):
"""Inicia el estado del test Se encarga de : * Loguearse ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetalleMuestra:
"""Hisotria de usuario desarrollada con TDD Se encarga de: * Comprobar que un asistente de laboratorio pueda listar y filtrar muestras * Comporbar que solo los autorizados vean las muestras."""
def setUp(self):
"""Inicia el estado del test Se encarga de : * Loguearse con un usario... | the_stack_v2_python_sparse | LabModule/app_tests/muestras_test.py | UAMISO4101/AresLabControl | train | 0 |
b2c8849b114ffbfe4722b43a1884203fb935c767 | [
"self._num_classes = num_classes\nself._endpoints_num_filters = endpoints_num_filters\nself._aggregation = aggregation\nself._dropout_rate = dropout_rate\nself._batch_norm_activation = batch_norm_activation\nself._data_format = data_format",
"with tf.variable_scope('classification_head'):\n if self._aggregatio... | <|body_start_0|>
self._num_classes = num_classes
self._endpoints_num_filters = endpoints_num_filters
self._aggregation = aggregation
self._dropout_rate = dropout_rate
self._batch_norm_activation = batch_norm_activation
self._data_format = data_format
<|end_body_0|>
<|bod... | Classification head. | ClassificationHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationHead:
"""Classification head."""
def __init__(self, num_classes, endpoints_num_filters=0, aggregation='top', dropout_rate=0.0, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'):
"""Initialize params to build classification head. Args: num_... | stack_v2_sparse_classes_36k_train_030310 | 46,218 | permissive | [
{
"docstring": "Initialize params to build classification head. Args: num_classes: the number of classes, including one background class. endpoints_num_filters: the number of filters of the optional embedding layer after the multiscale feature aggregation. If 0, no additional embedding layer is applied. aggrega... | 2 | null | Implement the Python class `ClassificationHead` described below.
Class description:
Classification head.
Method signatures and docstrings:
- def __init__(self, num_classes, endpoints_num_filters=0, aggregation='top', dropout_rate=0.0, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): I... | Implement the Python class `ClassificationHead` described below.
Class description:
Classification head.
Method signatures and docstrings:
- def __init__(self, num_classes, endpoints_num_filters=0, aggregation='top', dropout_rate=0.0, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): I... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class ClassificationHead:
"""Classification head."""
def __init__(self, num_classes, endpoints_num_filters=0, aggregation='top', dropout_rate=0.0, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'):
"""Initialize params to build classification head. Args: num_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationHead:
"""Classification head."""
def __init__(self, num_classes, endpoints_num_filters=0, aggregation='top', dropout_rate=0.0, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'):
"""Initialize params to build classification head. Args: num_classes: the ... | the_stack_v2_python_sparse | models/official/detection/modeling/architecture/heads.py | tensorflow/tpu | train | 5,627 |
9c137cdfac3645bdfecf8ef791e6dc94007141a2 | [
"seen = set()\noutput = set()\nfor j in range(i + 1, len(arr)):\n num = arr[j]\n complement = target - num\n if num not in seen:\n seen.add(complement)\n else:\n output.add((min(num, complement), max(num, complement)))\nreturn output",
"arr.sort()\ntriplets = {}\nfor root_index in range(... | <|body_start_0|>
seen = set()
output = set()
for j in range(i + 1, len(arr)):
num = arr[j]
complement = target - num
if num not in seen:
seen.add(complement)
else:
output.add((min(num, complement), max(num, complemen... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def two_sum(self, target, i, arr):
"""Runs in linear time Scan from (i+1)th index to end of the array"""
<|body_0|>
def three_sum_alternative(self, arr: List[int]) -> List[int]:
"""This approach is more optimal because we prevent recomputation NOTE: Remembe... | stack_v2_sparse_classes_36k_train_030311 | 5,213 | no_license | [
{
"docstring": "Runs in linear time Scan from (i+1)th index to end of the array",
"name": "two_sum",
"signature": "def two_sum(self, target, i, arr)"
},
{
"docstring": "This approach is more optimal because we prevent recomputation NOTE: Remember lists are not hashable but tuples are Complexity ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def two_sum(self, target, i, arr): Runs in linear time Scan from (i+1)th index to end of the array
- def three_sum_alternative(self, arr: List[int]) -> List[int]: This approach i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def two_sum(self, target, i, arr): Runs in linear time Scan from (i+1)th index to end of the array
- def three_sum_alternative(self, arr: List[int]) -> List[int]: This approach i... | c0d49423885832b616ae3c7cd58e8f24c17cfd4d | <|skeleton|>
class Solution:
def two_sum(self, target, i, arr):
"""Runs in linear time Scan from (i+1)th index to end of the array"""
<|body_0|>
def three_sum_alternative(self, arr: List[int]) -> List[int]:
"""This approach is more optimal because we prevent recomputation NOTE: Remembe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def two_sum(self, target, i, arr):
"""Runs in linear time Scan from (i+1)th index to end of the array"""
seen = set()
output = set()
for j in range(i + 1, len(arr)):
num = arr[j]
complement = target - num
if num not in seen:
... | the_stack_v2_python_sparse | Arrays/three_sum.py | miaviles/Data-Structures-Algorithms-Python | train | 0 | |
33f8363ce5b1bafaf6c830e8665c80f834104607 | [
"q = quantity.DipoleMoment(1.0, 'C*m')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, 6)\nself.assertEqual(q.units, 'C*m')",
"q = quantity.DipoleMoment(1.0, 'De')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si * constants.c * 1e+21, 1.0, 6)\nself.ass... | <|body_start_0|>
q = quantity.DipoleMoment(1.0, 'C*m')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, 6)
self.assertEqual(q.units, 'C*m')
<|end_body_0|>
<|body_start_1|>
q = quantity.DipoleMoment(1.0, 'De')
self.assertAlmostEqual(q.value,... | Contains unit tests of the DipoleMoment unit type object. | TestDipoleMoment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDipoleMoment:
"""Contains unit tests of the DipoleMoment unit type object."""
def test_coulomb_meter(self):
"""Test the creation of a dipole moment quantity with units of C*m."""
<|body_0|>
def test_debye(self):
"""Test the creation of a dipole moment quantit... | stack_v2_sparse_classes_36k_train_030312 | 49,563 | permissive | [
{
"docstring": "Test the creation of a dipole moment quantity with units of C*m.",
"name": "test_coulomb_meter",
"signature": "def test_coulomb_meter(self)"
},
{
"docstring": "Test the creation of a dipole moment quantity with units of Debye.",
"name": "test_debye",
"signature": "def tes... | 2 | null | Implement the Python class `TestDipoleMoment` described below.
Class description:
Contains unit tests of the DipoleMoment unit type object.
Method signatures and docstrings:
- def test_coulomb_meter(self): Test the creation of a dipole moment quantity with units of C*m.
- def test_debye(self): Test the creation of a ... | Implement the Python class `TestDipoleMoment` described below.
Class description:
Contains unit tests of the DipoleMoment unit type object.
Method signatures and docstrings:
- def test_coulomb_meter(self): Test the creation of a dipole moment quantity with units of C*m.
- def test_debye(self): Test the creation of a ... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestDipoleMoment:
"""Contains unit tests of the DipoleMoment unit type object."""
def test_coulomb_meter(self):
"""Test the creation of a dipole moment quantity with units of C*m."""
<|body_0|>
def test_debye(self):
"""Test the creation of a dipole moment quantit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDipoleMoment:
"""Contains unit tests of the DipoleMoment unit type object."""
def test_coulomb_meter(self):
"""Test the creation of a dipole moment quantity with units of C*m."""
q = quantity.DipoleMoment(1.0, 'C*m')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertA... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
ea6fef9ac972d1e786c90b4d7d7736647827eec9 | [
"if n < 3:\n return 1 if n else 0\na, b, c = (0, 1, 1)\nfor i in range(3, n + 1):\n a, b, c = (b, c, a + b + c)\nreturn c",
"T = numpy.mat([[1, 1, 0]]).transpose()\nif n < 2:\n return int(T[2 - n, 0])\nmtx = numpy.mat([[1, 1, 1], [1, 0, 0], [0, 1, 0]])\nres = mtx ** (n - 2) * T\nreturn int(res[0, 0])"
] | <|body_start_0|>
if n < 3:
return 1 if n else 0
a, b, c = (0, 1, 1)
for i in range(3, n + 1):
a, b, c = (b, c, a + b + c)
return c
<|end_body_0|>
<|body_start_1|>
T = numpy.mat([[1, 1, 0]]).transpose()
if n < 2:
return int(T[2 - n, 0])... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def tribonacci_MK1(self, n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def tribonacci_MK2(self, n: int) -> int:
"""Time complexity: O(lgn) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030313 | 683 | no_license | [
{
"docstring": "Time complexity: O(n) Space complexity: O(1)",
"name": "tribonacci_MK1",
"signature": "def tribonacci_MK1(self, n: int) -> int"
},
{
"docstring": "Time complexity: O(lgn) Space complexity: O(1)",
"name": "tribonacci_MK2",
"signature": "def tribonacci_MK2(self, n: int) -> ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tribonacci_MK1(self, n: int) -> int: Time complexity: O(n) Space complexity: O(1)
- def tribonacci_MK2(self, n: int) -> int: Time complexity: O(lgn) Space complexity: O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tribonacci_MK1(self, n: int) -> int: Time complexity: O(n) Space complexity: O(1)
- def tribonacci_MK2(self, n: int) -> int: Time complexity: O(lgn) Space complexity: O(1)
<... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def tribonacci_MK1(self, n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def tribonacci_MK2(self, n: int) -> int:
"""Time complexity: O(lgn) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def tribonacci_MK1(self, n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
if n < 3:
return 1 if n else 0
a, b, c = (0, 1, 1)
for i in range(3, n + 1):
a, b, c = (b, c, a + b + c)
return c
def tribonacci_MK2(self, ... | the_stack_v2_python_sparse | 1137. N-th Tribonacci Number/Solution.py | faterazer/LeetCode | train | 4 | |
d258fee93278ef51890946645b6b3113075faecb | [
"activities = []\nfor value in resp['activities']:\n activity = self.get_activity(value)\n activities.append(activity)\nreturn activities",
"activity = Activity()\nif 'id' in resp:\n activity.set_id(resp['id'])\nif 'state' in resp:\n activity.set_state(resp['state'])\nif 'activity_for' in resp:\n a... | <|body_start_0|>
activities = []
for value in resp['activities']:
activity = self.get_activity(value)
activities.append(activity)
return activities
<|end_body_0|>
<|body_start_1|>
activity = Activity()
if 'id' in resp:
activity.set_id(resp['id... | This class is used to create object for Dashboard parser. | DashboardParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardParser:
"""This class is used to create object for Dashboard parser."""
def get_activities(self, resp):
"""This method parses the given response and returns list of activities. Args: resp(dict): Dictionary containing json object for activities. Returns: list of instance: Lis... | stack_v2_sparse_classes_36k_train_030314 | 3,287 | permissive | [
{
"docstring": "This method parses the given response and returns list of activities. Args: resp(dict): Dictionary containing json object for activities. Returns: list of instance: List of activity object.",
"name": "get_activities",
"signature": "def get_activities(self, resp)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_003275 | Implement the Python class `DashboardParser` described below.
Class description:
This class is used to create object for Dashboard parser.
Method signatures and docstrings:
- def get_activities(self, resp): This method parses the given response and returns list of activities. Args: resp(dict): Dictionary containing j... | Implement the Python class `DashboardParser` described below.
Class description:
This class is used to create object for Dashboard parser.
Method signatures and docstrings:
- def get_activities(self, resp): This method parses the given response and returns list of activities. Args: resp(dict): Dictionary containing j... | 33e9f6bccba16a581b115c582033a93d43bb159c | <|skeleton|>
class DashboardParser:
"""This class is used to create object for Dashboard parser."""
def get_activities(self, resp):
"""This method parses the given response and returns list of activities. Args: resp(dict): Dictionary containing json object for activities. Returns: list of instance: Lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DashboardParser:
"""This class is used to create object for Dashboard parser."""
def get_activities(self, resp):
"""This method parses the given response and returns list of activities. Args: resp(dict): Dictionary containing json object for activities. Returns: list of instance: List of activity... | the_stack_v2_python_sparse | projects/parser/DashboardParser.py | vhatgithub/projects-python-wrappers | train | 0 |
02e50c1fdea9d978bdbe871b6aea8dd91bf72334 | [
"if not T:\n return []\nif len(T) == 1:\n return [0]\nres = [0 for _ in range(len(T))]\ntem_list = [None for _ in range(len(T))]\nfor index, each in enumerate(T):\n tem_list[index] = set(range(each + 1, 101))\n if index != 0 and each > T[index - 1]:\n for i in range(index, -1, -1):\n i... | <|body_start_0|>
if not T:
return []
if len(T) == 1:
return [0]
res = [0 for _ in range(len(T))]
tem_list = [None for _ in range(len(T))]
for index, each in enumerate(T):
tem_list[index] = set(range(each + 1, 101))
if index != 0 and... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int] 稍微进步点了, 吐血"""
<|body_1|>
def dailyTemperatures3(self, T):
""":type T: List[in... | stack_v2_sparse_classes_36k_train_030315 | 2,144 | no_license | [
{
"docstring": ":type T: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, T)"
},
{
"docstring": ":type T: List[int] :rtype: List[int] 稍微进步点了, 吐血",
"name": "dailyTemperatures2",
"signature": "def dailyTemperatures2(self, T)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004370 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] 稍微进步点了, 吐血
- def dailyTemperatures3(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] 稍微进步点了, 吐血
- def dailyTemperatures3(s... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int] 稍微进步点了, 吐血"""
<|body_1|>
def dailyTemperatures3(self, T):
""":type T: List[in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
if not T:
return []
if len(T) == 1:
return [0]
res = [0 for _ in range(len(T))]
tem_list = [None for _ in range(len(T))]
for index, each in enumerate(T):... | the_stack_v2_python_sparse | dailyTemperatures.py | NeilWangziyu/Leetcode_py | train | 2 | |
6ced01b005d905c3a622fc55d1629cf98e835c1c | [
"super(AudioTextVideoFusion, self).__init__(name=name)\nself._audio_backbone = audio_backbone\nself._audio_model_kwargs = audio_model_kwargs or {}\nself._text_backbone = text_backbone\nself._text_model_kwargs = text_model_kwargs or {}\nself._video_backbone = video_backbone\nself._video_model_kwargs = video_model_kw... | <|body_start_0|>
super(AudioTextVideoFusion, self).__init__(name=name)
self._audio_backbone = audio_backbone
self._audio_model_kwargs = audio_model_kwargs or {}
self._text_backbone = text_backbone
self._text_model_kwargs = text_model_kwargs or {}
self._video_backbone = vi... | Module to fuse audio, text and video for joint embedding learning. | AudioTextVideoFusion | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioTextVideoFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_backbone='resnet50', video_model_kwargs=None, name='audio_text_video_mod... | stack_v2_sparse_classes_36k_train_030316 | 7,989 | permissive | [
{
"docstring": "Initialize the AudioTextVideoFusion class. Args: audio_backbone: Backbone for audio. audio_model_kwargs: Other specific parameters to pass to the audio module. text_backbone: The base language model name. text_model_kwargs: Other specific parameters to pass to the text module. video_backbone: Th... | 2 | stack_v2_sparse_classes_30k_train_001333 | Implement the Python class `AudioTextVideoFusion` described below.
Class description:
Module to fuse audio, text and video for joint embedding learning.
Method signatures and docstrings:
- def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_back... | Implement the Python class `AudioTextVideoFusion` described below.
Class description:
Module to fuse audio, text and video for joint embedding learning.
Method signatures and docstrings:
- def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_back... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class AudioTextVideoFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_backbone='resnet50', video_model_kwargs=None, name='audio_text_video_mod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AudioTextVideoFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_backbone='resnet50', video_model_kwargs=None, name='audio_text_video_model', **kwargs... | the_stack_v2_python_sparse | vatt/modeling/backbones/multimodal.py | Jimmy-INL/google-research | train | 1 |
16a2106cde5f63dea37f61825877bf0d3afa4ce5 | [
"mapping = []\nindices = set([i for i in range(len(A))])\nfor a in A:\n for i in indices:\n if a == B[i]:\n mapping.append(i)\n indices.remove(i)\n break\nreturn mapping",
"d = collections.defaultdict(list)\nfor i, n in enumerate(B):\n d[n].append(i)\nmapping = []\nfo... | <|body_start_0|>
mapping = []
indices = set([i for i in range(len(A))])
for a in A:
for i in indices:
if a == B[i]:
mapping.append(i)
indices.remove(i)
break
return mapping
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def anagramMappings(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: List[int]"""
<|body_0|>
def anagramMappings2(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030317 | 1,253 | no_license | [
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: List[int]",
"name": "anagramMappings",
"signature": "def anagramMappings(self, A, B)"
},
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: List[int]",
"name": "anagramMappings2",
"signature": "def anagramMappings2(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def anagramMappings(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[int]
- def anagramMappings2(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def anagramMappings(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[int]
- def anagramMappings2(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[in... | 672816c504e56a1d2dfea72f96312f27cd9a3133 | <|skeleton|>
class Solution:
def anagramMappings(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: List[int]"""
<|body_0|>
def anagramMappings2(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def anagramMappings(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: List[int]"""
mapping = []
indices = set([i for i in range(len(A))])
for a in A:
for i in indices:
if a == B[i]:
mapping.append(i)
... | the_stack_v2_python_sparse | 760.Find_Anagram_Mappings.py | mikehung/leetcode | train | 3 | |
aa79383fe10ee11b82703955dd65ffbec4682003 | [
"self.iceContext = iceContext\nself.mets = Mets(iceContext, 'ICE-METS', Mets.Helper.METS_NLA_PROFILE)\nself.__includeExts = includeExts",
"fs = self.iceContext.FileSystem(basePath)\ncreationDate = strftime('%Y-%m-%dT%H:%M:%S', gmtime())\nself.mets.setCreateDate(creationDate)\nself.mets.setLastModDate(creationDate... | <|body_start_0|>
self.iceContext = iceContext
self.mets = Mets(iceContext, 'ICE-METS', Mets.Helper.METS_NLA_PROFILE)
self.__includeExts = includeExts
<|end_body_0|>
<|body_start_1|>
fs = self.iceContext.FileSystem(basePath)
creationDate = strftime('%Y-%m-%dT%H:%M:%S', gmtime())
... | Base class for MetsCreator | MetsCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetsCreator:
"""Base class for MetsCreator"""
def __init__(self, iceContext, includeExts):
"""Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list"""
<|body... | stack_v2_sparse_classes_36k_train_030318 | 19,400 | no_license | [
{
"docstring": "Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list",
"name": "__init__",
"signature": "def __init__(self, iceContext, includeExts)"
},
{
"docstring": "to crea... | 2 | stack_v2_sparse_classes_30k_train_007983 | Implement the Python class `MetsCreator` described below.
Class description:
Base class for MetsCreator
Method signatures and docstrings:
- def __init__(self, iceContext, includeExts): Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension... | Implement the Python class `MetsCreator` described below.
Class description:
Base class for MetsCreator
Method signatures and docstrings:
- def __init__(self, iceContext, includeExts): Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension... | c1d6b5a1bea3df4dde10cb582fb0da361dd747bc | <|skeleton|>
class MetsCreator:
"""Base class for MetsCreator"""
def __init__(self, iceContext, includeExts):
"""Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetsCreator:
"""Base class for MetsCreator"""
def __init__(self, iceContext, includeExts):
"""Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list"""
self.iceContext = i... | the_stack_v2_python_sparse | apps/ice/plugins/service/plugin_odp_ppt_service.py | ptsefton/integrated-content-environment | train | 0 |
77beaa7bd4c490cf4948c4ca25bb5d3c25483a9d | [
"super(FindAmazonMatchesParams, self).__init__(parent=parent)\nself.setupUi(self)\nsession = Session()\nlist_names = [result.name for result in session.query(List.name).filter_by(is_amazon=True).all()]\nself.listNamesBox.addItems(list_names)\nself.testMarginsCheck.stateChanged.connect(self.listNamesBox.setEnabled)"... | <|body_start_0|>
super(FindAmazonMatchesParams, self).__init__(parent=parent)
self.setupUi(self)
session = Session()
list_names = [result.name for result in session.query(List.name).filter_by(is_amazon=True).all()]
self.listNamesBox.addItems(list_names)
self.testMarginsCh... | A widget for specifying operations for the FindAmazonMatches operation. | FindAmazonMatchesParams | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindAmazonMatchesParams:
"""A widget for specifying operations for the FindAmazonMatches operation."""
def __init__(self, parent=None):
"""Initialize the widget."""
<|body_0|>
def params(self):
"""Return the selected parameters as a dictionary."""
<|body_... | stack_v2_sparse_classes_36k_train_030319 | 25,458 | no_license | [
{
"docstring": "Initialize the widget.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Return the selected parameters as a dictionary.",
"name": "params",
"signature": "def params(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014374 | Implement the Python class `FindAmazonMatchesParams` described below.
Class description:
A widget for specifying operations for the FindAmazonMatches operation.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the widget.
- def params(self): Return the selected parameters as a dictionar... | Implement the Python class `FindAmazonMatchesParams` described below.
Class description:
A widget for specifying operations for the FindAmazonMatches operation.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the widget.
- def params(self): Return the selected parameters as a dictionar... | 7d22707a1782125d86140c52d20eaadd2df6e4fc | <|skeleton|>
class FindAmazonMatchesParams:
"""A widget for specifying operations for the FindAmazonMatches operation."""
def __init__(self, parent=None):
"""Initialize the widget."""
<|body_0|>
def params(self):
"""Return the selected parameters as a dictionary."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindAmazonMatchesParams:
"""A widget for specifying operations for the FindAmazonMatches operation."""
def __init__(self, parent=None):
"""Initialize the widget."""
super(FindAmazonMatchesParams, self).__init__(parent=parent)
self.setupUi(self)
session = Session()
... | the_stack_v2_python_sparse | dialogs.py | garrettmk/Prowler | train | 1 |
aa017ef900145843d226e8c236c84d1cf765c914 | [
"self._wrapperCheck(value)\nif self.getPropertyType(id) == 'keyedselection':\n value = int(value)\nsetattr(self, id, value)",
"for prop in self._propertyMap():\n name = prop['id']\n if 'w' in prop.get('mode', 'wd'):\n value = REQUEST.get(name, '')\n self._updateProperty(name, value)\nself.i... | <|body_start_0|>
self._wrapperCheck(value)
if self.getPropertyType(id) == 'keyedselection':
value = int(value)
setattr(self, id, value)
<|end_body_0|>
<|body_start_1|>
for prop in self._propertyMap():
name = prop['id']
if 'w' in prop.get('mode', 'wd')... | ConfmonPropManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfmonPropManager:
def _setPropValue(self, id, value):
"""override from PerpertyManager to handle checks and ip creation"""
<|body_0|>
def manage_editProperties(self, REQUEST):
"""Edit object properties via the web. The purpose of this method is to change all proper... | stack_v2_sparse_classes_36k_train_030320 | 1,954 | no_license | [
{
"docstring": "override from PerpertyManager to handle checks and ip creation",
"name": "_setPropValue",
"signature": "def _setPropValue(self, id, value)"
},
{
"docstring": "Edit object properties via the web. The purpose of this method is to change all property values, even those not listed in... | 2 | stack_v2_sparse_classes_30k_train_005406 | Implement the Python class `ConfmonPropManager` described below.
Class description:
Implement the ConfmonPropManager class.
Method signatures and docstrings:
- def _setPropValue(self, id, value): override from PerpertyManager to handle checks and ip creation
- def manage_editProperties(self, REQUEST): Edit object pro... | Implement the Python class `ConfmonPropManager` described below.
Class description:
Implement the ConfmonPropManager class.
Method signatures and docstrings:
- def _setPropValue(self, id, value): override from PerpertyManager to handle checks and ip creation
- def manage_editProperties(self, REQUEST): Edit object pro... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class ConfmonPropManager:
def _setPropValue(self, id, value):
"""override from PerpertyManager to handle checks and ip creation"""
<|body_0|>
def manage_editProperties(self, REQUEST):
"""Edit object properties via the web. The purpose of this method is to change all proper... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfmonPropManager:
def _setPropValue(self, id, value):
"""override from PerpertyManager to handle checks and ip creation"""
self._wrapperCheck(value)
if self.getPropertyType(id) == 'keyedselection':
value = int(value)
setattr(self, id, value)
def manage_editPr... | the_stack_v2_python_sparse | Products/ZenModel/ConfmonPropManager.py | zenoss/zenoss-prodbin | train | 27 | |
658404c3eb8e3ada504d6bbea077f085005eab57 | [
"self.partner_id = partner_id\nself.pre_app_id = pre_app_id\nself.note = note\nself.eua_id = eua_id\nself.app_name = app_name\nself.submitted_date = submitted_date\nself.modified_date = modified_date\nself.status = status\nself.scopes = scopes\nself.institution_details = institution_details\nself.additional_propert... | <|body_start_0|>
self.partner_id = partner_id
self.pre_app_id = pre_app_id
self.note = note
self.eua_id = eua_id
self.app_name = app_name
self.submitted_date = submitted_date
self.modified_date = modified_date
self.status = status
self.scopes = sco... | Implementation of the 'App Status V1' model. The registration status fields for the application Attributes: partner_id (string): TODO: type description here. pre_app_id (long|int): An identifier to track the application registration request note (string): A note on registration. Typically used to indicate reasons for r... | AppStatusV1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppStatusV1:
"""Implementation of the 'App Status V1' model. The registration status fields for the application Attributes: partner_id (string): TODO: type description here. pre_app_id (long|int): An identifier to track the application registration request note (string): A note on registration. T... | stack_v2_sparse_classes_36k_train_030321 | 5,046 | permissive | [
{
"docstring": "Constructor for the AppStatusV1 class",
"name": "__init__",
"signature": "def __init__(self, partner_id=None, pre_app_id=None, app_name=None, submitted_date=None, modified_date=None, status=None, note=None, eua_id=None, scopes=None, institution_details=None, additional_properties={})"
... | 2 | stack_v2_sparse_classes_30k_train_018134 | Implement the Python class `AppStatusV1` described below.
Class description:
Implementation of the 'App Status V1' model. The registration status fields for the application Attributes: partner_id (string): TODO: type description here. pre_app_id (long|int): An identifier to track the application registration request n... | Implement the Python class `AppStatusV1` described below.
Class description:
Implementation of the 'App Status V1' model. The registration status fields for the application Attributes: partner_id (string): TODO: type description here. pre_app_id (long|int): An identifier to track the application registration request n... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class AppStatusV1:
"""Implementation of the 'App Status V1' model. The registration status fields for the application Attributes: partner_id (string): TODO: type description here. pre_app_id (long|int): An identifier to track the application registration request note (string): A note on registration. T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppStatusV1:
"""Implementation of the 'App Status V1' model. The registration status fields for the application Attributes: partner_id (string): TODO: type description here. pre_app_id (long|int): An identifier to track the application registration request note (string): A note on registration. Typically used... | the_stack_v2_python_sparse | finicityapi/models/app_status_v_1.py | monarchmoney/finicity-python | train | 0 |
f4cc49a6153b9d5fda25a7386ea34942d3d96557 | [
"sql = '\\n SELECT t.name,count(*) type_count FROM\\n cmdb.cmdb_equipment e,\\n cmdb.cmdb_baseequipmenttype t\\n WHERE t.id = e.assettype_id'\nif custid:\n sql = \"{0} AND e.cust_id='{1}' \".format(sql, custid)\nsql = '{0} GROUP BY e.assettype_id'.format(sql)\nresu... | <|body_start_0|>
sql = '\n SELECT t.name,count(*) type_count FROM\n cmdb.cmdb_equipment e,\n cmdb.cmdb_baseequipmenttype t\n WHERE t.id = e.assettype_id'
if custid:
sql = "{0} AND e.cust_id='{1}' ".format(sql, custid)
sql = '{0} GROUP B... | EquipmentManage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquipmentManage:
def equipment_type_group_count(self, custid=None):
"""统计网络设备数量,按设备类型分类统计 :return:"""
<|body_0|>
def month_group_count(self, month_value_dict, custid=None):
"""获取当前月份以及之前12月内所有设备数量统计 :param custid: 客户ID :return:"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_030322 | 7,277 | permissive | [
{
"docstring": "统计网络设备数量,按设备类型分类统计 :return:",
"name": "equipment_type_group_count",
"signature": "def equipment_type_group_count(self, custid=None)"
},
{
"docstring": "获取当前月份以及之前12月内所有设备数量统计 :param custid: 客户ID :return:",
"name": "month_group_count",
"signature": "def month_group_count(s... | 2 | stack_v2_sparse_classes_30k_train_012121 | Implement the Python class `EquipmentManage` described below.
Class description:
Implement the EquipmentManage class.
Method signatures and docstrings:
- def equipment_type_group_count(self, custid=None): 统计网络设备数量,按设备类型分类统计 :return:
- def month_group_count(self, month_value_dict, custid=None): 获取当前月份以及之前12月内所有设备数量统计 ... | Implement the Python class `EquipmentManage` described below.
Class description:
Implement the EquipmentManage class.
Method signatures and docstrings:
- def equipment_type_group_count(self, custid=None): 统计网络设备数量,按设备类型分类统计 :return:
- def month_group_count(self, month_value_dict, custid=None): 获取当前月份以及之前12月内所有设备数量统计 ... | 002f80dcc07e3502610b0a0be1e91fe61bcfc42c | <|skeleton|>
class EquipmentManage:
def equipment_type_group_count(self, custid=None):
"""统计网络设备数量,按设备类型分类统计 :return:"""
<|body_0|>
def month_group_count(self, month_value_dict, custid=None):
"""获取当前月份以及之前12月内所有设备数量统计 :param custid: 客户ID :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EquipmentManage:
def equipment_type_group_count(self, custid=None):
"""统计网络设备数量,按设备类型分类统计 :return:"""
sql = '\n SELECT t.name,count(*) type_count FROM\n cmdb.cmdb_equipment e,\n cmdb.cmdb_baseequipmenttype t\n WHERE t.id = e.assettype_id'
... | the_stack_v2_python_sparse | cmdb/afcat/cmdb/custmanage.py | tonglinge/MyProjects | train | 4 | |
cc11777e512aea4474ca2beb00a4b960d34830d0 | [
"self.interval = interval\nthread = threading.Thread(target=self.run, args=())\nthread.daemon = True\nthread.start()",
"while True:\n print('Doing something imporant in the background')\n time.sleep(self.interval)"
] | <|body_start_0|>
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
<|end_body_0|>
<|body_start_1|>
while True:
print('Doing something imporant in the background')
time.sleep(self.interval)
<|e... | Threading example class The run() method will be started and it will run in the background until the application exits. | ThreadingExample | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_030323 | 911 | permissive | [
{
"docstring": "Constructor :type interval: int :param interval: Check interval, in seconds",
"name": "__init__",
"signature": "def __init__(self, interval=1)"
},
{
"docstring": "Method that runs forever",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001127 | Implement the Python class `ThreadingExample` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, interval=1): Constructor :type interval: int :param interval:... | Implement the Python class `ThreadingExample` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, interval=1): Constructor :type interval: int :param interval:... | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | <|skeleton|>
class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
self.interval = interval
... | the_stack_v2_python_sparse | all-gists/832219525541e059aefa/snippet.py | gistable/gistable | train | 76 |
7ddc889f5da410d965c946ee084e94a008557be8 | [
"from .models import PaymentChannel, PaymentChannelSpend, BlockchainTransaction\nif allowed_methods is None:\n pc_db = bitserv.DatabaseDjango(PaymentChannel, PaymentChannelSpend)\n self.server = bitserv.PaymentServer(wallet, pc_db, zeroconf=zeroconf, sync_period=sync_period)\n self.allowed_methods = [bitse... | <|body_start_0|>
from .models import PaymentChannel, PaymentChannelSpend, BlockchainTransaction
if allowed_methods is None:
pc_db = bitserv.DatabaseDjango(PaymentChannel, PaymentChannelSpend)
self.server = bitserv.PaymentServer(wallet, pc_db, zeroconf=zeroconf, sync_period=sync_p... | Class to store merchant settings. | Payment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Payment:
"""Class to store merchant settings."""
def __init__(self, wallet, allowed_methods=None, zeroconf=True, sync_period=10):
"""Configure bitserv settings. Args: wallet (two1.wallet.Wallet): The merchant's wallet instance."""
<|body_0|>
def required(self, price, **k... | stack_v2_sparse_classes_36k_train_030324 | 3,966 | permissive | [
{
"docstring": "Configure bitserv settings. Args: wallet (two1.wallet.Wallet): The merchant's wallet instance.",
"name": "__init__",
"signature": "def __init__(self, wallet, allowed_methods=None, zeroconf=True, sync_period=10)"
},
{
"docstring": "API route decorator to request payment for a reso... | 3 | stack_v2_sparse_classes_30k_train_005506 | Implement the Python class `Payment` described below.
Class description:
Class to store merchant settings.
Method signatures and docstrings:
- def __init__(self, wallet, allowed_methods=None, zeroconf=True, sync_period=10): Configure bitserv settings. Args: wallet (two1.wallet.Wallet): The merchant's wallet instance.... | Implement the Python class `Payment` described below.
Class description:
Class to store merchant settings.
Method signatures and docstrings:
- def __init__(self, wallet, allowed_methods=None, zeroconf=True, sync_period=10): Configure bitserv settings. Args: wallet (two1.wallet.Wallet): The merchant's wallet instance.... | a5e99fccf11ed75420775ae3e924c9ce94f2e86d | <|skeleton|>
class Payment:
"""Class to store merchant settings."""
def __init__(self, wallet, allowed_methods=None, zeroconf=True, sync_period=10):
"""Configure bitserv settings. Args: wallet (two1.wallet.Wallet): The merchant's wallet instance."""
<|body_0|>
def required(self, price, **k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Payment:
"""Class to store merchant settings."""
def __init__(self, wallet, allowed_methods=None, zeroconf=True, sync_period=10):
"""Configure bitserv settings. Args: wallet (two1.wallet.Wallet): The merchant's wallet instance."""
from .models import PaymentChannel, PaymentChannelSpend, B... | the_stack_v2_python_sparse | two1/bitserv/django/decorator.py | shayanb/two1 | train | 4 |
f8867f2d69751f84fa1d61451ca1d884430197ea | [
"self.fn = ''\nself.pt_id = 'X X X X' + ' ' * 73\nself.rec_info = 'Startdate X X X X' + ' ' * 63\nself.start_date = '01.01.01'\nself.start_time = '01.01.01'\nself.py_h = 2\nself.pyedf_header = {'technician': '002', 'recording_additional': '', 'patientname': '', 'patient_additional': '', 'patientcode': '', 'equipmen... | <|body_start_0|>
self.fn = ''
self.pt_id = 'X X X X' + ' ' * 73
self.rec_info = 'Startdate X X X X' + ' ' * 63
self.start_date = '01.01.01'
self.start_time = '01.01.01'
self.py_h = 2
self.pyedf_header = {'technician': '002', 'recording_additional': '', 'patientnam... | Data structure for holding information for saving to edf namely the anonymized header | SaveEdfInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveEdfInfo:
"""Data structure for holding information for saving to edf namely the anonymized header"""
def __init__(self):
"""Header parameters set to default values"""
<|body_0|>
def convert_to_header(self):
"""Converts from native EDF format: self.data.pt_id ... | stack_v2_sparse_classes_36k_train_030325 | 3,114 | no_license | [
{
"docstring": "Header parameters set to default values",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Converts from native EDF format: self.data.pt_id = file[8:88].decode(\"utf-8\") self.data.rec_info = file[88:168].decode(\"utf-8\") self.data.start_date = file[168:1... | 2 | stack_v2_sparse_classes_30k_train_013603 | Implement the Python class `SaveEdfInfo` described below.
Class description:
Data structure for holding information for saving to edf namely the anonymized header
Method signatures and docstrings:
- def __init__(self): Header parameters set to default values
- def convert_to_header(self): Converts from native EDF for... | Implement the Python class `SaveEdfInfo` described below.
Class description:
Data structure for holding information for saving to edf namely the anonymized header
Method signatures and docstrings:
- def __init__(self): Header parameters set to default values
- def convert_to_header(self): Converts from native EDF for... | 099920716fdab891592ccc7f324445f088827298 | <|skeleton|>
class SaveEdfInfo:
"""Data structure for holding information for saving to edf namely the anonymized header"""
def __init__(self):
"""Header parameters set to default values"""
<|body_0|>
def convert_to_header(self):
"""Converts from native EDF format: self.data.pt_id ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaveEdfInfo:
"""Data structure for holding information for saving to edf namely the anonymized header"""
def __init__(self):
"""Header parameters set to default values"""
self.fn = ''
self.pt_id = 'X X X X' + ' ' * 73
self.rec_info = 'Startdate X X X X' + ' ' * 63
... | the_stack_v2_python_sparse | visualization/edf_saving/saveEdf_info.py | jcraley/jhu-eeg | train | 2 |
5c0dca7d4fd18ea5cd47f494bfd7a887f65fcf54 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.identityBuiltInUserFlowAttribute'.casefold(... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | IdentityUserFlowAttribute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityUserFlowAttribute:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttribute:
"""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 c... | stack_v2_sparse_classes_36k_train_030326 | 4,696 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: IdentityUserFlowAttribute",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `IdentityUserFlowAttribute` described below.
Class description:
Implement the IdentityUserFlowAttribute class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttribute: Creates a new instance of the appropriat... | Implement the Python class `IdentityUserFlowAttribute` described below.
Class description:
Implement the IdentityUserFlowAttribute class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttribute: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IdentityUserFlowAttribute:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttribute:
"""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 c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityUserFlowAttribute:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttribute:
"""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 obje... | the_stack_v2_python_sparse | msgraph/generated/models/identity_user_flow_attribute.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
57900062f3a74beb96084c6028884f8f6ae41c53 | [
"if REQUEST is not None:\n self.__dict__.update(REQUEST)\nif kw is not None:\n self.__dict__.update(kw)",
"if REQUEST is not None:\n aq_base(self).__dict__.update(REQUEST)\nif kw is not None:\n aq_base(self).__dict__.update(kw)\nif context is not None:\n return self.__of__(context)\nelse:\n retu... | <|body_start_0|>
if REQUEST is not None:
self.__dict__.update(REQUEST)
if kw is not None:
self.__dict__.update(kw)
<|end_body_0|>
<|body_start_1|>
if REQUEST is not None:
aq_base(self).__dict__.update(REQUEST)
if kw is not None:
aq_base(se... | Context objects are used all over ERP5 in so-called context dependent function. Examples of context dependent methods include: - price methods (price depends on the context: customer, quantity, etc.) - BOM methods | Context | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Context:
"""Context objects are used all over ERP5 in so-called context dependent function. Examples of context dependent methods include: - price methods (price depends on the context: customer, quantity, etc.) - BOM methods"""
def __init__(self, context=None, REQUEST=None, **kw):
"... | stack_v2_sparse_classes_36k_train_030327 | 2,898 | no_license | [
{
"docstring": "context -- The REQUEST -- the request object kw -- user specified parameters",
"name": "__init__",
"signature": "def __init__(self, context=None, REQUEST=None, **kw)"
},
{
"docstring": "Update args of context",
"name": "asContext",
"signature": "def asContext(self, contex... | 2 | stack_v2_sparse_classes_30k_train_004628 | Implement the Python class `Context` described below.
Class description:
Context objects are used all over ERP5 in so-called context dependent function. Examples of context dependent methods include: - price methods (price depends on the context: customer, quantity, etc.) - BOM methods
Method signatures and docstring... | Implement the Python class `Context` described below.
Class description:
Context objects are used all over ERP5 in so-called context dependent function. Examples of context dependent methods include: - price methods (price depends on the context: customer, quantity, etc.) - BOM methods
Method signatures and docstring... | dc02bfa887ffab9841abebc3f5c16d874388cef5 | <|skeleton|>
class Context:
"""Context objects are used all over ERP5 in so-called context dependent function. Examples of context dependent methods include: - price methods (price depends on the context: customer, quantity, etc.) - BOM methods"""
def __init__(self, context=None, REQUEST=None, **kw):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Context:
"""Context objects are used all over ERP5 in so-called context dependent function. Examples of context dependent methods include: - price methods (price depends on the context: customer, quantity, etc.) - BOM methods"""
def __init__(self, context=None, REQUEST=None, **kw):
"""context -- ... | the_stack_v2_python_sparse | product/ERP5Type/Context.py | jgpjuniorj/j | train | 1 |
87a88c2916fc72125e9ec15e9d2c6d875df98c0f | [
"super().__init__()\nif not lambdas:\n lambdas = [1.0 for l in losses]\nassert all((lam >= 0.0 for lam in lambdas))\nself.losses = nn.ModuleList(losses)\nself.lambdas = lambdas",
"head_losses = [ll for l, f, t in zip(self.losses, head_fields, head_targets) for ll in l(f, t)]\nassert len(self.lambdas) == len(he... | <|body_start_0|>
super().__init__()
if not lambdas:
lambdas = [1.0 for l in losses]
assert all((lam >= 0.0 for lam in lambdas))
self.losses = nn.ModuleList(losses)
self.lambdas = lambdas
<|end_body_0|>
<|body_start_1|>
head_losses = [ll for l, f, t in zip(sel... | collect all the loss we need | MultiHeadLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadLoss:
"""collect all the loss we need"""
def __init__(self, losses, lambdas=None):
"""Inputs: - losses: (list)[nn.Module, nn.Module, ...] - lambdas: (list)各个loss的权重"""
<|body_0|>
def forward(self, head_fields, head_targets):
"""Inputs: - head_fields: (li... | stack_v2_sparse_classes_36k_train_030328 | 1,804 | no_license | [
{
"docstring": "Inputs: - losses: (list)[nn.Module, nn.Module, ...] - lambdas: (list)各个loss的权重",
"name": "__init__",
"signature": "def __init__(self, losses, lambdas=None)"
},
{
"docstring": "Inputs: - head_fields: (list)各个head输出的数据 - head_targets: (list)各个head对应的gt Returns: - total_loss: sum of... | 2 | stack_v2_sparse_classes_30k_train_008974 | Implement the Python class `MultiHeadLoss` described below.
Class description:
collect all the loss we need
Method signatures and docstrings:
- def __init__(self, losses, lambdas=None): Inputs: - losses: (list)[nn.Module, nn.Module, ...] - lambdas: (list)各个loss的权重
- def forward(self, head_fields, head_targets): Input... | Implement the Python class `MultiHeadLoss` described below.
Class description:
collect all the loss we need
Method signatures and docstrings:
- def __init__(self, losses, lambdas=None): Inputs: - losses: (list)[nn.Module, nn.Module, ...] - lambdas: (list)各个loss的权重
- def forward(self, head_fields, head_targets): Input... | 16d283bc7696c34a1ef954d96a4a32dc865b1f9b | <|skeleton|>
class MultiHeadLoss:
"""collect all the loss we need"""
def __init__(self, losses, lambdas=None):
"""Inputs: - losses: (list)[nn.Module, nn.Module, ...] - lambdas: (list)各个loss的权重"""
<|body_0|>
def forward(self, head_fields, head_targets):
"""Inputs: - head_fields: (li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadLoss:
"""collect all the loss we need"""
def __init__(self, losses, lambdas=None):
"""Inputs: - losses: (list)[nn.Module, nn.Module, ...] - lambdas: (list)各个loss的权重"""
super().__init__()
if not lambdas:
lambdas = [1.0 for l in losses]
assert all((lam >... | the_stack_v2_python_sparse | lib/core/loss.py | EXPmaster/YOLOP | train | 2 |
42e72d88479772d8617878918d03b759cac61933 | [
"if not prerequisites:\n return True\nindegree = [0] * numCourses\ndict = {}\nfor i in range(len(prerequisites)):\n edge = prerequisites[i]\n src = edge[1]\n dst = edge[0]\n if not dict.get(src):\n indegree[dst] += 1\n dict[src] = [dst]\n elif dst not in dict[src]:\n indegree[... | <|body_start_0|>
if not prerequisites:
return True
indegree = [0] * numCourses
dict = {}
for i in range(len(prerequisites)):
edge = prerequisites[i]
src = edge[1]
dst = edge[0]
if not dict.get(src):
indegree[dst]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinishBFS(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
<|body_0|>
def canFinishDFS(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rty... | stack_v2_sparse_classes_36k_train_030329 | 4,104 | no_license | [
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "canFinishBFS",
"signature": "def canFinishBFS(self, numCourses, prerequisites)"
},
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "canFinishDF... | 3 | stack_v2_sparse_classes_30k_train_003956 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinishBFS(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
- def canFinishDFS(self, numCourses, prerequisites): :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinishBFS(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
- def canFinishDFS(self, numCourses, prerequisites): :t... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Solution:
def canFinishBFS(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
<|body_0|>
def canFinishDFS(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canFinishBFS(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
if not prerequisites:
return True
indegree = [0] * numCourses
dict = {}
for i in range(len(prerequisites)):
... | the_stack_v2_python_sparse | python_solution/201_210/CourseSchedule.py | CescWang1991/LeetCode-Python | train | 1 | |
edc9e3552f6aee4e98b0600bd02afdb8cccc26e1 | [
"l = longUrl.split('/')\nl.append(1)\nreturn l",
"l = shortUrl\ntmp = l[-1]\ndel l[-1]\ns = l[0] + '//'\ni = 2\nwhile i < len(l):\n s += l[i] + '/'\n i += 1\nreturn s[:-1]"
] | <|body_start_0|>
l = longUrl.split('/')
l.append(1)
return l
<|end_body_0|>
<|body_start_1|>
l = shortUrl
tmp = l[-1]
del l[-1]
s = l[0] + '//'
i = 2
while i < len(l):
s += l[i] + '/'
i += 1
return s[:-1]
<|end_body... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = longUrl.spli... | stack_v2_sparse_classes_36k_train_030330 | 639 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL.",
"name": "encode",
"signature": "def encode(self, longUrl: str) -> str"
},
{
"docstring": "Decodes a shortened URL to its original URL.",
"name": "decode",
"signature": "def decode(self, shortUrl: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_002071 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
<|skeleton|>
class Code... | 7aabed082826f8df555bf6e97046ee077becf759 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
l = longUrl.split('/')
l.append(1)
return l
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
l = shortUrl
tmp = l[-1]
... | the_stack_v2_python_sparse | Python 3/LeetCode/lc535.py | nsmith0310/Programming-Challenges | train | 0 | |
8b65546e0921706d76ff03285aaf646194255e69 | [
"team = Team.get_or_404(id=team_id)\nquery = TeamService.followers(team=team)\npage = self.paginate_query(query)\ndata = self.render_page_info(page)\ndata['followers'] = []\nuids = set()\n\ndef merge_followers(ids, parteam_users):\n for uid in ids:\n user = parteam_users[uid]\n data.setdefault('fol... | <|body_start_0|>
team = Team.get_or_404(id=team_id)
query = TeamService.followers(team=team)
page = self.paginate_query(query)
data = self.render_page_info(page)
data['followers'] = []
uids = set()
def merge_followers(ids, parteam_users):
for uid in i... | 用户关注和取消关注俱乐部 | FollowTeamHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowTeamHandler:
"""用户关注和取消关注俱乐部"""
def get(self, team_id: int):
"""俱乐部粉丝列表"""
<|body_0|>
def post(self, team_id: int):
"""关注俱乐部 :param team_id: :return:"""
<|body_1|>
def delete(self, team_id: int):
"""取消关注 :param team_id: :return:"""
... | stack_v2_sparse_classes_36k_train_030331 | 13,604 | no_license | [
{
"docstring": "俱乐部粉丝列表",
"name": "get",
"signature": "def get(self, team_id: int)"
},
{
"docstring": "关注俱乐部 :param team_id: :return:",
"name": "post",
"signature": "def post(self, team_id: int)"
},
{
"docstring": "取消关注 :param team_id: :return:",
"name": "delete",
"signat... | 3 | stack_v2_sparse_classes_30k_train_010993 | Implement the Python class `FollowTeamHandler` described below.
Class description:
用户关注和取消关注俱乐部
Method signatures and docstrings:
- def get(self, team_id: int): 俱乐部粉丝列表
- def post(self, team_id: int): 关注俱乐部 :param team_id: :return:
- def delete(self, team_id: int): 取消关注 :param team_id: :return: | Implement the Python class `FollowTeamHandler` described below.
Class description:
用户关注和取消关注俱乐部
Method signatures and docstrings:
- def get(self, team_id: int): 俱乐部粉丝列表
- def post(self, team_id: int): 关注俱乐部 :param team_id: :return:
- def delete(self, team_id: int): 取消关注 :param team_id: :return:
<|skeleton|>
class Fo... | 49c31d9cce6ca451ff069697913b33fe55028a46 | <|skeleton|>
class FollowTeamHandler:
"""用户关注和取消关注俱乐部"""
def get(self, team_id: int):
"""俱乐部粉丝列表"""
<|body_0|>
def post(self, team_id: int):
"""关注俱乐部 :param team_id: :return:"""
<|body_1|>
def delete(self, team_id: int):
"""取消关注 :param team_id: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FollowTeamHandler:
"""用户关注和取消关注俱乐部"""
def get(self, team_id: int):
"""俱乐部粉丝列表"""
team = Team.get_or_404(id=team_id)
query = TeamService.followers(team=team)
page = self.paginate_query(query)
data = self.render_page_info(page)
data['followers'] = []
... | the_stack_v2_python_sparse | PaiDuiGuanJia/yiyun/handlers/rest/team.py | haoweiking/image_tesseract_private | train | 0 |
9e0e45d46a3d8009059101e433f45d7038fedd31 | [
"modules_data = data[src]\nif self._n_modules == 1:\n return np.expand_dims(np.moveaxis(modules_data, -1, 0), axis=1)\nif isinstance(modules_data, np.ndarray):\n if modules_data.shape[1] == self._module_shape[0]:\n modules_data = np.moveaxis(modules_data, -1, 0)\n return modules_data\nreturn _stack_... | <|body_start_0|>
modules_data = data[src]
if self._n_modules == 1:
return np.expand_dims(np.moveaxis(modules_data, -1, 0), axis=1)
if isinstance(modules_data, np.ndarray):
if modules_data.shape[1] == self._module_shape[0]:
modules_data = np.moveaxis(module... | JungFrauImageAssembler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JungFrauImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. Calibrated data only. Single module: - calibrated, "data.adc", (y, x, memory cells) - raw, "data.adc", TODO Stacked module: - calibrated, "data.adc", (modules, y, x, memory cells) - raw, "data.adc", T... | stack_v2_sparse_classes_36k_train_030332 | 23,340 | permissive | [
{
"docstring": "Override. Calibrated data only. Single module: - calibrated, \"data.adc\", (y, x, memory cells) - raw, \"data.adc\", TODO Stacked module: - calibrated, \"data.adc\", (modules, y, x, memory cells) - raw, \"data.adc\", TODO -> (memory cells, modules, y, x)",
"name": "_get_modules_bridge",
... | 2 | stack_v2_sparse_classes_30k_train_005683 | Implement the Python class `JungFrauImageAssembler` described below.
Class description:
Implement the JungFrauImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src, modules): Override. Calibrated data only. Single module: - calibrated, "data.adc", (y, x, memory cells) - raw... | Implement the Python class `JungFrauImageAssembler` described below.
Class description:
Implement the JungFrauImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src, modules): Override. Calibrated data only. Single module: - calibrated, "data.adc", (y, x, memory cells) - raw... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class JungFrauImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. Calibrated data only. Single module: - calibrated, "data.adc", (y, x, memory cells) - raw, "data.adc", TODO Stacked module: - calibrated, "data.adc", (modules, y, x, memory cells) - raw, "data.adc", T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JungFrauImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. Calibrated data only. Single module: - calibrated, "data.adc", (y, x, memory cells) - raw, "data.adc", TODO Stacked module: - calibrated, "data.adc", (modules, y, x, memory cells) - raw, "data.adc", TODO -> (memory... | the_stack_v2_python_sparse | extra_foam/pipeline/processors/image_assembler.py | European-XFEL/EXtra-foam | train | 8 | |
fb6e51f3f5ecd74dc41dfbade1c4059fae3f90dd | [
"args = parse_base.parse_args()\npid = args.get('pid')\nname = args.get('name')\nurl = args.get('url')\nicon = args.get('icon')\nsort = args.get('sort')\n_data = Menu.query.filter_by(name=name, is_del='0').first()\nif _data:\n abort(RET.Forbidden, msg='菜单已存在')\nmodel_data = Menu()\nmodel_data.pid = pid\nmodel_da... | <|body_start_0|>
args = parse_base.parse_args()
pid = args.get('pid')
name = args.get('name')
url = args.get('url')
icon = args.get('icon')
sort = args.get('sort')
_data = Menu.query.filter_by(name=name, is_del='0').first()
if _data:
abort(RET.... | MenuResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuResource:
def post(self):
"""添加菜单"""
<|body_0|>
def put(self):
"""修改菜单"""
<|body_1|>
def get(self):
"""获取菜单树"""
<|body_2|>
def delete(self):
"""删除菜单"""
<|body_3|>
<|end_skeleton|>
<|body_start_0|>
args =... | stack_v2_sparse_classes_36k_train_030333 | 5,254 | permissive | [
{
"docstring": "添加菜单",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "修改菜单",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "获取菜单树",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "删除菜单",
"name": "delete",
"s... | 4 | stack_v2_sparse_classes_30k_train_019434 | Implement the Python class `MenuResource` described below.
Class description:
Implement the MenuResource class.
Method signatures and docstrings:
- def post(self): 添加菜单
- def put(self): 修改菜单
- def get(self): 获取菜单树
- def delete(self): 删除菜单 | Implement the Python class `MenuResource` described below.
Class description:
Implement the MenuResource class.
Method signatures and docstrings:
- def post(self): 添加菜单
- def put(self): 修改菜单
- def get(self): 获取菜单树
- def delete(self): 删除菜单
<|skeleton|>
class MenuResource:
def post(self):
"""添加菜单"""
... | 35ddd2946bf4c97806bb38057a7dc9d6fa97c118 | <|skeleton|>
class MenuResource:
def post(self):
"""添加菜单"""
<|body_0|>
def put(self):
"""修改菜单"""
<|body_1|>
def get(self):
"""获取菜单树"""
<|body_2|>
def delete(self):
"""删除菜单"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MenuResource:
def post(self):
"""添加菜单"""
args = parse_base.parse_args()
pid = args.get('pid')
name = args.get('name')
url = args.get('url')
icon = args.get('icon')
sort = args.get('sort')
_data = Menu.query.filter_by(name=name, is_del='0').first(... | the_stack_v2_python_sparse | service/app/apis/admin/menu.py | xuannanxan/maitul-manage | train | 0 | |
c6b0e1e1489fd9a86b00426967ba18a37300a96b | [
"tweet = line.split(',')[1].lower()\ntweet = re.sub('[^a-z 0-9]', '', tweet)\nwords = tweet.split()\nfor word in words:\n yield (word, 1)",
"total = sum(values)\nif total > 10000:\n yield (key, total)"
] | <|body_start_0|>
tweet = line.split(',')[1].lower()
tweet = re.sub('[^a-z 0-9]', '', tweet)
words = tweet.split()
for word in words:
yield (word, 1)
<|end_body_0|>
<|body_start_1|>
total = sum(values)
if total > 10000:
yield (key, total)
<|end_bod... | MRWordFrequencyCount | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRWordFrequencyCount:
def mapper(self, _, line):
"""Parse tweets from input, remove non-alphanumeric characters and return key,value pair for each word"""
<|body_0|>
def reducer(self, key, values):
"""Aggregate total instances of words, and only return those that app... | stack_v2_sparse_classes_36k_train_030334 | 1,406 | no_license | [
{
"docstring": "Parse tweets from input, remove non-alphanumeric characters and return key,value pair for each word",
"name": "mapper",
"signature": "def mapper(self, _, line)"
},
{
"docstring": "Aggregate total instances of words, and only return those that appear more than 10,000 times",
"... | 2 | stack_v2_sparse_classes_30k_train_001493 | Implement the Python class `MRWordFrequencyCount` described below.
Class description:
Implement the MRWordFrequencyCount class.
Method signatures and docstrings:
- def mapper(self, _, line): Parse tweets from input, remove non-alphanumeric characters and return key,value pair for each word
- def reducer(self, key, va... | Implement the Python class `MRWordFrequencyCount` described below.
Class description:
Implement the MRWordFrequencyCount class.
Method signatures and docstrings:
- def mapper(self, _, line): Parse tweets from input, remove non-alphanumeric characters and return key,value pair for each word
- def reducer(self, key, va... | a0706171ec7d502eb85397862b1daf9912ac15a5 | <|skeleton|>
class MRWordFrequencyCount:
def mapper(self, _, line):
"""Parse tweets from input, remove non-alphanumeric characters and return key,value pair for each word"""
<|body_0|>
def reducer(self, key, values):
"""Aggregate total instances of words, and only return those that app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MRWordFrequencyCount:
def mapper(self, _, line):
"""Parse tweets from input, remove non-alphanumeric characters and return key,value pair for each word"""
tweet = line.split(',')[1].lower()
tweet = re.sub('[^a-z 0-9]', '', tweet)
words = tweet.split()
for word in words:... | the_stack_v2_python_sparse | word_count.py | nickhamlin/MIDS-W205_A4 | train | 0 | |
c6165281e20c1cbfe0226ec5adaa0ad246e71348 | [
"super().__init__()\nassert (kernel_size - 1) % 2 == 0, 'Not support even number kernel size.'\nassert dilation_factor > 0, 'Dilation factor must be > 0.'\nself.conv_layers = torch.nn.ModuleList()\nconv_in_channels = in_channels\nfor i in range(layers - 1):\n if i == 0:\n dilation = 1\n else:\n ... | <|body_start_0|>
super().__init__()
assert (kernel_size - 1) % 2 == 0, 'Not support even number kernel size.'
assert dilation_factor > 0, 'Dilation factor must be > 0.'
self.conv_layers = torch.nn.ModuleList()
conv_in_channels = in_channels
for i in range(layers - 1):
... | Parallel WaveGAN Discriminator module. | ParallelWaveGANDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelWaveGANDiscriminator:
"""Parallel WaveGAN Discriminator module."""
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=10, conv_channels: int=64, dilation_factor: int=1, nonlinear_activation: str='LeakyReLU', nonlinear_activation_params: Dict[s... | stack_v2_sparse_classes_36k_train_030335 | 12,423 | permissive | [
{
"docstring": "Initialize ParallelWaveGANDiscriminator module. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. kernel_size (int): Number of output channels. layers (int): Number of conv layers. conv_channels (int): Number of chnn layers. dilation_factor (int): ... | 4 | null | Implement the Python class `ParallelWaveGANDiscriminator` described below.
Class description:
Parallel WaveGAN Discriminator module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=10, conv_channels: int=64, dilation_factor: int=1, nonlin... | Implement the Python class `ParallelWaveGANDiscriminator` described below.
Class description:
Parallel WaveGAN Discriminator module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=10, conv_channels: int=64, dilation_factor: int=1, nonlin... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class ParallelWaveGANDiscriminator:
"""Parallel WaveGAN Discriminator module."""
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=10, conv_channels: int=64, dilation_factor: int=1, nonlinear_activation: str='LeakyReLU', nonlinear_activation_params: Dict[s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelWaveGANDiscriminator:
"""Parallel WaveGAN Discriminator module."""
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=10, conv_channels: int=64, dilation_factor: int=1, nonlinear_activation: str='LeakyReLU', nonlinear_activation_params: Dict[str, Any]={'ne... | the_stack_v2_python_sparse | espnet2/gan_tts/parallel_wavegan/parallel_wavegan.py | espnet/espnet | train | 7,242 |
796cfb8e71990ec8a252dc775aaff0e21be06e15 | [
"self.do_lower_case = do_lower_case\nself.never_split = never_split if never_split is not None else []\nself.normalize_text = normalize_text\nself.trim_whitespace = trim_whitespace\ntry:\n import rhoknp\nexcept ImportError:\n raise ImportError('You need to install rhoknp to use JumanppTokenizer. See https://g... | <|body_start_0|>
self.do_lower_case = do_lower_case
self.never_split = never_split if never_split is not None else []
self.normalize_text = normalize_text
self.trim_whitespace = trim_whitespace
try:
import rhoknp
except ImportError:
raise ImportErr... | Runs basic tokenization with jumanpp morphological parser. | JumanppTokenizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JumanppTokenizer:
"""Runs basic tokenization with jumanpp morphological parser."""
def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False):
"""Constructs a JumanppTokenizer. Args: **do_lower_case**: (*optional*) boolean (default True) Whe... | stack_v2_sparse_classes_36k_train_030336 | 40,187 | permissive | [
{
"docstring": "Constructs a JumanppTokenizer. Args: **do_lower_case**: (*optional*) boolean (default True) Whether to lowercase the input. **never_split**: (*optional*) list of str Kept for backward compatibility purposes. Now implemented directly at the base class level (see [`PreTrainedTokenizer.tokenize`]) ... | 2 | stack_v2_sparse_classes_30k_train_006987 | Implement the Python class `JumanppTokenizer` described below.
Class description:
Runs basic tokenization with jumanpp morphological parser.
Method signatures and docstrings:
- def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False): Constructs a JumanppTokenizer. Args: *... | Implement the Python class `JumanppTokenizer` described below.
Class description:
Runs basic tokenization with jumanpp morphological parser.
Method signatures and docstrings:
- def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False): Constructs a JumanppTokenizer. Args: *... | 4fa0aff21ee083d0197a898cdf17ff476fae2ac3 | <|skeleton|>
class JumanppTokenizer:
"""Runs basic tokenization with jumanpp morphological parser."""
def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False):
"""Constructs a JumanppTokenizer. Args: **do_lower_case**: (*optional*) boolean (default True) Whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JumanppTokenizer:
"""Runs basic tokenization with jumanpp morphological parser."""
def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False):
"""Constructs a JumanppTokenizer. Args: **do_lower_case**: (*optional*) boolean (default True) Whether to lower... | the_stack_v2_python_sparse | src/transformers/models/bert_japanese/tokenization_bert_japanese.py | huggingface/transformers | train | 102,193 |
b08395a93b717ce972fce37a427e7b2ae3915bbd | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_posix_time.PosixTimeInMicroseconds(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = FirefoxDownloadEventData()\nevent_data.end_time = self._GetDateTimeRowValue(query_hash, row, 'end... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_posix_time.PosixTimeInMicroseconds(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = FirefoxDownlo... | SQLite parser plugin for Mozilla Firefox downloads database files. The Mozilla Firefox downloads database file is typically stored in: downloads.sqlite | FirefoxDownloadsPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirefoxDownloadsPlugin:
"""SQLite parser plugin for Mozilla Firefox downloads database files. The Mozilla Firefox downloads database file is typically stored in: downloads.sqlite"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from t... | stack_v2_sparse_classes_36k_train_030337 | 5,102 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTimeInMicroseconds: date and time value or None if not availabl... | 2 | null | Implement the Python class `FirefoxDownloadsPlugin` described below.
Class description:
SQLite parser plugin for Mozilla Firefox downloads database files. The Mozilla Firefox downloads database file is typically stored in: downloads.sqlite
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash,... | Implement the Python class `FirefoxDownloadsPlugin` described below.
Class description:
SQLite parser plugin for Mozilla Firefox downloads database files. The Mozilla Firefox downloads database file is typically stored in: downloads.sqlite
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash,... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class FirefoxDownloadsPlugin:
"""SQLite parser plugin for Mozilla Firefox downloads database files. The Mozilla Firefox downloads database file is typically stored in: downloads.sqlite"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirefoxDownloadsPlugin:
"""SQLite parser plugin for Mozilla Firefox downloads database files. The Mozilla Firefox downloads database file is typically stored in: downloads.sqlite"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args:... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/firefox_downloads.py | log2timeline/plaso | train | 1,506 |
f0ca8c23852c0e78e947bb372518d41ae296ecbf | [
"self.matrix = matrix\nfor i in range(len(matrix)):\n for j in range(1, len(matrix[0])):\n self.matrix[i][j] += self.matrix[i][j - 1]",
"result = 0\nif col1 == 0:\n for i in range(row1, row2 + 1):\n result += self.matrix[i][col2]\nelse:\n for i in range(row1, row2 + 1):\n result += s... | <|body_start_0|>
self.matrix = matrix
for i in range(len(matrix)):
for j in range(1, len(matrix[0])):
self.matrix[i][j] += self.matrix[i][j - 1]
<|end_body_0|>
<|body_start_1|>
result = 0
if col1 == 0:
for i in range(row1, row2 + 1):
... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_030338 | 910 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 801beb43235872b2419a92b11c4eb05f7ea2adab | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.matrix = matrix
for i in range(len(matrix)):
for j in range(1, len(matrix[0])):
self.matrix[i][j] += self.matrix[i][j - 1]
def sumRegion(self, row1, col1, row2, col2):
... | the_stack_v2_python_sparse | Python/304__Range_Sum_Query_2D-Immutable.py | FIRESTROM/Leetcode | train | 2 | |
0396aee9be9fb2f95172367c6f72288641864231 | [
"self.main_bin = Queue()\nfor num in num_list:\n self.main_bin.enqueue(num)\nself.bin_0 = Queue()\nself.bin_1 = Queue()\nself.bin_2 = Queue()\nself.bin_3 = Queue()\nself.bin_4 = Queue()\nself.bin_5 = Queue()\nself.bin_6 = Queue()\nself.bin_7 = Queue()\nself.bin_8 = Queue()\nself.bin_9 = Queue()",
"while self.m... | <|body_start_0|>
self.main_bin = Queue()
for num in num_list:
self.main_bin.enqueue(num)
self.bin_0 = Queue()
self.bin_1 = Queue()
self.bin_2 = Queue()
self.bin_3 = Queue()
self.bin_4 = Queue()
self.bin_5 = Queue()
self.bin_6 = Queue()
... | RadixSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadixSort:
def __init__(self, num_list):
"""Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:"""
<|body_0|>
def radix_sort(self):
"""Combin... | stack_v2_sparse_classes_36k_train_030339 | 4,261 | no_license | [
{
"docstring": "Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:",
"name": "__init__",
"signature": "def __init__(self, num_list)"
},
{
"docstring": "Combines the Radi... | 4 | stack_v2_sparse_classes_30k_train_010537 | Implement the Python class `RadixSort` described below.
Class description:
Implement the RadixSort class.
Method signatures and docstrings:
- def __init__(self, num_list): Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 di... | Implement the Python class `RadixSort` described below.
Class description:
Implement the RadixSort class.
Method signatures and docstrings:
- def __init__(self, num_list): Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 di... | b36aa897a83a21560a5e80674dd10f5a00d97fa4 | <|skeleton|>
class RadixSort:
def __init__(self, num_list):
"""Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:"""
<|body_0|>
def radix_sort(self):
"""Combin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RadixSort:
def __init__(self, num_list):
"""Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:"""
self.main_bin = Queue()
for num in num_list:
self... | the_stack_v2_python_sparse | DataStructure/week 4/radix_speed.py | Himanshudhir50/Himanshudhir50.github.io | train | 0 | |
872261ec672a8fcc354b6518e4c2e17574b23b4c | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cxiao_jchew1', 'cxiao_jchew1')\nCR = repo['cxiao_jchew1.crime_reports'].find()\nDC = repo['cxiao_jchew1.dispatch_counts'].find()\ncrimeReports = []\nfor i in CR:\n try:\n crimeReports.append({'... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cxiao_jchew1', 'cxiao_jchew1')
CR = repo['cxiao_jchew1.crime_reports'].find()
DC = repo['cxiao_jchew1.dispatch_counts'].find()
crimeReport... | mergeDispatchReports | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mergeDispatchReports:
def execute(trial=False):
"""Merge data sets"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of the script will... | stack_v2_sparse_classes_36k_train_030340 | 4,773 | no_license | [
{
"docstring": "Merge data sets",
"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 document describing that invocation event.",
"name": "prov... | 2 | stack_v2_sparse_classes_30k_train_004500 | Implement the Python class `mergeDispatchReports` described below.
Class description:
Implement the mergeDispatchReports class.
Method signatures and docstrings:
- def execute(trial=False): Merge data sets
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document de... | Implement the Python class `mergeDispatchReports` described below.
Class description:
Implement the mergeDispatchReports class.
Method signatures and docstrings:
- def execute(trial=False): Merge data sets
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document de... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class mergeDispatchReports:
def execute(trial=False):
"""Merge data sets"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of the script will... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mergeDispatchReports:
def execute(trial=False):
"""Merge data sets"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cxiao_jchew1', 'cxiao_jchew1')
CR = repo['cxiao_jchew1.crime_reports'].find()
... | the_stack_v2_python_sparse | cxiao_jchew1/mergeDispatchReports.py | lingyigu/course-2017-spr-proj | train | 0 | |
47c71ca91a7dd0bd27a51e4b155dab3c1279b638 | [
"image = ImagesPerm.objects.filter(img_id=self, username=healthcare, perm_value__in=[2, 3])\nif image.count() == 0:\n return False\nelse:\n return True",
"if self.patient_id == patient:\n return True\nelse:\n return False"
] | <|body_start_0|>
image = ImagesPerm.objects.filter(img_id=self, username=healthcare, perm_value__in=[2, 3])
if image.count() == 0:
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
if self.patient_id == patient:
return True
else:
... | Images | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Images:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the reading."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
image... | stack_v2_sparse_classes_36k_train_030341 | 12,031 | no_license | [
{
"docstring": "Checks if a user has permissions to view the reading.",
"name": "has_permission",
"signature": "def has_permission(self, healthcare)"
},
{
"docstring": "Checks if the record belongs to the patient.",
"name": "is_patient",
"signature": "def is_patient(self, patient)"
}
] | 2 | null | Implement the Python class `Images` described below.
Class description:
Implement the Images class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the reading.
- def is_patient(self, patient): Checks if the record belongs to the patient. | Implement the Python class `Images` described below.
Class description:
Implement the Images class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the reading.
- def is_patient(self, patient): Checks if the record belongs to the patient.
<|skeleton|... | 685c2b9d40fb24ca1735352846a39fdf5d3728eb | <|skeleton|>
class Images:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the reading."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Images:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the reading."""
image = ImagesPerm.objects.filter(img_id=self, username=healthcare, perm_value__in=[2, 3])
if image.count() == 0:
return False
else:
return True
... | the_stack_v2_python_sparse | patientrecords/models.py | guekling/ifs4205team1 | train | 0 | |
05f07a76dddded07a535778a4586a897075b7660 | [
"torch.manual_seed(0)\nmodel = goalDNN(in_dim=20, nb_category=3, nb_measures=1, p_dropout=0.1, hidden_dims=[64, 32])\nrng = np.random.default_rng(seed=0)\nx = torch.tensor(rng.random(size=(10, 20))).float()\n[mmse_hat, dx_hat] = model(x)\nmmse_hat_mean = torch.mean(mmse_hat).detach().numpy()\ndx_hat_mean = torch.me... | <|body_start_0|>
torch.manual_seed(0)
model = goalDNN(in_dim=20, nb_category=3, nb_measures=1, p_dropout=0.1, hidden_dims=[64, 32])
rng = np.random.default_rng(seed=0)
x = torch.tensor(rng.random(size=(10, 20))).float()
[mmse_hat, dx_hat] = model(x)
mmse_hat_mean = torch.... | CBIG_gcVAE_unit_test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBIG_gcVAE_unit_test:
def test_goaldnn_init(self):
"""Test initialization of goalDNN"""
<|body_0|>
def test_cvae_init(self):
"""Test initialization of cVAE"""
<|body_1|>
def test_training(self):
"""Test the training of goalDNN, cVAE, gcVAE, XGBoo... | stack_v2_sparse_classes_36k_train_030342 | 3,321 | permissive | [
{
"docstring": "Test initialization of goalDNN",
"name": "test_goaldnn_init",
"signature": "def test_goaldnn_init(self)"
},
{
"docstring": "Test initialization of cVAE",
"name": "test_cvae_init",
"signature": "def test_cvae_init(self)"
},
{
"docstring": "Test the training of goal... | 3 | stack_v2_sparse_classes_30k_train_018873 | Implement the Python class `CBIG_gcVAE_unit_test` described below.
Class description:
Implement the CBIG_gcVAE_unit_test class.
Method signatures and docstrings:
- def test_goaldnn_init(self): Test initialization of goalDNN
- def test_cvae_init(self): Test initialization of cVAE
- def test_training(self): Test the tr... | Implement the Python class `CBIG_gcVAE_unit_test` described below.
Class description:
Implement the CBIG_gcVAE_unit_test class.
Method signatures and docstrings:
- def test_goaldnn_init(self): Test initialization of goalDNN
- def test_cvae_init(self): Test initialization of cVAE
- def test_training(self): Test the tr... | c773720ad340dcb1d566b0b8de68b6acdf2ca505 | <|skeleton|>
class CBIG_gcVAE_unit_test:
def test_goaldnn_init(self):
"""Test initialization of goalDNN"""
<|body_0|>
def test_cvae_init(self):
"""Test initialization of cVAE"""
<|body_1|>
def test_training(self):
"""Test the training of goalDNN, cVAE, gcVAE, XGBoo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CBIG_gcVAE_unit_test:
def test_goaldnn_init(self):
"""Test initialization of goalDNN"""
torch.manual_seed(0)
model = goalDNN(in_dim=20, nb_category=3, nb_measures=1, p_dropout=0.1, hidden_dims=[64, 32])
rng = np.random.default_rng(seed=0)
x = torch.tensor(rng.random(siz... | the_stack_v2_python_sparse | stable_projects/predict_phenotypes/An2022_gcVAE/unit_tests/CBIG_gcVAE_unit_test.py | ThomasYeoLab/CBIG | train | 508 | |
9290f3a963fc0ba881cc178c29b9f4bbc46c3b9d | [
"create_empty_db()\nadd_customer(**user_1)\nquery = Customer.get(Customer.customer_id == user_1['customer_id'])\nself.assertEqual(user_1['name'], query.customer_name)\nself.assertEqual(user_1['lastname'], query.customer_last_name)\nself.assertEqual(user_1['home_address'], query.customer_address)\nself.assertEqual(u... | <|body_start_0|>
create_empty_db()
add_customer(**user_1)
query = Customer.get(Customer.customer_id == user_1['customer_id'])
self.assertEqual(user_1['name'], query.customer_name)
self.assertEqual(user_1['lastname'], query.customer_last_name)
self.assertEqual(user_1['home... | Tests basic_operations program, along with customer_model | BasicOperationsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicOperationsTest:
"""Tests basic_operations program, along with customer_model"""
def test_add_customer(self):
"""Tests if a new customer is added to database"""
<|body_0|>
def test_search_customer(self):
"""Tests customer search function"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_030343 | 5,205 | no_license | [
{
"docstring": "Tests if a new customer is added to database",
"name": "test_add_customer",
"signature": "def test_add_customer(self)"
},
{
"docstring": "Tests customer search function",
"name": "test_search_customer",
"signature": "def test_search_customer(self)"
},
{
"docstring... | 6 | stack_v2_sparse_classes_30k_val_000727 | Implement the Python class `BasicOperationsTest` described below.
Class description:
Tests basic_operations program, along with customer_model
Method signatures and docstrings:
- def test_add_customer(self): Tests if a new customer is added to database
- def test_search_customer(self): Tests customer search function
... | Implement the Python class `BasicOperationsTest` described below.
Class description:
Tests basic_operations program, along with customer_model
Method signatures and docstrings:
- def test_add_customer(self): Tests if a new customer is added to database
- def test_search_customer(self): Tests customer search function
... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class BasicOperationsTest:
"""Tests basic_operations program, along with customer_model"""
def test_add_customer(self):
"""Tests if a new customer is added to database"""
<|body_0|>
def test_search_customer(self):
"""Tests customer search function"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicOperationsTest:
"""Tests basic_operations program, along with customer_model"""
def test_add_customer(self):
"""Tests if a new customer is added to database"""
create_empty_db()
add_customer(**user_1)
query = Customer.get(Customer.customer_id == user_1['customer_id'])... | the_stack_v2_python_sparse | students/njschafi/Lesson04/assignment/test_basic_operations.py | JavaRod/SP_Python220B_2019 | train | 1 |
e2e77b9bbaeeacff458e42b53d6f9bc550cd479d | [
"self.host = args['host']\nself.port = args['port']\nself.debug = args['debug']\ntemplate_folder = f'{T_SYSTEM_PATH}/remote_ui/www'\nstatic_folder = f'{template_folder}/static'\nself.app = Flask(__name__, template_folder=template_folder, static_folder=static_folder)\nself.remote_ui_dir = f'{dot_t_system_dir}/remote... | <|body_start_0|>
self.host = args['host']
self.port = args['port']
self.debug = args['debug']
template_folder = f'{T_SYSTEM_PATH}/remote_ui/www'
static_folder = f'{template_folder}/static'
self.app = Flask(__name__, template_folder=template_folder, static_folder=static_fo... | Class to define a flask handler to T_System communication ability with html and js. This class provides necessary initiations and a function named :func:`t_system.remote_ui.RemoteUI.__set_app` for the using flask api to communications with html and js. | RemoteUI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteUI:
"""Class to define a flask handler to T_System communication ability with html and js. This class provides necessary initiations and a function named :func:`t_system.remote_ui.RemoteUI.__set_app` for the using flask api to communications with html and js."""
def __init__(self, args... | stack_v2_sparse_classes_36k_train_030344 | 4,779 | permissive | [
{
"docstring": "Initialization method of :class:`t_system.remote_ui.RemoteUI` class. Args: args: Command-line arguments.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Method to setting flask API.",
"name": "__set_app",
"signature": "def __set_app(self)"... | 3 | stack_v2_sparse_classes_30k_train_003958 | Implement the Python class `RemoteUI` described below.
Class description:
Class to define a flask handler to T_System communication ability with html and js. This class provides necessary initiations and a function named :func:`t_system.remote_ui.RemoteUI.__set_app` for the using flask api to communications with html ... | Implement the Python class `RemoteUI` described below.
Class description:
Class to define a flask handler to T_System communication ability with html and js. This class provides necessary initiations and a function named :func:`t_system.remote_ui.RemoteUI.__set_app` for the using flask api to communications with html ... | 4cf34572b8f8eac54d6c339f37aa72b6a13d8934 | <|skeleton|>
class RemoteUI:
"""Class to define a flask handler to T_System communication ability with html and js. This class provides necessary initiations and a function named :func:`t_system.remote_ui.RemoteUI.__set_app` for the using flask api to communications with html and js."""
def __init__(self, args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteUI:
"""Class to define a flask handler to T_System communication ability with html and js. This class provides necessary initiations and a function named :func:`t_system.remote_ui.RemoteUI.__set_app` for the using flask api to communications with html and js."""
def __init__(self, args):
""... | the_stack_v2_python_sparse | t_system/remote_ui/__main__.py | LookAtMe-Genius-Cameraman/T_System | train | 9 |
6e6a50744aad518130f21d5630d0cb7c11dd745f | [
"super().__init__(*args, **kwargs)\nif 'context' in kwargs:\n self.fields['task_queue'].queryset = get_allowed_queues_sorted(user=kwargs['context']['request'].user)",
"attrs = super().validate(attrs)\ntry:\n arguments = attrs['arguments']\n assert arguments is not None\nexcept (KeyError, AssertionError):... | <|body_start_0|>
super().__init__(*args, **kwargs)
if 'context' in kwargs:
self.fields['task_queue'].queryset = get_allowed_queues_sorted(user=kwargs['context']['request'].user)
<|end_body_0|>
<|body_start_1|>
attrs = super().validate(attrs)
try:
arguments = attr... | A serializer for reading a task instance. | AbstractTaskInstanceSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractTaskInstanceSerializer:
"""A serializer for reading a task instance."""
def __init__(self, *args, **kwargs):
"""Initialize the queryset for task queues."""
<|body_0|>
def validate(self, attrs):
"""Ensure the arguments fields passed in are valid. Relies on... | stack_v2_sparse_classes_36k_train_030345 | 4,896 | permissive | [
{
"docstring": "Initialize the queryset for task queues.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Ensure the arguments fields passed in are valid. Relies on the model's clean method. Note that the object-level validation used here effectively pr... | 2 | stack_v2_sparse_classes_30k_train_010624 | Implement the Python class `AbstractTaskInstanceSerializer` described below.
Class description:
A serializer for reading a task instance.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the queryset for task queues.
- def validate(self, attrs): Ensure the arguments fields passed in... | Implement the Python class `AbstractTaskInstanceSerializer` described below.
Class description:
A serializer for reading a task instance.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the queryset for task queues.
- def validate(self, attrs): Ensure the arguments fields passed in... | db498a1186fc74221f8214ad1819dd03bf4b08ac | <|skeleton|>
class AbstractTaskInstanceSerializer:
"""A serializer for reading a task instance."""
def __init__(self, *args, **kwargs):
"""Initialize the queryset for task queues."""
<|body_0|>
def validate(self, attrs):
"""Ensure the arguments fields passed in are valid. Relies on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractTaskInstanceSerializer:
"""A serializer for reading a task instance."""
def __init__(self, *args, **kwargs):
"""Initialize the queryset for task queues."""
super().__init__(*args, **kwargs)
if 'context' in kwargs:
self.fields['task_queue'].queryset = get_allowe... | the_stack_v2_python_sparse | tasksapi/serializers/abstract_tasks.py | saltant-org/saltant | train | 3 |
810ca16f0874a8ee107c7cd91085ccb0463962b3 | [
"shape = [cls.params['batch_size']]\nshape.extend(cls.params['input_shape'])\nreturn shape",
"if normalization_type == 'BatchNormalization':\n normalization = keras.layers.BatchNormalization\nelif normalization_type == 'SyncBatchNormalization':\n normalization = keras.layers.experimental.SyncBatchNormalizat... | <|body_start_0|>
shape = [cls.params['batch_size']]
shape.extend(cls.params['input_shape'])
return shape
<|end_body_0|>
<|body_start_1|>
if normalization_type == 'BatchNormalization':
normalization = keras.layers.BatchNormalization
elif normalization_type == 'SyncBat... | Construct and access Dense + BatchNorm + activation models. | DenseModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseModel:
"""Construct and access Dense + BatchNorm + activation models."""
def get_batched_input_shape(cls):
"""Return input shape with batch size."""
<|body_0|>
def get_nonfolded_batchnorm_model(cls, post_bn_activation=None, normalization_type='BatchNormalization'):
... | stack_v2_sparse_classes_36k_train_030346 | 2,078 | permissive | [
{
"docstring": "Return input shape with batch size.",
"name": "get_batched_input_shape",
"signature": "def get_batched_input_shape(cls)"
},
{
"docstring": "Return nonfolded Dense + BN + optional activation model.",
"name": "get_nonfolded_batchnorm_model",
"signature": "def get_nonfolded_... | 2 | stack_v2_sparse_classes_30k_train_013173 | Implement the Python class `DenseModel` described below.
Class description:
Construct and access Dense + BatchNorm + activation models.
Method signatures and docstrings:
- def get_batched_input_shape(cls): Return input shape with batch size.
- def get_nonfolded_batchnorm_model(cls, post_bn_activation=None, normalizat... | Implement the Python class `DenseModel` described below.
Class description:
Construct and access Dense + BatchNorm + activation models.
Method signatures and docstrings:
- def get_batched_input_shape(cls): Return input shape with batch size.
- def get_nonfolded_batchnorm_model(cls, post_bn_activation=None, normalizat... | 4733c85f21d1eb570fd575ea201cb211a485bfb0 | <|skeleton|>
class DenseModel:
"""Construct and access Dense + BatchNorm + activation models."""
def get_batched_input_shape(cls):
"""Return input shape with batch size."""
<|body_0|>
def get_nonfolded_batchnorm_model(cls, post_bn_activation=None, normalization_type='BatchNormalization'):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DenseModel:
"""Construct and access Dense + BatchNorm + activation models."""
def get_batched_input_shape(cls):
"""Return input shape with batch size."""
shape = [cls.params['batch_size']]
shape.extend(cls.params['input_shape'])
return shape
def get_nonfolded_batchnor... | the_stack_v2_python_sparse | tensorflow_model_optimization/python/core/quantization/keras/layers/dense_batchnorm_test_utils.py | tensorflow/model-optimization | train | 1,550 |
0229a268b1563f09b84cb6f679f9cdaffd8510b1 | [
"stack = []\nresult = []\nfor num in array:\n while stack and stack[-1] >= num:\n stack.pop()\n if stack:\n result.append(stack[-1])\n else:\n result.append(-1)\n stack.append(num)\nreturn result",
"result = [-1]\nfor i in range(1, len(array)):\n if array[i - 1] < array[i]:\n ... | <|body_start_0|>
stack = []
result = []
for num in array:
while stack and stack[-1] >= num:
stack.pop()
if stack:
result.append(stack[-1])
else:
result.append(-1)
stack.append(num)
return resu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def prevSmaller(self, array):
"""Algorithm based on using stack. Time complexity: O(n). Space complexity: O(n), n is len(array)."""
<|body_0|>
def prevSmaller(self, array):
"""Dynamic programming algorithm. The idea is to use output array to store previous ... | stack_v2_sparse_classes_36k_train_030347 | 2,176 | no_license | [
{
"docstring": "Algorithm based on using stack. Time complexity: O(n). Space complexity: O(n), n is len(array).",
"name": "prevSmaller",
"signature": "def prevSmaller(self, array)"
},
{
"docstring": "Dynamic programming algorithm. The idea is to use output array to store previous smaller integer... | 2 | stack_v2_sparse_classes_30k_val_000540 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prevSmaller(self, array): Algorithm based on using stack. Time complexity: O(n). Space complexity: O(n), n is len(array).
- def prevSmaller(self, array): Dynamic programming ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prevSmaller(self, array): Algorithm based on using stack. Time complexity: O(n). Space complexity: O(n), n is len(array).
- def prevSmaller(self, array): Dynamic programming ... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def prevSmaller(self, array):
"""Algorithm based on using stack. Time complexity: O(n). Space complexity: O(n), n is len(array)."""
<|body_0|>
def prevSmaller(self, array):
"""Dynamic programming algorithm. The idea is to use output array to store previous ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def prevSmaller(self, array):
"""Algorithm based on using stack. Time complexity: O(n). Space complexity: O(n), n is len(array)."""
stack = []
result = []
for num in array:
while stack and stack[-1] >= num:
stack.pop()
if stack:... | the_stack_v2_python_sparse | Stack/nearest_smaller_element.py | vladn90/Algorithms | train | 0 | |
dc3bbb76f8ec9c767b6529a2901447d782dd33c2 | [
"EzvizEntity.__init__(self, coordinator, serial)\nImageEntity.__init__(self, hass)\nself._attr_unique_id = f'{serial}_{IMAGE_TYPE.key}'\nself.entity_description = IMAGE_TYPE\nself._attr_image_url = self.data['last_alarm_pic']\nself._attr_image_last_updated = dt_util.parse_datetime(str(self.data['last_alarm_time']))... | <|body_start_0|>
EzvizEntity.__init__(self, coordinator, serial)
ImageEntity.__init__(self, hass)
self._attr_unique_id = f'{serial}_{IMAGE_TYPE.key}'
self.entity_description = IMAGE_TYPE
self._attr_image_url = self.data['last_alarm_pic']
self._attr_image_last_updated = dt... | Return Last Motion Image from Ezviz Camera. | EzvizLastMotion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EzvizLastMotion:
"""Return Last Motion Image from Ezviz Camera."""
def __init__(self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize a image entity."""
<|body_0|>
async def _async_load_image_from_url(self, url: str) -> I... | stack_v2_sparse_classes_36k_train_030348 | 2,705 | permissive | [
{
"docstring": "Initialize a image entity.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None"
},
{
"docstring": "Load an image by url.",
"name": "_async_load_image_from_url",
"signature": "async def _... | 3 | null | Implement the Python class `EzvizLastMotion` described below.
Class description:
Return Last Motion Image from Ezviz Camera.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None: Initialize a image entity.
- async def _async_load_ima... | Implement the Python class `EzvizLastMotion` described below.
Class description:
Return Last Motion Image from Ezviz Camera.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None: Initialize a image entity.
- async def _async_load_ima... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EzvizLastMotion:
"""Return Last Motion Image from Ezviz Camera."""
def __init__(self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize a image entity."""
<|body_0|>
async def _async_load_image_from_url(self, url: str) -> I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EzvizLastMotion:
"""Return Last Motion Image from Ezviz Camera."""
def __init__(self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize a image entity."""
EzvizEntity.__init__(self, coordinator, serial)
ImageEntity.__init__(self, has... | the_stack_v2_python_sparse | homeassistant/components/ezviz/image.py | home-assistant/core | train | 35,501 |
bc38fce3df94037e322af0b50699555dbbe1135e | [
"def validMutation(curr, next):\n return sum([c != n for c, n in zip(curr, next)]) == 1\nfrom collections import deque\nqueue = deque([[start, 0]])\nexplored = set()\nwhile queue:\n curr, mutations = queue.popleft()\n if curr == end:\n return mutations\n for s in bank:\n if validMutation(c... | <|body_start_0|>
def validMutation(curr, next):
return sum([c != n for c, n in zip(curr, next)]) == 1
from collections import deque
queue = deque([[start, 0]])
explored = set()
while queue:
curr, mutations = queue.popleft()
if curr == end:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMutation1(self, start: str, end: str, bank: List[str]) -> int:
"""1. BFS: 遍历基因库(bank),保留能由当前序列(curr)合法变异得到的序列。"""
<|body_0|>
def minMutation2(self, start: str, end: str, bank: List[str]) -> int:
"""2. BFS: 由当前序列(curr)生成所有可能的变异,遍历并判断是否为合法的变异。"""
... | stack_v2_sparse_classes_36k_train_030349 | 4,085 | no_license | [
{
"docstring": "1. BFS: 遍历基因库(bank),保留能由当前序列(curr)合法变异得到的序列。",
"name": "minMutation1",
"signature": "def minMutation1(self, start: str, end: str, bank: List[str]) -> int"
},
{
"docstring": "2. BFS: 由当前序列(curr)生成所有可能的变异,遍历并判断是否为合法的变异。",
"name": "minMutation2",
"signature": "def minMutatio... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMutation1(self, start: str, end: str, bank: List[str]) -> int: 1. BFS: 遍历基因库(bank),保留能由当前序列(curr)合法变异得到的序列。
- def minMutation2(self, start: str, end: str, bank: List[str])... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMutation1(self, start: str, end: str, bank: List[str]) -> int: 1. BFS: 遍历基因库(bank),保留能由当前序列(curr)合法变异得到的序列。
- def minMutation2(self, start: str, end: str, bank: List[str])... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def minMutation1(self, start: str, end: str, bank: List[str]) -> int:
"""1. BFS: 遍历基因库(bank),保留能由当前序列(curr)合法变异得到的序列。"""
<|body_0|>
def minMutation2(self, start: str, end: str, bank: List[str]) -> int:
"""2. BFS: 由当前序列(curr)生成所有可能的变异,遍历并判断是否为合法的变异。"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minMutation1(self, start: str, end: str, bank: List[str]) -> int:
"""1. BFS: 遍历基因库(bank),保留能由当前序列(curr)合法变异得到的序列。"""
def validMutation(curr, next):
return sum([c != n for c, n in zip(curr, next)]) == 1
from collections import deque
queue = deque([[star... | the_stack_v2_python_sparse | .leetcode/433.最小基因变化.py | xiaoruijiang/algorithm | train | 0 | |
9f2ee347ef49c508215cb7aebdbbe62734b471cf | [
"serial = []\nq = []\nif root:\n q.append((root, 1))\n serial.append(str(root.val))\n serial.append('None')\nwhile q:\n root, level = q.pop(0)\n if root.children:\n for child in root.children:\n serial.append(str(child.val))\n q.append((child, level + 1))\n serial.appe... | <|body_start_0|>
serial = []
q = []
if root:
q.append((root, 1))
serial.append(str(root.val))
serial.append('None')
while q:
root, level = q.pop(0)
if root.children:
for child in root.children:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_030350 | 1,824 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 920b65db80031fad45d495431eda8d3fb4ef06e5 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
serial = []
q = []
if root:
q.append((root, 1))
serial.append(str(root.val))
serial.append('None')
while q:
... | the_stack_v2_python_sparse | hard/ex428.py | ziyuan-shen/leetcode_algorithm_python_solution | train | 2 | |
f8847d1c5a362efb57abaa7c0831d17b4d569a38 | [
"self._reauth_entry = None\nself._email = None\nself._region = None",
"errors = {}\nif user_input is not None:\n self._email = user_input[CONF_EMAIL]\n self._region = user_input[CONF_REGION]\n unique_id = user_input[CONF_EMAIL].lower()\n await self.async_set_unique_id(unique_id)\n if not self._reau... | <|body_start_0|>
self._reauth_entry = None
self._email = None
self._region = None
<|end_body_0|>
<|body_start_1|>
errors = {}
if user_input is not None:
self._email = user_input[CONF_EMAIL]
self._region = user_input[CONF_REGION]
unique_id = us... | Handle a config flow for Mazda Connected Services. | MazdaConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MazdaConfigFlow:
"""Handle a config flow for Mazda Connected Services."""
def __init__(self):
"""Start the mazda config flow."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_1|>
async def async_st... | stack_v2_sparse_classes_36k_train_030351 | 3,926 | permissive | [
{
"docstring": "Start the mazda config flow.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Perform reauth if the u... | 3 | stack_v2_sparse_classes_30k_train_011054 | Implement the Python class `MazdaConfigFlow` described below.
Class description:
Handle a config flow for Mazda Connected Services.
Method signatures and docstrings:
- def __init__(self): Start the mazda config flow.
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_r... | Implement the Python class `MazdaConfigFlow` described below.
Class description:
Handle a config flow for Mazda Connected Services.
Method signatures and docstrings:
- def __init__(self): Start the mazda config flow.
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_r... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MazdaConfigFlow:
"""Handle a config flow for Mazda Connected Services."""
def __init__(self):
"""Start the mazda config flow."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_1|>
async def async_st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MazdaConfigFlow:
"""Handle a config flow for Mazda Connected Services."""
def __init__(self):
"""Start the mazda config flow."""
self._reauth_entry = None
self._email = None
self._region = None
async def async_step_user(self, user_input=None):
"""Handle the in... | the_stack_v2_python_sparse | homeassistant/components/mazda/config_flow.py | home-assistant/core | train | 35,501 |
d16195cef1951489851676f3ab61c2660aaf4322 | [
"self.input_basis = input_basis\nself.input_molecule = input_molecule\nself.integrator_3D = integrator_3D\nself.integrator_6D = integrator_6D\nself.convergence_config = convergence_config",
"S = Overlap(self.input_basis, self.integrator_3D)\nT = KineticEnergy(self.input_basis, self.integrator_3D)\nV_nuc = Nuclear... | <|body_start_0|>
self.input_basis = input_basis
self.input_molecule = input_molecule
self.integrator_3D = integrator_3D
self.integrator_6D = integrator_6D
self.convergence_config = convergence_config
<|end_body_0|>
<|body_start_1|>
S = Overlap(self.input_basis, self.inte... | Object responsible for running SCF procedure | SelfConsistentFieldProcedure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfConsistentFieldProcedure:
"""Object responsible for running SCF procedure"""
def __init__(self, input_basis: RootBasis, input_molecule: Molecule, integrator_3D: BaseIntegrator, integrator_6D: BaseIntegrator, convergence_config: ConvergenceConfig):
""":param basis: RootBasis (pare... | stack_v2_sparse_classes_36k_train_030352 | 2,966 | no_license | [
{
"docstring": ":param basis: RootBasis (parent class), object representing basis set used for calculation :param molecule: Molecule: object which defines the distribution of nuclei in space and their atomic numbers :param integrator_3D: BaseIntegrator (parent class), integrator object with predefined values of... | 2 | stack_v2_sparse_classes_30k_train_013966 | Implement the Python class `SelfConsistentFieldProcedure` described below.
Class description:
Object responsible for running SCF procedure
Method signatures and docstrings:
- def __init__(self, input_basis: RootBasis, input_molecule: Molecule, integrator_3D: BaseIntegrator, integrator_6D: BaseIntegrator, convergence_... | Implement the Python class `SelfConsistentFieldProcedure` described below.
Class description:
Object responsible for running SCF procedure
Method signatures and docstrings:
- def __init__(self, input_basis: RootBasis, input_molecule: Molecule, integrator_3D: BaseIntegrator, integrator_6D: BaseIntegrator, convergence_... | 04b34d97f72329a39d3974ec7011bc0266efface | <|skeleton|>
class SelfConsistentFieldProcedure:
"""Object responsible for running SCF procedure"""
def __init__(self, input_basis: RootBasis, input_molecule: Molecule, integrator_3D: BaseIntegrator, integrator_6D: BaseIntegrator, convergence_config: ConvergenceConfig):
""":param basis: RootBasis (pare... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfConsistentFieldProcedure:
"""Object responsible for running SCF procedure"""
def __init__(self, input_basis: RootBasis, input_molecule: Molecule, integrator_3D: BaseIntegrator, integrator_6D: BaseIntegrator, convergence_config: ConvergenceConfig):
""":param basis: RootBasis (parent class), ob... | the_stack_v2_python_sparse | SCF_method/calculation/procedure.py | Semanames/quantum_chemistry | train | 0 |
ef73339436ae53e0b7927deff34b202f6a79ae75 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('id', required=False, type=int, store_missing=False)\nself.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)\nself.reqparser.add_argument('attribute_id', required=False, type=str, store_missing=False)",
"args = ... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('id', required=False, type=int, store_missing=False)
self.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)
self.reqparser.add_argument('attribute_id', required=False, ty... | Delete an alert. Use a POST request to delete an alert. The following parameters can be parsed as a JSON body content: * id: Alert Id. * user_id: User Id. * attribute_Id: Attribute Id. All parameters are optional but at least one of the above parameters are required. | DeleteAlerts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteAlerts:
"""Delete an alert. Use a POST request to delete an alert. The following parameters can be parsed as a JSON body content: * id: Alert Id. * user_id: User Id. * attribute_Id: Attribute Id. All parameters are optional but at least one of the above parameters are required."""
def ... | stack_v2_sparse_classes_36k_train_030353 | 2,911 | permissive | [
{
"docstring": "Instantiate reqpare for POST request.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Delete an alert. :return: On success, A HTTP response with a a JSON body content containing a message, a list of deleted alerts and an HTTP status code 200 (OK... | 2 | stack_v2_sparse_classes_30k_train_006640 | Implement the Python class `DeleteAlerts` described below.
Class description:
Delete an alert. Use a POST request to delete an alert. The following parameters can be parsed as a JSON body content: * id: Alert Id. * user_id: User Id. * attribute_Id: Attribute Id. All parameters are optional but at least one of the abov... | Implement the Python class `DeleteAlerts` described below.
Class description:
Delete an alert. Use a POST request to delete an alert. The following parameters can be parsed as a JSON body content: * id: Alert Id. * user_id: User Id. * attribute_Id: Attribute Id. All parameters are optional but at least one of the abov... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class DeleteAlerts:
"""Delete an alert. Use a POST request to delete an alert. The following parameters can be parsed as a JSON body content: * id: Alert Id. * user_id: User Id. * attribute_Id: Attribute Id. All parameters are optional but at least one of the above parameters are required."""
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteAlerts:
"""Delete an alert. Use a POST request to delete an alert. The following parameters can be parsed as a JSON body content: * id: Alert Id. * user_id: User Id. * attribute_Id: Attribute Id. All parameters are optional but at least one of the above parameters are required."""
def __init__(self... | the_stack_v2_python_sparse | Analytics/resources/alerts/delete_alert.py | thanosbnt/SharingCitiesDashboard | train | 0 |
d47915b62f9f4b4ddf879a588a331aefc7712abc | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('nhuang54_wud', 'nhuang54_wud')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/eee77dc4ab3d479f83b2100542285727_12.csv'\njson_file = csv_to_json(url)\nrepo.dropCollection('trafficSignal... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('nhuang54_wud', 'nhuang54_wud')
url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/eee77dc4ab3d479f83b2100542285727_12.csv'
json_file... | getTrafficSignal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getTrafficSignal:
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 everyth... | stack_v2_sparse_classes_36k_train_030354 | 4,078 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `getTrafficSignal` described below.
Class description:
Implement the getTrafficSignal 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=N... | Implement the Python class `getTrafficSignal` described below.
Class description:
Implement the getTrafficSignal 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=N... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class getTrafficSignal:
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 everyth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getTrafficSignal:
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('nhuang54_wud', 'nhuang54_wud')
... | the_stack_v2_python_sparse | nhuang54_wud/getTrafficSignal.py | maximega/course-2019-spr-proj | train | 2 | |
a20d519881ca401ca644c2ceb93c5ce58635cbb8 | [
"for article in self.articles['all']:\n if self.mock_datetime():\n self.mocked_datetime.now.side_effect = [article['bson']['post_create']['created_at'], article['bson']['post_create']['updated_at']]\n self.mock_queues()\n create_article(article['message_body']['pre_create'], self.mocked_message)\n ... | <|body_start_0|>
for article in self.articles['all']:
if self.mock_datetime():
self.mocked_datetime.now.side_effect = [article['bson']['post_create']['created_at'], article['bson']['post_create']['updated_at']]
self.mock_queues()
create_article(article['messag... | SpreadArticleCreateWithDatastoreTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpreadArticleCreateWithDatastoreTest:
def test_article_create_uncreated(self):
"""spread.articles—create—unmocked datastores,uncreated"""
<|body_0|>
def test_article_create_created(self):
"""spread.articles—create—unmocked datastores,created"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_030355 | 8,186 | no_license | [
{
"docstring": "spread.articles—create—unmocked datastores,uncreated",
"name": "test_article_create_uncreated",
"signature": "def test_article_create_uncreated(self)"
},
{
"docstring": "spread.articles—create—unmocked datastores,created",
"name": "test_article_create_created",
"signature... | 2 | stack_v2_sparse_classes_30k_train_002067 | Implement the Python class `SpreadArticleCreateWithDatastoreTest` described below.
Class description:
Implement the SpreadArticleCreateWithDatastoreTest class.
Method signatures and docstrings:
- def test_article_create_uncreated(self): spread.articles—create—unmocked datastores,uncreated
- def test_article_create_cr... | Implement the Python class `SpreadArticleCreateWithDatastoreTest` described below.
Class description:
Implement the SpreadArticleCreateWithDatastoreTest class.
Method signatures and docstrings:
- def test_article_create_uncreated(self): spread.articles—create—unmocked datastores,uncreated
- def test_article_create_cr... | a1eaa4d46824222dbab840df06bce2302e8407e7 | <|skeleton|>
class SpreadArticleCreateWithDatastoreTest:
def test_article_create_uncreated(self):
"""spread.articles—create—unmocked datastores,uncreated"""
<|body_0|>
def test_article_create_created(self):
"""spread.articles—create—unmocked datastores,created"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpreadArticleCreateWithDatastoreTest:
def test_article_create_uncreated(self):
"""spread.articles—create—unmocked datastores,uncreated"""
for article in self.articles['all']:
if self.mock_datetime():
self.mocked_datetime.now.side_effect = [article['bson']['post_crea... | the_stack_v2_python_sparse | test_margarine/test_integration/test_spread/test_articles.py | alunduil/margarine | train | 3 | |
c069b814c4ea92976e1a759963e063c33df202f7 | [
"super().__init__(name=name)\nself.model = model\nself.opt = opt\nself.loss = loss",
"step = hk.get_state('step', [], init=lambda *_: 0)\nparams, state = hk.get_state('model_params_state', [], init=lambda *_: ParamsState(*self.model.init(hk.next_rng_key(), x)))\nopt_state = hk.get_state('opt_state', [], init=lamb... | <|body_start_0|>
super().__init__(name=name)
self.model = model
self.opt = opt
self.loss = loss
<|end_body_0|>
<|body_start_1|>
step = hk.get_state('step', [], init=lambda *_: 0)
params, state = hk.get_state('model_params_state', [], init=lambda *_: ParamsState(*self.mod... | Online supervised learner. | OnlineSupervisedLearner | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnlineSupervisedLearner:
"""Online supervised learner."""
def __init__(self, model: Any, opt: Any, loss: Callable, name: str=None):
"""Initialize module. Args: model : model to optimize. opt : optimizer. loss : loss function. name : name of the module"""
<|body_0|>
def _... | stack_v2_sparse_classes_36k_train_030356 | 2,540 | permissive | [
{
"docstring": "Initialize module. Args: model : model to optimize. opt : optimizer. loss : loss function. name : name of the module",
"name": "__init__",
"signature": "def __init__(self, model: Any, opt: Any, loss: Callable, name: str=None)"
},
{
"docstring": "Update learner. Args: x : features... | 2 | stack_v2_sparse_classes_30k_train_007227 | Implement the Python class `OnlineSupervisedLearner` described below.
Class description:
Online supervised learner.
Method signatures and docstrings:
- def __init__(self, model: Any, opt: Any, loss: Callable, name: str=None): Initialize module. Args: model : model to optimize. opt : optimizer. loss : loss function. n... | Implement the Python class `OnlineSupervisedLearner` described below.
Class description:
Online supervised learner.
Method signatures and docstrings:
- def __init__(self, model: Any, opt: Any, loss: Callable, name: str=None): Initialize module. Args: model : model to optimize. opt : optimizer. loss : loss function. n... | ab18e064f9fa1c95458978f501efb6cde9ab64d5 | <|skeleton|>
class OnlineSupervisedLearner:
"""Online supervised learner."""
def __init__(self, model: Any, opt: Any, loss: Callable, name: str=None):
"""Initialize module. Args: model : model to optimize. opt : optimizer. loss : loss function. name : name of the module"""
<|body_0|>
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnlineSupervisedLearner:
"""Online supervised learner."""
def __init__(self, model: Any, opt: Any, loss: Callable, name: str=None):
"""Initialize module. Args: model : model to optimize. opt : optimizer. loss : loss function. name : name of the module"""
super().__init__(name=name)
... | the_stack_v2_python_sparse | wax/modules/online_supervised_learner.py | zggl/wax-ml | train | 0 |
b50bcb43043412079a1d839ea590f3ccfe583c88 | [
"self.read = read\nself.strand_p = strand_p\nself.ref = ref\nself.bsmb = bsmb\nself.original_length = original_length\nself.sequence_context = sequence_context\nself.BS_conversion = {'+': ('C', 'T'), '-': ('G', 'A')}\nself.reverse_strand = ['-+']",
"read_s = RI(self.read, self.bsmb)\nread_info = read_s.extract_in... | <|body_start_0|>
self.read = read
self.strand_p = strand_p
self.ref = ref
self.bsmb = bsmb
self.original_length = original_length
self.sequence_context = sequence_context
self.BS_conversion = {'+': ('C', 'T'), '-': ('G', 'A')}
self.reverse_strand = ['-+']
... | For a single-end or paired-end read, according to the reference genome, if the C in one position is CpG, we record the methylation state. the process is stratified by strand and read length. | MethReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethReader:
"""For a single-end or paired-end read, according to the reference genome, if the C in one position is CpG, we record the methylation state. the process is stratified by strand and read length."""
def __init__(self, read, strand_p, ref, bsmb, original_length, sequence_context):
... | stack_v2_sparse_classes_36k_train_030357 | 6,960 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, read, strand_p, ref, bsmb, original_length, sequence_context)"
},
{
"docstring": "Using the read class If the read is unique mapping or unique and paired mapping, we will get a information list. If not, we will get... | 6 | stack_v2_sparse_classes_30k_train_020172 | Implement the Python class `MethReader` described below.
Class description:
For a single-end or paired-end read, according to the reference genome, if the C in one position is CpG, we record the methylation state. the process is stratified by strand and read length.
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `MethReader` described below.
Class description:
For a single-end or paired-end read, according to the reference genome, if the C in one position is CpG, we record the methylation state. the process is stratified by strand and read length.
Method signatures and docstrings:
- def __init__(se... | 2ada5de21b644c28cecc3357a82fb25faa124a50 | <|skeleton|>
class MethReader:
"""For a single-end or paired-end read, according to the reference genome, if the C in one position is CpG, we record the methylation state. the process is stratified by strand and read length."""
def __init__(self, read, strand_p, ref, bsmb, original_length, sequence_context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MethReader:
"""For a single-end or paired-end read, according to the reference genome, if the C in one position is CpG, we record the methylation state. the process is stratified by strand and read length."""
def __init__(self, read, strand_p, ref, bsmb, original_length, sequence_context):
"""Ini... | the_stack_v2_python_sparse | BSeQC/read/C_information.py | lijinbio/BSeQCpkg | train | 0 |
96e32d4446eef4a08cf5d42b33ec12f5183a6d21 | [
"if self.train_verbose >= 2 and self.trainer.is_chief and (batch_index % self.train_report_steps == 0):\n try:\n out_buffer = OrderedDict(time=time.strftime('%Y-%m-%d @ %H:%M:%S'), epoch=f'{self.cur_epoch}/{self.trainer.epochs}', step=f'{self._format_batch(batch_index, self.train_num_batches)}', lr=f\"{se... | <|body_start_0|>
if self.train_verbose >= 2 and self.trainer.is_chief and (batch_index % self.train_report_steps == 0):
try:
out_buffer = OrderedDict(time=time.strftime('%Y-%m-%d @ %H:%M:%S'), epoch=f'{self.cur_epoch}/{self.trainer.epochs}', step=f'{self._format_batch(batch_index, se... | Callback that shows the progress of evaluating metrics. | DetectionProgressLogger | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetectionProgressLogger:
"""Callback that shows the progress of evaluating metrics."""
def after_train_step(self, batch_index, logs=None):
"""Be called before each batch training."""
<|body_0|>
def after_valid_step(self, batch_index, logs=None):
"""Be called afte... | stack_v2_sparse_classes_36k_train_030358 | 3,641 | permissive | [
{
"docstring": "Be called before each batch training.",
"name": "after_train_step",
"signature": "def after_train_step(self, batch_index, logs=None)"
},
{
"docstring": "Be called after each batch of the validation.",
"name": "after_valid_step",
"signature": "def after_valid_step(self, ba... | 3 | null | Implement the Python class `DetectionProgressLogger` described below.
Class description:
Callback that shows the progress of evaluating metrics.
Method signatures and docstrings:
- def after_train_step(self, batch_index, logs=None): Be called before each batch training.
- def after_valid_step(self, batch_index, logs=... | Implement the Python class `DetectionProgressLogger` described below.
Class description:
Callback that shows the progress of evaluating metrics.
Method signatures and docstrings:
- def after_train_step(self, batch_index, logs=None): Be called before each batch training.
- def after_valid_step(self, batch_index, logs=... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class DetectionProgressLogger:
"""Callback that shows the progress of evaluating metrics."""
def after_train_step(self, batch_index, logs=None):
"""Be called before each batch training."""
<|body_0|>
def after_valid_step(self, batch_index, logs=None):
"""Be called afte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetectionProgressLogger:
"""Callback that shows the progress of evaluating metrics."""
def after_train_step(self, batch_index, logs=None):
"""Be called before each batch training."""
if self.train_verbose >= 2 and self.trainer.is_chief and (batch_index % self.train_report_steps == 0):
... | the_stack_v2_python_sparse | vega/trainer/callbacks/detection_progress_logger.py | huawei-noah/vega | train | 850 |
19e740c58b6ffea526b0d01592f3bf43b4136535 | [
"_input = [dict(a=1, b=2)]\nexpected = '\\r\\n'.join(['sep=,', '\"a\",\"b\"', '\"1\",\"2\"'])\nassert CsvConverter(_input).convert_to_ms_excel() == expected",
"_input = [dict(a=1, b=2)]\nexpected = '\\r\\n'.join(['sep=,', '\"a\",=\"b\"', '\"1\",=\"2\"'])\nassert CsvConverter(_input).convert_to_ms_excel(text_field... | <|body_start_0|>
_input = [dict(a=1, b=2)]
expected = '\r\n'.join(['sep=,', '"a","b"', '"1","2"'])
assert CsvConverter(_input).convert_to_ms_excel() == expected
<|end_body_0|>
<|body_start_1|>
_input = [dict(a=1, b=2)]
expected = '\r\n'.join(['sep=,', '"a",="b"', '"1",="2"'])
... | TestCsvMSExcel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCsvMSExcel:
def test_ms_excel_format():
"""MS Excel treats CSV files with 'sep=,' as the first line to get automatically columnized"""
<|body_0|>
def test_text_fields():
"""MS Excel CSV fields prefixed with '=' will be treated as equations to string. This makes i... | stack_v2_sparse_classes_36k_train_030359 | 6,227 | permissive | [
{
"docstring": "MS Excel treats CSV files with 'sep=,' as the first line to get automatically columnized",
"name": "test_ms_excel_format",
"signature": "def test_ms_excel_format()"
},
{
"docstring": "MS Excel CSV fields prefixed with '=' will be treated as equations to string. This makes it poss... | 4 | stack_v2_sparse_classes_30k_train_019496 | Implement the Python class `TestCsvMSExcel` described below.
Class description:
Implement the TestCsvMSExcel class.
Method signatures and docstrings:
- def test_ms_excel_format(): MS Excel treats CSV files with 'sep=,' as the first line to get automatically columnized
- def test_text_fields(): MS Excel CSV fields pre... | Implement the Python class `TestCsvMSExcel` described below.
Class description:
Implement the TestCsvMSExcel class.
Method signatures and docstrings:
- def test_ms_excel_format(): MS Excel treats CSV files with 'sep=,' as the first line to get automatically columnized
- def test_text_fields(): MS Excel CSV fields pre... | f303b9c84b1fb8c145645cb49f88d21efb6ead95 | <|skeleton|>
class TestCsvMSExcel:
def test_ms_excel_format():
"""MS Excel treats CSV files with 'sep=,' as the first line to get automatically columnized"""
<|body_0|>
def test_text_fields():
"""MS Excel CSV fields prefixed with '=' will be treated as equations to string. This makes i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCsvMSExcel:
def test_ms_excel_format():
"""MS Excel treats CSV files with 'sep=,' as the first line to get automatically columnized"""
_input = [dict(a=1, b=2)]
expected = '\r\n'.join(['sep=,', '"a","b"', '"1","2"'])
assert CsvConverter(_input).convert_to_ms_excel() == expe... | the_stack_v2_python_sparse | tools/convert_test.py | cachengo/rec-build-tools | train | 0 | |
7d596da67bd5973431e3a4e4a99edcba6f78bb2d | [
"instance = parser.add_argument('instance', help='Cloud SQL instance ID.')\ncli = Connect.GetCLIGenerator()\ninstance.completer = remote_completion.RemoteCompletion.GetCompleterForResource('sql.instances', cli)\nparser.add_argument('--user', '-u', required=False, help='Cloud SQL instance user to connect as.')",
"... | <|body_start_0|>
instance = parser.add_argument('instance', help='Cloud SQL instance ID.')
cli = Connect.GetCLIGenerator()
instance.completer = remote_completion.RemoteCompletion.GetCompleterForResource('sql.instances', cli)
parser.add_argument('--user', '-u', required=False, help='Cloud... | Connects to a Cloud SQL instance. | Connect | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Connect:
"""Connects to a Cloud SQL instance."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowe... | stack_v2_sparse_classes_36k_train_030360 | 6,959 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstri... | 2 | null | Implement the Python class `Connect` described below.
Class description:
Connects to a Cloud SQL instance.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command... | Implement the Python class `Connect` described below.
Class description:
Connects to a Cloud SQL instance.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command... | b7f676ab7bd494d71dbb5bda1d6a9094dfaedc0a | <|skeleton|>
class Connect:
"""Connects to a Cloud SQL instance."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Connect:
"""Connects to a Cloud SQL instance."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed."""
... | the_stack_v2_python_sparse | smry/server-auth/ls/google-cloud-sdk/lib/googlecloudsdk/sql/tools/connect.py | wemanuel/smry | train | 0 |
d675ffb926b6f8f2fb131440c062b5fa10eee2f4 | [
"super().__init__()\nself.encoder = ConvEncoder(H, W, input_channel, channel_list, hidden_dims, z_dim)\nchannel_list.reverse()\nhidden_dims.reverse()\nself.decoder = ConvDecoder(H, W, input_channel, channel_list, hidden_dims, z_dim)\nself.noise = noise",
"z = self.encoder(x)\nif self.noise > 0:\n z_decoder = z... | <|body_start_0|>
super().__init__()
self.encoder = ConvEncoder(H, W, input_channel, channel_list, hidden_dims, z_dim)
channel_list.reverse()
hidden_dims.reverse()
self.decoder = ConvDecoder(H, W, input_channel, channel_list, hidden_dims, z_dim)
self.noise = noise
<|end_bo... | Autoencoder with convolutions for image datasets. | ConvAutoencoderModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvAutoencoderModule:
"""Autoencoder with convolutions for image datasets."""
def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim, noise):
"""Init. Arguments specify the architecture of the encoder. Decoder will use the reverse architecture. Args: H(int): Height... | stack_v2_sparse_classes_36k_train_030361 | 10,936 | no_license | [
{
"docstring": "Init. Arguments specify the architecture of the encoder. Decoder will use the reverse architecture. Args: H(int): Height of the input data. W(int): Width of the input data input_channel(int): Number of channels in the input data. Typically 1 for grayscale and 3 for RGB. channel_list(List[int]): ... | 2 | stack_v2_sparse_classes_30k_train_003741 | Implement the Python class `ConvAutoencoderModule` described below.
Class description:
Autoencoder with convolutions for image datasets.
Method signatures and docstrings:
- def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim, noise): Init. Arguments specify the architecture of the encoder. Decode... | Implement the Python class `ConvAutoencoderModule` described below.
Class description:
Autoencoder with convolutions for image datasets.
Method signatures and docstrings:
- def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim, noise): Init. Arguments specify the architecture of the encoder. Decode... | 9027b529eaa4cf0a38f25512141810f92db99639 | <|skeleton|>
class ConvAutoencoderModule:
"""Autoencoder with convolutions for image datasets."""
def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim, noise):
"""Init. Arguments specify the architecture of the encoder. Decoder will use the reverse architecture. Args: H(int): Height... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvAutoencoderModule:
"""Autoencoder with convolutions for image datasets."""
def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim, noise):
"""Init. Arguments specify the architecture of the encoder. Decoder will use the reverse architecture. Args: H(int): Height of the input... | the_stack_v2_python_sparse | grae/models/torch_modules.py | jakerhodes/GRAE | train | 0 |
6469253f368155117f91d8c22133bac03f7296cf | [
"self.manager = SessionManager()\nself.config = dict()\nself.config['exempt_routes'] = exempt_routes\nself.config['exempt_methods'] = dict()\nself.config['exempt_methods']['global'] = exempt_methods\nroutes = self._get_all_routes(api)\nfor route in routes:\n self._get_settings(*route)",
"routes = []\n\ndef get... | <|body_start_0|>
self.manager = SessionManager()
self.config = dict()
self.config['exempt_routes'] = exempt_routes
self.config['exempt_methods'] = dict()
self.config['exempt_methods']['global'] = exempt_methods
routes = self._get_all_routes(api)
for route in route... | SessionMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionMiddleware:
def __init__(self, api, exempt_routes=list(), exempt_methods=list()):
"""Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конс... | stack_v2_sparse_classes_36k_train_030362 | 4,747 | permissive | [
{
"docstring": "Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конструктора. Аргументы: api(falcon.App, необходим): ссылка на экземпляр API. exempt_routes(list, опцион... | 5 | stack_v2_sparse_classes_30k_train_003484 | Implement the Python class `SessionMiddleware` described below.
Class description:
Implement the SessionMiddleware class.
Method signatures and docstrings:
- def __init__(self, api, exempt_routes=list(), exempt_methods=list()): Класс, содержащий сессионный middleware. Для настройки исключений используется проход по в... | Implement the Python class `SessionMiddleware` described below.
Class description:
Implement the SessionMiddleware class.
Method signatures and docstrings:
- def __init__(self, api, exempt_routes=list(), exempt_methods=list()): Класс, содержащий сессионный middleware. Для настройки исключений используется проход по в... | 37cdc4702dcacd0f187cca788e751e187fcd4499 | <|skeleton|>
class SessionMiddleware:
def __init__(self, api, exempt_routes=list(), exempt_methods=list()):
"""Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конс... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionMiddleware:
def __init__(self, api, exempt_routes=list(), exempt_methods=list()):
"""Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конструктора. Аргу... | the_stack_v2_python_sparse | cyberdas/middleware/session.py | wild-trip/CyberDAS-API | train | 0 | |
837f447dd37254c8db13d7618419491eccef726e | [
"subclasses = Catalog.subclasses(Catalog)\nsubclasses.reverse()\nfor subclass in subclasses:\n if str(subclass.__name__) == facility + technique + instrument:\n return super(cls, subclass).__new__(subclass)\n elif str(subclass.__name__) == facility + technique:\n return super(cls, subclass).__ne... | <|body_start_0|>
subclasses = Catalog.subclasses(Catalog)
subclasses.reverse()
for subclass in subclasses:
if str(subclass.__name__) == facility + technique + instrument:
return super(cls, subclass).__new__(subclass)
elif str(subclass.__name__) == facility... | The main methods to be defined in the subclasses are here. | Catalog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Catalog:
"""The main methods to be defined in the subclasses are here."""
def __new__(cls, facility, technique='', instrument='', *args, **kwargs):
"""This allows to great subclasses from this base class, given: - facility name - technique name - instrument name See in the database f... | stack_v2_sparse_classes_36k_train_030363 | 3,859 | no_license | [
{
"docstring": "This allows to great subclasses from this base class, given: - facility name - technique name - instrument name See in the database for every instrument the valid - instrument.facility.name - instrument.name - instrument.technique The Catalog should be constructed like these examples: sns = Cata... | 2 | null | Implement the Python class `Catalog` described below.
Class description:
The main methods to be defined in the subclasses are here.
Method signatures and docstrings:
- def __new__(cls, facility, technique='', instrument='', *args, **kwargs): This allows to great subclasses from this base class, given: - facility name... | Implement the Python class `Catalog` described below.
Class description:
The main methods to be defined in the subclasses are here.
Method signatures and docstrings:
- def __new__(cls, facility, technique='', instrument='', *args, **kwargs): This allows to great subclasses from this base class, given: - facility name... | c7301fb7983edbe3492e7d78d531ba2f427d2f3e | <|skeleton|>
class Catalog:
"""The main methods to be defined in the subclasses are here."""
def __new__(cls, facility, technique='', instrument='', *args, **kwargs):
"""This allows to great subclasses from this base class, given: - facility name - technique name - instrument name See in the database f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Catalog:
"""The main methods to be defined in the subclasses are here."""
def __new__(cls, facility, technique='', instrument='', *args, **kwargs):
"""This allows to great subclasses from this base class, given: - facility name - technique name - instrument name See in the database for every inst... | the_stack_v2_python_sparse | Design/sub_classing.py | Silentsoul04/PythonCode | train | 0 |
8ed0aaee9b129f278d3bb9fba49085a37e5f3149 | [
"model = model_for_script(opspec)\nif not model:\n return None\nself.log.debug('%s is a %s framework operation', opspec, model.framework)\nreturn (model, model.op_name)",
"if opdef.output_scalars is not None:\n return\nscript = _python_script_for_opdef_main(opdef)\nif not script:\n return\nframework = _f... | <|body_start_0|>
model = model_for_script(opspec)
if not model:
return None
self.log.debug('%s is a %s framework operation', opspec, model.framework)
return (model, model.op_name)
<|end_body_0|>
<|body_start_1|>
if opdef.output_scalars is not None:
return... | PythonFrameworksPlugin | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonFrameworksPlugin:
def resolve_model_op(self, opspec):
"""Provide model op when running framework scripts directly."""
<|body_0|>
def python_script_opdef_loaded(self, opdef):
"""Apply framework output scalars to opdef main modules."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_030364 | 3,802 | permissive | [
{
"docstring": "Provide model op when running framework scripts directly.",
"name": "resolve_model_op",
"signature": "def resolve_model_op(self, opspec)"
},
{
"docstring": "Apply framework output scalars to opdef main modules.",
"name": "python_script_opdef_loaded",
"signature": "def pyt... | 2 | null | Implement the Python class `PythonFrameworksPlugin` described below.
Class description:
Implement the PythonFrameworksPlugin class.
Method signatures and docstrings:
- def resolve_model_op(self, opspec): Provide model op when running framework scripts directly.
- def python_script_opdef_loaded(self, opdef): Apply fra... | Implement the Python class `PythonFrameworksPlugin` described below.
Class description:
Implement the PythonFrameworksPlugin class.
Method signatures and docstrings:
- def resolve_model_op(self, opspec): Provide model op when running framework scripts directly.
- def python_script_opdef_loaded(self, opdef): Apply fra... | 149055da49f57eaf4aec418f2e339c8905c1f02f | <|skeleton|>
class PythonFrameworksPlugin:
def resolve_model_op(self, opspec):
"""Provide model op when running framework scripts directly."""
<|body_0|>
def python_script_opdef_loaded(self, opdef):
"""Apply framework output scalars to opdef main modules."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonFrameworksPlugin:
def resolve_model_op(self, opspec):
"""Provide model op when running framework scripts directly."""
model = model_for_script(opspec)
if not model:
return None
self.log.debug('%s is a %s framework operation', opspec, model.framework)
r... | the_stack_v2_python_sparse | guild/plugins/python_frameworks.py | guildai/guildai | train | 833 | |
bd46ffc6d823f2679cfefcdf03638ff274353b2c | [
"start = 0\nend = len(arr) - 1\nwhile end >= start:\n mid = (start + end) // 2\n if arr[mid] < value:\n start = mid + 1\n elif arr[mid] > value:\n end = mid - 1\n else:\n return mid\nreturn -1",
"left = self.binarySearch(arr, value)\nif left == -1:\n return -1\nelse:\n i = l... | <|body_start_0|>
start = 0
end = len(arr) - 1
while end >= start:
mid = (start + end) // 2
if arr[mid] < value:
start = mid + 1
elif arr[mid] > value:
end = mid - 1
else:
return mid
return -1
... | SolutionSearchRange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionSearchRange:
def binarySearch(self, arr, value):
"""Returns the index position of the target element if found Returns -1 if target is not in array"""
<|body_0|>
def leftIndex(self, arr, value):
"""Returns the index(left) of the first occurence of the element"... | stack_v2_sparse_classes_36k_train_030365 | 2,036 | no_license | [
{
"docstring": "Returns the index position of the target element if found Returns -1 if target is not in array",
"name": "binarySearch",
"signature": "def binarySearch(self, arr, value)"
},
{
"docstring": "Returns the index(left) of the first occurence of the element",
"name": "leftIndex",
... | 4 | stack_v2_sparse_classes_30k_train_002095 | Implement the Python class `SolutionSearchRange` described below.
Class description:
Implement the SolutionSearchRange class.
Method signatures and docstrings:
- def binarySearch(self, arr, value): Returns the index position of the target element if found Returns -1 if target is not in array
- def leftIndex(self, arr... | Implement the Python class `SolutionSearchRange` described below.
Class description:
Implement the SolutionSearchRange class.
Method signatures and docstrings:
- def binarySearch(self, arr, value): Returns the index position of the target element if found Returns -1 if target is not in array
- def leftIndex(self, arr... | f7c7fcf27751f740c232a87b234d6a74e5ac30bb | <|skeleton|>
class SolutionSearchRange:
def binarySearch(self, arr, value):
"""Returns the index position of the target element if found Returns -1 if target is not in array"""
<|body_0|>
def leftIndex(self, arr, value):
"""Returns the index(left) of the first occurence of the element"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionSearchRange:
def binarySearch(self, arr, value):
"""Returns the index position of the target element if found Returns -1 if target is not in array"""
start = 0
end = len(arr) - 1
while end >= start:
mid = (start + end) // 2
if arr[mid] < value:
... | the_stack_v2_python_sparse | Algorithms Python/searchRange.py | wittywatz/Algorithms | train | 0 | |
e00d6c369bcfcecdd10a257d4e9da71a74ec6b10 | [
"self.question = question\nself.true_branch = true_branch\nself.false_branch = false_branch",
"t = self.true_branch == other.true_branch\nf = self.false_branch == other.false_branch\nq = self.question == other.question\nreturn q and t and f"
] | <|body_start_0|>
self.question = question
self.true_branch = true_branch
self.false_branch = false_branch
<|end_body_0|>
<|body_start_1|>
t = self.true_branch == other.true_branch
f = self.false_branch == other.false_branch
q = self.question == other.question
ret... | A node higher up the decision tree than the leaf. Used to partion the data until pure | Decision_Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decision_Node:
"""A node higher up the decision tree than the leaf. Used to partion the data until pure"""
def __init__(self, question, true_branch, false_branch):
"""A constructor for the decison node. Keyword Argument: question: A Question class object to partion the data on true_b... | stack_v2_sparse_classes_36k_train_030366 | 15,954 | no_license | [
{
"docstring": "A constructor for the decison node. Keyword Argument: question: A Question class object to partion the data on true_branch: The Decision Node/Leaf that is True to the Question false_branch: The Decision Node/Leaf that is false to the data",
"name": "__init__",
"signature": "def __init__(... | 2 | stack_v2_sparse_classes_30k_train_019367 | Implement the Python class `Decision_Node` described below.
Class description:
A node higher up the decision tree than the leaf. Used to partion the data until pure
Method signatures and docstrings:
- def __init__(self, question, true_branch, false_branch): A constructor for the decison node. Keyword Argument: questi... | Implement the Python class `Decision_Node` described below.
Class description:
A node higher up the decision tree than the leaf. Used to partion the data until pure
Method signatures and docstrings:
- def __init__(self, question, true_branch, false_branch): A constructor for the decison node. Keyword Argument: questi... | 0022c0bee14cdc3a773c0fe60d196cb12a0dd9f0 | <|skeleton|>
class Decision_Node:
"""A node higher up the decision tree than the leaf. Used to partion the data until pure"""
def __init__(self, question, true_branch, false_branch):
"""A constructor for the decison node. Keyword Argument: question: A Question class object to partion the data on true_b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decision_Node:
"""A node higher up the decision tree than the leaf. Used to partion the data until pure"""
def __init__(self, question, true_branch, false_branch):
"""A constructor for the decison node. Keyword Argument: question: A Question class object to partion the data on true_branch: The De... | the_stack_v2_python_sparse | random forest tree/InsuranceClaimPrediction.py | ShaaficiAli/PersonalProjects | train | 0 |
ca54b3f61cd29e0ebf226207120f4a6b4384d6c6 | [
"super(PositionalEncodingSineLearned, self).__init__(input_channels, **kwargs)\nself.use_conv2d = conv_dim == 2\nif self.use_conv2d:\n conv_cfg = dict(type='Conv2d')\nelse:\n conv_cfg = dict(type='Conv1d')\nif out_channels is None:\n out_channels = self.embedding_dim\nlayers = []\nfor _ in range(num_layers... | <|body_start_0|>
super(PositionalEncodingSineLearned, self).__init__(input_channels, **kwargs)
self.use_conv2d = conv_dim == 2
if self.use_conv2d:
conv_cfg = dict(type='Conv2d')
else:
conv_cfg = dict(type='Conv1d')
if out_channels is None:
out_... | PositionalEncodingSineLearned | [
"Apache-2.0",
"BSD-2-Clause-Views",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncodingSineLearned:
def __init__(self, input_channels: int, out_channels: int=None, conv_dim: int=2, num_layers: int=1, out_relu: bool=False, norm_cfg: dict=None, **kwargs):
"""Sine postional embedding with learnable transformation. Args: input_channels (int): the dimension of... | stack_v2_sparse_classes_36k_train_030367 | 12,251 | permissive | [
{
"docstring": "Sine postional embedding with learnable transformation. Args: input_channels (int): the dimension of input. with_sigmoid (bool, optional): add sigmoid function on the top of output. Defaults to False. conv_dim (int, optional): 1 or 2. If it is 2, the input positions much be [N,H,W,C]. Defaults t... | 2 | null | Implement the Python class `PositionalEncodingSineLearned` described below.
Class description:
Implement the PositionalEncodingSineLearned class.
Method signatures and docstrings:
- def __init__(self, input_channels: int, out_channels: int=None, conv_dim: int=2, num_layers: int=1, out_relu: bool=False, norm_cfg: dict... | Implement the Python class `PositionalEncodingSineLearned` described below.
Class description:
Implement the PositionalEncodingSineLearned class.
Method signatures and docstrings:
- def __init__(self, input_channels: int, out_channels: int=None, conv_dim: int=2, num_layers: int=1, out_relu: bool=False, norm_cfg: dict... | 3652b18c7ce68122dae7a32670624727d50e0914 | <|skeleton|>
class PositionalEncodingSineLearned:
def __init__(self, input_channels: int, out_channels: int=None, conv_dim: int=2, num_layers: int=1, out_relu: bool=False, norm_cfg: dict=None, **kwargs):
"""Sine postional embedding with learnable transformation. Args: input_channels (int): the dimension of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncodingSineLearned:
def __init__(self, input_channels: int, out_channels: int=None, conv_dim: int=2, num_layers: int=1, out_relu: bool=False, norm_cfg: dict=None, **kwargs):
"""Sine postional embedding with learnable transformation. Args: input_channels (int): the dimension of input. with_s... | the_stack_v2_python_sparse | mmdet/models/utils/bvr_transformer/positional_encoding.py | shinya7y/UniverseNet | train | 407 | |
9cea73822853a0a1d73761413469a847fd3efd1f | [
"self.description = description\nself.domain = domain\nself.object_class = object_class\nself.principal_name = principal_name\nself.restricted = restricted\nself.roles = roles",
"if dictionary is None:\n return None\ndescription = dictionary.get('description')\ndomain = dictionary.get('domain')\nobject_class =... | <|body_start_0|>
self.description = description
self.domain = domain
self.object_class = object_class
self.principal_name = principal_name
self.restricted = restricted
self.roles = roles
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return No... | Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in the default Cohesity domain called 'LOCAL' using this operation. A... | ActiveDirectoryPrincipalsAddParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveDirectoryPrincipalsAddParameters:
"""Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in ... | stack_v2_sparse_classes_36k_train_030368 | 4,214 | permissive | [
{
"docstring": "Constructor for the ActiveDirectoryPrincipalsAddParameters class",
"name": "__init__",
"signature": "def __init__(self, description=None, domain=None, object_class=None, principal_name=None, restricted=None, roles=None)"
},
{
"docstring": "Creates an instance of this model from a... | 2 | stack_v2_sparse_classes_30k_train_005593 | Implement the Python class `ActiveDirectoryPrincipalsAddParameters` described below.
Class description:
Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster.... | Implement the Python class `ActiveDirectoryPrincipalsAddParameters` described below.
Class description:
Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster.... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ActiveDirectoryPrincipalsAddParameters:
"""Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveDirectoryPrincipalsAddParameters:
"""Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in the default C... | the_stack_v2_python_sparse | cohesity_management_sdk/models/active_directory_principals_add_parameters.py | cohesity/management-sdk-python | train | 24 |
8613b18e9a67bcfd19303ab3a8c2c958cbf23c7d | [
"self.logger = logging.getLogger(__name__)\nself.filename = filename\nif display is None:\n display = os.environ['DISPLAY']\nself.display = display\nif size is None:\n size = (1024, 768)\nself.size = size\nself.p = None",
"cmd = 'ffmpeg -y' + ' -video_size %sx%s' % self.size + ' -framerate 25' + ' -preset u... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.filename = filename
if display is None:
display = os.environ['DISPLAY']
self.display = display
if size is None:
size = (1024, 768)
self.size = size
self.p = None
<|end_body_0|>... | WebRecordXvfb | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
<|body_0|>
def sta... | stack_v2_sparse_classes_36k_train_030369 | 3,050 | permissive | [
{
"docstring": "record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0').",
"name": "__init__",
"signature": "def __init__(self, filename, size=None, display=None)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_020028 | Implement the Python class `WebRecordXvfb` described below.
Class description:
Implement the WebRecordXvfb class.
Method signatures and docstrings:
- def __init__(self, filename, size=None, display=None): record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (... | Implement the Python class `WebRecordXvfb` described below.
Class description:
Implement the WebRecordXvfb class.
Method signatures and docstrings:
- def __init__(self, filename, size=None, display=None): record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (... | 2ff506eb56ba00f035300862f8848e4168452a17 | <|skeleton|>
class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
<|body_0|>
def sta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
self.logger = logging.getLogger(__nam... | the_stack_v2_python_sparse | hubcheck/utils/record.py | ken2190/hubcheck | train | 0 | |
7d909e276595c85832834ec914192556d63de4ae | [
"def fill_void():\n for ticker in universe['ticker']:\n if ticker not in self.equity:\n self.equity[ticker] = Order(ticker=ticker, date=date)\nsuper().__init__(order_list)\nfill_void()",
"long_asset, short_asset = (0.0, 0.0)\nfor ticker in self.equity:\n if self.equity[ticker].position == ... | <|body_start_0|>
def fill_void():
for ticker in universe['ticker']:
if ticker not in self.equity:
self.equity[ticker] = Order(ticker=ticker, date=date)
super().__init__(order_list)
fill_void()
<|end_body_0|>
<|body_start_1|>
long_asset, sh... | Current Holding inherit from OrderBook object: 1. Track current holding position | Holding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Holding:
"""Current Holding inherit from OrderBook object: 1. Track current holding position"""
def __init__(self, order_list: list, universe: pd.DataFrame, date: dt.date):
"""Init function Parameters ---------- order_list: list = [] The list of order class being placed, [Order] univ... | stack_v2_sparse_classes_36k_train_030370 | 7,011 | no_license | [
{
"docstring": "Init function Parameters ---------- order_list: list = [] The list of order class being placed, [Order] universe: pd.DataFrame The universe where the backtesting is taking place on date: dt.date The current date of backtesting Returns ------- None",
"name": "__init__",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_014948 | Implement the Python class `Holding` described below.
Class description:
Current Holding inherit from OrderBook object: 1. Track current holding position
Method signatures and docstrings:
- def __init__(self, order_list: list, universe: pd.DataFrame, date: dt.date): Init function Parameters ---------- order_list: lis... | Implement the Python class `Holding` described below.
Class description:
Current Holding inherit from OrderBook object: 1. Track current holding position
Method signatures and docstrings:
- def __init__(self, order_list: list, universe: pd.DataFrame, date: dt.date): Init function Parameters ---------- order_list: lis... | b5727f994f9be4d23768d6837c2c2c9c191c9af6 | <|skeleton|>
class Holding:
"""Current Holding inherit from OrderBook object: 1. Track current holding position"""
def __init__(self, order_list: list, universe: pd.DataFrame, date: dt.date):
"""Init function Parameters ---------- order_list: list = [] The list of order class being placed, [Order] univ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Holding:
"""Current Holding inherit from OrderBook object: 1. Track current holding position"""
def __init__(self, order_list: list, universe: pd.DataFrame, date: dt.date):
"""Init function Parameters ---------- order_list: list = [] The list of order class being placed, [Order] universe: pd.Data... | the_stack_v2_python_sparse | Sandbox/Asset/order.py | AlbertLin0327/QEF-Backtesting-System | train | 1 |
abf103845299e7eb8edd6df81b7b2244f466e5d9 | [
"tf.reset_default_graph()\noptim = tf.train.GradientDescentOptimizer(0.1)\nsparse_optim = sparse_optimizers.SparseStaticOptimizer(optim, start_iter, end_iter, freq_iter, drop_fraction=drop_frac)\nx = tf.random.uniform((1, n_inp))\ny = layers.masked_fully_connected(x, n_out, activation_fn=None)\nglobal_step = tf.tra... | <|body_start_0|>
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.1)
sparse_optim = sparse_optimizers.SparseStaticOptimizer(optim, start_iter, end_iter, freq_iter, drop_fraction=drop_frac)
x = tf.random.uniform((1, n_inp))
y = layers.masked_fully_connected(x, ... | SparseStaticOptimizerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseStaticOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testMaskStatic(self, n_inp, n_out, drop_frac):
"""Training a layer for 5 i... | stack_v2_sparse_classes_36k_train_030371 | 25,606 | permissive | [
{
"docstring": "Setups a trivial training procedure for sparse training.",
"name": "_setup_graph",
"signature": "def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2)"
},
{
"docstring": "Training a layer for 5 iterations and see whether mask is kept intact. The m... | 2 | null | Implement the Python class `SparseStaticOptimizerTest` described below.
Class description:
Implement the SparseStaticOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2): Setups a trivial training procedure for sparse training.... | Implement the Python class `SparseStaticOptimizerTest` described below.
Class description:
Implement the SparseStaticOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2): Setups a trivial training procedure for sparse training.... | d39fc7d46505cb3196cb1edeb32ed0b6dd44c0f9 | <|skeleton|>
class SparseStaticOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testMaskStatic(self, n_inp, n_out, drop_frac):
"""Training a layer for 5 i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseStaticOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2):
"""Setups a trivial training procedure for sparse training."""
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.1)
sparse_optim = sparse_optimi... | the_stack_v2_python_sparse | rigl/sparse_optimizers_test.py | google-research/rigl | train | 324 | |
e973f52c8190ceb9b938c37138849bfce97d9aa6 | [
"passengers = 0\nevents = self._get_events(trips)\nfor net_change in events:\n passengers += net_change\n if passengers > capacity:\n return False\nreturn True",
"events = collections.defaultdict(int)\nfor num_passengers, start, end in trips:\n events[start] += num_passengers\n events[end] -= n... | <|body_start_0|>
passengers = 0
events = self._get_events(trips)
for net_change in events:
passengers += net_change
if passengers > capacity:
return False
return True
<|end_body_0|>
<|body_start_1|>
events = collections.defaultdict(int)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def carPooling(self, trips, capacity):
"""@description Returns if we take all passengers on the trip @param1 trips : arr[arr[int]] @param2 capacity : int @return answer : bool [num passengers, start, end] 0 1 trips = [[2,1,5],[3,3,7]] ^ events : time event 1 : += 2 3 : += 3 5 :... | stack_v2_sparse_classes_36k_train_030372 | 3,172 | no_license | [
{
"docstring": "@description Returns if we take all passengers on the trip @param1 trips : arr[arr[int]] @param2 capacity : int @return answer : bool [num passengers, start, end] 0 1 trips = [[2,1,5],[3,3,7]] ^ events : time event 1 : += 2 3 : += 3 5 : -= 2, += 3 7 : curr_capacity = 2 road start end 1 7 curr_ca... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def carPooling(self, trips, capacity): @description Returns if we take all passengers on the trip @param1 trips : arr[arr[int]] @param2 capacity : int @return answer : bool [num ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def carPooling(self, trips, capacity): @description Returns if we take all passengers on the trip @param1 trips : arr[arr[int]] @param2 capacity : int @return answer : bool [num ... | bbfee57ae89d23cd4f4132fbb62d8931ea654a0e | <|skeleton|>
class Solution:
def carPooling(self, trips, capacity):
"""@description Returns if we take all passengers on the trip @param1 trips : arr[arr[int]] @param2 capacity : int @return answer : bool [num passengers, start, end] 0 1 trips = [[2,1,5],[3,3,7]] ^ events : time event 1 : += 2 3 : += 3 5 :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def carPooling(self, trips, capacity):
"""@description Returns if we take all passengers on the trip @param1 trips : arr[arr[int]] @param2 capacity : int @return answer : bool [num passengers, start, end] 0 1 trips = [[2,1,5],[3,3,7]] ^ events : time event 1 : += 2 3 : += 3 5 : -= 2, += 3 7 ... | the_stack_v2_python_sparse | Algorithms/Leetcode/1094 - Car Pooling.py | timpark0807/self-taught-swe | train | 1 | |
e083d704b7969b667a9ad50be3fd6c3f202dfff0 | [
"parser.add_mutually_exclusive_group()\nparser.add_argument('--delete', action='store_true', help='Delete existing data')\nparser.add_argument('--preserve', action='store_true', help='Preserve existing data')",
"if not settings.DEBUG:\n raise Exception('Trying to seed in production.')\nassert not (delete and p... | <|body_start_0|>
parser.add_mutually_exclusive_group()
parser.add_argument('--delete', action='store_true', help='Delete existing data')
parser.add_argument('--preserve', action='store_true', help='Preserve existing data')
<|end_body_0|>
<|body_start_1|>
if not settings.DEBUG:
... | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
def add_arguments(self, parser):
"""Add arguments to the argparser for the command"""
<|body_0|>
def handle(self, *args, delete: bool, preserve: bool, **options):
"""Handle the command and do the seeding"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_030373 | 24,783 | permissive | [
{
"docstring": "Add arguments to the argparser for the command",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Handle the command and do the seeding",
"name": "handle",
"signature": "def handle(self, *args, delete: bool, preserve: bool, **opti... | 2 | null | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the argparser for the command
- def handle(self, *args, delete: bool, preserve: bool, **options): Handle the command and do the se... | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the argparser for the command
- def handle(self, *args, delete: bool, preserve: bool, **options): Handle the command and do the se... | 5661cbea1011f8851a244ae3d72351fce647123f | <|skeleton|>
class Command:
def add_arguments(self, parser):
"""Add arguments to the argparser for the command"""
<|body_0|>
def handle(self, *args, delete: bool, preserve: bool, **options):
"""Handle the command and do the seeding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
def add_arguments(self, parser):
"""Add arguments to the argparser for the command"""
parser.add_mutually_exclusive_group()
parser.add_argument('--delete', action='store_true', help='Delete existing data')
parser.add_argument('--preserve', action='store_true', help='Pr... | the_stack_v2_python_sparse | nablapps/core/management/commands/seed.py | Nabla-NTNU/nablaweb | train | 21 | |
6f3e053584cfbd3e490a07b364faa6df1decec8f | [
"if plan == {}:\n return\nself.mode.store(plan.mode)\nself.timestep.store(plan.ccdyn.dt)\nself.thermostat.store(plan.ccdyn.thermostat)\nself.nmts.store(plan.ccdyn.nmts)\nself.nsamples.store(plan.nsamples)\nself.stride.store(plan.stride)\nself.screen.store(plan.screen)",
"rv = super(InputPlanetary, self).fetch(... | <|body_start_0|>
if plan == {}:
return
self.mode.store(plan.mode)
self.timestep.store(plan.ccdyn.dt)
self.thermostat.store(plan.ccdyn.thermostat)
self.nmts.store(plan.ccdyn.nmts)
self.nsamples.store(plan.nsamples)
self.stride.store(plan.stride)
... | Planetary input class. Handles generating the appropriate ensemble class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the mode (ensemble) to be simulated. Defaults to 'unknown'. Fields: thermostat: The thermostat to ... | InputPlanetary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputPlanetary:
"""Planetary input class. Handles generating the appropriate ensemble class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the mode (ensemble) to be simulated. Defaults to 'unknow... | stack_v2_sparse_classes_36k_train_030374 | 4,311 | no_license | [
{
"docstring": "Takes a planetary instance and stores a minimal representation of it. Args: dyn: An integrator object.",
"name": "store",
"signature": "def store(self, plan)"
},
{
"docstring": "Creates an ensemble object. Returns: An ensemble object of the appropriate mode and with the appropria... | 2 | stack_v2_sparse_classes_30k_train_010070 | Implement the Python class `InputPlanetary` described below.
Class description:
Planetary input class. Handles generating the appropriate ensemble class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the mode (ensembl... | Implement the Python class `InputPlanetary` described below.
Class description:
Planetary input class. Handles generating the appropriate ensemble class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the mode (ensembl... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class InputPlanetary:
"""Planetary input class. Handles generating the appropriate ensemble class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the mode (ensemble) to be simulated. Defaults to 'unknow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputPlanetary:
"""Planetary input class. Handles generating the appropriate ensemble class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the mode (ensemble) to be simulated. Defaults to 'unknown'. Fields: t... | the_stack_v2_python_sparse | ipi/inputs/motion/planetary.py | i-pi/i-pi | train | 170 |
c67153089127a7f59ec310e2e2ae566ebad508bb | [
"self._to_update = None\nself._to_remove = None\nself._clear_others = clear_others\nif env_vars_to_update:\n self._to_update = {k.strip(): v for k, v in env_vars_to_update.items()}\nif env_vars_to_remove:\n self._to_remove = [k.lstrip() for k in env_vars_to_remove]",
"if self._clear_others:\n resource.te... | <|body_start_0|>
self._to_update = None
self._to_remove = None
self._clear_others = clear_others
if env_vars_to_update:
self._to_update = {k.strip(): v for k, v in env_vars_to_update.items()}
if env_vars_to_remove:
self._to_remove = [k.lstrip() for k in en... | Represents the user intent to modify environment variables string literals. | EnvVarLiteralChanges | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvVarLiteralChanges:
"""Represents the user intent to modify environment variables string literals."""
def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False):
"""Initialize a new EnvVarLiteralChanges object. Args: env_vars_to_update: {str, str}, Upd... | stack_v2_sparse_classes_36k_train_030375 | 24,166 | permissive | [
{
"docstring": "Initialize a new EnvVarLiteralChanges object. Args: env_vars_to_update: {str, str}, Update env var names and values. env_vars_to_remove: [str], List of env vars to remove. clear_others: bool, If true, clear all non-updated env vars.",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | null | Implement the Python class `EnvVarLiteralChanges` described below.
Class description:
Represents the user intent to modify environment variables string literals.
Method signatures and docstrings:
- def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False): Initialize a new EnvVarLiteral... | Implement the Python class `EnvVarLiteralChanges` described below.
Class description:
Represents the user intent to modify environment variables string literals.
Method signatures and docstrings:
- def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False): Initialize a new EnvVarLiteral... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class EnvVarLiteralChanges:
"""Represents the user intent to modify environment variables string literals."""
def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False):
"""Initialize a new EnvVarLiteralChanges object. Args: env_vars_to_update: {str, str}, Upd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvVarLiteralChanges:
"""Represents the user intent to modify environment variables string literals."""
def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False):
"""Initialize a new EnvVarLiteralChanges object. Args: env_vars_to_update: {str, str}, Update env var n... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/run/config_changes.py | bopopescu/socialliteapp | train | 0 |
ad3f4df2546fd6e40267041de63f5de166c06f9d | [
"vowel = 'AEIOUaeiou'\ns = list(s)\ni, j = (0, len(s) - 1)\nwhile i < j:\n while s[i] not in vowel and i < j:\n i += 1\n while s[j] not in vowel and i < j:\n j -= 1\n s[i], s[j] = (s[j], s[i])\n i, j = (i + 1, j - 1)\nreturn ''.join(s)",
"if len(s) == 0:\n return s\nvolwels = set('aei... | <|body_start_0|>
vowel = 'AEIOUaeiou'
s = list(s)
i, j = (0, len(s) - 1)
while i < j:
while s[i] not in vowel and i < j:
i += 1
while s[j] not in vowel and i < j:
j -= 1
s[i], s[j] = (s[j], s[i])
i, j = (i + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
"""前后指针法 :type s: str :rtype: str"""
<|body_0|>
def reverseVowels_timeout(self, s):
"""超时算法! 一个case通不过, O(2n) :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vowel = 'AEIOUaeiou'
... | stack_v2_sparse_classes_36k_train_030376 | 1,797 | no_license | [
{
"docstring": "前后指针法 :type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": "超时算法! 一个case通不过, O(2n) :type s: str :rtype: str",
"name": "reverseVowels_timeout",
"signature": "def reverseVowels_timeout(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001637 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): 前后指针法 :type s: str :rtype: str
- def reverseVowels_timeout(self, s): 超时算法! 一个case通不过, O(2n) :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): 前后指针法 :type s: str :rtype: str
- def reverseVowels_timeout(self, s): 超时算法! 一个case通不过, O(2n) :type s: str :rtype: str
<|skeleton|>
class Solution:
... | e4d21223c85b622b5a905d1a056dfb2f300964b1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
"""前后指针法 :type s: str :rtype: str"""
<|body_0|>
def reverseVowels_timeout(self, s):
"""超时算法! 一个case通不过, O(2n) :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseVowels(self, s):
"""前后指针法 :type s: str :rtype: str"""
vowel = 'AEIOUaeiou'
s = list(s)
i, j = (0, len(s) - 1)
while i < j:
while s[i] not in vowel and i < j:
i += 1
while s[j] not in vowel and i < j:
... | the_stack_v2_python_sparse | Algorithms/345.Reverse_Vowels_of_a_String/reverse_vowels_of_a_string.py | gosyang/leetcode | train | 1 | |
4c3ff1408f9a92cb5cfab61546b39836426ebd02 | [
"super(AnalysisStorage, self).__init__(filename=filename, mode='r')\nself.set_caching_mode(caching_mode)\nAnalysisStorage.cache_for_analysis(self)",
"with AnalysisStorage.CacheTimer('Cached all CVs'):\n for cv, cv_store in storage.snapshots.attribute_list.items():\n if cv_store:\n cv_store.ca... | <|body_start_0|>
super(AnalysisStorage, self).__init__(filename=filename, mode='r')
self.set_caching_mode(caching_mode)
AnalysisStorage.cache_for_analysis(self)
<|end_body_0|>
<|body_start_1|>
with AnalysisStorage.CacheTimer('Cached all CVs'):
for cv, cv_store in storage.sna... | Open a storage in read-only and do caching useful for analysis. | AnalysisStorage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisStorage:
"""Open a storage in read-only and do caching useful for analysis."""
def __init__(self, filename, caching_mode='analysis'):
"""Open a storage in read-only and do caching useful for analysis. Parameters ---------- filename : str The filename of the storage to be open... | stack_v2_sparse_classes_36k_train_030377 | 17,720 | permissive | [
{
"docstring": "Open a storage in read-only and do caching useful for analysis. Parameters ---------- filename : str The filename of the storage to be opened caching_mode : str The caching mode to be used. Default is `analysis` which will cache lots of usually relevant object. If you have a decent size system a... | 2 | null | Implement the Python class `AnalysisStorage` described below.
Class description:
Open a storage in read-only and do caching useful for analysis.
Method signatures and docstrings:
- def __init__(self, filename, caching_mode='analysis'): Open a storage in read-only and do caching useful for analysis. Parameters -------... | Implement the Python class `AnalysisStorage` described below.
Class description:
Open a storage in read-only and do caching useful for analysis.
Method signatures and docstrings:
- def __init__(self, filename, caching_mode='analysis'): Open a storage in read-only and do caching useful for analysis. Parameters -------... | 3d02df4ccdeb6d62030a28e371a6b4ea9aaee5fe | <|skeleton|>
class AnalysisStorage:
"""Open a storage in read-only and do caching useful for analysis."""
def __init__(self, filename, caching_mode='analysis'):
"""Open a storage in read-only and do caching useful for analysis. Parameters ---------- filename : str The filename of the storage to be open... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalysisStorage:
"""Open a storage in read-only and do caching useful for analysis."""
def __init__(self, filename, caching_mode='analysis'):
"""Open a storage in read-only and do caching useful for analysis. Parameters ---------- filename : str The filename of the storage to be opened caching_mo... | the_stack_v2_python_sparse | openpathsampling/storage/storage.py | dwhswenson/openpathsampling | train | 3 |
7518ec57cee1db9011db43c2edee61b1aaee2e03 | [
"kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')\nsuper().__init__(*args, **kwargs)\nif InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_TWICE'):\n self.fields['email2'] = forms.EmailField(label=_('Email (again)'), widget=forms.TextInput(attrs={'type': 'email', 'placeholder': _('Ema... | <|body_start_0|>
kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')
super().__init__(*args, **kwargs)
if InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_TWICE'):
self.fields['email2'] = forms.EmailField(label=_('Email (again)'), widget=forms.TextInput(attr... | Override to use dynamic settings. | CustomSignupForm | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
<|body_0|>
def clean(self):
"""Make sure the supllied emails match if enabled in settings."""
<|body_... | stack_v2_sparse_classes_36k_train_030378 | 12,546 | permissive | [
{
"docstring": "Check settings to influence which fields are needed.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Make sure the supllied emails match if enabled in settings.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005644 | Implement the Python class `CustomSignupForm` described below.
Class description:
Override to use dynamic settings.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Check settings to influence which fields are needed.
- def clean(self): Make sure the supllied emails match if enabled in setting... | Implement the Python class `CustomSignupForm` described below.
Class description:
Override to use dynamic settings.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Check settings to influence which fields are needed.
- def clean(self): Make sure the supllied emails match if enabled in setting... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
<|body_0|>
def clean(self):
"""Make sure the supllied emails match if enabled in settings."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')
super().__init__(*args, **kwargs)
if Inv... | the_stack_v2_python_sparse | InvenTree/InvenTree/forms.py | inventree/InvenTree | train | 3,077 |
10a99c45ff439865eda09df35df7b5fef493f86a | [
"super().__init__(n_splits, shuffle=False, random_state=None)\nself.samples_info_sets_dict = samples_info_sets_dict\nself.pct_embargo = pct_embargo",
"first_asset = list(X_dict.keys())[0]\nfor asset in X_dict:\n if X_dict[asset].shape[0] != self.samples_info_sets_dict[asset].shape[0]:\n raise ValueError... | <|body_start_0|>
super().__init__(n_splits, shuffle=False, random_state=None)
self.samples_info_sets_dict = samples_info_sets_dict
self.pct_embargo = pct_embargo
<|end_body_0|>
<|body_start_1|>
first_asset = list(X_dict.keys())[0]
for asset in X_dict:
if X_dict[asset... | Extend KFold class to work with labels that span intervals in multi-asset datasets. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between. | StackedPurgedKFold | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackedPurgedKFold:
"""Extend KFold class to work with labels that span intervals in multi-asset datasets. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between."""
def __init__(self, n_splits: in... | stack_v2_sparse_classes_36k_train_030379 | 19,555 | permissive | [
{
"docstring": "Initialize. :param n_splits: (int) The number of splits. Default to 3. :param samples_info_sets_dict: (dict) Dictionary of asset: the information range on which each record is *constructed from samples_info_sets.index*: Time when the information extraction started. *samples_info_sets.value*: Tim... | 2 | stack_v2_sparse_classes_30k_train_000470 | Implement the Python class `StackedPurgedKFold` described below.
Class description:
Extend KFold class to work with labels that span intervals in multi-asset datasets. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.
... | Implement the Python class `StackedPurgedKFold` described below.
Class description:
Extend KFold class to work with labels that span intervals in multi-asset datasets. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.
... | 046c47d995da08b1003bba3f9c07d5bfb73d9c1f | <|skeleton|>
class StackedPurgedKFold:
"""Extend KFold class to work with labels that span intervals in multi-asset datasets. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between."""
def __init__(self, n_splits: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StackedPurgedKFold:
"""Extend KFold class to work with labels that span intervals in multi-asset datasets. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between."""
def __init__(self, n_splits: int=3, samples_... | the_stack_v2_python_sparse | src/collection/mlfinlab/cross_validation/cross_validation.py | Ta-nu-ki/dissertacao | train | 0 |
d5d7f1c335d80c1e9e58b3b5d476ffb548e4f1e5 | [
"pygame.init()\n'Set the window Size'\nself.width = width\nself.height = height\n'Create the Screen'\nself.screen = pygame.display.set_mode((self.width, self.height))\nself.background = pygame.Surface(self.screen.get_size())\nself.background = self.background.convert()\nself.background.fill((0, 250, 250))",
"\"\"... | <|body_start_0|>
pygame.init()
'Set the window Size'
self.width = width
self.height = height
'Create the Screen'
self.screen = pygame.display.set_mode((self.width, self.height))
self.background = pygame.Surface(self.screen.get_size())
self.background = sel... | The Main Class - This class handles the main initialization and creating of the Game. | Main | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Main:
"""The Main Class - This class handles the main initialization and creating of the Game."""
def __init__(self, width=640, height=480):
"""Initialize PyGame"""
<|body_0|>
def MainLoop(self):
"""This is the Main Loop of the Game"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_030380 | 2,068 | no_license | [
{
"docstring": "Initialize PyGame",
"name": "__init__",
"signature": "def __init__(self, width=640, height=480)"
},
{
"docstring": "This is the Main Loop of the Game",
"name": "MainLoop",
"signature": "def MainLoop(self)"
},
{
"docstring": "Load the sprites that we need",
"na... | 3 | stack_v2_sparse_classes_30k_train_004277 | Implement the Python class `Main` described below.
Class description:
The Main Class - This class handles the main initialization and creating of the Game.
Method signatures and docstrings:
- def __init__(self, width=640, height=480): Initialize PyGame
- def MainLoop(self): This is the Main Loop of the Game
- def Loa... | Implement the Python class `Main` described below.
Class description:
The Main Class - This class handles the main initialization and creating of the Game.
Method signatures and docstrings:
- def __init__(self, width=640, height=480): Initialize PyGame
- def MainLoop(self): This is the Main Loop of the Game
- def Loa... | 20d96c3633548974685febad1f2e2b0825df6f34 | <|skeleton|>
class Main:
"""The Main Class - This class handles the main initialization and creating of the Game."""
def __init__(self, width=640, height=480):
"""Initialize PyGame"""
<|body_0|>
def MainLoop(self):
"""This is the Main Loop of the Game"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Main:
"""The Main Class - This class handles the main initialization and creating of the Game."""
def __init__(self, width=640, height=480):
"""Initialize PyGame"""
pygame.init()
'Set the window Size'
self.width = width
self.height = height
'Create the Scre... | the_stack_v2_python_sparse | ssf-python/simulator/main.py | S3FA/super-street-fire | train | 1 |
358afdd8b06306e4e43aed50c6931e93204a894b | [
"super().__init__(**kwargs)\nself._djvu = djvu\nself._index = index\nself._prefix = self._index.title(with_ns=False)\nself._page_ns = self.site._proofread_page_ns.custom_name\nif not pages:\n self._pages = (1, self._djvu.number_of_images())\nelse:\n self._pages = pages\nif not self.opt.summary:\n self.opt.... | <|body_start_0|>
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
el... | A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot | DjVuTextBot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjVuTextBot:
"""A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot"""
def __init__(self, djvu, index, pages: Optional[tuple]=None, **kwargs) -> None:
"""... | stack_v2_sparse_classes_36k_train_030381 | 6,604 | permissive | [
{
"docstring": "Initializer. :param djvu: djvu from where to fetch the text layer :type djvu: DjVuFile object :param index: index page in the Index: namespace :type index: Page object :param pages: page interval to upload (start, end)",
"name": "__init__",
"signature": "def __init__(self, djvu, index, p... | 4 | stack_v2_sparse_classes_30k_train_021259 | Implement the Python class `DjVuTextBot` described below.
Class description:
A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot
Method signatures and docstrings:
- def __init__(self, djvu... | Implement the Python class `DjVuTextBot` described below.
Class description:
A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot
Method signatures and docstrings:
- def __init__(self, djvu... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class DjVuTextBot:
"""A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot"""
def __init__(self, djvu, index, pages: Optional[tuple]=None, **kwargs) -> None:
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DjVuTextBot:
"""A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot"""
def __init__(self, djvu, index, pages: Optional[tuple]=None, **kwargs) -> None:
"""Initializer. ... | the_stack_v2_python_sparse | scripts/djvutext.py | wikimedia/pywikibot | train | 432 |
ea8c0a32e2a0ba36ea9e29e1bbea77e68f5fb8b6 | [
"start = 0\ntotal = 0\ntank = 0\nfor i in range(len(gas)):\n tank += gas[i] - cost[i]\n if tank < 0:\n start = i + 1\n total += tank\n tank = 0\nif total + tank < 0:\n start = -1\nreturn start",
"start = len(gas) - 1\nend = 0\ntotal = gas[start] - cost[start]\nwhile end < start:\n ... | <|body_start_0|>
start = 0
total = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
total += tank
tank = 0
if total + tank < 0:
start = -1
return st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_030382 | 1,455 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit2",
"signature": "def canCo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
start = 0
total = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
... | the_stack_v2_python_sparse | prob134_gas_station.py | Hu-Wenchao/leetcode | train | 0 | |
abe7cfd8d0733d37bcc78cbca32ae742cf4e858f | [
"if UserProfile.objects.filter(username=username):\n raise serializers.ValidationError(username + ' 账号已存在')\nreturn username",
"REGEX_MOBILE = '^1[358]\\\\d{9}$|^147\\\\d{8}$|^176\\\\d{8}$'\nif not re.match(REGEX_MOBILE, mobile):\n raise serializers.ValidationError('手机号码不合法')\nif UserProfile.objects.filter(... | <|body_start_0|>
if UserProfile.objects.filter(username=username):
raise serializers.ValidationError(username + ' 账号已存在')
return username
<|end_body_0|>
<|body_start_1|>
REGEX_MOBILE = '^1[358]\\d{9}$|^147\\d{8}$|^176\\d{8}$'
if not re.match(REGEX_MOBILE, mobile):
... | 创建用户序列化 | UserCreateSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreateSerializer:
"""创建用户序列化"""
def validate_username(self, username):
"""校验用户名是否存在 :param username: :return:"""
<|body_0|>
def validate_mobile(self, mobile):
"""校验手机号是否合法、是否已被注册 :param mobile: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_030383 | 3,031 | no_license | [
{
"docstring": "校验用户名是否存在 :param username: :return:",
"name": "validate_username",
"signature": "def validate_username(self, username)"
},
{
"docstring": "校验手机号是否合法、是否已被注册 :param mobile: :return:",
"name": "validate_mobile",
"signature": "def validate_mobile(self, mobile)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007952 | Implement the Python class `UserCreateSerializer` described below.
Class description:
创建用户序列化
Method signatures and docstrings:
- def validate_username(self, username): 校验用户名是否存在 :param username: :return:
- def validate_mobile(self, mobile): 校验手机号是否合法、是否已被注册 :param mobile: :return: | Implement the Python class `UserCreateSerializer` described below.
Class description:
创建用户序列化
Method signatures and docstrings:
- def validate_username(self, username): 校验用户名是否存在 :param username: :return:
- def validate_mobile(self, mobile): 校验手机号是否合法、是否已被注册 :param mobile: :return:
<|skeleton|>
class UserCreateSeria... | db1d7c4eb2d5d229ab54c6d5775f96fc1843716e | <|skeleton|>
class UserCreateSerializer:
"""创建用户序列化"""
def validate_username(self, username):
"""校验用户名是否存在 :param username: :return:"""
<|body_0|>
def validate_mobile(self, mobile):
"""校验手机号是否合法、是否已被注册 :param mobile: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreateSerializer:
"""创建用户序列化"""
def validate_username(self, username):
"""校验用户名是否存在 :param username: :return:"""
if UserProfile.objects.filter(username=username):
raise serializers.ValidationError(username + ' 账号已存在')
return username
def validate_mobile(self, ... | the_stack_v2_python_sparse | apps/rbac/serializers/user_serializer.py | fengjy96/rest_task | train | 0 |
74d8c37775bcba9cac2315c1d7f9a27e52f89daf | [
"super().__init__(n_head=n_head, n_feat=n_feat, dropout_rate=dropout_rate, max_cache_len=max_cache_len)\nself.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\nif pos_bias_u is None or pos_bias_v is None:\n self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d_k))\n self.pos_bias_v = nn.Parameter(... | <|body_start_0|>
super().__init__(n_head=n_head, n_feat=n_feat, dropout_rate=dropout_rate, max_cache_len=max_cache_len)
self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
if pos_bias_u is None or pos_bias_v is None:
self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d... | Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate | RelPositionMultiHeadAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionMultiHeadAttention:
"""Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate"""
def __init__(self,... | stack_v2_sparse_classes_36k_train_030384 | 45,820 | permissive | [
{
"docstring": "Construct an RelPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate, pos_bias_u, pos_bias_v, max_cache_len=0)"
},
{
"docstring": "Compute relative positional encoding. Args: x (torch.Tensor): (batch, nheads, tim... | 3 | stack_v2_sparse_classes_30k_train_001500 | Implement the Python class `RelPositionMultiHeadAttention` described below.
Class description:
Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): ... | Implement the Python class `RelPositionMultiHeadAttention` described below.
Class description:
Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): ... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class RelPositionMultiHeadAttention:
"""Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate"""
def __init__(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionMultiHeadAttention:
"""Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): number of heads n_feat (int): size of the features dropout_rate (float): dropout rate"""
def __init__(self, n_head, n_fe... | the_stack_v2_python_sparse | nemo/collections/asr/parts/submodules/multi_head_attention.py | NVIDIA/NeMo | train | 7,957 |
1a01bbdef7aa756f3d68096015ad97e0cda7fd05 | [
"self.zuora_conn_id = zuora_conn_id\nself.wsdl_url = wsdl_url\nself._args = args\nself._kwargs = kwargs\nself.connection = self.get_connection(zuora_conn_id)\nself.extras = self.connection.extra_dejson",
"if hasattr(self, 'client'):\n return self.client\nclient = zeep.Client(wsdl=self.wsdl_url)\nresponse = cli... | <|body_start_0|>
self.zuora_conn_id = zuora_conn_id
self.wsdl_url = wsdl_url
self._args = args
self._kwargs = kwargs
self.connection = self.get_connection(zuora_conn_id)
self.extras = self.connection.extra_dejson
<|end_body_0|>
<|body_start_1|>
if hasattr(self, '... | ZuoraSoapHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZuoraSoapHook:
def __init__(self, zuora_conn_id, wsdl_url='https://www.zuora.com/apps/services/a/91.0', *args, **kwargs):
"""Create new connection to Zuora and allows you to pull data out of Zuora. :param zuora_conn_id: the name of the connection that has the parameters we need to connec... | stack_v2_sparse_classes_36k_train_030385 | 3,347 | permissive | [
{
"docstring": "Create new connection to Zuora and allows you to pull data out of Zuora. :param zuora_conn_id: the name of the connection that has the parameters we need to connect to Zuora. The connection shoud be type `http` and include the API endpoint in the `Extras` field. .. note:: For the HTTP connection... | 3 | stack_v2_sparse_classes_30k_train_020262 | Implement the Python class `ZuoraSoapHook` described below.
Class description:
Implement the ZuoraSoapHook class.
Method signatures and docstrings:
- def __init__(self, zuora_conn_id, wsdl_url='https://www.zuora.com/apps/services/a/91.0', *args, **kwargs): Create new connection to Zuora and allows you to pull data ou... | Implement the Python class `ZuoraSoapHook` described below.
Class description:
Implement the ZuoraSoapHook class.
Method signatures and docstrings:
- def __init__(self, zuora_conn_id, wsdl_url='https://www.zuora.com/apps/services/a/91.0', *args, **kwargs): Create new connection to Zuora and allows you to pull data ou... | 5cc651ea0a6a08fcca1278a8135481c15c90d6c6 | <|skeleton|>
class ZuoraSoapHook:
def __init__(self, zuora_conn_id, wsdl_url='https://www.zuora.com/apps/services/a/91.0', *args, **kwargs):
"""Create new connection to Zuora and allows you to pull data out of Zuora. :param zuora_conn_id: the name of the connection that has the parameters we need to connec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZuoraSoapHook:
def __init__(self, zuora_conn_id, wsdl_url='https://www.zuora.com/apps/services/a/91.0', *args, **kwargs):
"""Create new connection to Zuora and allows you to pull data out of Zuora. :param zuora_conn_id: the name of the connection that has the parameters we need to connect to Zuora. Th... | the_stack_v2_python_sparse | zuora_plugin/hooks/zuora_soap_hook.py | animeshinvinci/airflow-plugins | train | 0 | |
2b43483fe46a177feefa0f9dcf5c2d02b657407c | [
"tmp = sorted((x for i, j, k in trips for x in [[j, i], [k, -i]]))\nfor i, j in tmp:\n capacity -= j\n if capacity < 0:\n return False\nreturn True",
"res = [0] * 1001\nfor trip in trips:\n num, start, end = trip\n for i in range(start, end):\n res[i] += num\nfor val in res:\n if val ... | <|body_start_0|>
tmp = sorted((x for i, j, k in trips for x in [[j, i], [k, -i]]))
for i, j in tmp:
capacity -= j
if capacity < 0:
return False
return True
<|end_body_0|>
<|body_start_1|>
res = [0] * 1001
for trip in trips:
num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def carPooling(self, trips, capacity):
""":type trips: List[List[int]] :type capacity: int :rtype: bool"""
<|body_0|>
def carPooling2(self, trips, capacity):
""":type trips: List[List[int]] :type capacity: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_030386 | 2,249 | no_license | [
{
"docstring": ":type trips: List[List[int]] :type capacity: int :rtype: bool",
"name": "carPooling",
"signature": "def carPooling(self, trips, capacity)"
},
{
"docstring": ":type trips: List[List[int]] :type capacity: int :rtype: bool",
"name": "carPooling2",
"signature": "def carPoolin... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def carPooling(self, trips, capacity): :type trips: List[List[int]] :type capacity: int :rtype: bool
- def carPooling2(self, trips, capacity): :type trips: List[List[int]] :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def carPooling(self, trips, capacity): :type trips: List[List[int]] :type capacity: int :rtype: bool
- def carPooling2(self, trips, capacity): :type trips: List[List[int]] :type ... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def carPooling(self, trips, capacity):
""":type trips: List[List[int]] :type capacity: int :rtype: bool"""
<|body_0|>
def carPooling2(self, trips, capacity):
""":type trips: List[List[int]] :type capacity: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def carPooling(self, trips, capacity):
""":type trips: List[List[int]] :type capacity: int :rtype: bool"""
tmp = sorted((x for i, j, k in trips for x in [[j, i], [k, -i]]))
for i, j in tmp:
capacity -= j
if capacity < 0:
return False
... | the_stack_v2_python_sparse | python/1094.car-pooling.py | tainenko/Leetcode2019 | train | 5 | |
420f47b162af0e86cac2c42effdb1860f8bb569b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EdgeSearchEngineCustom()",
"from .edge_search_engine_base import EdgeSearchEngineBase\nfrom .edge_search_engine_base import EdgeSearchEngineBase\nfields: Dict[str, Callable[[Any], None]] = {'edgeSearchEngineOpenSearchXmlUrl': lambda n:... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EdgeSearchEngineCustom()
<|end_body_0|>
<|body_start_1|>
from .edge_search_engine_base import EdgeSearchEngineBase
from .edge_search_engine_base import EdgeSearchEngineBase
field... | Allows IT admins to set a custom default search engine for MDM-Controlled devices. | EdgeSearchEngineCustom | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeSearchEngineCustom:
"""Allows IT admins to set a custom default search engine for MDM-Controlled devices."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdgeSearchEngineCustom:
"""Creates a new instance of the appropriate class based on discrimina... | stack_v2_sparse_classes_36k_train_030387 | 2,503 | 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: EdgeSearchEngineCustom",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `EdgeSearchEngineCustom` described below.
Class description:
Allows IT admins to set a custom default search engine for MDM-Controlled devices.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdgeSearchEngineCustom: Creates a ... | Implement the Python class `EdgeSearchEngineCustom` described below.
Class description:
Allows IT admins to set a custom default search engine for MDM-Controlled devices.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdgeSearchEngineCustom: Creates a ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EdgeSearchEngineCustom:
"""Allows IT admins to set a custom default search engine for MDM-Controlled devices."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdgeSearchEngineCustom:
"""Creates a new instance of the appropriate class based on discrimina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeSearchEngineCustom:
"""Allows IT admins to set a custom default search engine for MDM-Controlled devices."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdgeSearchEngineCustom:
"""Creates a new instance of the appropriate class based on discriminator value Arg... | the_stack_v2_python_sparse | msgraph/generated/models/edge_search_engine_custom.py | microsoftgraph/msgraph-sdk-python | train | 135 |
9eb69b1ee067fc4ce8ffc7fda39146693790ccde | [
"if t not in cls.EMBED_MAPPER:\n raise DependencyEmbedderError('Type %s is not mapped! Types mapped: %s' % (t, cls.EMBED_MAPPER.keys()))\nembed_list = []\nfor ef, ev in cls.EMBED_MAPPER[t].items():\n if not ev:\n embed_list.append('.'.join([base_path, ef]))\n else:\n embed_list.extend(['.'.jo... | <|body_start_0|>
if t not in cls.EMBED_MAPPER:
raise DependencyEmbedderError('Type %s is not mapped! Types mapped: %s' % (t, cls.EMBED_MAPPER.keys()))
embed_list = []
for ef, ev in cls.EMBED_MAPPER[t].items():
if not ev:
embed_list.append('.'.join([base_pa... | Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top level properties have None value while linked em... | DependencyEmbedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top le... | stack_v2_sparse_classes_36k_train_030388 | 5,519 | permissive | [
{
"docstring": "Embeds the fields necessary for a default embed of the given type and base_path :param base_path: path to linkTo :param t: item type this embed is for :return: list of embeds",
"name": "embed_defaults_for_type",
"signature": "def embed_defaults_for_type(cls, *, base_path, t)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_015440 | Implement the Python class `DependencyEmbedder` described below.
Class description:
Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are sp... | Implement the Python class `DependencyEmbedder` described below.
Class description:
Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are sp... | e6542da84eb40e190653fd868e9b89015dfb829e | <|skeleton|>
class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top le... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top level propertie... | the_stack_v2_python_sparse | src/encoded/types/dependencies.py | 4dn-dcic/fourfront | train | 13 |
3fbffef035f896a0f2ebdcecb5ac44ee4faf4bc6 | [
"l_tenant = get_tenant(edge, name)\nif not len(l_tenant):\n d_msg = {'error': 'name {} is not found.'.format(name)}\n return (d_msg, 404)\nreturn l_tenant[0]",
"b_ret, s_msg = delete_tenant(name)\nif not b_ret:\n d_msg = {'error': s_msg}\n return (d_msg, 404)\nreturn (None, 204)"
] | <|body_start_0|>
l_tenant = get_tenant(edge, name)
if not len(l_tenant):
d_msg = {'error': 'name {} is not found.'.format(name)}
return (d_msg, 404)
return l_tenant[0]
<|end_body_0|>
<|body_start_1|>
b_ret, s_msg = delete_tenant(name)
if not b_ret:
... | TenantItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantItem:
def get(self, edge, name):
"""Returns the tenant information."""
<|body_0|>
def delete(self, edge, name):
"""Deletes the tenant."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l_tenant = get_tenant(edge, name)
if not len(l_tenan... | stack_v2_sparse_classes_36k_train_030389 | 2,228 | permissive | [
{
"docstring": "Returns the tenant information.",
"name": "get",
"signature": "def get(self, edge, name)"
},
{
"docstring": "Deletes the tenant.",
"name": "delete",
"signature": "def delete(self, edge, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000624 | Implement the Python class `TenantItem` described below.
Class description:
Implement the TenantItem class.
Method signatures and docstrings:
- def get(self, edge, name): Returns the tenant information.
- def delete(self, edge, name): Deletes the tenant. | Implement the Python class `TenantItem` described below.
Class description:
Implement the TenantItem class.
Method signatures and docstrings:
- def get(self, edge, name): Returns the tenant information.
- def delete(self, edge, name): Deletes the tenant.
<|skeleton|>
class TenantItem:
def get(self, edge, name):... | 65d01799296fce043e87ba58106f8fa8c1d8aa98 | <|skeleton|>
class TenantItem:
def get(self, edge, name):
"""Returns the tenant information."""
<|body_0|>
def delete(self, edge, name):
"""Deletes the tenant."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenantItem:
def get(self, edge, name):
"""Returns the tenant information."""
l_tenant = get_tenant(edge, name)
if not len(l_tenant):
d_msg = {'error': 'name {} is not found.'.format(name)}
return (d_msg, 404)
return l_tenant[0]
def delete(self, edge... | the_stack_v2_python_sparse | pengrixio/api/tenant/endpoints/route.py | iorchard/pengrixio | train | 0 | |
04d61ce9ab9fa4ee3847d76ebbd683f06b4290bf | [
"for i in self.field_list:\n if ArcComments.objects.filter(table_pk=self.pk, field_name=i).exists():\n log = ArcComments.objects.get(table_pk=self.pk, field_name=i)\n try:\n if log.flagged:\n raise forms.ValidationError(log.comment)\n else:\n form... | <|body_start_0|>
for i in self.field_list:
if ArcComments.objects.filter(table_pk=self.pk, field_name=i).exists():
log = ArcComments.objects.get(table_pk=self.pk, field_name=i)
try:
if log.flagged:
raise forms.ValidationErro... | Parent class of all later forms. Contains methods for checking the existence, and the removing, of flags from the ARC user. | ChildminderForms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChildminderForms:
"""Parent class of all later forms. Contains methods for checking the existence, and the removing, of flags from the ARC user."""
def check_flag(self):
"""For a class to call this method it must set self.pk and self.field_list. This method simply checks whether or n... | stack_v2_sparse_classes_36k_train_030390 | 4,837 | no_license | [
{
"docstring": "For a class to call this method it must set self.pk and self.field_list. This method simply checks whether or not a field is flagged, and raises a validation error if it is :return: Form validation error.",
"name": "check_flag",
"signature": "def check_flag(self)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_021424 | Implement the Python class `ChildminderForms` described below.
Class description:
Parent class of all later forms. Contains methods for checking the existence, and the removing, of flags from the ARC user.
Method signatures and docstrings:
- def check_flag(self): For a class to call this method it must set self.pk an... | Implement the Python class `ChildminderForms` described below.
Class description:
Parent class of all later forms. Contains methods for checking the existence, and the removing, of flags from the ARC user.
Method signatures and docstrings:
- def check_flag(self): For a class to call this method it must set self.pk an... | fa6ca6a8164763e1dfe1581702ca5d36e44859de | <|skeleton|>
class ChildminderForms:
"""Parent class of all later forms. Contains methods for checking the existence, and the removing, of flags from the ARC user."""
def check_flag(self):
"""For a class to call this method it must set self.pk and self.field_list. This method simply checks whether or n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChildminderForms:
"""Parent class of all later forms. Contains methods for checking the existence, and the removing, of flags from the ARC user."""
def check_flag(self):
"""For a class to call this method it must set self.pk and self.field_list. This method simply checks whether or not a field is... | the_stack_v2_python_sparse | application/forms/childminder.py | IS-JAQU-CAZ/OFS-MORE-Childminder-Website | train | 0 |
fd30a0c30d6e92eadfba5352dc53d42b8403447e | [
"super().__init__()\nself.centroidsRes = centroidsRes\nself.omega = Omega()\nself.fcom = Fcom()\nself.threshold = 0.98\nself.satisfy = False",
"VMAXELLI = 4 / 3 * pi * Auto2Para().MAXABR ** 3 / Auto2Para().K ** 2\nvomega = self.omega.vtk.volume()\nprint('omega体积', round(vomega / 1000, 2), '理论最大椭球体积', round(VMAXEL... | <|body_start_0|>
super().__init__()
self.centroidsRes = centroidsRes
self.omega = Omega()
self.fcom = Fcom()
self.threshold = 0.98
self.satisfy = False
<|end_body_0|>
<|body_start_1|>
VMAXELLI = 4 / 3 * pi * Auto2Para().MAXABR ** 3 / Auto2Para().K ** 2
vo... | ====step3:聚类全过程求解 规划方法2的求解聚类结果的代理类 负责聚类以及消融效果的验证 | CentroidsResAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CentroidsResAgent:
"""====step3:聚类全过程求解 规划方法2的求解聚类结果的代理类 负责聚类以及消融效果的验证"""
def __init__(self, centroidsRes):
"""传入omega对象作为属性 以代理方法 :param omega:"""
<|body_0|>
def init_num(self):
"""初始化self.clusterRes.num :return:"""
<|body_1|>
def get(self):
... | stack_v2_sparse_classes_36k_train_030391 | 4,188 | no_license | [
{
"docstring": "传入omega对象作为属性 以代理方法 :param omega:",
"name": "__init__",
"signature": "def __init__(self, centroidsRes)"
},
{
"docstring": "初始化self.clusterRes.num :return:",
"name": "init_num",
"signature": "def init_num(self)"
},
{
"docstring": "对待消融区域的体点云omega.bodypts进行聚类 以获得聚类结... | 6 | stack_v2_sparse_classes_30k_train_016020 | Implement the Python class `CentroidsResAgent` described below.
Class description:
====step3:聚类全过程求解 规划方法2的求解聚类结果的代理类 负责聚类以及消融效果的验证
Method signatures and docstrings:
- def __init__(self, centroidsRes): 传入omega对象作为属性 以代理方法 :param omega:
- def init_num(self): 初始化self.clusterRes.num :return:
- def get(self): 对待消融区域的体点云o... | Implement the Python class `CentroidsResAgent` described below.
Class description:
====step3:聚类全过程求解 规划方法2的求解聚类结果的代理类 负责聚类以及消融效果的验证
Method signatures and docstrings:
- def __init__(self, centroidsRes): 传入omega对象作为属性 以代理方法 :param omega:
- def init_num(self): 初始化self.clusterRes.num :return:
- def get(self): 对待消融区域的体点云o... | 1b8e324dc99f932e4648e0a4bb8bdce0317f8542 | <|skeleton|>
class CentroidsResAgent:
"""====step3:聚类全过程求解 规划方法2的求解聚类结果的代理类 负责聚类以及消融效果的验证"""
def __init__(self, centroidsRes):
"""传入omega对象作为属性 以代理方法 :param omega:"""
<|body_0|>
def init_num(self):
"""初始化self.clusterRes.num :return:"""
<|body_1|>
def get(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CentroidsResAgent:
"""====step3:聚类全过程求解 规划方法2的求解聚类结果的代理类 负责聚类以及消融效果的验证"""
def __init__(self, centroidsRes):
"""传入omega对象作为属性 以代理方法 :param omega:"""
super().__init__()
self.centroidsRes = centroidsRes
self.omega = Omega()
self.fcom = Fcom()
self.threshold = ... | the_stack_v2_python_sparse | ablation-algorithm/class/step1agent/CentroidsResAgent.py | USTLZh/student-projects | train | 0 |
ad72a87f07082451f004ec6c9896b74118c61712 | [
"name, = valuelist\nself.data = name\ntry:\n identifier = db.helpers.identifier(name)\nexcept ValueError:\n self.item = None\n return\ntry:\n item = db.DBSession.query(db.Item).filter_by(identifier=identifier).one()\n self.item = item\nexcept NoResultFound:\n self.item = None",
"if self.item is ... | <|body_start_0|>
name, = valuelist
self.data = name
try:
identifier = db.helpers.identifier(name)
except ValueError:
self.item = None
return
try:
item = db.DBSession.query(db.Item).filter_by(identifier=identifier).one()
... | A text field for the name of an item to buy, which also fetches and validates the item. | ItemField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemField:
"""A text field for the name of an item to buy, which also fetches and validates the item."""
def process_formdata(self, valuelist):
"""Fetch the item and stash it in an attribute."""
<|body_0|>
def pre_validate(self, form):
"""Make sure we got an actu... | stack_v2_sparse_classes_36k_train_030392 | 15,939 | no_license | [
{
"docstring": "Fetch the item and stash it in an attribute.",
"name": "process_formdata",
"signature": "def process_formdata(self, valuelist)"
},
{
"docstring": "Make sure we got an actual, buyable item.",
"name": "pre_validate",
"signature": "def pre_validate(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004639 | Implement the Python class `ItemField` described below.
Class description:
A text field for the name of an item to buy, which also fetches and validates the item.
Method signatures and docstrings:
- def process_formdata(self, valuelist): Fetch the item and stash it in an attribute.
- def pre_validate(self, form): Mak... | Implement the Python class `ItemField` described below.
Class description:
A text field for the name of an item to buy, which also fetches and validates the item.
Method signatures and docstrings:
- def process_formdata(self, valuelist): Fetch the item and stash it in an attribute.
- def pre_validate(self, form): Mak... | 872c0b21ed8d45a4c88d51969d3531b8b7913e71 | <|skeleton|>
class ItemField:
"""A text field for the name of an item to buy, which also fetches and validates the item."""
def process_formdata(self, valuelist):
"""Fetch the item and stash it in an attribute."""
<|body_0|>
def pre_validate(self, form):
"""Make sure we got an actu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemField:
"""A text field for the name of an item to buy, which also fetches and validates the item."""
def process_formdata(self, valuelist):
"""Fetch the item and stash it in an attribute."""
name, = valuelist
self.data = name
try:
identifier = db.helpers.id... | the_stack_v2_python_sparse | asb/views/item.py | CatTrinket/tcod-asb | train | 1 |
7415e5523ffae32aa545f9313941625a10966d46 | [
"args = ['--prefix={0}'.format(prefix)]\nif spec.satisfies('@:3.0 %aocc'):\n args.append('--compiler=aocc')\nvar_prefix = '' if spec.satisfies('@:3.0') else 'ALM_'\nargs.append('{0}CC={1}'.format(var_prefix, self.compiler.cc))\nargs.append('{0}CXX={1}'.format(var_prefix, self.compiler.cxx))\nif '+verbose' in spe... | <|body_start_0|>
args = ['--prefix={0}'.format(prefix)]
if spec.satisfies('@:3.0 %aocc'):
args.append('--compiler=aocc')
var_prefix = '' if spec.satisfies('@:3.0') else 'ALM_'
args.append('{0}CC={1}'.format(var_prefix, self.compiler.cc))
args.append('{0}CXX={1}'.forma... | AMD LibM is a software library containing a collection of basic math functions optimized for x86-64 processor-based machines. It provides many routines from the list of standard C99 math functions. Applications can link into AMD LibM library and invoke math functions instead of compiler's math functions for better accu... | Amdlibm | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.1-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Amdlibm:
"""AMD LibM is a software library containing a collection of basic math functions optimized for x86-64 processor-based machines. It provides many routines from the list of standard C99 math functions. Applications can link into AMD LibM library and invoke math functions instead of compil... | stack_v2_sparse_classes_36k_train_030393 | 2,985 | permissive | [
{
"docstring": "Setting build arguments for amdlibm",
"name": "build_args",
"signature": "def build_args(self, spec, prefix)"
},
{
"docstring": "Symbolic link for backward compatibility",
"name": "create_symlink",
"signature": "def create_symlink(self)"
}
] | 2 | null | Implement the Python class `Amdlibm` described below.
Class description:
AMD LibM is a software library containing a collection of basic math functions optimized for x86-64 processor-based machines. It provides many routines from the list of standard C99 math functions. Applications can link into AMD LibM library and ... | Implement the Python class `Amdlibm` described below.
Class description:
AMD LibM is a software library containing a collection of basic math functions optimized for x86-64 processor-based machines. It provides many routines from the list of standard C99 math functions. Applications can link into AMD LibM library and ... | 6c2df00443a2cd092446c7d84431ae37e64e4296 | <|skeleton|>
class Amdlibm:
"""AMD LibM is a software library containing a collection of basic math functions optimized for x86-64 processor-based machines. It provides many routines from the list of standard C99 math functions. Applications can link into AMD LibM library and invoke math functions instead of compil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Amdlibm:
"""AMD LibM is a software library containing a collection of basic math functions optimized for x86-64 processor-based machines. It provides many routines from the list of standard C99 math functions. Applications can link into AMD LibM library and invoke math functions instead of compiler's math fun... | the_stack_v2_python_sparse | var/spack/repos/builtin/packages/amdlibm/package.py | JayjeetAtGithub/spack | train | 0 |
e9332f48244bacb6546fe3ced15adacce9086bf6 | [
"if not inode and (not location) or not parent:\n raise ValueError('Missing inode and location, or parent value.')\nsuper(XFSPathSpec, self).__init__(parent=parent, **kwargs)\nself.inode = inode\nself.location = location",
"string_parts = []\nif self.inode is not None:\n string_parts.append(f'inode: {self.i... | <|body_start_0|>
if not inode and (not location) or not parent:
raise ValueError('Missing inode and location, or parent value.')
super(XFSPathSpec, self).__init__(parent=parent, **kwargs)
self.inode = inode
self.location = location
<|end_body_0|>
<|body_start_1|>
str... | XFS path specification implementation. Attributes: inode (int): inode. location (str): location. | XFSPathSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XFSPathSpec:
"""XFS path specification implementation. Attributes: inode (int): inode. location (str): location."""
def __init__(self, inode=None, location=None, parent=None, **kwargs):
"""Initializes a path specification. Note that an XFS path specification must have a parent. Args:... | stack_v2_sparse_classes_36k_train_030394 | 1,475 | permissive | [
{
"docstring": "Initializes a path specification. Note that an XFS path specification must have a parent. Args: inode (Optional[int]): inode. location (Optional[str]): location. parent (Optional[PathSpec]): parent path specification. Raises: ValueError: when parent or both inode and location are not set.",
... | 2 | stack_v2_sparse_classes_30k_train_001208 | Implement the Python class `XFSPathSpec` described below.
Class description:
XFS path specification implementation. Attributes: inode (int): inode. location (str): location.
Method signatures and docstrings:
- def __init__(self, inode=None, location=None, parent=None, **kwargs): Initializes a path specification. Note... | Implement the Python class `XFSPathSpec` described below.
Class description:
XFS path specification implementation. Attributes: inode (int): inode. location (str): location.
Method signatures and docstrings:
- def __init__(self, inode=None, location=None, parent=None, **kwargs): Initializes a path specification. Note... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class XFSPathSpec:
"""XFS path specification implementation. Attributes: inode (int): inode. location (str): location."""
def __init__(self, inode=None, location=None, parent=None, **kwargs):
"""Initializes a path specification. Note that an XFS path specification must have a parent. Args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XFSPathSpec:
"""XFS path specification implementation. Attributes: inode (int): inode. location (str): location."""
def __init__(self, inode=None, location=None, parent=None, **kwargs):
"""Initializes a path specification. Note that an XFS path specification must have a parent. Args: inode (Optio... | the_stack_v2_python_sparse | dfvfs/path/xfs_path_spec.py | log2timeline/dfvfs | train | 197 |
884811598f616ec11ce7f481233fd82766f31512 | [
"preprocessed_data_path = os.path.join(Resources.get_root(), config.PREPROCESSED_DATA_FOLDER_NAME)\nfor dataset_pkl in os.listdir(preprocessed_data_path):\n if not dataset_pkl.endswith(config.PKL_EXTENSION):\n continue\n name = dataset_pkl.strip(config.PKL_EXTENSION)\n try:\n with open(os.pat... | <|body_start_0|>
preprocessed_data_path = os.path.join(Resources.get_root(), config.PREPROCESSED_DATA_FOLDER_NAME)
for dataset_pkl in os.listdir(preprocessed_data_path):
if not dataset_pkl.endswith(config.PKL_EXTENSION):
continue
name = dataset_pkl.strip(config.PK... | Manager for all preprocessing and retrieval of preprocessed data. | Preprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocessor:
"""Manager for all preprocessing and retrieval of preprocessed data."""
def init_cached_preprocessed_data(cls) -> None:
"""Initialize the preprocessor with previously cached preprocessed data from disk."""
<|body_0|>
def cache_preprocessed_data(cls, name: s... | stack_v2_sparse_classes_36k_train_030395 | 5,155 | no_license | [
{
"docstring": "Initialize the preprocessor with previously cached preprocessed data from disk.",
"name": "init_cached_preprocessed_data",
"signature": "def init_cached_preprocessed_data(cls) -> None"
},
{
"docstring": "Cache the given <dataset> with the given <name>. Stores the dataset locally ... | 5 | stack_v2_sparse_classes_30k_train_002360 | Implement the Python class `Preprocessor` described below.
Class description:
Manager for all preprocessing and retrieval of preprocessed data.
Method signatures and docstrings:
- def init_cached_preprocessed_data(cls) -> None: Initialize the preprocessor with previously cached preprocessed data from disk.
- def cach... | Implement the Python class `Preprocessor` described below.
Class description:
Manager for all preprocessing and retrieval of preprocessed data.
Method signatures and docstrings:
- def init_cached_preprocessed_data(cls) -> None: Initialize the preprocessor with previously cached preprocessed data from disk.
- def cach... | a069672356934e2ed3422f55d084f2b6fa50d8e1 | <|skeleton|>
class Preprocessor:
"""Manager for all preprocessing and retrieval of preprocessed data."""
def init_cached_preprocessed_data(cls) -> None:
"""Initialize the preprocessor with previously cached preprocessed data from disk."""
<|body_0|>
def cache_preprocessed_data(cls, name: s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preprocessor:
"""Manager for all preprocessing and retrieval of preprocessed data."""
def init_cached_preprocessed_data(cls) -> None:
"""Initialize the preprocessor with previously cached preprocessed data from disk."""
preprocessed_data_path = os.path.join(Resources.get_root(), config.PR... | the_stack_v2_python_sparse | lns/common/preprocess.py | ziyadedher/lights-n-signs | train | 1 |
85961012b7f49355528df1eabfc720cf321ae6d0 | [
"Report.__init__(self, database, options, user)\nmenu = options.menu\npid = menu.get_option_by_name('pid').get_value()\nself.center_person = database.get_person_from_gramps_id(pid)\nif self.center_person == None:\n raise ReportError(_('Person %s is not in the Database') % pid)\nself.set_locale(menu.get_option_by... | <|body_start_0|>
Report.__init__(self, database, options, user)
menu = options.menu
pid = menu.get_option_by_name('pid').get_value()
self.center_person = database.get_person_from_gramps_id(pid)
if self.center_person == None:
raise ReportError(_('Person %s is not in th... | EndOfLineReport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EndOfLineReport:
def __init__(self, database, options, user):
"""Create the EndOfLineReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance This report ne... | stack_v2_sparse_classes_36k_train_030396 | 12,659 | no_license | [
{
"docstring": "Create the EndOfLineReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance This report needs the following parameters (class variables) that come in the options c... | 6 | null | Implement the Python class `EndOfLineReport` described below.
Class description:
Implement the EndOfLineReport class.
Method signatures and docstrings:
- def __init__(self, database, options, user): Create the EndOfLineReport object that produces the report. The arguments are: database - the GRAMPS database instance ... | Implement the Python class `EndOfLineReport` described below.
Class description:
Implement the EndOfLineReport class.
Method signatures and docstrings:
- def __init__(self, database, options, user): Create the EndOfLineReport object that produces the report. The arguments are: database - the GRAMPS database instance ... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class EndOfLineReport:
def __init__(self, database, options, user):
"""Create the EndOfLineReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance This report ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EndOfLineReport:
def __init__(self, database, options, user):
"""Create the EndOfLineReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance This report needs the follow... | the_stack_v2_python_sparse | plugins/textreport/endoflinereport.py | balrok/gramps_addon | train | 2 | |
f05d2f337f97404c504945c0149a1b7a1be99e64 | [
"self.validate_dict(change_dict)\ncmd_name = change_dict['cmd']\nself.cmd = cmd_name\nall_allowed_commands = self.ALLOWED_COMMANDS + self.COMMON_ALLOWED_COMMANDS\ncmd_attribute_names = []\nfor cmd in all_allowed_commands:\n if cmd['name'] == cmd_name:\n cmd_attribute_names = cmd['required_attribute_names'... | <|body_start_0|>
self.validate_dict(change_dict)
cmd_name = change_dict['cmd']
self.cmd = cmd_name
all_allowed_commands = self.ALLOWED_COMMANDS + self.COMMON_ALLOWED_COMMANDS
cmd_attribute_names = []
for cmd in all_allowed_commands:
if cmd['name'] == cmd_name:... | Domain object for changes made to storage models' domain objects. | BaseChange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseChange:
"""Domain object for changes made to storage models' domain objects."""
def __init__(self, change_dict):
"""Initializes a BaseChange object from a dict. Args: change_dict: dict. The dict containing cmd name and attributes. Raises: ValidationError: The given change_dict is... | stack_v2_sparse_classes_36k_train_030397 | 7,289 | permissive | [
{
"docstring": "Initializes a BaseChange object from a dict. Args: change_dict: dict. The dict containing cmd name and attributes. Raises: ValidationError: The given change_dict is not valid.",
"name": "__init__",
"signature": "def __init__(self, change_dict)"
},
{
"docstring": "Checks that the ... | 3 | null | Implement the Python class `BaseChange` described below.
Class description:
Domain object for changes made to storage models' domain objects.
Method signatures and docstrings:
- def __init__(self, change_dict): Initializes a BaseChange object from a dict. Args: change_dict: dict. The dict containing cmd name and attr... | Implement the Python class `BaseChange` described below.
Class description:
Domain object for changes made to storage models' domain objects.
Method signatures and docstrings:
- def __init__(self, change_dict): Initializes a BaseChange object from a dict. Args: change_dict: dict. The dict containing cmd name and attr... | 899b9755a6b795a8991e596055ac24065a8435e0 | <|skeleton|>
class BaseChange:
"""Domain object for changes made to storage models' domain objects."""
def __init__(self, change_dict):
"""Initializes a BaseChange object from a dict. Args: change_dict: dict. The dict containing cmd name and attributes. Raises: ValidationError: The given change_dict is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseChange:
"""Domain object for changes made to storage models' domain objects."""
def __init__(self, change_dict):
"""Initializes a BaseChange object from a dict. Args: change_dict: dict. The dict containing cmd name and attributes. Raises: ValidationError: The given change_dict is not valid.""... | the_stack_v2_python_sparse | core/domain/change_domain.py | import-keshav/oppia | train | 4 |
788e6e3cf4aa4b777a072e472b9304d3e01400b7 | [
"self.entity_description = description\nself._attr_name = f'{name} {description.name}'\nself.bbox_data = bbox_data",
"self.bbox_data.update()\nsensor_type = self.entity_description.key\nif sensor_type == 'down_max_bandwidth':\n self._attr_native_value = round(self.bbox_data.data['rx']['maxBandwidth'] / 1000, 2... | <|body_start_0|>
self.entity_description = description
self._attr_name = f'{name} {description.name}'
self.bbox_data = bbox_data
<|end_body_0|>
<|body_start_1|>
self.bbox_data.update()
sensor_type = self.entity_description.key
if sensor_type == 'down_max_bandwidth':
... | Implementation of a Bbox sensor. | BboxSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BboxSensor:
"""Implementation of a Bbox sensor."""
def __init__(self, bbox_data, name, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Get the latest data from Bbox and update the state."""
... | stack_v2_sparse_classes_36k_train_030398 | 6,509 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, bbox_data, name, description: SensorEntityDescription) -> None"
},
{
"docstring": "Get the latest data from Bbox and update the state.",
"name": "update",
"signature": "def update(self) -> None"... | 2 | stack_v2_sparse_classes_30k_train_018984 | Implement the Python class `BboxSensor` described below.
Class description:
Implementation of a Bbox sensor.
Method signatures and docstrings:
- def __init__(self, bbox_data, name, description: SensorEntityDescription) -> None: Initialize the sensor.
- def update(self) -> None: Get the latest data from Bbox and updat... | Implement the Python class `BboxSensor` described below.
Class description:
Implementation of a Bbox sensor.
Method signatures and docstrings:
- def __init__(self, bbox_data, name, description: SensorEntityDescription) -> None: Initialize the sensor.
- def update(self) -> None: Get the latest data from Bbox and updat... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BboxSensor:
"""Implementation of a Bbox sensor."""
def __init__(self, bbox_data, name, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Get the latest data from Bbox and update the state."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BboxSensor:
"""Implementation of a Bbox sensor."""
def __init__(self, bbox_data, name, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
self.entity_description = description
self._attr_name = f'{name} {description.name}'
self.bbox_data = bbox_dat... | the_stack_v2_python_sparse | homeassistant/components/bbox/sensor.py | home-assistant/core | train | 35,501 |
3dbcdfb679e1bd333ea7cd020dfc4f44fe4ec82a | [
"if tau <= 0:\n raise ValueError('context parameter tau should be greater than zero')\nself._tau = tau\nsuper(DatasetWithTimeContext, self).__init__(hdfFile, **kwargs)",
"if seq_idx >= self.num_seqs:\n return None\noriginalSeq = super(DatasetWithTimeContext, self)._collect_single_seq(seq_idx)\ninputFeatures... | <|body_start_0|>
if tau <= 0:
raise ValueError('context parameter tau should be greater than zero')
self._tau = tau
super(DatasetWithTimeContext, self).__init__(hdfFile, **kwargs)
<|end_body_0|>
<|body_start_1|>
if seq_idx >= self.num_seqs:
return None
or... | This dataset composes a context feature by stacking together time frames. | DatasetWithTimeContext | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetWithTimeContext:
"""This dataset composes a context feature by stacking together time frames."""
def __init__(self, hdfFile, tau=1, **kwargs):
"""Constructor :type hdfFile: string :param hdfFile: see the StereoHdfDataset :type tau: int :param tau: how many time frames should b... | stack_v2_sparse_classes_36k_train_030399 | 13,279 | no_license | [
{
"docstring": "Constructor :type hdfFile: string :param hdfFile: see the StereoHdfDataset :type tau: int :param tau: how many time frames should be on the left and on the right. E.g. if tau = 2 then the context feature will be created by stacking two neighboring time frames from left and two neighboring time f... | 2 | null | Implement the Python class `DatasetWithTimeContext` described below.
Class description:
This dataset composes a context feature by stacking together time frames.
Method signatures and docstrings:
- def __init__(self, hdfFile, tau=1, **kwargs): Constructor :type hdfFile: string :param hdfFile: see the StereoHdfDataset... | Implement the Python class `DatasetWithTimeContext` described below.
Class description:
This dataset composes a context feature by stacking together time frames.
Method signatures and docstrings:
- def __init__(self, hdfFile, tau=1, **kwargs): Constructor :type hdfFile: string :param hdfFile: see the StereoHdfDataset... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class DatasetWithTimeContext:
"""This dataset composes a context feature by stacking together time frames."""
def __init__(self, hdfFile, tau=1, **kwargs):
"""Constructor :type hdfFile: string :param hdfFile: see the StereoHdfDataset :type tau: int :param tau: how many time frames should b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetWithTimeContext:
"""This dataset composes a context feature by stacking together time frames."""
def __init__(self, hdfFile, tau=1, **kwargs):
"""Constructor :type hdfFile: string :param hdfFile: see the StereoHdfDataset :type tau: int :param tau: how many time frames should be on the left... | the_stack_v2_python_sparse | python/rwth-i6_returnn/returnn-master/StereoDataset.py | LiuFang816/SALSTM_py_data | train | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.