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
892cbc07a1524f47caaf9eddeb1e1485bb79c915
[ "data = form.cleaned_data\nself.success_url = reverse('flush_tokens', kwargs={'level': int(data['level']), 'semester': int(data['semester']), 'course': int(data['course'].id)})\nreturn super().form_valid(form)", "context = super().get_context_data(**kwargs)\ncontext['title_text'] = \"Choose Course To Flush It's T...
<|body_start_0|> data = form.cleaned_data self.success_url = reverse('flush_tokens', kwargs={'level': int(data['level']), 'semester': int(data['semester']), 'course': int(data['course'].id)}) return super().form_valid(form) <|end_body_0|> <|body_start_1|> context = super().get_context_d...
View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid.
ShowFlushTokensView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShowFlushTokensView: """View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid.""" def form_valid(self, form): """Compute the success URL and call super.form_valid()""" <|body_0|> def g...
stack_v2_sparse_classes_36k_train_021200
29,759
no_license
[ { "docstring": "Compute the success URL and call super.form_valid()", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "Return the data used in the templates rendering.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" } ...
2
stack_v2_sparse_classes_30k_train_017594
Implement the Python class `ShowFlushTokensView` described below. Class description: View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid. Method signatures and docstrings: - def form_valid(self, form): Compute the success URL and...
Implement the Python class `ShowFlushTokensView` described below. Class description: View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid. Method signatures and docstrings: - def form_valid(self, form): Compute the success URL and...
06bc577d01d3dbf6c425e03dcb903977a38e377c
<|skeleton|> class ShowFlushTokensView: """View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid.""" def form_valid(self, form): """Compute the success URL and call super.form_valid()""" <|body_0|> def g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ShowFlushTokensView: """View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid.""" def form_valid(self, form): """Compute the success URL and call super.form_valid()""" data = form.cleaned_data s...
the_stack_v2_python_sparse
cbt/views.py
Festusali/CBTest
train
6
e16501c77850dc0c342db7324b3abbe315b9d7c6
[ "def rec(node, level):\n if not node:\n return ' '\n serialized = str(node.val) + '/' + str(level) + '/' + rec(node.left, level + 1) + '/' + str(level) + '/' + rec(node.right, level + 1)\n return serialized\nreturn rec(root, 0)", "def rec(text, level):\n if text == ' ':\n return None\n ...
<|body_start_0|> def rec(node, level): if not node: return ' ' serialized = str(node.val) + '/' + str(level) + '/' + rec(node.left, level + 1) + '/' + str(level) + '/' + rec(node.right, level + 1) return serialized return rec(root, 0) <|end_body_0|> <...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_021201
1,511
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:...
0da45559271d3dba687858b8945b3e361ecc813c
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def rec(node, level): if not node: return ' ' serialized = str(node.val) + '/' + str(level) + '/' + rec(node.left, level + 1) + '/' + str(level) +...
the_stack_v2_python_sparse
449-serialize-and-deserialize-bst/solution.py
katryo/leetcode
train
0
b80b274f95b407ace8bf851914a89206d9dd1b5c
[ "if len(matrix) == 0:\n return False\nif len(matrix[0]) == 0:\n return False\nwhile len(matrix) >= 1:\n if matrix[-1][-1] < target:\n return False\n elif matrix[-1].count(target) > 0:\n return True\n else:\n del matrix[-1]\nreturn False", "if not matrix:\n return False\nnrow...
<|body_start_0|> if len(matrix) == 0: return False if len(matrix[0]) == 0: return False while len(matrix) >= 1: if matrix[-1][-1] < target: return False elif matrix[-1].count(target) > 0: return True else...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_0|> def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k_train_021202
1,099
no_license
[ { "docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool", "name": "searchMatrix", "signature": "def searchMatrix(self, matrix, target)" }, { "docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool", "name": "searchMatrix", "signature": "def searchM...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool - def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool - def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type...
16e8a7935811fa71ce71998da8549e29ba68f847
<|skeleton|> class Solution: def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_0|> def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" if len(matrix) == 0: return False if len(matrix[0]) == 0: return False while len(matrix) >= 1: if matrix[-1][-1] < target: ...
the_stack_v2_python_sparse
leetcode4/searchMatrix.py
lizyang95/leetcode
train
0
e31b38478eeaa124b93cf7078e530ffe1552f6c2
[ "if len(strs) == 0:\n return ''\ntmp = [strs[0][i] for i in range(len(strs[0]))]\nres = []\nj = 0\nwhile j < len(tmp):\n for i in strs:\n if j >= len(i) or i[j] != tmp[j]:\n return ''.join(res)\n res.append(tmp[j])\n j += 1\nreturn strs[0]", "if not strs:\n return ''\nfor i, ch in...
<|body_start_0|> if len(strs) == 0: return '' tmp = [strs[0][i] for i in range(len(strs[0]))] res = [] j = 0 while j < len(tmp): for i in strs: if j >= len(i) or i[j] != tmp[j]: return ''.join(res) res.append...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefix0(self, strs): """:type strs: List[str] :rtype: str ["flower","flow","flight"]""" <|body_1|> <|end_skeleton|> <|body_start_0|> i...
stack_v2_sparse_classes_36k_train_021203
849
no_license
[ { "docstring": ":type strs: List[str] :rtype: str", "name": "longestCommonPrefix", "signature": "def longestCommonPrefix(self, strs)" }, { "docstring": ":type strs: List[str] :rtype: str [\"flower\",\"flow\",\"flight\"]", "name": "longestCommonPrefix0", "signature": "def longestCommonPre...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefix0(self, strs): :type strs: List[str] :rtype: str ["flower","flow","flight"]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefix0(self, strs): :type strs: List[str] :rtype: str ["flower","flow","flight"] <|ske...
9e49b2c6003b957276737005d4aaac276b44d251
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefix0(self, strs): """:type strs: List[str] :rtype: str ["flower","flow","flight"]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" if len(strs) == 0: return '' tmp = [strs[0][i] for i in range(len(strs[0]))] res = [] j = 0 while j < len(tmp): for i in strs: if j >= ...
the_stack_v2_python_sparse
PythonCode/src/0014_Longest_Common_Prefix.py
oneyuan/CodeforFun
train
0
f4be023aa1220b4a51d353188b6e5d2634bbf010
[ "self.surface = pygame.Surface(DIM)\nappendix = ' ' * (self.surface.get_width() // size)\nself.text = appendix + text + appendix\nself.hpos = hpos\nself.amplitude = amplitude\nself.frequency = frequency\nself.color = color\nself.size = size\nself.position = 0\nself.font = pygame.font.SysFont('mono', self.size, bold...
<|body_start_0|> self.surface = pygame.Surface(DIM) appendix = ' ' * (self.surface.get_width() // size) self.text = appendix + text + appendix self.hpos = hpos self.amplitude = amplitude self.frequency = frequency self.color = color self.size = size ...
Sinus wave scroll text
SinusText
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SinusText: """Sinus wave scroll text""" def __init__(self, dim: tuple, text: str, hpos: int, amplitude: int, frequency: int, color: tuple, size: int=30): """:param surface: surface to draw on :param text: text to draw :param hpos: horizontal position on y axis :param amplitude: ampli...
stack_v2_sparse_classes_36k_train_021204
2,922
no_license
[ { "docstring": ":param surface: surface to draw on :param text: text to draw :param hpos: horizontal position on y axis :param amplitude: amplitude of sinus wave :param frequency: frequency of sinus wave :param color: color of font :param size: size of font", "name": "__init__", "signature": "def __init...
2
stack_v2_sparse_classes_30k_train_019047
Implement the Python class `SinusText` described below. Class description: Sinus wave scroll text Method signatures and docstrings: - def __init__(self, dim: tuple, text: str, hpos: int, amplitude: int, frequency: int, color: tuple, size: int=30): :param surface: surface to draw on :param text: text to draw :param hp...
Implement the Python class `SinusText` described below. Class description: Sinus wave scroll text Method signatures and docstrings: - def __init__(self, dim: tuple, text: str, hpos: int, amplitude: int, frequency: int, color: tuple, size: int=30): :param surface: surface to draw on :param text: text to draw :param hp...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class SinusText: """Sinus wave scroll text""" def __init__(self, dim: tuple, text: str, hpos: int, amplitude: int, frequency: int, color: tuple, size: int=30): """:param surface: surface to draw on :param text: text to draw :param hpos: horizontal position on y axis :param amplitude: ampli...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SinusText: """Sinus wave scroll text""" def __init__(self, dim: tuple, text: str, hpos: int, amplitude: int, frequency: int, color: tuple, size: int=30): """:param surface: surface to draw on :param text: text to draw :param hpos: horizontal position on y axis :param amplitude: amplitude of sinus...
the_stack_v2_python_sparse
effects/SinusText.py
gunny26/pygame
train
5
d1de51861655c5b6f23ac101ab5a67507e31988a
[ "self.shooters_total = difficulty\nself.asteroids_total = difficulty\nsuper().__init__(**kwargs)", "player = GamePlayer.random()\nshooters = ShooterGroup.random(n=self.shooters_total)\nplayers = PlayerGroup(player, shooters, activate=True, shooting=True)\nspaceships = SuperSpaceShipGroup(players, active=True)\nas...
<|body_start_0|> self.shooters_total = difficulty self.asteroids_total = difficulty super().__init__(**kwargs) <|end_body_0|> <|body_start_1|> player = GamePlayer.random() shooters = ShooterGroup.random(n=self.shooters_total) players = PlayerGroup(player, shooters, activ...
Level in which the goal is to destroy all shooters.
DestroyShooters
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DestroyShooters: """Level in which the goal is to destroy all shooters.""" def __init__(self, difficulty, **kwargs): """Create the level by creating the groups.""" <|body_0|> def start(self): """Start the game by creating the game group with shooters.""" ...
stack_v2_sparse_classes_36k_train_021205
10,293
no_license
[ { "docstring": "Create the level by creating the groups.", "name": "__init__", "signature": "def __init__(self, difficulty, **kwargs)" }, { "docstring": "Start the game by creating the game group with shooters.", "name": "start", "signature": "def start(self)" }, { "docstring": "...
3
null
Implement the Python class `DestroyShooters` described below. Class description: Level in which the goal is to destroy all shooters. Method signatures and docstrings: - def __init__(self, difficulty, **kwargs): Create the level by creating the groups. - def start(self): Start the game by creating the game group with ...
Implement the Python class `DestroyShooters` described below. Class description: Level in which the goal is to destroy all shooters. Method signatures and docstrings: - def __init__(self, difficulty, **kwargs): Create the level by creating the groups. - def start(self): Start the game by creating the game group with ...
ebfcaaf4a028eddb36bbc99184eb3f7a86eb24ed
<|skeleton|> class DestroyShooters: """Level in which the goal is to destroy all shooters.""" def __init__(self, difficulty, **kwargs): """Create the level by creating the groups.""" <|body_0|> def start(self): """Start the game by creating the game group with shooters.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DestroyShooters: """Level in which the goal is to destroy all shooters.""" def __init__(self, difficulty, **kwargs): """Create the level by creating the groups.""" self.shooters_total = difficulty self.asteroids_total = difficulty super().__init__(**kwargs) def start(...
the_stack_v2_python_sparse
Game Structure/geometry/version5/myasteroidgame.py
MarcPartensky/Python-Games
train
2
aa178235470e50a0624128c357488a5cdc23c4b6
[ "self.n = n\nself.a = a\nself.b = b\nself.m = m\nself.y = [random.random() for i in range(n)]\nassert len(self.a) == n\nfor ai in a:\n assert 0 <= ai <= m - 1\nassert 0 <= b <= m - 1\nassert m >= 2", "rand = 0\nfor k in range(self.n):\n rand += self.a[k] * self.y[-(k + 1)]\nrand = (rand + self.b) % self.m\n...
<|body_start_0|> self.n = n self.a = a self.b = b self.m = m self.y = [random.random() for i in range(n)] assert len(self.a) == n for ai in a: assert 0 <= ai <= m - 1 assert 0 <= b <= m - 1 assert m >= 2 <|end_body_0|> <|body_start_1|>...
CongruenceGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CongruenceGenerator: def __init__(self, n, a, b, m): """a: list of ai, where ai is elem of {0, .., m - 1}, |a| = k b: constant increment, b elem of {0, .., m - 1} n: constant, nr. of remembered last random numbers m: contant nr., m elem of {2, .. inf}""" <|body_0|> def next_...
stack_v2_sparse_classes_36k_train_021206
6,586
no_license
[ { "docstring": "a: list of ai, where ai is elem of {0, .., m - 1}, |a| = k b: constant increment, b elem of {0, .., m - 1} n: constant, nr. of remembered last random numbers m: contant nr., m elem of {2, .. inf}", "name": "__init__", "signature": "def __init__(self, n, a, b, m)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_007993
Implement the Python class `CongruenceGenerator` described below. Class description: Implement the CongruenceGenerator class. Method signatures and docstrings: - def __init__(self, n, a, b, m): a: list of ai, where ai is elem of {0, .., m - 1}, |a| = k b: constant increment, b elem of {0, .., m - 1} n: constant, nr. ...
Implement the Python class `CongruenceGenerator` described below. Class description: Implement the CongruenceGenerator class. Method signatures and docstrings: - def __init__(self, n, a, b, m): a: list of ai, where ai is elem of {0, .., m - 1}, |a| = k b: constant increment, b elem of {0, .., m - 1} n: constant, nr. ...
88b5dd04e3d4392a1d0781837f4fd5e97abe0e39
<|skeleton|> class CongruenceGenerator: def __init__(self, n, a, b, m): """a: list of ai, where ai is elem of {0, .., m - 1}, |a| = k b: constant increment, b elem of {0, .., m - 1} n: constant, nr. of remembered last random numbers m: contant nr., m elem of {2, .. inf}""" <|body_0|> def next_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CongruenceGenerator: def __init__(self, n, a, b, m): """a: list of ai, where ai is elem of {0, .., m - 1}, |a| = k b: constant increment, b elem of {0, .., m - 1} n: constant, nr. of remembered last random numbers m: contant nr., m elem of {2, .. inf}""" self.n = n self.a = a s...
the_stack_v2_python_sparse
lib.py
yanickdi/sugimoto_course
train
1
2ebe5aacac4291b0e022cb3fc8ce4472a446212d
[ "mean = self._get_mean(imt, rup.mag, rup.hypo_depth, dists.rrup, d=-0.02)\nstddevs = self._get_stddevs(stddev_types, 10 ** mean)\nmean = self._apply_amplification_factor(mean)\nreturn (mean, stddevs)", "assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))\nstd = n...
<|body_start_0|> mean = self._get_mean(imt, rup.mag, rup.hypo_depth, dists.rrup, d=-0.02) stddevs = self._get_stddevs(stddev_types, 10 ** mean) mean = self._apply_amplification_factor(mean) return (mean, stddevs) <|end_body_0|> <|body_start_1|> assert all((stddev_type in self.DE...
Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements the equations for 'Subduction Interface' (that's ...
SiMidorikawa1999SInter
[ "BSD-3-Clause", "AGPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SiMidorikawa1999SInter: """Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements...
stack_v2_sparse_classes_36k_train_021207
15,234
permissive
[ { "docstring": "Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.", "name": "get_mean_and_stddevs", "signature": "def ...
2
null
Implement the Python class `SiMidorikawa1999SInter` described below. Class description: Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan...
Implement the Python class `SiMidorikawa1999SInter` described below. Class description: Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan...
0da9ba5a575360081715e8b90c71d4b16c6687c8
<|skeleton|> class SiMidorikawa1999SInter: """Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SiMidorikawa1999SInter: """Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements the equation...
the_stack_v2_python_sparse
openquake/hazardlib/gsim/si_midorikawa_1999.py
GFZ-Centre-for-Early-Warning/shakyground
train
1
082ce4e73277ac6949606ff297b343c648964a5f
[ "self.smp = smp\nself.nangles = nangles\nself.angles = np.linspace(0, np.pi, nangles, endpoint=False)", "smp = self.smp\nangles = self.angles\nsmp.compCov(y)\nspec = np.zeros(angles.shape)\nfor i in range(self.nangles):\n spec[i] = smp.compSpecSample(angles[i])\nangle = angles[np.argmax(spec)]\nif retspec:\n ...
<|body_start_0|> self.smp = smp self.nangles = nangles self.angles = np.linspace(0, np.pi, nangles, endpoint=False) <|end_body_0|> <|body_start_1|> smp = self.smp angles = self.angles smp.compCov(y) spec = np.zeros(angles.shape) for i in range(self.nangle...
DOA tracker without any filtering. It always computes the full spectrum. Attributes ---------- angles : (nangles,) ndarray Vector of angles to be sampled in a spatial spectrum. It is sampled in a linear space. Reference --------- Zhong, X., Prekumar, A. B., and Madhukumar, A. S., "Particle filtering for acoustic source...
NaiveTracker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NaiveTracker: """DOA tracker without any filtering. It always computes the full spectrum. Attributes ---------- angles : (nangles,) ndarray Vector of angles to be sampled in a spatial spectrum. It is sampled in a linear space. Reference --------- Zhong, X., Prekumar, A. B., and Madhukumar, A. S.,...
stack_v2_sparse_classes_36k_train_021208
2,209
no_license
[ { "docstring": "Parameters ---------- smp : SpectrumSampler Sampler of spatial spectrum. nangles : int Number of angle samples in a spatial spectrum. The angles will be sampled as a linear space in [0, pi).", "name": "__init__", "signature": "def __init__(self, smp, nangles)" }, { "docstring": "...
2
stack_v2_sparse_classes_30k_train_006806
Implement the Python class `NaiveTracker` described below. Class description: DOA tracker without any filtering. It always computes the full spectrum. Attributes ---------- angles : (nangles,) ndarray Vector of angles to be sampled in a spatial spectrum. It is sampled in a linear space. Reference --------- Zhong, X., ...
Implement the Python class `NaiveTracker` described below. Class description: DOA tracker without any filtering. It always computes the full spectrum. Attributes ---------- angles : (nangles,) ndarray Vector of angles to be sampled in a spatial spectrum. It is sampled in a linear space. Reference --------- Zhong, X., ...
4cbb2eba87c6ffd79e474014584ee31c893ade13
<|skeleton|> class NaiveTracker: """DOA tracker without any filtering. It always computes the full spectrum. Attributes ---------- angles : (nangles,) ndarray Vector of angles to be sampled in a spatial spectrum. It is sampled in a linear space. Reference --------- Zhong, X., Prekumar, A. B., and Madhukumar, A. S.,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NaiveTracker: """DOA tracker without any filtering. It always computes the full spectrum. Attributes ---------- angles : (nangles,) ndarray Vector of angles to be sampled in a spatial spectrum. It is sampled in a linear space. Reference --------- Zhong, X., Prekumar, A. B., and Madhukumar, A. S., "Particle fi...
the_stack_v2_python_sparse
naivetracker.py
qrqiuren/particle
train
5
060e6b05b9a6e44d69cec0361e332d8b46179083
[ "num_r = 0\nnum_w = 0\nnum_b = 0\nfor num in nums:\n if num == 0:\n num_r += 1\n elif num == 1:\n num_w += 1\n else:\n num_b += 1\nprint(num_r, num_r + len(nums) - num_r - num_b, len(nums) - num_b)\nfor i in range(0, num_r):\n nums[i] = 0\nfor i in range(num_r, num_r + len(nums) - n...
<|body_start_0|> num_r = 0 num_w = 0 num_b = 0 for num in nums: if num == 0: num_r += 1 elif num == 1: num_w += 1 else: num_b += 1 print(num_r, num_r + len(nums) - num_r - num_b, len(nums) - num_b...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortColors(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def sortColorsOnePass(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_021209
2,691
no_license
[ { "docstring": "Do not return anything, modify nums in-place instead.", "name": "sortColors", "signature": "def sortColors(self, nums: List[int]) -> None" }, { "docstring": "Do not return anything, modify nums in-place instead.", "name": "sortColorsOnePass", "signature": "def sortColorsO...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def sortColorsOnePass(self, nums: List[int]) -> None: Do not return anythin...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def sortColorsOnePass(self, nums: List[int]) -> None: Do not return anythin...
f61d1573c8963b8b813c662a6c1ef4f7dda64146
<|skeleton|> class Solution: def sortColors(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def sortColorsOnePass(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def sortColors(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" num_r = 0 num_w = 0 num_b = 0 for num in nums: if num == 0: num_r += 1 elif num == 1: num_w += 1 ...
the_stack_v2_python_sparse
two-pointers/Sort Colors.py
jojojoseph94/lc-practice
train
0
d048fd94c0dcafb1222ab702a1c7c80446544bfd
[ "if alg.cluster:\n host = alg.cluster.host\n port = alg.cluster.port\n token = alg.cluster.token\n fd, cert = tempfile.mkstemp(text=True)\n with open(fd, 'w') as f:\n f.write(alg.cluster.cert)\n conf = Configuration()\n conf.api_key['authorization'] = token\n conf.host = f'{PROTO}{hos...
<|body_start_0|> if alg.cluster: host = alg.cluster.host port = alg.cluster.port token = alg.cluster.token fd, cert = tempfile.mkstemp(text=True) with open(fd, 'w') as f: f.write(alg.cluster.cert) conf = Configuration() ...
Interface to kubernetes REST API for starting algorithms.
TatorAlgorithm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TatorAlgorithm: """Interface to kubernetes REST API for starting algorithms.""" def __init__(self, alg): """Intializes the connection. If algorithm object includes a remote cluster, use that. Otherwise, use this cluster.""" <|body_0|> def start_algorithm(self, media_ids,...
stack_v2_sparse_classes_36k_train_021210
43,176
permissive
[ { "docstring": "Intializes the connection. If algorithm object includes a remote cluster, use that. Otherwise, use this cluster.", "name": "__init__", "signature": "def __init__(self, alg)" }, { "docstring": "Starts an algorithm job, substituting in parameters in the workflow spec.", "name":...
2
null
Implement the Python class `TatorAlgorithm` described below. Class description: Interface to kubernetes REST API for starting algorithms. Method signatures and docstrings: - def __init__(self, alg): Intializes the connection. If algorithm object includes a remote cluster, use that. Otherwise, use this cluster. - def ...
Implement the Python class `TatorAlgorithm` described below. Class description: Interface to kubernetes REST API for starting algorithms. Method signatures and docstrings: - def __init__(self, alg): Intializes the connection. If algorithm object includes a remote cluster, use that. Otherwise, use this cluster. - def ...
0eb75ee9333316b06f773de2b75e8e797a98ffdb
<|skeleton|> class TatorAlgorithm: """Interface to kubernetes REST API for starting algorithms.""" def __init__(self, alg): """Intializes the connection. If algorithm object includes a remote cluster, use that. Otherwise, use this cluster.""" <|body_0|> def start_algorithm(self, media_ids,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TatorAlgorithm: """Interface to kubernetes REST API for starting algorithms.""" def __init__(self, alg): """Intializes the connection. If algorithm object includes a remote cluster, use that. Otherwise, use this cluster.""" if alg.cluster: host = alg.cluster.host p...
the_stack_v2_python_sparse
main/kube.py
kristianmk/tator
train
0
f05d13978cca7829f393a6088c65c16c1fbe5d0a
[ "logging.debug('%s', request)\nnow = utils.utcnow()\nq = bot_management.BotInfo.query()\ntry:\n q = bot_management.filter_dimensions(q, request.dimensions)\n q = bot_management.filter_availability(q, swarming_rpcs.to_bool(request.quarantined), swarming_rpcs.to_bool(request.is_dead), now, swarming_rpcs.to_bool...
<|body_start_0|> logging.debug('%s', request) now = utils.utcnow() q = bot_management.BotInfo.query() try: q = bot_management.filter_dimensions(q, request.dimensions) q = bot_management.filter_availability(q, swarming_rpcs.to_bool(request.quarantined), swarming_rp...
Bots-related API.
SwarmingBotsService
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SwarmingBotsService: """Bots-related API.""" def list(self, request): """Provides list of known bots. Deleted bots will not be listed.""" <|body_0|> def count(self, request): """Counts number of bots with given dimensions.""" <|body_1|> def dimension...
stack_v2_sparse_classes_36k_train_021211
31,178
permissive
[ { "docstring": "Provides list of known bots. Deleted bots will not be listed.", "name": "list", "signature": "def list(self, request)" }, { "docstring": "Counts number of bots with given dimensions.", "name": "count", "signature": "def count(self, request)" }, { "docstring": "Ret...
3
stack_v2_sparse_classes_30k_train_017123
Implement the Python class `SwarmingBotsService` described below. Class description: Bots-related API. Method signatures and docstrings: - def list(self, request): Provides list of known bots. Deleted bots will not be listed. - def count(self, request): Counts number of bots with given dimensions. - def dimensions(se...
Implement the Python class `SwarmingBotsService` described below. Class description: Bots-related API. Method signatures and docstrings: - def list(self, request): Provides list of known bots. Deleted bots will not be listed. - def count(self, request): Counts number of bots with given dimensions. - def dimensions(se...
3fa4c520dddd82ed190152709e0a54b35faa3bae
<|skeleton|> class SwarmingBotsService: """Bots-related API.""" def list(self, request): """Provides list of known bots. Deleted bots will not be listed.""" <|body_0|> def count(self, request): """Counts number of bots with given dimensions.""" <|body_1|> def dimension...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SwarmingBotsService: """Bots-related API.""" def list(self, request): """Provides list of known bots. Deleted bots will not be listed.""" logging.debug('%s', request) now = utils.utcnow() q = bot_management.BotInfo.query() try: q = bot_management.filter...
the_stack_v2_python_sparse
appengine/swarming/handlers_endpoints.py
Slayo2008/New2
train
1
272e4272491deeb7d1567a9db00f757c242f8170
[ "connection = None\nchannel = None\ntry:\n parameters = pika.ConnectionParameters(host=host)\n connection = BlockingConnection(parameters)\n connection.set_backpressure_multiplier(50)\n channel = connection.channel()\n channel.exchange_declare(exchange=self.exchange, durable=False, auto_delete=True)\...
<|body_start_0|> connection = None channel = None try: parameters = pika.ConnectionParameters(host=host) connection = BlockingConnection(parameters) connection.set_backpressure_multiplier(50) channel = connection.channel() channel.excha...
RabbitMQMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RabbitMQMixin: def connect_rabbitmq(self, host): """Connect rabbitmq""" <|body_0|> def reconnect_rabbitmq(self, connection, host): """This is for catching any unpredictable AMQPConnectionError. Release resource for reconnect.""" <|body_1|> def close_rabb...
stack_v2_sparse_classes_36k_train_021212
3,364
no_license
[ { "docstring": "Connect rabbitmq", "name": "connect_rabbitmq", "signature": "def connect_rabbitmq(self, host)" }, { "docstring": "This is for catching any unpredictable AMQPConnectionError. Release resource for reconnect.", "name": "reconnect_rabbitmq", "signature": "def reconnect_rabbit...
3
null
Implement the Python class `RabbitMQMixin` described below. Class description: Implement the RabbitMQMixin class. Method signatures and docstrings: - def connect_rabbitmq(self, host): Connect rabbitmq - def reconnect_rabbitmq(self, connection, host): This is for catching any unpredictable AMQPConnectionError. Release...
Implement the Python class `RabbitMQMixin` described below. Class description: Implement the RabbitMQMixin class. Method signatures and docstrings: - def connect_rabbitmq(self, host): Connect rabbitmq - def reconnect_rabbitmq(self, connection, host): This is for catching any unpredictable AMQPConnectionError. Release...
3b095a325581b1fc48497c234f0ad55e928586a1
<|skeleton|> class RabbitMQMixin: def connect_rabbitmq(self, host): """Connect rabbitmq""" <|body_0|> def reconnect_rabbitmq(self, connection, host): """This is for catching any unpredictable AMQPConnectionError. Release resource for reconnect.""" <|body_1|> def close_rabb...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RabbitMQMixin: def connect_rabbitmq(self, host): """Connect rabbitmq""" connection = None channel = None try: parameters = pika.ConnectionParameters(host=host) connection = BlockingConnection(parameters) connection.set_backpressure_multiplier...
the_stack_v2_python_sparse
apps/gateway/mixin/mq.py
jcsy521/ydws
train
0
9e5ce91a7e1caca5554100eea65c801108f2ee29
[ "self._root_dir = os.path.abspath(root_dir)\nself._all_components = {}\nself._required_compnames = []\nfor comp in model:\n src = _External(self._root_dir, comp, model[comp])\n self._all_components[comp] = src\n if model[comp][ExternalsDescription.REQUIRED]:\n self._required_compnames.append(comp)",...
<|body_start_0|> self._root_dir = os.path.abspath(root_dir) self._all_components = {} self._required_compnames = [] for comp in model: src = _External(self._root_dir, comp, model[comp]) self._all_components[comp] = src if model[comp][ExternalsDescripti...
SourceTree represents a group of managed externals
SourceTree
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourceTree: """SourceTree represents a group of managed externals""" def __init__(self, root_dir, model): """Build a SourceTree object from a model description""" <|body_0|> def status(self, relative_path_base=LOCAL_PATH_INDICATOR): """Report the status component...
stack_v2_sparse_classes_36k_train_021213
12,567
permissive
[ { "docstring": "Build a SourceTree object from a model description", "name": "__init__", "signature": "def __init__(self, root_dir, model)" }, { "docstring": "Report the status components FIXME(bja, 2017-10) what do we do about situations where the user checked out the optional components, but d...
3
null
Implement the Python class `SourceTree` described below. Class description: SourceTree represents a group of managed externals Method signatures and docstrings: - def __init__(self, root_dir, model): Build a SourceTree object from a model description - def status(self, relative_path_base=LOCAL_PATH_INDICATOR): Report...
Implement the Python class `SourceTree` described below. Class description: SourceTree represents a group of managed externals Method signatures and docstrings: - def __init__(self, root_dir, model): Build a SourceTree object from a model description - def status(self, relative_path_base=LOCAL_PATH_INDICATOR): Report...
a666ac3b58d19f04249f76c9340f2e4a4a27939b
<|skeleton|> class SourceTree: """SourceTree represents a group of managed externals""" def __init__(self, root_dir, model): """Build a SourceTree object from a model description""" <|body_0|> def status(self, relative_path_base=LOCAL_PATH_INDICATOR): """Report the status component...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SourceTree: """SourceTree represents a group of managed externals""" def __init__(self, root_dir, model): """Build a SourceTree object from a model description""" self._root_dir = os.path.abspath(root_dir) self._all_components = {} self._required_compnames = [] for...
the_stack_v2_python_sparse
manage_externals/manic/sourcetree.py
dtcenter/METplus
train
41
facd24cb62423151fa145d9d9798c46eb1c76360
[ "self.frequency = frequency\nself.octaves = octaves\nself.light_forest_thresh = light_forest_thresh\nself.heavy_forest_thresh = heavy_forest_thresh\nself.seed_modifier = seed_modifier", "modded_seed = self._get_modified_seed_val(seed_val, self.seed_modifier)\nfor y in range(0, mmap.get_map_height()):\n for x i...
<|body_start_0|> self.frequency = frequency self.octaves = octaves self.light_forest_thresh = light_forest_thresh self.heavy_forest_thresh = heavy_forest_thresh self.seed_modifier = seed_modifier <|end_body_0|> <|body_start_1|> modded_seed = self._get_modified_seed_val(s...
A simplex noise-based forest grower. This is very rudimentary. You'll probably get the best results by stacking multiple invocations of this with varying forest threses.
SimplexForestModifier
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimplexForestModifier: """A simplex noise-based forest grower. This is very rudimentary. You'll probably get the best results by stacking multiple invocations of this with varying forest threses.""" def __init__(self, frequency=20.0, octaves=3, light_forest_thresh=0.2, heavy_forest_thresh=0....
stack_v2_sparse_classes_36k_train_021214
2,504
permissive
[ { "docstring": ":keyword float frequency: Adjusts the frequency of the simplex noise. Higher values will lead to larger chunks of forests. Smaller values will cause smaller clusters to be scattered all over the map. :keyword int octaves: The number of noise passes to make on each hex. Additional passes may lead...
2
stack_v2_sparse_classes_30k_train_006226
Implement the Python class `SimplexForestModifier` described below. Class description: A simplex noise-based forest grower. This is very rudimentary. You'll probably get the best results by stacking multiple invocations of this with varying forest threses. Method signatures and docstrings: - def __init__(self, freque...
Implement the Python class `SimplexForestModifier` described below. Class description: A simplex noise-based forest grower. This is very rudimentary. You'll probably get the best results by stacking multiple invocations of this with varying forest threses. Method signatures and docstrings: - def __init__(self, freque...
001d35dbaef1f89e9b441fe63c7182cb1f3cda40
<|skeleton|> class SimplexForestModifier: """A simplex noise-based forest grower. This is very rudimentary. You'll probably get the best results by stacking multiple invocations of this with varying forest threses.""" def __init__(self, frequency=20.0, octaves=3, light_forest_thresh=0.2, heavy_forest_thresh=0....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimplexForestModifier: """A simplex noise-based forest grower. This is very rudimentary. You'll probably get the best results by stacking multiple invocations of this with varying forest threses.""" def __init__(self, frequency=20.0, octaves=3, light_forest_thresh=0.2, heavy_forest_thresh=0.3, seed_modif...
the_stack_v2_python_sparse
btmux_maplib/map_generator/modifiers/forests.py
gtaylor/btmux_maplib
train
0
a9ae7db40d5dfe0db8a5b380b155cd97b0f46df2
[ "n = len(nums)\ncounter = Counter(nums)\nfreq = SortedList(counter.values())\nfor i in range(n - 1, -1, -1):\n if len(freq) <= 1:\n return i + 1\n if freq[0] == 1 and freq[1] == freq[-1]:\n return i + 1\n if freq[0] == freq[-2] and freq[-1] == freq[-2] + 1:\n return i + 1\n num = nu...
<|body_start_0|> n = len(nums) counter = Counter(nums) freq = SortedList(counter.values()) for i in range(n - 1, -1, -1): if len(freq) <= 1: return i + 1 if freq[0] == 1 and freq[1] == freq[-1]: return i + 1 if freq[0] =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxEqualFreq(self, nums: List[int]) -> int: """有序集合维护有序的频率 during iteration 1. decrement the biggest count or 2. decrement the smallest count 移除最多或者最少的""" <|body_0|> def maxEqualFreq2(self, nums: List[int]) -> int: """分三种情况讨论 1. 最大出现次数 maxFreq == 1 随意删除...
stack_v2_sparse_classes_36k_train_021215
3,113
no_license
[ { "docstring": "有序集合维护有序的频率 during iteration 1. decrement the biggest count or 2. decrement the smallest count 移除最多或者最少的", "name": "maxEqualFreq", "signature": "def maxEqualFreq(self, nums: List[int]) -> int" }, { "docstring": "分三种情况讨论 1. 最大出现次数 maxFreq == 1 随意删除一个元素 2. 所有数出现次数都是 maxFreq 或者 maxF...
2
stack_v2_sparse_classes_30k_train_002993
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxEqualFreq(self, nums: List[int]) -> int: 有序集合维护有序的频率 during iteration 1. decrement the biggest count or 2. decrement the smallest count 移除最多或者最少的 - def maxEqualFreq2(self,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxEqualFreq(self, nums: List[int]) -> int: 有序集合维护有序的频率 during iteration 1. decrement the biggest count or 2. decrement the smallest count 移除最多或者最少的 - def maxEqualFreq2(self,...
7e79e26bb8f641868561b186e34c1127ed63c9e0
<|skeleton|> class Solution: def maxEqualFreq(self, nums: List[int]) -> int: """有序集合维护有序的频率 during iteration 1. decrement the biggest count or 2. decrement the smallest count 移除最多或者最少的""" <|body_0|> def maxEqualFreq2(self, nums: List[int]) -> int: """分三种情况讨论 1. 最大出现次数 maxFreq == 1 随意删除...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: """有序集合维护有序的频率 during iteration 1. decrement the biggest count or 2. decrement the smallest count 移除最多或者最少的""" n = len(nums) counter = Counter(nums) freq = SortedList(counter.values()) for i in range(n - 1, -1, -...
the_stack_v2_python_sparse
5_map/经典题/哈希表统计/1224. 最大相等频率-有序集合维护有序的频率.py
981377660LMT/algorithm-study
train
225
0949634a1477577fdaf6639bf57aa9672c1c9116
[ "if not isinstance(config, KubeflowV2DagRunnerConfig):\n raise TypeError('config must be type of KubeflowV2DagRunnerConfig.')\nsuper().__init__()\nself._config = config\nself._output_dir = output_dir or os.getcwd()\nself._output_filename = output_filename or 'pipeline.json'\nself._exit_handler = None", "if not...
<|body_start_0|> if not isinstance(config, KubeflowV2DagRunnerConfig): raise TypeError('config must be type of KubeflowV2DagRunnerConfig.') super().__init__() self._config = config self._output_dir = output_dir or os.getcwd() self._output_filename = output_filename or...
Kubeflow V2 pipeline runner (currently for managed pipelines). Builds a pipeline job spec in json format based on TFX pipeline DSL object.
KubeflowV2DagRunner
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KubeflowV2DagRunner: """Kubeflow V2 pipeline runner (currently for managed pipelines). Builds a pipeline job spec in json format based on TFX pipeline DSL object.""" def __init__(self, config: KubeflowV2DagRunnerConfig, output_dir: Optional[str]=None, output_filename: Optional[str]=None): ...
stack_v2_sparse_classes_36k_train_021216
8,534
permissive
[ { "docstring": "Constructs an KubeflowV2DagRunner for compiling pipelines. Args: config: An KubeflowV2DagRunnerConfig object to specify runtime configuration when running the pipeline in Kubeflow. output_dir: An optional output directory into which to output the pipeline definition files. Defaults to the curren...
3
stack_v2_sparse_classes_30k_val_000335
Implement the Python class `KubeflowV2DagRunner` described below. Class description: Kubeflow V2 pipeline runner (currently for managed pipelines). Builds a pipeline job spec in json format based on TFX pipeline DSL object. Method signatures and docstrings: - def __init__(self, config: KubeflowV2DagRunnerConfig, outp...
Implement the Python class `KubeflowV2DagRunner` described below. Class description: Kubeflow V2 pipeline runner (currently for managed pipelines). Builds a pipeline job spec in json format based on TFX pipeline DSL object. Method signatures and docstrings: - def __init__(self, config: KubeflowV2DagRunnerConfig, outp...
1b328504fa08a70388691e4072df76f143631325
<|skeleton|> class KubeflowV2DagRunner: """Kubeflow V2 pipeline runner (currently for managed pipelines). Builds a pipeline job spec in json format based on TFX pipeline DSL object.""" def __init__(self, config: KubeflowV2DagRunnerConfig, output_dir: Optional[str]=None, output_filename: Optional[str]=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KubeflowV2DagRunner: """Kubeflow V2 pipeline runner (currently for managed pipelines). Builds a pipeline job spec in json format based on TFX pipeline DSL object.""" def __init__(self, config: KubeflowV2DagRunnerConfig, output_dir: Optional[str]=None, output_filename: Optional[str]=None): """Cons...
the_stack_v2_python_sparse
tfx/orchestration/kubeflow/v2/kubeflow_v2_dag_runner.py
tensorflow/tfx
train
2,116
5029c65fd044aa23de717775f434d10f1a15d135
[ "self.datadir = datadir\nself.pglogdir = os.path.join(self.datadir, 'pg_log')\nself.ignore = {}\nfor path in matching_files(self.pglogdir, setlimit=True):\n self.ignore[path] = True\nself.handles = {}\nself.maxlines = 1000\nself.timelimit = 3\nself.delay = 0.1", "start = time.time()\nelapsed = 0\ncount = 0\ntp...
<|body_start_0|> self.datadir = datadir self.pglogdir = os.path.join(self.datadir, 'pg_log') self.ignore = {} for path in matching_files(self.pglogdir, setlimit=True): self.ignore[path] = True self.handles = {} self.maxlines = 1000 self.timelimit = 3 ...
Watch changes to files in the pg_log directory recorded by the gpsyncmaster.
SyncmasterWatcher
[ "MIT", "BSD-4-Clause-UC", "BSD-3-Clause", "ISC", "bzip2-1.0.6", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-4-Clause", "Artistic-2.0", "PostgreSQL", "LicenseRef-scancode-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SyncmasterWatcher: """Watch changes to files in the pg_log directory recorded by the gpsyncmaster.""" def __init__(self, datadir): """Build a map containing the existing contents of the pg_log directory so that we can avoid getting confused by them after we start the syncmaster.""" ...
stack_v2_sparse_classes_36k_train_021217
8,586
permissive
[ { "docstring": "Build a map containing the existing contents of the pg_log directory so that we can avoid getting confused by them after we start the syncmaster.", "name": "__init__", "signature": "def __init__(self, datadir)" }, { "docstring": "Generate lines recently added to log files in the ...
4
stack_v2_sparse_classes_30k_train_018087
Implement the Python class `SyncmasterWatcher` described below. Class description: Watch changes to files in the pg_log directory recorded by the gpsyncmaster. Method signatures and docstrings: - def __init__(self, datadir): Build a map containing the existing contents of the pg_log directory so that we can avoid get...
Implement the Python class `SyncmasterWatcher` described below. Class description: Watch changes to files in the pg_log directory recorded by the gpsyncmaster. Method signatures and docstrings: - def __init__(self, datadir): Build a map containing the existing contents of the pg_log directory so that we can avoid get...
aea301f532079c3a7f1ccf0a452ed79785a1a3a3
<|skeleton|> class SyncmasterWatcher: """Watch changes to files in the pg_log directory recorded by the gpsyncmaster.""" def __init__(self, datadir): """Build a map containing the existing contents of the pg_log directory so that we can avoid getting confused by them after we start the syncmaster.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SyncmasterWatcher: """Watch changes to files in the pg_log directory recorded by the gpsyncmaster.""" def __init__(self, datadir): """Build a map containing the existing contents of the pg_log directory so that we can avoid getting confused by them after we start the syncmaster.""" self.d...
the_stack_v2_python_sparse
tools/sbin/hawqstandbywatch.py
DalavanCloud/hawq
train
1
d305f1870b6c70dd447b39d202d420daeeb492dd
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MainError()", "from .error_details import ErrorDetails\nfrom .inner_error import InnerError\nfrom .error_details import ErrorDetails\nfrom .inner_error import InnerError\nfields: Dict[str, Callable[[Any], None]] = {'code': lambda n: se...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return MainError() <|end_body_0|> <|body_start_1|> from .error_details import ErrorDetails from .inner_error import InnerError from .error_details import ErrorDetails from .inne...
MainError
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MainError: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MainError: """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: MainEr...
stack_v2_sparse_classes_36k_train_021218
3,350
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: MainError", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(par...
3
stack_v2_sparse_classes_30k_train_008708
Implement the Python class `MainError` described below. Class description: Implement the MainError class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MainError: Creates a new instance of the appropriate class based on discriminator value Args: parse...
Implement the Python class `MainError` described below. Class description: Implement the MainError class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MainError: Creates a new instance of the appropriate class based on discriminator value Args: parse...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class MainError: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MainError: """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: MainEr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MainError: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MainError: """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: MainError""" ...
the_stack_v2_python_sparse
msgraph/generated/models/o_data_errors/main_error.py
microsoftgraph/msgraph-sdk-python
train
135
0f5b8118301f844b09dd7cd2e60299b8ba8b6c89
[ "self.client = rospy.ServiceProxy(service_name, object_type, persistent)\nself._service_name = service_name\nself._max_retry_attempts = max_retry_attempts", "try_count = 0\nwhile True:\n try:\n return self.client(*argv)\n except TypeError as err:\n log_and_exit('Invalid arguments for client {}...
<|body_start_0|> self.client = rospy.ServiceProxy(service_name, object_type, persistent) self._service_name = service_name self._max_retry_attempts = max_retry_attempts <|end_body_0|> <|body_start_1|> try_count = 0 while True: try: return self.client(...
This class wraps rospy's ServiceProxy method so that we can wait 5 minutes if a service throws an exception. This is required to prevent our metrics from being flooded since an exception is thrown by service calls when the cancel simulation API is called. Because robomaker gives us no way of knowing whether or not the ...
ServiceProxyWrapper
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceProxyWrapper: """This class wraps rospy's ServiceProxy method so that we can wait 5 minutes if a service throws an exception. This is required to prevent our metrics from being flooded since an exception is thrown by service calls when the cancel simulation API is called. Because robomaker...
stack_v2_sparse_classes_36k_train_021219
2,979
permissive
[ { "docstring": "service_name (str): Name of the service to create a client for object_type (object): The object type for making a service request persistent (bool): flag to whether keep the connection open or not max_retry_attempts (int): maximum number of retry", "name": "__init__", "signature": "def _...
2
stack_v2_sparse_classes_30k_train_019960
Implement the Python class `ServiceProxyWrapper` described below. Class description: This class wraps rospy's ServiceProxy method so that we can wait 5 minutes if a service throws an exception. This is required to prevent our metrics from being flooded since an exception is thrown by service calls when the cancel simu...
Implement the Python class `ServiceProxyWrapper` described below. Class description: This class wraps rospy's ServiceProxy method so that we can wait 5 minutes if a service throws an exception. This is required to prevent our metrics from being flooded since an exception is thrown by service calls when the cancel simu...
2ce50508dd4100eaef7f8729436549a801505705
<|skeleton|> class ServiceProxyWrapper: """This class wraps rospy's ServiceProxy method so that we can wait 5 minutes if a service throws an exception. This is required to prevent our metrics from being flooded since an exception is thrown by service calls when the cancel simulation API is called. Because robomaker...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServiceProxyWrapper: """This class wraps rospy's ServiceProxy method so that we can wait 5 minutes if a service throws an exception. This is required to prevent our metrics from being flooded since an exception is thrown by service calls when the cancel simulation API is called. Because robomaker gives us no ...
the_stack_v2_python_sparse
bundle/markov/rospy_wrappers.py
aws-deepracer-community/deepracer-simapp
train
83
150b66be3afb67a93774bea2d72c7c11848f8824
[ "self.config = config\nself._dag_builder = dag_builder\nself._start = start\nself._end = end\nself._freq = freq\nself._fit_state = fit_state\nself.dag = self._dag_builder.get_dag(self.config)\nset_fit_state(self.dag, self._fit_state)\nself._methods = self._dag_builder.methods\nself._column_to_tags_mapping = self._d...
<|body_start_0|> self.config = config self._dag_builder = dag_builder self._start = start self._end = end self._freq = freq self._fit_state = fit_state self.dag = self._dag_builder.get_dag(self.config) set_fit_state(self.dag, self._fit_state) self....
Class for running DAGs.
IncrementalDagRunner
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IncrementalDagRunner: """Class for running DAGs.""" def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: """Initialize DAG. :param config: config for DAG :param dag_builder...
stack_v2_sparse_classes_36k_train_021220
8,311
permissive
[ { "docstring": "Initialize DAG. :param config: config for DAG :param dag_builder: `DagBuilder` instance :param start: first prediction datetime (e.g., first time at which we generate a prediction in `predict` mode, using all available data up to and including `start`) :param end: last prediction datetime :param...
4
stack_v2_sparse_classes_30k_train_001318
Implement the Python class `IncrementalDagRunner` described below. Class description: Class for running DAGs. Method signatures and docstrings: - def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: Initial...
Implement the Python class `IncrementalDagRunner` described below. Class description: Class for running DAGs. Method signatures and docstrings: - def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: Initial...
363c59fa29df2ba2719cbad2f8a19ae12cc54a92
<|skeleton|> class IncrementalDagRunner: """Class for running DAGs.""" def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: """Initialize DAG. :param config: config for DAG :param dag_builder...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IncrementalDagRunner: """Class for running DAGs.""" def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: """Initialize DAG. :param config: config for DAG :param dag_builder: `DagBuilder...
the_stack_v2_python_sparse
core/dataflow/runners.py
srlindemann/amp
train
0
33dd6597dc36645bf9b6f23b878c80d4f009ee67
[ "super().__init__()\nself.backbone_model = ElectraModel.from_cfg(backbone_cfg)\nif weight_initializer is None:\n weight_initializer = self.backbone_model.weight_initializer\nif bias_initializer is None:\n bias_initializer = self.backbone_model.bias_initializer\nself.rtd_encoder = nn.HybridSequential()\nself.r...
<|body_start_0|> super().__init__() self.backbone_model = ElectraModel.from_cfg(backbone_cfg) if weight_initializer is None: weight_initializer = self.backbone_model.weight_initializer if bias_initializer is None: bias_initializer = self.backbone_model.bias_initia...
It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether it is an original or a replacement.
ElectraDiscriminator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElectraDiscriminator: """It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether...
stack_v2_sparse_classes_36k_train_021221
45,388
permissive
[ { "docstring": "Parameters ---------- backbone_cfg weight_initializer bias_initializer", "name": "__init__", "signature": "def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None)" }, { "docstring": "Getting the scores of the replaced token detection of the whole sentence...
2
null
Implement the Python class `ElectraDiscriminator` described below. Class description: It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classificati...
Implement the Python class `ElectraDiscriminator` described below. Class description: It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classificati...
1df42c561ae9552960e3f8b5f22e74de812a29c6
<|skeleton|> class ElectraDiscriminator: """It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ElectraDiscriminator: """It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether it is an ori...
the_stack_v2_python_sparse
src/gluonnlp/models/electra.py
akshatgui/gluon-nlp
train
0
520b5f5cf43da09273c596fd08a25a323ea7fb54
[ "self.item_list = arr\nself.n = n\nself.w = w\nself.maxW = -math.inf\nself.maxV = -math.inf", "if cw == w or i == n:\n if cw > self.maxW:\n self.maxW = cw\n return\nself.f(i + 1, cw)\nif cw + self.item_list[i] <= w:\n self.f(i + 1, cw + self.item_list[i])" ]
<|body_start_0|> self.item_list = arr self.n = n self.w = w self.maxW = -math.inf self.maxV = -math.inf <|end_body_0|> <|body_start_1|> if cw == w or i == n: if cw > self.maxW: self.maxW = cw return self.f(i + 1, cw) ...
BagZeroOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BagZeroOne: def __init__(self, arr, n, w): """:param arr: the item list :param n:the number of item in bag :param w: max total weight of bag""" <|body_0|> def f(self, i, cw): """:param i: the item index to check :param cw: current weight :return:""" <|body_1|...
stack_v2_sparse_classes_36k_train_021222
1,706
no_license
[ { "docstring": ":param arr: the item list :param n:the number of item in bag :param w: max total weight of bag", "name": "__init__", "signature": "def __init__(self, arr, n, w)" }, { "docstring": ":param i: the item index to check :param cw: current weight :return:", "name": "f", "signat...
2
null
Implement the Python class `BagZeroOne` described below. Class description: Implement the BagZeroOne class. Method signatures and docstrings: - def __init__(self, arr, n, w): :param arr: the item list :param n:the number of item in bag :param w: max total weight of bag - def f(self, i, cw): :param i: the item index t...
Implement the Python class `BagZeroOne` described below. Class description: Implement the BagZeroOne class. Method signatures and docstrings: - def __init__(self, arr, n, w): :param arr: the item list :param n:the number of item in bag :param w: max total weight of bag - def f(self, i, cw): :param i: the item index t...
2864e2fd90fb28b172a01aef31a29df039fd26a4
<|skeleton|> class BagZeroOne: def __init__(self, arr, n, w): """:param arr: the item list :param n:the number of item in bag :param w: max total weight of bag""" <|body_0|> def f(self, i, cw): """:param i: the item index to check :param cw: current weight :return:""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BagZeroOne: def __init__(self, arr, n, w): """:param arr: the item list :param n:the number of item in bag :param w: max total weight of bag""" self.item_list = arr self.n = n self.w = w self.maxW = -math.inf self.maxV = -math.inf def f(self, i, cw): ...
the_stack_v2_python_sparse
data_structure/backtracking/knapsack.py
guihehans/self_improvement
train
0
5e4d55ecb70982d46e9a322dd8c80bc25ab4163a
[ "if User.objects.count() > 0:\n return redirect('/')\nreturn super(FirstRunView, self).get(request, *args, **kwargs)", "context = super(FirstRunView, self).get_context_data(**kwargs)\ntry:\n numbers = twilio_client.phone_numbers.list(phone_number=settings.TWILIO_FROM_NUM)\n if numbers:\n number = ...
<|body_start_0|> if User.objects.count() > 0: return redirect('/') return super(FirstRunView, self).get(request, *args, **kwargs) <|end_body_0|> <|body_start_1|> context = super(FirstRunView, self).get_context_data(**kwargs) try: numbers = twilio_client.phone_num...
View to make initial run experience easier.
FirstRunView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FirstRunView: """View to make initial run experience easier.""" def get(self, request, *args, **kwargs): """Deny access if already setup.""" <|body_0|> def get_context_data(self, **kwargs): """Inject data into context.""" <|body_1|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_36k_train_021223
8,391
permissive
[ { "docstring": "Deny access if already setup.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Inject data into context.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_007482
Implement the Python class `FirstRunView` described below. Class description: View to make initial run experience easier. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Deny access if already setup. - def get_context_data(self, **kwargs): Inject data into context.
Implement the Python class `FirstRunView` described below. Class description: View to make initial run experience easier. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Deny access if already setup. - def get_context_data(self, **kwargs): Inject data into context. <|skeleton|> class Fir...
1827547b5a8cf94bf1708bb4029c0b0e834416a9
<|skeleton|> class FirstRunView: """View to make initial run experience easier.""" def get(self, request, *args, **kwargs): """Deny access if already setup.""" <|body_0|> def get_context_data(self, **kwargs): """Inject data into context.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FirstRunView: """View to make initial run experience easier.""" def get(self, request, *args, **kwargs): """Deny access if already setup.""" if User.objects.count() > 0: return redirect('/') return super(FirstRunView, self).get(request, *args, **kwargs) def get_co...
the_stack_v2_python_sparse
site_config/views.py
armenzg/apostello
train
0
aacc5340ec18bc2e4399a6b9485e448d72d4b5b5
[ "for line in text:\n if line.startswith('import') or (line.startswith('from') and ' import ' in line):\n continue\n elif line.isspace() or line == '':\n continue\n elif '#' in line:\n if line.split('#')[0].isspace():\n continue\n elif line.startswith('class '):\n c...
<|body_start_0|> for line in text: if line.startswith('import') or (line.startswith('from') and ' import ' in line): continue elif line.isspace() or line == '': continue elif '#' in line: if line.split('#')[0].isspace(): ...
Scripts
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Scripts: def CheckScript(text): """Check if ``text`` is a valid script for PyUnity. Parameters ---------- text : list List of lines Returns ------- bool If script is valid or not. Notes ----- This function checks each line to see if it matches at least one of these criteria: 1. The line ...
stack_v2_sparse_classes_36k_train_021224
5,343
permissive
[ { "docstring": "Check if ``text`` is a valid script for PyUnity. Parameters ---------- text : list List of lines Returns ------- bool If script is valid or not. Notes ----- This function checks each line to see if it matches at least one of these criteria: 1. The line is an ``import`` statement 2. The line is j...
2
stack_v2_sparse_classes_30k_train_008031
Implement the Python class `Scripts` described below. Class description: Implement the Scripts class. Method signatures and docstrings: - def CheckScript(text): Check if ``text`` is a valid script for PyUnity. Parameters ---------- text : list List of lines Returns ------- bool If script is valid or not. Notes ----- ...
Implement the Python class `Scripts` described below. Class description: Implement the Scripts class. Method signatures and docstrings: - def CheckScript(text): Check if ``text`` is a valid script for PyUnity. Parameters ---------- text : list List of lines Returns ------- bool If script is valid or not. Notes ----- ...
0ecf82a3913cd38b3dc47e711a03935630323ecf
<|skeleton|> class Scripts: def CheckScript(text): """Check if ``text`` is a valid script for PyUnity. Parameters ---------- text : list List of lines Returns ------- bool If script is valid or not. Notes ----- This function checks each line to see if it matches at least one of these criteria: 1. The line ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Scripts: def CheckScript(text): """Check if ``text`` is a valid script for PyUnity. Parameters ---------- text : list List of lines Returns ------- bool If script is valid or not. Notes ----- This function checks each line to see if it matches at least one of these criteria: 1. The line is an ``import...
the_stack_v2_python_sparse
pyunity/files.py
wilzegers/pyunity
train
0
d1ac42be54d2e210db652e5663ffe14d7e659fab
[ "super().__init__(name=name, identity=identity, channel_division=channel_division, gain_provider=gain_provider, mode_class=mode_class)\nself.gain_range = Range()\nself.solve_signal = True", "if branch is None:\n branch = f'correlated.{self.name}'\nsuper().set_options(configuration, branch=branch)\nif isinstanc...
<|body_start_0|> super().__init__(name=name, identity=identity, channel_division=channel_division, gain_provider=gain_provider, mode_class=mode_class) self.gain_range = Range() self.solve_signal = True <|end_body_0|> <|body_start_1|> if branch is None: branch = f'correlated....
CorrelatedModality
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CorrelatedModality: def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): """Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of c...
stack_v2_sparse_classes_36k_train_021225
5,391
permissive
[ { "docstring": "Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of channels). Modes are created by the modality from a channel division which is a collection of channel groups. The type of mode may be expl...
4
stack_v2_sparse_classes_30k_train_005986
Implement the Python class `CorrelatedModality` described below. Class description: Implement the CorrelatedModality class. Method signatures and docstrings: - def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): Create a correlated modality. A Modality is a collec...
Implement the Python class `CorrelatedModality` described below. Class description: Implement the CorrelatedModality class. Method signatures and docstrings: - def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): Create a correlated modality. A Modality is a collec...
493700340cd34d5f319af6f3a562a82135bb30dd
<|skeleton|> class CorrelatedModality: def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): """Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CorrelatedModality: def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): """Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of channels). Mode...
the_stack_v2_python_sparse
sofia_redux/scan/channels/modality/correlated_modality.py
SOFIA-USRA/sofia_redux
train
12
0a129579441bd3f7369d8ec2d86a86977399f2d5
[ "color_dict = color_df.rename(columns={color_df.columns[0]: 'Generator', color_df.columns[1]: 'Colour'})\ncolor_dict['Generator'] = color_dict['Generator'].str.strip()\ncolor_dict['Colour'] = color_dict['Colour'].str.strip()\ncolor_dict = color_dict[['Generator', 'Colour']].set_index('Generator').to_dict()['Colour'...
<|body_start_0|> color_dict = color_df.rename(columns={color_df.columns[0]: 'Generator', color_df.columns[1]: 'Colour'}) color_dict['Generator'] = color_dict['Generator'].str.strip() color_dict['Colour'] = color_dict['Colour'].str.strip() color_dict = color_dict[['Generator', 'Colour']]....
Dictionary of gen names to colors for generation plots. The dictionary is usually set with the colour_dictionary.csv using the set_colors_from_df method. The file should have the following format: https://nrel.github.io/Marmot/references/input-files/mapping-folder/colour_dictionary.html Random colors can also be set wi...
GeneratorColorDict
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeneratorColorDict: """Dictionary of gen names to colors for generation plots. The dictionary is usually set with the colour_dictionary.csv using the set_colors_from_df method. The file should have the following format: https://nrel.github.io/Marmot/references/input-files/mapping-folder/colour_di...
stack_v2_sparse_classes_36k_train_021226
3,001
permissive
[ { "docstring": "Sets colors from a dataframe. The dataframe should have the following format: https://nrel.github.io/Marmot/references/input-files/mapping-folder/colour_dictionary.html Args: color_df (pd.DataFrame): DataFrame with Generator and Color column Returns: GeneratorColorDict: Instance of class", "...
2
stack_v2_sparse_classes_30k_train_008390
Implement the Python class `GeneratorColorDict` described below. Class description: Dictionary of gen names to colors for generation plots. The dictionary is usually set with the colour_dictionary.csv using the set_colors_from_df method. The file should have the following format: https://nrel.github.io/Marmot/referenc...
Implement the Python class `GeneratorColorDict` described below. Class description: Dictionary of gen names to colors for generation plots. The dictionary is usually set with the colour_dictionary.csv using the set_colors_from_df method. The file should have the following format: https://nrel.github.io/Marmot/referenc...
caee0b8775510576ae64bd91c95837f6a0ee7c0a
<|skeleton|> class GeneratorColorDict: """Dictionary of gen names to colors for generation plots. The dictionary is usually set with the colour_dictionary.csv using the set_colors_from_df method. The file should have the following format: https://nrel.github.io/Marmot/references/input-files/mapping-folder/colour_di...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GeneratorColorDict: """Dictionary of gen names to colors for generation plots. The dictionary is usually set with the colour_dictionary.csv using the set_colors_from_df method. The file should have the following format: https://nrel.github.io/Marmot/references/input-files/mapping-folder/colour_dictionary.html...
the_stack_v2_python_sparse
marmot/plottingmodules/plotutils/styles.py
NREL/Marmot
train
9
0e5ca0152863d4767c3b6bb06f72c7ef8112cb20
[ "str_num = str(num)\na, b = (1, 1)\nfor i in range(len(str_num) - 2, -1, -1):\n a, b = (a + b if '10' <= str_num[i:i + 2] <= '25' else a, a)\nreturn a", "a = 1\nb = 1\ny = num % 10\nwhile num != 0:\n num //= 10\n x = num % 10\n tmp = 10 * x + y\n c = a + b if 10 <= tmp <= 25 else a\n b, a = (a, ...
<|body_start_0|> str_num = str(num) a, b = (1, 1) for i in range(len(str_num) - 2, -1, -1): a, b = (a + b if '10' <= str_num[i:i + 2] <= '25' else a, a) return a <|end_body_0|> <|body_start_1|> a = 1 b = 1 y = num % 10 while num != 0: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def translateNum(self, num: int) -> int: """将数字翻译成字符串 :param num: :return: 复杂度分析:时间复杂度O(N),空间复杂度O(N),N为字符串的长度,决定了循环的次数""" <|body_0|> def translateNumPlus(self, num: int) -> int: """将数字翻译成字符串 优化:利用求余运算 num \\% 10num%10 和求整运算 num // 10num//10 ,可获取数字 numnum 的各...
stack_v2_sparse_classes_36k_train_021227
2,735
no_license
[ { "docstring": "将数字翻译成字符串 :param num: :return: 复杂度分析:时间复杂度O(N),空间复杂度O(N),N为字符串的长度,决定了循环的次数", "name": "translateNum", "signature": "def translateNum(self, num: int) -> int" }, { "docstring": "将数字翻译成字符串 优化:利用求余运算 num \\\\% 10num%10 和求整运算 num // 10num//10 ,可获取数字 numnum 的各位数字(获取顺序为个位、十位、百位…)。 :param...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def translateNum(self, num: int) -> int: 将数字翻译成字符串 :param num: :return: 复杂度分析:时间复杂度O(N),空间复杂度O(N),N为字符串的长度,决定了循环的次数 - def translateNumPlus(self, num: int) -> int: 将数字翻译成字符串 优化:利用...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def translateNum(self, num: int) -> int: 将数字翻译成字符串 :param num: :return: 复杂度分析:时间复杂度O(N),空间复杂度O(N),N为字符串的长度,决定了循环的次数 - def translateNumPlus(self, num: int) -> int: 将数字翻译成字符串 优化:利用...
32941ee052d0985a9569441d314378700ff4d225
<|skeleton|> class Solution: def translateNum(self, num: int) -> int: """将数字翻译成字符串 :param num: :return: 复杂度分析:时间复杂度O(N),空间复杂度O(N),N为字符串的长度,决定了循环的次数""" <|body_0|> def translateNumPlus(self, num: int) -> int: """将数字翻译成字符串 优化:利用求余运算 num \\% 10num%10 和求整运算 num // 10num//10 ,可获取数字 numnum 的各...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def translateNum(self, num: int) -> int: """将数字翻译成字符串 :param num: :return: 复杂度分析:时间复杂度O(N),空间复杂度O(N),N为字符串的长度,决定了循环的次数""" str_num = str(num) a, b = (1, 1) for i in range(len(str_num) - 2, -1, -1): a, b = (a + b if '10' <= str_num[i:i + 2] <= '25' else a, a...
the_stack_v2_python_sparse
cecilia-python/剑指offer/chapter-7/TranslateNum.py
Cecilia520/algorithmic-learning-leetcode
train
7
8336d0bcc1a9ef04698dacc1f18ab425adca17dc
[ "node = head\ncount = 0\nwhile node:\n count += 1\n node = node.next\nnode = head\nfor _ in range(count // 2):\n node = node.next\nreturn node", "fast = slow = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\nreturn slow" ]
<|body_start_0|> node = head count = 0 while node: count += 1 node = node.next node = head for _ in range(count // 2): node = node.next return node <|end_body_0|> <|body_start_1|> fast = slow = head while fast and fast....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def middleNode(self, head): """解題思路:暴力法。 從頭開始遍歷並計算linked list的長度,找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode""" <|body_0|> def middleNode2(self, head): """解題思路: 例用兩個指標fast和slow從頭遍歷,當fast走完linked list時,slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(...
stack_v2_sparse_classes_36k_train_021228
2,066
no_license
[ { "docstring": "解題思路:暴力法。 從頭開始遍歷並計算linked list的長度,找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode", "name": "middleNode", "signature": "def middleNode(self, head)" }, { "docstring": "解題思路: 例用兩個指標fast和slow從頭遍歷,當fast走完linked list時,slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(1) :param head:...
2
stack_v2_sparse_classes_30k_train_008125
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def middleNode(self, head): 解題思路:暴力法。 從頭開始遍歷並計算linked list的長度,找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode - def middleNode2(self, head): 解題思路: 例用兩個指標fast和slow從頭遍歷,當...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def middleNode(self, head): 解題思路:暴力法。 從頭開始遍歷並計算linked list的長度,找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode - def middleNode2(self, head): 解題思路: 例用兩個指標fast和slow從頭遍歷,當...
8595b04cf5a024c2cd8a97f750d890a818568401
<|skeleton|> class Solution: def middleNode(self, head): """解題思路:暴力法。 從頭開始遍歷並計算linked list的長度,找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode""" <|body_0|> def middleNode2(self, head): """解題思路: 例用兩個指標fast和slow從頭遍歷,當fast走完linked list時,slow會剛好停在middle node 時間複雜度: O(N) 空間複雜度: O(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def middleNode(self, head): """解題思路:暴力法。 從頭開始遍歷並計算linked list的長度,找完後再回頭遍歷middle node :type head: ListNode :rtype: ListNode""" node = head count = 0 while node: count += 1 node = node.next node = head for _ in range(count // 2): ...
the_stack_v2_python_sparse
python/876.middle-of-the-linked-list.py
tainenko/Leetcode2019
train
5
740ec3a924d08100f6fc19da9bbd53f0cc1391d4
[ "self.error = 0\nself.errorPrevious = 0\nself.eP = 0\nself.eI = 0\nself.eD = 0\nself.kP = kp\nself.kI = ki\nself.kD = kd\nself.u = 0", "self.errorPrevious = self.error\nif abs(error) < 90:\n self.error = error\nelse:\n pass\nself.eP = self.error\nself.eD = self.error - self.errorPrevious\nself.eI = self.eI ...
<|body_start_0|> self.error = 0 self.errorPrevious = 0 self.eP = 0 self.eI = 0 self.eD = 0 self.kP = kp self.kI = ki self.kD = kd self.u = 0 <|end_body_0|> <|body_start_1|> self.errorPrevious = self.error if abs(error) < 90: ...
PIDController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PIDController: def __init__(self, kp, ki, kd): """Initialize the PID controller. :param kp: (float) Proportional gain :param ki: (float) Integral gain :param kd: (float) Differential gain""" <|body_0|> def update(self, error, dt=None): """Update the PID controller wi...
stack_v2_sparse_classes_36k_train_021229
1,428
no_license
[ { "docstring": "Initialize the PID controller. :param kp: (float) Proportional gain :param ki: (float) Integral gain :param kd: (float) Differential gain", "name": "__init__", "signature": "def __init__(self, kp, ki, kd)" }, { "docstring": "Update the PID controller with new error values. :param...
2
stack_v2_sparse_classes_30k_train_017135
Implement the Python class `PIDController` described below. Class description: Implement the PIDController class. Method signatures and docstrings: - def __init__(self, kp, ki, kd): Initialize the PID controller. :param kp: (float) Proportional gain :param ki: (float) Integral gain :param kd: (float) Differential gai...
Implement the Python class `PIDController` described below. Class description: Implement the PIDController class. Method signatures and docstrings: - def __init__(self, kp, ki, kd): Initialize the PID controller. :param kp: (float) Proportional gain :param ki: (float) Integral gain :param kd: (float) Differential gai...
e6c9686c440486831ce5ea246ab05af5b4f6ea01
<|skeleton|> class PIDController: def __init__(self, kp, ki, kd): """Initialize the PID controller. :param kp: (float) Proportional gain :param ki: (float) Integral gain :param kd: (float) Differential gain""" <|body_0|> def update(self, error, dt=None): """Update the PID controller wi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PIDController: def __init__(self, kp, ki, kd): """Initialize the PID controller. :param kp: (float) Proportional gain :param ki: (float) Integral gain :param kd: (float) Differential gain""" self.error = 0 self.errorPrevious = 0 self.eP = 0 self.eI = 0 self.eD =...
the_stack_v2_python_sparse
Controllers/PIDController.py
augustusellis/balance_bot
train
1
225bfce3dd8611ddd90bf48606676b54a84abd7e
[ "direct_x = [1, -1, -1, 0, 1, -1, 0, 1]\ndirect_y = [0, 0, -1, -1, -1, 1, 1, 1]\nm = len(board)\nn = len(board[0])\nlive_num = 0\nfor k in range(8):\n x = direct_x[k] + j\n y = direct_y[k] + i\n if 0 <= x < n and 0 <= y < m and (board[y][x] % 2 > 0):\n live_num += 1\nreturn live_num", "m = len(boa...
<|body_start_0|> direct_x = [1, -1, -1, 0, 1, -1, 0, 1] direct_y = [0, 0, -1, -1, -1, 1, 1, 1] m = len(board) n = len(board[0]) live_num = 0 for k in range(8): x = direct_x[k] + j y = direct_y[k] + i if 0 <= x < n and 0 <= y < m and (bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def liveAroundCellNum(self, i, j, board): """Return the live cell number around the position (i, j) in the board.""" <|body_0|> def gameOfLife(self, board): """next_state current_state (01) represents (dead, live) (00) represents(dead, dead) (11) represents...
stack_v2_sparse_classes_36k_train_021230
3,332
no_license
[ { "docstring": "Return the live cell number around the position (i, j) in the board.", "name": "liveAroundCellNum", "signature": "def liveAroundCellNum(self, i, j, board)" }, { "docstring": "next_state current_state (01) represents (dead, live) (00) represents(dead, dead) (11) represents(live, l...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def liveAroundCellNum(self, i, j, board): Return the live cell number around the position (i, j) in the board. - def gameOfLife(self, board): next_state current_state (01) repres...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def liveAroundCellNum(self, i, j, board): Return the live cell number around the position (i, j) in the board. - def gameOfLife(self, board): next_state current_state (01) repres...
052bd7915257679877dbe55b60ed1abb7528eaa2
<|skeleton|> class Solution: def liveAroundCellNum(self, i, j, board): """Return the live cell number around the position (i, j) in the board.""" <|body_0|> def gameOfLife(self, board): """next_state current_state (01) represents (dead, live) (00) represents(dead, dead) (11) represents...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def liveAroundCellNum(self, i, j, board): """Return the live cell number around the position (i, j) in the board.""" direct_x = [1, -1, -1, 0, 1, -1, 0, 1] direct_y = [0, 0, -1, -1, -1, 1, 1, 1] m = len(board) n = len(board[0]) live_num = 0 for...
the_stack_v2_python_sparse
python_solution/Array/289_GameOfLife.py
Dimen61/leetcode
train
4
85806abf49bb166009598cb03801393829985c69
[ "pointers = [lists[i] for i in range(len(lists))]\ndummy = ListNode(0)\ncurrent = dummy\nwhile self.is_valid(pointers):\n current.next = self.get_min(pointers)\n current = current.next\nreturn dummy.next", "for pt in pointers:\n if pt:\n return True\nreturn False", "min_value = float('inf')\nmin...
<|body_start_0|> pointers = [lists[i] for i in range(len(lists))] dummy = ListNode(0) current = dummy while self.is_valid(pointers): current.next = self.get_min(pointers) current = current.next return dummy.next <|end_body_0|> <|body_start_1|> for...
Runtime: 6900 ms, faster than 6.28% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 17.2 MB, less than 15.94% of Python3 online submissions for Merge k Sorted Lists.
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Runtime: 6900 ms, faster than 6.28% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 17.2 MB, less than 15.94% of Python3 online submissions for Merge k Sorted Lists.""" def mergeKLists(self, lists): """Merge k sorted linked lists and return it as on...
stack_v2_sparse_classes_36k_train_021231
2,236
no_license
[ { "docstring": "Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 Args: lists: list of linked-lists to merge from Returns: ListNode: head node for a merged linked-list", "name": "mergeK...
3
null
Implement the Python class `Solution` described below. Class description: Runtime: 6900 ms, faster than 6.28% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 17.2 MB, less than 15.94% of Python3 online submissions for Merge k Sorted Lists. Method signatures and docstrings: - def mergeKLists(self...
Implement the Python class `Solution` described below. Class description: Runtime: 6900 ms, faster than 6.28% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 17.2 MB, less than 15.94% of Python3 online submissions for Merge k Sorted Lists. Method signatures and docstrings: - def mergeKLists(self...
01fe893ba2e37c9bda79e3081c556698f0b6d2f0
<|skeleton|> class Solution: """Runtime: 6900 ms, faster than 6.28% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 17.2 MB, less than 15.94% of Python3 online submissions for Merge k Sorted Lists.""" def mergeKLists(self, lists): """Merge k sorted linked lists and return it as on...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Runtime: 6900 ms, faster than 6.28% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 17.2 MB, less than 15.94% of Python3 online submissions for Merge k Sorted Lists.""" def mergeKLists(self, lists): """Merge k sorted linked lists and return it as one sorted list...
the_stack_v2_python_sparse
LeetCode/23_merge_k_sorted_lists.py
KKosukeee/CodingQuestions
train
1
7a37d7fd23e1ec59636847a95de0a238a699bbb4
[ "super(RestDataElement, self).__init__()\nself.Database = kwargs['Database']\nself.dbTable = kwargs['Table']\nself.Key = kwargs['Key']\nself.SingleElementTitle = kwargs['SingleElementTitle']\nself.DisplayFormat = kwargs['DisplayFormat']\nself.PutParser = kwargs['PutParser']\nself.has_parent = False\nif kwargs.has_k...
<|body_start_0|> super(RestDataElement, self).__init__() self.Database = kwargs['Database'] self.dbTable = kwargs['Table'] self.Key = kwargs['Key'] self.SingleElementTitle = kwargs['SingleElementTitle'] self.DisplayFormat = kwargs['DisplayFormat'] self.PutParser =...
Single element from RestDataCollection: Manage with REST a single element of a RestDataCollection : - GET : is allowing to display one given element of the collection - PUT : is allowing to modify one given element of the collection - DELETE : is allowing to delete one given element of the collection
RestDataElement
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestDataElement: """Single element from RestDataCollection: Manage with REST a single element of a RestDataCollection : - GET : is allowing to display one given element of the collection - PUT : is allowing to modify one given element of the collection - DELETE : is allowing to delete one given e...
stack_v2_sparse_classes_36k_train_021232
4,414
no_license
[ { "docstring": "RestDataElement collection element constructor: - Database : SQL database which is containing table - Table : data persistence table - SingleElementTitle : JSON title to display for a single element display - DisplayFormat : JSON list of fields to be displayed when a GET is issued - PutParser : ...
4
null
Implement the Python class `RestDataElement` described below. Class description: Single element from RestDataCollection: Manage with REST a single element of a RestDataCollection : - GET : is allowing to display one given element of the collection - PUT : is allowing to modify one given element of the collection - DEL...
Implement the Python class `RestDataElement` described below. Class description: Single element from RestDataCollection: Manage with REST a single element of a RestDataCollection : - GET : is allowing to display one given element of the collection - PUT : is allowing to modify one given element of the collection - DEL...
8f107644a74fe46827ec5ed53d0457022bd1608b
<|skeleton|> class RestDataElement: """Single element from RestDataCollection: Manage with REST a single element of a RestDataCollection : - GET : is allowing to display one given element of the collection - PUT : is allowing to modify one given element of the collection - DELETE : is allowing to delete one given e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestDataElement: """Single element from RestDataCollection: Manage with REST a single element of a RestDataCollection : - GET : is allowing to display one given element of the collection - PUT : is allowing to modify one given element of the collection - DELETE : is allowing to delete one given element of the...
the_stack_v2_python_sparse
restapp/view_RestDataElement.py
ldurandadomia/Flask-Restful
train
0
5a47430abc711e038cfa59b56b18a4230fb427ba
[ "try:\n user = User.objects.get(pk=request.user.id)\n fcm_token = request.data.get('fcm_token')\n if fcm_token is None:\n return Response('Bad request', status=status.HTTP_400_BAD_REQUEST)\n user_fcm, created = UserFcm.objects.get_or_create(user_id=request.user.id)\n user_fcm.fcm_token = fcm_t...
<|body_start_0|> try: user = User.objects.get(pk=request.user.id) fcm_token = request.data.get('fcm_token') if fcm_token is None: return Response('Bad request', status=status.HTTP_400_BAD_REQUEST) user_fcm, created = UserFcm.objects.get_or_create(u...
A view to associate the Firebase Cloud Messaging token with the user.
FcmTokenView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FcmTokenView: """A view to associate the Firebase Cloud Messaging token with the user.""" def put(self, request, user_id, format=None): """Saves a FCM token for a user.""" <|body_0|> def delete(self, request, user_id, format=None): """Deletes a FCM token for a us...
stack_v2_sparse_classes_36k_train_021233
31,707
no_license
[ { "docstring": "Saves a FCM token for a user.", "name": "put", "signature": "def put(self, request, user_id, format=None)" }, { "docstring": "Deletes a FCM token for a user.", "name": "delete", "signature": "def delete(self, request, user_id, format=None)" } ]
2
stack_v2_sparse_classes_30k_train_002603
Implement the Python class `FcmTokenView` described below. Class description: A view to associate the Firebase Cloud Messaging token with the user. Method signatures and docstrings: - def put(self, request, user_id, format=None): Saves a FCM token for a user. - def delete(self, request, user_id, format=None): Deletes...
Implement the Python class `FcmTokenView` described below. Class description: A view to associate the Firebase Cloud Messaging token with the user. Method signatures and docstrings: - def put(self, request, user_id, format=None): Saves a FCM token for a user. - def delete(self, request, user_id, format=None): Deletes...
473b7f6f791c5fd129fae287209d6fb6e57ff268
<|skeleton|> class FcmTokenView: """A view to associate the Firebase Cloud Messaging token with the user.""" def put(self, request, user_id, format=None): """Saves a FCM token for a user.""" <|body_0|> def delete(self, request, user_id, format=None): """Deletes a FCM token for a us...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FcmTokenView: """A view to associate the Firebase Cloud Messaging token with the user.""" def put(self, request, user_id, format=None): """Saves a FCM token for a user.""" try: user = User.objects.get(pk=request.user.id) fcm_token = request.data.get('fcm_token') ...
the_stack_v2_python_sparse
server/server/favoureat/views.py
steventce/FavourEAT
train
0
6de0436abd47ba94fac9bb05fdbe77550bf7c91f
[ "super().__init__(*args, **kargs)\nself.set_field_from_dict('token')\nself.fields['token'].help_text = _('Authentication token provided by the external platform.')", "form_data = super().clean()\nself.store_field_in_dict('token')\nreturn form_data" ]
<|body_start_0|> super().__init__(*args, **kargs) self.set_field_from_dict('token') self.fields['token'].help_text = _('Authentication token provided by the external platform.') <|end_body_0|> <|body_start_1|> form_data = super().clean() self.store_field_in_dict('token') ...
Form to include a token field.
JSONTokenForm
[ "MIT", "LGPL-2.0-or-later", "Python-2.0", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSONTokenForm: """Form to include a token field.""" def __init__(self, *args, **kargs): """Modify the fields with the adequate information.""" <|body_0|> def clean(self): """Verify form values.""" <|body_1|> <|end_skeleton|> <|body_start_0|> sup...
stack_v2_sparse_classes_36k_train_021234
20,237
permissive
[ { "docstring": "Modify the fields with the adequate information.", "name": "__init__", "signature": "def __init__(self, *args, **kargs)" }, { "docstring": "Verify form values.", "name": "clean", "signature": "def clean(self)" } ]
2
stack_v2_sparse_classes_30k_val_000514
Implement the Python class `JSONTokenForm` described below. Class description: Form to include a token field. Method signatures and docstrings: - def __init__(self, *args, **kargs): Modify the fields with the adequate information. - def clean(self): Verify form values.
Implement the Python class `JSONTokenForm` described below. Class description: Form to include a token field. Method signatures and docstrings: - def __init__(self, *args, **kargs): Modify the fields with the adequate information. - def clean(self): Verify form values. <|skeleton|> class JSONTokenForm: """Form t...
5473e9faa24c71a2a1102d47ebc2cbf27608e42a
<|skeleton|> class JSONTokenForm: """Form to include a token field.""" def __init__(self, *args, **kargs): """Modify the fields with the adequate information.""" <|body_0|> def clean(self): """Verify form values.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JSONTokenForm: """Form to include a token field.""" def __init__(self, *args, **kargs): """Modify the fields with the adequate information.""" super().__init__(*args, **kargs) self.set_field_from_dict('token') self.fields['token'].help_text = _('Authentication token provid...
the_stack_v2_python_sparse
ontask/action/forms/run.py
LucasFranciscoCorreia/ontask_b
train
0
b7c021335237a360542601e7b8972b8b202480e3
[ "leaves = []\nself.dfs(root, leaves)\nreturn leaves", "if not node:\n return -1\nheight = 1 + max(self.dfs(node.left, leaves), self.dfs(node.right, leaves))\nif height >= len(leaves):\n leaves.append([])\nleaves[height].append(node.val)\nreturn height" ]
<|body_start_0|> leaves = [] self.dfs(root, leaves) return leaves <|end_body_0|> <|body_start_1|> if not node: return -1 height = 1 + max(self.dfs(node.left, leaves), self.dfs(node.right, leaves)) if height >= len(leaves): leaves.append([]) ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findLeaves(self, root): """The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def dfs(self, node, l...
stack_v2_sparse_classes_36k_train_021235
999
permissive
[ { "docstring": "The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]", "name": "findLeaves", "signature": "def findLeaves(self, root)" }, { "docstring...
2
stack_v2_sparse_classes_30k_train_017522
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findLeaves(self, root): The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest le...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findLeaves(self, root): The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest le...
cbbd4a67ab342ada2421e13f82d660b1d47d4d20
<|skeleton|> class Solution: def findLeaves(self, root): """The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def dfs(self, node, l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findLeaves(self, root): """The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]""" leaves = [] self.dfs(root, leaves) ...
the_stack_v2_python_sparse
366 Find Leaves of Binary Tree.py
Aminaba123/LeetCode
train
1
05e51e2bbc093f36e603d9a832ba4b4c3ac55091
[ "if element:\n self.type = element.type\n self.name = element.navn\n self.file_name = element.Vedleggsdel[0].filnavn\n self.reference_format = element.Vedleggsdel[0].DataRef.referanseFormat\n self.format = element.Vedleggsdel[0].DataRef.format\n self.sequence_no = element.Vedleggsdel[0].sekvensnr\...
<|body_start_0|> if element: self.type = element.type self.name = element.navn self.file_name = element.Vedleggsdel[0].filnavn self.reference_format = element.Vedleggsdel[0].DataRef.referanseFormat self.format = element.Vedleggsdel[0].DataRef.format ...
brreg:Melding:Vedlegg Attachments for the inquiry.
BrregInquiryAttachment
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BrregInquiryAttachment: """brreg:Melding:Vedlegg Attachments for the inquiry.""" def __init__(self, type=None, name=None, file_name=None, reference_format=None, checksum=None, sequence_no='1', element=None, file_data=None, format=None): """If element is provided, all other arguments ...
stack_v2_sparse_classes_36k_train_021236
12,499
permissive
[ { "docstring": "If element is provided, all other arguments are ignored. :param type: Attachment type :type type: basestring :param name: Name of the file :type name: basestring :param file_name: Filename (Can be identical to name) :type file_name: basestring :param reference_format: Format of the reference :ty...
2
stack_v2_sparse_classes_30k_test_000061
Implement the Python class `BrregInquiryAttachment` described below. Class description: brreg:Melding:Vedlegg Attachments for the inquiry. Method signatures and docstrings: - def __init__(self, type=None, name=None, file_name=None, reference_format=None, checksum=None, sequence_no='1', element=None, file_data=None, f...
Implement the Python class `BrregInquiryAttachment` described below. Class description: brreg:Melding:Vedlegg Attachments for the inquiry. Method signatures and docstrings: - def __init__(self, type=None, name=None, file_name=None, reference_format=None, checksum=None, sequence_no='1', element=None, file_data=None, f...
ecb471065795ae4bba1d5b3466756df8e8db848e
<|skeleton|> class BrregInquiryAttachment: """brreg:Melding:Vedlegg Attachments for the inquiry.""" def __init__(self, type=None, name=None, file_name=None, reference_format=None, checksum=None, sequence_no='1', element=None, file_data=None, format=None): """If element is provided, all other arguments ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BrregInquiryAttachment: """brreg:Melding:Vedlegg Attachments for the inquiry.""" def __init__(self, type=None, name=None, file_name=None, reference_format=None, checksum=None, sequence_no='1', element=None, file_data=None, format=None): """If element is provided, all other arguments are ignored. ...
the_stack_v2_python_sparse
pybrreg/models/new_inquiry.py
unicornis/pybrreg
train
0
516c048b39c7de65727b06bbd92b02c80fb33cc5
[ "self.is_migrated = is_migrated\nself.migrated_time_usecs = migrated_time_usecs\nself.previous_vm_entity_id = previous_vm_entity_id\nself.previous_vm_parent_source_id = previous_vm_parent_source_id", "if dictionary is None:\n return None\nis_migrated = dictionary.get('isMigrated')\nmigrated_time_usecs = dictio...
<|body_start_0|> self.is_migrated = is_migrated self.migrated_time_usecs = migrated_time_usecs self.previous_vm_entity_id = previous_vm_entity_id self.previous_vm_parent_source_id = previous_vm_parent_source_id <|end_body_0|> <|body_start_1|> if dictionary is None: r...
Implementation of the 'VmLinkingInfo' model. VM Linking Info Attributes: is_migrated (bool): This is set to true if a VM is linked in entity provenance by edge type kVMMigration. migrated_time_usecs (long|int): This is the time when ther VM was identified to have been migrated by Cohesity. Note that this time can diffe...
VmLinkingInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VmLinkingInfo: """Implementation of the 'VmLinkingInfo' model. VM Linking Info Attributes: is_migrated (bool): This is set to true if a VM is linked in entity provenance by edge type kVMMigration. migrated_time_usecs (long|int): This is the time when ther VM was identified to have been migrated b...
stack_v2_sparse_classes_36k_train_021237
2,662
permissive
[ { "docstring": "Constructor for the VmLinkingInfo class", "name": "__init__", "signature": "def __init__(self, is_migrated=None, migrated_time_usecs=None, previous_vm_entity_id=None, previous_vm_parent_source_id=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: ...
2
null
Implement the Python class `VmLinkingInfo` described below. Class description: Implementation of the 'VmLinkingInfo' model. VM Linking Info Attributes: is_migrated (bool): This is set to true if a VM is linked in entity provenance by edge type kVMMigration. migrated_time_usecs (long|int): This is the time when ther VM...
Implement the Python class `VmLinkingInfo` described below. Class description: Implementation of the 'VmLinkingInfo' model. VM Linking Info Attributes: is_migrated (bool): This is set to true if a VM is linked in entity provenance by edge type kVMMigration. migrated_time_usecs (long|int): This is the time when ther VM...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class VmLinkingInfo: """Implementation of the 'VmLinkingInfo' model. VM Linking Info Attributes: is_migrated (bool): This is set to true if a VM is linked in entity provenance by edge type kVMMigration. migrated_time_usecs (long|int): This is the time when ther VM was identified to have been migrated b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VmLinkingInfo: """Implementation of the 'VmLinkingInfo' model. VM Linking Info Attributes: is_migrated (bool): This is set to true if a VM is linked in entity provenance by edge type kVMMigration. migrated_time_usecs (long|int): This is the time when ther VM was identified to have been migrated by Cohesity. N...
the_stack_v2_python_sparse
cohesity_management_sdk/models/vm_linking_info.py
cohesity/management-sdk-python
train
24
43e216bc9db3387c574592bcf91f6f152f4a8a94
[ "self.tasks = tasks\nself.ml_strucs = ml_strucs\nself.task_types = task_types\nself.query = query if query else None\nsuper().__init__(sources=[tasks], targets=[ml_strucs], **kwargs)", "self.logger.info('Machine Learning Structure Database Builder Started')\nself.logger.info('Setting indexes')\nself.ensure_indexe...
<|body_start_0|> self.tasks = tasks self.ml_strucs = ml_strucs self.task_types = task_types self.query = query if query else None super().__init__(sources=[tasks], targets=[ml_strucs], **kwargs) <|end_body_0|> <|body_start_1|> self.logger.info('Machine Learning Structure...
MLStructuresBuilder
[ "LicenseRef-scancode-hdf5", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MLStructuresBuilder: def __init__(self, tasks, ml_strucs, task_types=('Structure Optimization',), query=None, **kwargs): """Creates a collection of structures, energies, forces, and stresses for machine learning efforts Args: tasks (Store): Store of task documents ml_strucs (Store): Stor...
stack_v2_sparse_classes_36k_train_021238
5,005
permissive
[ { "docstring": "Creates a collection of structures, energies, forces, and stresses for machine learning efforts Args: tasks (Store): Store of task documents ml_strucs (Store): Store of materials documents to generate tasK_types (list): list of substrings for task_types to process", "name": "__init__", "...
5
stack_v2_sparse_classes_30k_train_002201
Implement the Python class `MLStructuresBuilder` described below. Class description: Implement the MLStructuresBuilder class. Method signatures and docstrings: - def __init__(self, tasks, ml_strucs, task_types=('Structure Optimization',), query=None, **kwargs): Creates a collection of structures, energies, forces, an...
Implement the Python class `MLStructuresBuilder` described below. Class description: Implement the MLStructuresBuilder class. Method signatures and docstrings: - def __init__(self, tasks, ml_strucs, task_types=('Structure Optimization',), query=None, **kwargs): Creates a collection of structures, energies, forces, an...
2540fd8f6905be7290ead1b8a9dadca84d5d03fa
<|skeleton|> class MLStructuresBuilder: def __init__(self, tasks, ml_strucs, task_types=('Structure Optimization',), query=None, **kwargs): """Creates a collection of structures, energies, forces, and stresses for machine learning efforts Args: tasks (Store): Store of task documents ml_strucs (Store): Stor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MLStructuresBuilder: def __init__(self, tasks, ml_strucs, task_types=('Structure Optimization',), query=None, **kwargs): """Creates a collection of structures, energies, forces, and stresses for machine learning efforts Args: tasks (Store): Store of task documents ml_strucs (Store): Store of materials...
the_stack_v2_python_sparse
emmet/vasp/ml_structures.py
jerrymlin/emmet
train
2
0bf40241710cf09f23cd8dcaf357a872193cdabb
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ruipang_zhou482', 'ruipang_zhou482')\npublic_school = []\nfor i in repo['ruipang_zhou482.PublicSchool'].find():\n public_school.append(i)\nprivate_school = []\nfor i in repo['ruipang_zhou482.PrivateSc...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('ruipang_zhou482', 'ruipang_zhou482') public_school = [] for i in repo['ruipang_zhou482.PublicSchool'].find(): public_school.append(i) ...
TotalSchool
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TotalSchool: 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 everything h...
stack_v2_sparse_classes_36k_train_021239
3,994
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 `TotalSchool` described below. Class description: Implement the TotalSchool class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi...
Implement the Python class `TotalSchool` described below. Class description: Implement the TotalSchool class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class TotalSchool: 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 everything h...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TotalSchool: 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('ruipang_zhou482', 'ruipang_zhou482') ...
the_stack_v2_python_sparse
ruipang_zhou482/TotalSchool.py
maximega/course-2019-spr-proj
train
2
7473c6611aa0f26ba76cffba3b0188d40e896a29
[ "self.chrom = chrom\nself.taxon = taxon\nself.parser = Parser(species_string=species)\nself.out_dir = out_dir\nself.char_limit = char_limit\nself.maf_file = maf_file\nself.char_count = 0\nself.file_num = 1\nself.current_file = open(self.current_filename, 'w')\nself.maf_lines = gzopen(maf_file, 'r') if self.maf_file...
<|body_start_0|> self.chrom = chrom self.taxon = taxon self.parser = Parser(species_string=species) self.out_dir = out_dir self.char_limit = char_limit self.maf_file = maf_file self.char_count = 0 self.file_num = 1 self.current_file = open(self.cur...
An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file.
Splitter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Splitter: """An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file.""" def __init__(self, chrom, taxon, spec...
stack_v2_sparse_classes_36k_train_021240
11,087
no_license
[ { "docstring": "Load input and ouput paths :param chrom: chromosome for the current data :param taxon: taxon name given to splitter output :param species: comma-separated string of species IDs used by Parser to select MAF lines :param out_dir: destination for MAF files :param char_limit: file size limit in char...
5
stack_v2_sparse_classes_30k_train_010797
Implement the Python class `Splitter` described below. Class description: An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file. Metho...
Implement the Python class `Splitter` described below. Class description: An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file. Metho...
c09a98ac4c82e7d1c9c5d1cc7c283b13dca76db4
<|skeleton|> class Splitter: """An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file.""" def __init__(self, chrom, taxon, spec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Splitter: """An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file.""" def __init__(self, chrom, taxon, species, out_dir,...
the_stack_v2_python_sparse
phast/maf_tools.py
sellalab/HumanLinkedSelectionMaps
train
1
88457991776798e466428296f924d9813c424af1
[ "proxies = []\npath = os.path.join(os.getcwd(), fname)\nif os.path.exists(path):\n with open(path, 'r') as pf:\n for line in pf.readlines():\n if not (line.strip().startswith('#') or line.strip().startswith('//')):\n tokens = line.replace('\\n', '').split(' ')\n tr...
<|body_start_0|> proxies = [] path = os.path.join(os.getcwd(), fname) if os.path.exists(path): with open(path, 'r') as pf: for line in pf.readlines(): if not (line.strip().startswith('#') or line.strip().startswith('//')): t...
Proxies
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Proxies: def parse_proxy_file(self, fname): """Parses a proxy file The format should be like the following: socks5 XX.XXX.XX.XX:1080 username:password socks4 XX.XXX.XX.XX:80 username:password http XX.XXX.XX.XX:80 If username and password aren't provided, we assumes that the proxy doesn't...
stack_v2_sparse_classes_36k_train_021241
6,416
permissive
[ { "docstring": "Parses a proxy file The format should be like the following: socks5 XX.XXX.XX.XX:1080 username:password socks4 XX.XXX.XX.XX:80 username:password http XX.XXX.XX.XX:80 If username and password aren't provided, we assumes that the proxy doesn't need auth credentials. Args: fname: The file name wher...
2
stack_v2_sparse_classes_30k_train_003238
Implement the Python class `Proxies` described below. Class description: Implement the Proxies class. Method signatures and docstrings: - def parse_proxy_file(self, fname): Parses a proxy file The format should be like the following: socks5 XX.XXX.XX.XX:1080 username:password socks4 XX.XXX.XX.XX:80 username:password ...
Implement the Python class `Proxies` described below. Class description: Implement the Proxies class. Method signatures and docstrings: - def parse_proxy_file(self, fname): Parses a proxy file The format should be like the following: socks5 XX.XXX.XX.XX:1080 username:password socks4 XX.XXX.XX.XX:80 username:password ...
b003de371ebd07cd296585bc4e077cc0f2ca03d5
<|skeleton|> class Proxies: def parse_proxy_file(self, fname): """Parses a proxy file The format should be like the following: socks5 XX.XXX.XX.XX:1080 username:password socks4 XX.XXX.XX.XX:80 username:password http XX.XXX.XX.XX:80 If username and password aren't provided, we assumes that the proxy doesn't...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Proxies: def parse_proxy_file(self, fname): """Parses a proxy file The format should be like the following: socks5 XX.XXX.XX.XX:1080 username:password socks4 XX.XXX.XX.XX:80 username:password http XX.XXX.XX.XX:80 If username and password aren't provided, we assumes that the proxy doesn't need auth cre...
the_stack_v2_python_sparse
scrapcore/tools.py
nickmvincent/SerpScrap
train
2
b00f119c871ab01134e58d807bf7c121968b0076
[ "parser = MagicCommandParser(prog='compress', description='display the content of a repository (GIT or SVN)')\nparser.add_argument('dest', type=str, help='destination, the extension defines the compression format, zip, gzip 7z')\nparser.add_argument('files', type=str, nargs='?', help='files to compress or a python ...
<|body_start_0|> parser = MagicCommandParser(prog='compress', description='display the content of a repository (GIT or SVN)') parser.add_argument('dest', type=str, help='destination, the extension defines the compression format, zip, gzip 7z') parser.add_argument('files', type=str, nargs='?', he...
Defines magic commands to compress files.
MagicCompress
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MagicCompress: """Defines magic commands to compress files.""" def compress_parser(): """defines the way to parse the magic command ``%compress``""" <|body_0|> def compress(self, line): """.. nbref:: :title: %compress It compresses a list of files, it returns the...
stack_v2_sparse_classes_36k_train_021242
2,650
permissive
[ { "docstring": "defines the way to parse the magic command ``%compress``", "name": "compress_parser", "signature": "def compress_parser()" }, { "docstring": ".. nbref:: :title: %compress It compresses a list of files, it returns the number of compressed files:: from pyquickhelper import zip_file...
2
stack_v2_sparse_classes_30k_train_020525
Implement the Python class `MagicCompress` described below. Class description: Defines magic commands to compress files. Method signatures and docstrings: - def compress_parser(): defines the way to parse the magic command ``%compress`` - def compress(self, line): .. nbref:: :title: %compress It compresses a list of ...
Implement the Python class `MagicCompress` described below. Class description: Defines magic commands to compress files. Method signatures and docstrings: - def compress_parser(): defines the way to parse the magic command ``%compress`` - def compress(self, line): .. nbref:: :title: %compress It compresses a list of ...
860ec5b9a53bae4fc616076c0b52dbe2a1153d30
<|skeleton|> class MagicCompress: """Defines magic commands to compress files.""" def compress_parser(): """defines the way to parse the magic command ``%compress``""" <|body_0|> def compress(self, line): """.. nbref:: :title: %compress It compresses a list of files, it returns the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MagicCompress: """Defines magic commands to compress files.""" def compress_parser(): """defines the way to parse the magic command ``%compress``""" parser = MagicCommandParser(prog='compress', description='display the content of a repository (GIT or SVN)') parser.add_argument('de...
the_stack_v2_python_sparse
src/pyquickhelper/ipythonhelper/magic_class_compress.py
Pandinosaurus/pyquickhelper
train
0
957413dd8b740f48a575af4b9057da939ce79338
[ "super(AnalysisComponent, self).__init__(config)\nself.analysis_in_path = None\nself.analysis_out_path = None\nself.analysis_extr_path = None\nself.analysis_plot_path = None\nself.analysis_misc_path = None\nself.analysis_attenuation_path = None\nself.analysis_colours_path = None\nself.analysis_residuals_path = None...
<|body_start_0|> super(AnalysisComponent, self).__init__(config) self.analysis_in_path = None self.analysis_out_path = None self.analysis_extr_path = None self.analysis_plot_path = None self.analysis_misc_path = None self.analysis_attenuation_path = None s...
This class...
AnalysisComponent
[ "GPL-1.0-or-later", "AGPL-3.0-only", "AGPL-3.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-philippe-de-muyter", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnalysisComponent: """This class...""" def __init__(self, config=None): """The constructor ... :param config: :return:""" <|body_0|> def setup(self): """This function ... :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(AnalysisCom...
stack_v2_sparse_classes_36k_train_021243
5,091
permissive
[ { "docstring": "The constructor ... :param config: :return:", "name": "__init__", "signature": "def __init__(self, config=None)" }, { "docstring": "This function ... :return:", "name": "setup", "signature": "def setup(self)" } ]
2
null
Implement the Python class `AnalysisComponent` described below. Class description: This class... Method signatures and docstrings: - def __init__(self, config=None): The constructor ... :param config: :return: - def setup(self): This function ... :return:
Implement the Python class `AnalysisComponent` described below. Class description: This class... Method signatures and docstrings: - def __init__(self, config=None): The constructor ... :param config: :return: - def setup(self): This function ... :return: <|skeleton|> class AnalysisComponent: """This class..."""...
62b2339beb2eb956565e1605d44d92f934361ad7
<|skeleton|> class AnalysisComponent: """This class...""" def __init__(self, config=None): """The constructor ... :param config: :return:""" <|body_0|> def setup(self): """This function ... :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnalysisComponent: """This class...""" def __init__(self, config=None): """The constructor ... :param config: :return:""" super(AnalysisComponent, self).__init__(config) self.analysis_in_path = None self.analysis_out_path = None self.analysis_extr_path = None ...
the_stack_v2_python_sparse
CAAPR/CAAPR_AstroMagic/PTS/pts/modeling/analysis/component.py
Stargrazer82301/CAAPR
train
8
c6b6ec09b49c18405946e6fb3f6bdfd6e56bb6bf
[ "for a in mdargs:\n if not isinstance(a, (int, str)):\n raise TypeError('a is of invalid type')\nself.mdargs = mdargs", "@wraps(f)\ndef wrapper(*args, **kwargs):\n if self.mdargs:\n mdargs = self.mdargs\n else:\n mdargs = range(len(args)) + kwargs.keys()\n arglength = len(args)\n ...
<|body_start_0|> for a in mdargs: if not isinstance(a, (int, str)): raise TypeError('a is of invalid type') self.mdargs = mdargs <|end_body_0|> <|body_start_1|> @wraps(f) def wrapper(*args, **kwargs): if self.mdargs: mdargs = self....
Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0) ... def vsin(x): ... return sin(x) >>> vsin([1, x, y]) [sin(1), sin(x), si...
vectorize
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class vectorize: """Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0) ... def vsin(x): ... return sin(x) >>...
stack_v2_sparse_classes_36k_train_021244
4,233
permissive
[ { "docstring": "The given numbers and strings characterize the arguments that will be treated as data structures, where the decorated function will be applied to every single element. If no argument is given, everything is treated multidimensional.", "name": "__init__", "signature": "def __init__(self, ...
2
null
Implement the Python class `vectorize` described below. Class description: Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0...
Implement the Python class `vectorize` described below. Class description: Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0...
69f98fb2b0d845e76874067a381dba37b577e8c5
<|skeleton|> class vectorize: """Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0) ... def vsin(x): ... return sin(x) >>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class vectorize: """Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0) ... def vsin(x): ... return sin(x) >>> vsin([1, x,...
the_stack_v2_python_sparse
sympy/core/multidimensional.py
sympy/sympy
train
10,928
4a54be725f2780c7cfb1b1c91e315dfa286e8c82
[ "self.entity = entity\nself.team = team\nself.move_chooser = move_chooser\nself.turn_number = turn_number\nself.effects = []\n\"Right now, you should just append to this list since we don't have a special method to add effects.\"", "for effect in self.effects:\n if isinstance(effect, item):\n return eff...
<|body_start_0|> self.entity = entity self.team = team self.move_chooser = move_chooser self.turn_number = turn_number self.effects = [] "Right now, you should just append to this list since we don't have a special method to add effects." <|end_body_0|> <|body_start_1|> ...
An object that stores information on the current turn and what moves it can use Later, if the api is changed for a pokemon like game, we want to make sure this class doesn't heavily rely on Entity when Entity could be changed drastically for a Pokemon game. Just a thought for future maintainability
Target
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Target: """An object that stores information on the current turn and what moves it can use Later, if the api is changed for a pokemon like game, we want to make sure this class doesn't heavily rely on Entity when Entity could be changed drastically for a Pokemon game. Just a thought for future ma...
stack_v2_sparse_classes_36k_train_021245
9,549
no_license
[ { "docstring": ":param entity: The entity :param team: The team that the entity is on", "name": "__init__", "signature": "def __init__(self, entity: Entity, team: Team, move_chooser: 'MoveChooser', turn_number: int)" }, { "docstring": "T is recommended to be PropertyEffect and using this to get ...
4
null
Implement the Python class `Target` described below. Class description: An object that stores information on the current turn and what moves it can use Later, if the api is changed for a pokemon like game, we want to make sure this class doesn't heavily rely on Entity when Entity could be changed drastically for a Pok...
Implement the Python class `Target` described below. Class description: An object that stores information on the current turn and what moves it can use Later, if the api is changed for a pokemon like game, we want to make sure this class doesn't heavily rely on Entity when Entity could be changed drastically for a Pok...
701fe2e26f04e941ae1a54b85890aa3fe1d352ac
<|skeleton|> class Target: """An object that stores information on the current turn and what moves it can use Later, if the api is changed for a pokemon like game, we want to make sure this class doesn't heavily rely on Entity when Entity could be changed drastically for a Pokemon game. Just a thought for future ma...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Target: """An object that stores information on the current turn and what moves it can use Later, if the api is changed for a pokemon like game, we want to make sure this class doesn't heavily rely on Entity when Entity could be changed drastically for a Pokemon game. Just a thought for future maintainability...
the_stack_v2_python_sparse
textadventure/battling/move.py
rkoblents/python-text-adventure-api
train
0
cba3ec4e0ee795c812730a86b165af9b0b1f30ed
[ "newPath = self._generate_new_path_name()\nnewFile = csv.writer(open(newPath, 'wb'), quoting=csv.QUOTE_ALL)\ncol_name_list = ['project', 'subject', 'session', 'imagefiles']\nnewFile.writerow(col_name_list)\noldFile = csv.reader(open(inputArguments.autoWorkupFile, 'rb'), delimiter=',', quotechar='\"')\nNewImageDict ...
<|body_start_0|> newPath = self._generate_new_path_name() newFile = csv.writer(open(newPath, 'wb'), quoting=csv.QUOTE_ALL) col_name_list = ['project', 'subject', 'session', 'imagefiles'] newFile.writerow(col_name_list) oldFile = csv.reader(open(inputArguments.autoWorkupFile, 'rb'...
This class represents a...
UpdateAutoWorkup
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateAutoWorkup: """This class represents a...""" def update_auto_workup(self): """This function...""" <|body_0|> def _generate_new_path_name(self): """This function... :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> newPath = self._ge...
stack_v2_sparse_classes_36k_train_021246
7,696
permissive
[ { "docstring": "This function...", "name": "update_auto_workup", "signature": "def update_auto_workup(self)" }, { "docstring": "This function... :return:", "name": "_generate_new_path_name", "signature": "def _generate_new_path_name(self)" } ]
2
null
Implement the Python class `UpdateAutoWorkup` described below. Class description: This class represents a... Method signatures and docstrings: - def update_auto_workup(self): This function... - def _generate_new_path_name(self): This function... :return:
Implement the Python class `UpdateAutoWorkup` described below. Class description: This class represents a... Method signatures and docstrings: - def update_auto_workup(self): This function... - def _generate_new_path_name(self): This function... :return: <|skeleton|> class UpdateAutoWorkup: """This class represe...
64bb590918a188b660225e44ae54c1072f3a8056
<|skeleton|> class UpdateAutoWorkup: """This class represents a...""" def update_auto_workup(self): """This function...""" <|body_0|> def _generate_new_path_name(self): """This function... :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateAutoWorkup: """This class represents a...""" def update_auto_workup(self): """This function...""" newPath = self._generate_new_path_name() newFile = csv.writer(open(newPath, 'wb'), quoting=csv.QUOTE_ALL) col_name_list = ['project', 'subject', 'session', 'imagefiles']...
the_stack_v2_python_sparse
AutoWorkup/BAW/updateAutoWorkupFile_DWI.py
BRAINSia/BRAINSTools
train
101
9c7759987f5b1a32aedf6cee1f23863d049d6cab
[ "with _Record.lock:\n with open(_Record.file, 'a+') as f:\n try:\n f.seek(0)\n r = json.load(f)\n except Exception as _:\n r = {}\n json.dump(r, f)\nreturn r", "with _Record.lock:\n with open(_Record.file, 'r+') as f:\n r = json.load(f)\n ...
<|body_start_0|> with _Record.lock: with open(_Record.file, 'a+') as f: try: f.seek(0) r = json.load(f) except Exception as _: r = {} json.dump(r, f) return r <|end_body_0|> <|bod...
Default tasks record handler Will read/write from/to ./tasks.json
_Record
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Record: """Default tasks record handler Will read/write from/to ./tasks.json""" def read(): """Reads persistence record to dict Returns dict""" <|body_0|> def write(name, le): """Writes record to record_handler name (str): name of task le (str): str() cast of da...
stack_v2_sparse_classes_36k_train_021247
13,873
permissive
[ { "docstring": "Reads persistence record to dict Returns dict", "name": "read", "signature": "def read()" }, { "docstring": "Writes record to record_handler name (str): name of task le (str): str() cast of datetime.datetime object for last execution Does not return", "name": "write", "si...
2
stack_v2_sparse_classes_30k_train_007483
Implement the Python class `_Record` described below. Class description: Default tasks record handler Will read/write from/to ./tasks.json Method signatures and docstrings: - def read(): Reads persistence record to dict Returns dict - def write(name, le): Writes record to record_handler name (str): name of task le (s...
Implement the Python class `_Record` described below. Class description: Default tasks record handler Will read/write from/to ./tasks.json Method signatures and docstrings: - def read(): Reads persistence record to dict Returns dict - def write(name, le): Writes record to record_handler name (str): name of task le (s...
6c42679cc129656e9216fc847e5839d6496dc452
<|skeleton|> class _Record: """Default tasks record handler Will read/write from/to ./tasks.json""" def read(): """Reads persistence record to dict Returns dict""" <|body_0|> def write(name, le): """Writes record to record_handler name (str): name of task le (str): str() cast of da...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _Record: """Default tasks record handler Will read/write from/to ./tasks.json""" def read(): """Reads persistence record to dict Returns dict""" with _Record.lock: with open(_Record.file, 'a+') as f: try: f.seek(0) r = js...
the_stack_v2_python_sparse
lib/cherrypyscheduler.py
sinopsysHK/Watcher3
train
0
6635b58e3e193db9c876f0c944948c37beeaaaef
[ "import bisect\na = sorted(A)\nresult = []\nfor b in B:\n p = bisect.bisect(a, b)\n if p < len(a):\n result.append(a[p])\n a.pop(p)\n else:\n result.append(a[0])\n a.pop(0)\nreturn result", "l = len(A)\nres = [0] * l\nidx = range(l)\nidx.sort(key=lambda x: B[x])\nA.sort()\nlef...
<|body_start_0|> import bisect a = sorted(A) result = [] for b in B: p = bisect.bisect(a, b) if p < len(a): result.append(a[p]) a.pop(p) else: result.append(a[0]) a.pop(0) return r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def advantageCount(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 316 ms""" <|body_0|> def advantageCount_1(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 220ms""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_021248
1,670
no_license
[ { "docstring": ":type A: List[int] :type B: List[int] :rtype: List[int] 316 ms", "name": "advantageCount", "signature": "def advantageCount(self, A, B)" }, { "docstring": ":type A: List[int] :type B: List[int] :rtype: List[int] 220ms", "name": "advantageCount_1", "signature": "def advant...
2
stack_v2_sparse_classes_30k_train_017174
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def advantageCount(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[int] 316 ms - def advantageCount_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: L...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def advantageCount(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[int] 316 ms - def advantageCount_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: L...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def advantageCount(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 316 ms""" <|body_0|> def advantageCount_1(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 220ms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def advantageCount(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 316 ms""" import bisect a = sorted(A) result = [] for b in B: p = bisect.bisect(a, b) if p < len(a): result.append(a[p]) ...
the_stack_v2_python_sparse
AdvantageShuffle_MID_870.py
953250587/leetcode-python
train
2
728b7213957771505cc3874ff5b7088e68502e86
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SharedWithChannelTeamInfo()", "from .conversation_member import ConversationMember\nfrom .team_info import TeamInfo\nfrom .conversation_member import ConversationMember\nfrom .team_info import TeamInfo\nfields: Dict[str, Callable[[Any]...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return SharedWithChannelTeamInfo() <|end_body_0|> <|body_start_1|> from .conversation_member import ConversationMember from .team_info import TeamInfo from .conversation_member import C...
SharedWithChannelTeamInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharedWithChannelTeamInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: """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_021249
2,593
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: SharedWithChannelTeamInfo", "name": "create_from_discriminator_value", "signature": "def create_from_discrim...
3
null
Implement the Python class `SharedWithChannelTeamInfo` described below. Class description: Implement the SharedWithChannelTeamInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: Creates a new instance of the appropriat...
Implement the Python class `SharedWithChannelTeamInfo` described below. Class description: Implement the SharedWithChannelTeamInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: Creates a new instance of the appropriat...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class SharedWithChannelTeamInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: """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 SharedWithChannelTeamInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: """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/shared_with_channel_team_info.py
microsoftgraph/msgraph-sdk-python
train
135
c1b35d83a41e042c15f1885a24c4fcc8919d4521
[ "super().__init__(*args, **kwargs)\nif isinstance(file, pd.DataFrame):\n self.order_df = file\nelse:\n with get_io_object(file) as f:\n self.order_df = pd.read_csv(f, dtype={'datetime': str})\nself.order_df['datetime'] = self.order_df['datetime'].apply(pd.Timestamp)\nself.order_df = self.order_df.set_i...
<|body_start_0|> super().__init__(*args, **kwargs) if isinstance(file, pd.DataFrame): self.order_df = file else: with get_io_object(file) as f: self.order_df = pd.read_csv(f, dtype={'datetime': str}) self.order_df['datetime'] = self.order_df['datet...
Motivation: - This class provides an interface for user to read orders from csv files.
FileOrderStrategy
[ "LicenseRef-scancode-generic-cla", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileOrderStrategy: """Motivation: - This class provides an interface for user to read orders from csv files.""" def __init__(self, file: Union[IO, str, Path, pd.DataFrame], trade_range: Union[Tuple[int, int], TradeRange]=None, *args, **kwargs): """Parameters ---------- file : Union[I...
stack_v2_sparse_classes_36k_train_021250
29,373
permissive
[ { "docstring": "Parameters ---------- file : Union[IO, str, Path, pd.DataFrame] this parameters will specify the info of expected orders Here is an example of the content 1) Amount (**adjusted**) based strategy datetime,instrument,amount,direction 20200102, SH600519, 1000, sell 20200103, SH600519, 1000, buy 202...
2
null
Implement the Python class `FileOrderStrategy` described below. Class description: Motivation: - This class provides an interface for user to read orders from csv files. Method signatures and docstrings: - def __init__(self, file: Union[IO, str, Path, pd.DataFrame], trade_range: Union[Tuple[int, int], TradeRange]=Non...
Implement the Python class `FileOrderStrategy` described below. Class description: Motivation: - This class provides an interface for user to read orders from csv files. Method signatures and docstrings: - def __init__(self, file: Union[IO, str, Path, pd.DataFrame], trade_range: Union[Tuple[int, int], TradeRange]=Non...
4c30e5827b74bcc45f14cf3ae0c1715459ed09ae
<|skeleton|> class FileOrderStrategy: """Motivation: - This class provides an interface for user to read orders from csv files.""" def __init__(self, file: Union[IO, str, Path, pd.DataFrame], trade_range: Union[Tuple[int, int], TradeRange]=None, *args, **kwargs): """Parameters ---------- file : Union[I...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileOrderStrategy: """Motivation: - This class provides an interface for user to read orders from csv files.""" def __init__(self, file: Union[IO, str, Path, pd.DataFrame], trade_range: Union[Tuple[int, int], TradeRange]=None, *args, **kwargs): """Parameters ---------- file : Union[IO, str, Path,...
the_stack_v2_python_sparse
qlib/contrib/strategy/rule_strategy.py
microsoft/qlib
train
12,822
c627d91b66216d6c8f763a0b794ca6667ebeed2e
[ "nums = sorted(nums)\nsize = len(nums)\ndiff = sys.maxsize\nfor i in range(2, size):\n remaining_target = target - nums[i]\n cur_diff = self.explore(nums, 0, i - 1, remaining_target)\n if abs(cur_diff) < abs(diff):\n diff = cur_diff\nreturn target - diff", "diff = sys.maxsize\nwhile left < right:\...
<|body_start_0|> nums = sorted(nums) size = len(nums) diff = sys.maxsize for i in range(2, size): remaining_target = target - nums[i] cur_diff = self.explore(nums, 0, i - 1, remaining_target) if abs(cur_diff) < abs(diff): diff = cur_dif...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def explore(self, nums, left, right, target): """return the smallest diff found (target - (nums[i] + nums[j]))""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_021251
1,168
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "threeSumClosest", "signature": "def threeSumClosest(self, nums, target)" }, { "docstring": "return the smallest diff found (target - (nums[i] + nums[j]))", "name": "explore", "signature": "def explore(self, nu...
2
stack_v2_sparse_classes_30k_train_018658
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def explore(self, nums, left, right, target): return the smallest diff found (targe...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def explore(self, nums, left, right, target): return the smallest diff found (targe...
78a8b27ee108ba93aa7b659665976112f48fc2c2
<|skeleton|> class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def explore(self, nums, left, right, target): """return the smallest diff found (target - (nums[i] + nums[j]))""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" nums = sorted(nums) size = len(nums) diff = sys.maxsize for i in range(2, size): remaining_target = target - nums[i] cur_diff = self.expl...
the_stack_v2_python_sparse
companies/airbnb/p16/Solution.py
pololee/oj-leetcode
train
0
d2200198e771ef72b2fff099c47686f53c7ff7cf
[ "if new == 'DSI':\n pass\nelif new == 'DTI':\n self.local_model_editor = {False: '1:Tensor', True: '2:Constrained Spherical Deconvolution'}\nelif new == 'multishell' or new == 'HARDI':\n self.local_model_editor = {True: 'Constrained Spherical Deconvolution'}\n self.local_model = True", "if new == 'Pro...
<|body_start_0|> if new == 'DSI': pass elif new == 'DTI': self.local_model_editor = {False: '1:Tensor', True: '2:Constrained Spherical Deconvolution'} elif new == 'multishell' or new == 'HARDI': self.local_model_editor = {True: 'Constrained Spherical Deconvolu...
Class used to store Dipy diffusion reconstruction sub-workflow configuration parameters. Attributes ---------- imaging_model : Str Diffusion imaging model (For instance 'DTI') flip_table_axis : traits.List(['x', 'y', 'z']) Axis to be flipped in the gradient table. local_model_editor : {False: '1:Tensor', True: '2:Const...
DipyReconConfig
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DipyReconConfig: """Class used to store Dipy diffusion reconstruction sub-workflow configuration parameters. Attributes ---------- imaging_model : Str Diffusion imaging model (For instance 'DTI') flip_table_axis : traits.List(['x', 'y', 'z']) Axis to be flipped in the gradient table. local_model_...
stack_v2_sparse_classes_36k_train_021252
24,160
permissive
[ { "docstring": "Update ``local_model_editor`` and ``self.local_model`` when ``imaging_model`` is updated. Parameters ---------- new : string New value of ``imaging_model``", "name": "_imaging_model_changed", "signature": "def _imaging_model_changed(self, new)" }, { "docstring": "Update ``local_m...
2
null
Implement the Python class `DipyReconConfig` described below. Class description: Class used to store Dipy diffusion reconstruction sub-workflow configuration parameters. Attributes ---------- imaging_model : Str Diffusion imaging model (For instance 'DTI') flip_table_axis : traits.List(['x', 'y', 'z']) Axis to be flip...
Implement the Python class `DipyReconConfig` described below. Class description: Class used to store Dipy diffusion reconstruction sub-workflow configuration parameters. Attributes ---------- imaging_model : Str Diffusion imaging model (For instance 'DTI') flip_table_axis : traits.List(['x', 'y', 'z']) Axis to be flip...
35cb2ee7be2e73896061359a6cd0a10503fadd42
<|skeleton|> class DipyReconConfig: """Class used to store Dipy diffusion reconstruction sub-workflow configuration parameters. Attributes ---------- imaging_model : Str Diffusion imaging model (For instance 'DTI') flip_table_axis : traits.List(['x', 'y', 'z']) Axis to be flipped in the gradient table. local_model_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DipyReconConfig: """Class used to store Dipy diffusion reconstruction sub-workflow configuration parameters. Attributes ---------- imaging_model : Str Diffusion imaging model (For instance 'DTI') flip_table_axis : traits.List(['x', 'y', 'z']) Axis to be flipped in the gradient table. local_model_editor : {Fal...
the_stack_v2_python_sparse
cmp/stages/diffusion/reconstruction.py
jwirsich/connectomemapper3
train
0
914424bcae3623f25b0c31ccd906c74a0851e9e3
[ "cls.custom = True\ncls.User = get_user_model()\ncls.user = cls.User.objects.create_user(username='Test1', email='Test1@example.com', password='12345')\nif cls.custom:\n cls.practical = Practical.objects.create()\n cls.group = Group.objects.create(name='group1', practical=cls.practical)\n cls.user.group = ...
<|body_start_0|> cls.custom = True cls.User = get_user_model() cls.user = cls.User.objects.create_user(username='Test1', email='Test1@example.com', password='12345') if cls.custom: cls.practical = Practical.objects.create() cls.group = Group.objects.create(name='g...
Logout Tests.
LogoutTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogoutTest: """Logout Tests.""" def setUpTestData(cls): """Run once before the tests.""" <|body_0|> def test_valid_logout(self): """If the authentication credential (token) matches that of a registered user, the user's authentication token is deleted and http_200...
stack_v2_sparse_classes_36k_train_021253
9,175
permissive
[ { "docstring": "Run once before the tests.", "name": "setUpTestData", "signature": "def setUpTestData(cls)" }, { "docstring": "If the authentication credential (token) matches that of a registered user, the user's authentication token is deleted and http_200_ok is returned in the response.", ...
3
stack_v2_sparse_classes_30k_train_016344
Implement the Python class `LogoutTest` described below. Class description: Logout Tests. Method signatures and docstrings: - def setUpTestData(cls): Run once before the tests. - def test_valid_logout(self): If the authentication credential (token) matches that of a registered user, the user's authentication token is...
Implement the Python class `LogoutTest` described below. Class description: Logout Tests. Method signatures and docstrings: - def setUpTestData(cls): Run once before the tests. - def test_valid_logout(self): If the authentication credential (token) matches that of a registered user, the user's authentication token is...
ac03b03c1bb029eaadc34aee21fac692500b23d0
<|skeleton|> class LogoutTest: """Logout Tests.""" def setUpTestData(cls): """Run once before the tests.""" <|body_0|> def test_valid_logout(self): """If the authentication credential (token) matches that of a registered user, the user's authentication token is deleted and http_200...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogoutTest: """Logout Tests.""" def setUpTestData(cls): """Run once before the tests.""" cls.custom = True cls.User = get_user_model() cls.user = cls.User.objects.create_user(username='Test1', email='Test1@example.com', password='12345') if cls.custom: ...
the_stack_v2_python_sparse
src/vm-django/authentication/tests.py
utmandrew/virtual-mystery
train
2
a77e2604399d2cdeb7cc13840fb77807116731c8
[ "if args is None:\n args = ['']\nself.binary = binary\nself.directory = directory\nself.run_cmd = run_cmd\nself.omp_num_threads = omp_num_threads\nself.time_out = time_out\nself.args = args\ntry:\n os.path.isfile(self.binary)\nexcept FileNotFoundError:\n self.binary = shutil.which(self.binary)\n if self...
<|body_start_0|> if args is None: args = [''] self.binary = binary self.directory = directory self.run_cmd = run_cmd self.omp_num_threads = omp_num_threads self.time_out = time_out self.args = args try: os.path.isfile(self.binary) ...
Compose a run command, and run a binary
BinaryRunner
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryRunner: """Compose a run command, and run a binary""" def __init__(self, binary: str, run_cmd: List[str], omp_num_threads: int, time_out: int, directory: Optional[path_type]='./', args=None) -> None: """:param str binary: Binary name prepended by full path, or just binary name ...
stack_v2_sparse_classes_36k_train_021254
4,483
no_license
[ { "docstring": ":param str binary: Binary name prepended by full path, or just binary name (if present in $PATH) :param List[str] run_cmd: Run commands sequentially as a list. For example: * For serial: ['./'] * For MPI: ['mpirun', '-np', '2'] :param int omp_num_threads: Number of OMP threads :param int time_ou...
3
null
Implement the Python class `BinaryRunner` described below. Class description: Compose a run command, and run a binary Method signatures and docstrings: - def __init__(self, binary: str, run_cmd: List[str], omp_num_threads: int, time_out: int, directory: Optional[path_type]='./', args=None) -> None: :param str binary:...
Implement the Python class `BinaryRunner` described below. Class description: Compose a run command, and run a binary Method signatures and docstrings: - def __init__(self, binary: str, run_cmd: List[str], omp_num_threads: int, time_out: int, directory: Optional[path_type]='./', args=None) -> None: :param str binary:...
40a3c90b9e551b26de2a5f9d57ce83053912cd76
<|skeleton|> class BinaryRunner: """Compose a run command, and run a binary""" def __init__(self, binary: str, run_cmd: List[str], omp_num_threads: int, time_out: int, directory: Optional[path_type]='./', args=None) -> None: """:param str binary: Binary name prepended by full path, or just binary name ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryRunner: """Compose a run command, and run a binary""" def __init__(self, binary: str, run_cmd: List[str], omp_num_threads: int, time_out: int, directory: Optional[path_type]='./', args=None) -> None: """:param str binary: Binary name prepended by full path, or just binary name (if present i...
the_stack_v2_python_sparse
pycharm_projects/tb_benchmarking/tb_lite/src/runner.py
AlexBuccheri/python
train
0
c60700065f46daff70c2095fe4819112d01731dd
[ "re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])", "re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c...
<|body_start_0|> re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo']) result = re Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg']) <|end_body_0|> <|body_start_1|> ...
智泊云月票类型创建,月票开通,车辆进出,是月票
TestCreateMonthTicketProcess
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCreateMonthTicketProcess: """智泊云月票类型创建,月票开通,车辆进出,是月票""" def test_createMonthTicketConfig(self, userLogin, send_data, expect): """创建自定义月票类型""" <|body_0|> def test_openMonthTicketBill(self, userLogin, send_data, expect): """用自定义月票类型开通月票""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_021255
3,267
no_license
[ { "docstring": "创建自定义月票类型", "name": "test_createMonthTicketConfig", "signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)" }, { "docstring": "用自定义月票类型开通月票", "name": "test_openMonthTicketBill", "signature": "def test_openMonthTicketBill(self, userLogin, send_d...
6
stack_v2_sparse_classes_30k_train_006453
Implement the Python class `TestCreateMonthTicketProcess` described below. Class description: 智泊云月票类型创建,月票开通,车辆进出,是月票 Method signatures and docstrings: - def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型 - def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票 - d...
Implement the Python class `TestCreateMonthTicketProcess` described below. Class description: 智泊云月票类型创建,月票开通,车辆进出,是月票 Method signatures and docstrings: - def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型 - def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票 - d...
34c368c109867da26d9256bca85f872b0fac2ea7
<|skeleton|> class TestCreateMonthTicketProcess: """智泊云月票类型创建,月票开通,车辆进出,是月票""" def test_createMonthTicketConfig(self, userLogin, send_data, expect): """创建自定义月票类型""" <|body_0|> def test_openMonthTicketBill(self, userLogin, send_data, expect): """用自定义月票类型开通月票""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCreateMonthTicketProcess: """智泊云月票类型创建,月票开通,车辆进出,是月票""" def test_createMonthTicketConfig(self, userLogin, send_data, expect): """创建自定义月票类型""" re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_da...
the_stack_v2_python_sparse
test_suite/parkingManage/monthTicket/test_createMonthTicketProcess.py
oyebino/pomp_api
train
1
aba90880a22a390ad5e7a439e2f5ef70fa622308
[ "tempdir = tempfile.mkdtemp()\nfilename = 'model.keras'\nmodel.save(os.path.join(tempdir, filename))\ncheckpoint = cls.from_directory(tempdir)\nif preprocessor:\n checkpoint.set_preprocessor(preprocessor)\ncheckpoint.update_metadata({cls.MODEL_FILENAME_KEY: filename})\nreturn checkpoint", "if not os.path.isfil...
<|body_start_0|> tempdir = tempfile.mkdtemp() filename = 'model.keras' model.save(os.path.join(tempdir, filename)) checkpoint = cls.from_directory(tempdir) if preprocessor: checkpoint.set_preprocessor(preprocessor) checkpoint.update_metadata({cls.MODEL_FILENAM...
A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.
TensorflowCheckpoint
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TensorflowCheckpoint: """A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.""" def from_model(cls, model: keras.Model, *, preprocessor: Optional['Preprocessor']=None) -> 'TensorflowCheckpoint': """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras...
stack_v2_sparse_classes_36k_train_021256
13,589
permissive
[ { "docstring": "Create a :py:class:`~ray.train.Checkpoint` that stores a Keras model. The checkpoint created with this method needs to be paired with `model` when used. Args: model: The Keras model, whose weights are stored in the checkpoint. preprocessor: A fitted preprocessor to be applied before inference. R...
4
null
Implement the Python class `TensorflowCheckpoint` described below. Class description: A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality. Method signatures and docstrings: - def from_model(cls, model: keras.Model, *, preprocessor: Optional['Preprocessor']=None) -> 'TensorflowCheckpoint': Creat...
Implement the Python class `TensorflowCheckpoint` described below. Class description: A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality. Method signatures and docstrings: - def from_model(cls, model: keras.Model, *, preprocessor: Optional['Preprocessor']=None) -> 'TensorflowCheckpoint': Creat...
edba68c3e7cf255d1d6479329f305adb7fa4c3ed
<|skeleton|> class TensorflowCheckpoint: """A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.""" def from_model(cls, model: keras.Model, *, preprocessor: Optional['Preprocessor']=None) -> 'TensorflowCheckpoint': """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TensorflowCheckpoint: """A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.""" def from_model(cls, model: keras.Model, *, preprocessor: Optional['Preprocessor']=None) -> 'TensorflowCheckpoint': """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras model. The c...
the_stack_v2_python_sparse
python/ray/train/tensorflow/tensorflow_checkpoint.py
ray-project/ray
train
29,482
f6a9da15cd7d656815adf5d4625f848a44487e39
[ "SFA_generic.__init__(self, Sym, basis_name=bname, prefix=pfix, graded=False)\nself._other = other_basis\nself.module_morphism(self._self_to_other_on_basis, codomain=self._other).register_as_coercion()\nself.register_coercion(SetMorphism(Hom(self._other, self), self._other_to_self))", "if not lam:\n return sel...
<|body_start_0|> SFA_generic.__init__(self, Sym, basis_name=bname, prefix=pfix, graded=False) self._other = other_basis self.module_morphism(self._self_to_other_on_basis, codomain=self._other).register_as_coercion() self.register_coercion(SetMorphism(Hom(self._other, self), self._other_t...
General code for a character basis (irreducible and induced trivial). This is a basis of the symmetric functions that has the property that ``self(la).character_to_frobenius_image(n)`` is equal to ``other([n-sum(la)]+la)``. It should also have the property that the (outer) structure constants are the analogue of the st...
character_basis
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class character_basis: """General code for a character basis (irreducible and induced trivial). This is a basis of the symmetric functions that has the property that ``self(la).character_to_frobenius_image(n)`` is equal to ``other([n-sum(la)]+la)``. It should also have the property that the (outer) str...
stack_v2_sparse_classes_36k_train_021257
16,482
no_license
[ { "docstring": "Initialize the basis and register coercions. The coercions are set up between the ``other_basis``. INPUT: - ``Sym`` -- an instance of the symmetric function algebra - ``other_basis`` -- a basis of Sym - ``bname`` -- the name for this basis (convention: ends in \"character\") - ``pfix`` -- a pref...
2
stack_v2_sparse_classes_30k_train_019943
Implement the Python class `character_basis` described below. Class description: General code for a character basis (irreducible and induced trivial). This is a basis of the symmetric functions that has the property that ``self(la).character_to_frobenius_image(n)`` is equal to ``other([n-sum(la)]+la)``. It should also...
Implement the Python class `character_basis` described below. Class description: General code for a character basis (irreducible and induced trivial). This is a basis of the symmetric functions that has the property that ``self(la).character_to_frobenius_image(n)`` is equal to ``other([n-sum(la)]+la)``. It should also...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class character_basis: """General code for a character basis (irreducible and induced trivial). This is a basis of the symmetric functions that has the property that ``self(la).character_to_frobenius_image(n)`` is equal to ``other([n-sum(la)]+la)``. It should also have the property that the (outer) str...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class character_basis: """General code for a character basis (irreducible and induced trivial). This is a basis of the symmetric functions that has the property that ``self(la).character_to_frobenius_image(n)`` is equal to ``other([n-sum(la)]+la)``. It should also have the property that the (outer) structure consta...
the_stack_v2_python_sparse
sage/src/sage/combinat/sf/character.py
bopopescu/geosci
train
0
f3f55db0dacfc8d67583e2bdafe7aa8a0544b2fa
[ "if WebAuth.test_token(auth_service):\n return redirect(url_for('get_home'))\nreturn render_template('login.html')", "response: ResponseData = auth_service.login(request.form['user'], request.form['pass'])\nWebUtils.flash_response_messages(response)\nif not response.is_successful():\n return redirect(url_fo...
<|body_start_0|> if WebAuth.test_token(auth_service): return redirect(url_for('get_home')) return render_template('login.html') <|end_body_0|> <|body_start_1|> response: ResponseData = auth_service.login(request.form['user'], request.form['pass']) WebUtils.flash_response_mes...
Monostate class responsible of handling the session web endpoint requests.
SessionEndpoints
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionEndpoints: """Monostate class responsible of handling the session web endpoint requests.""" def get_login(auth_service: AuthService) -> Union[Response, Text]: """Handles the GET requests to the login endpoint. Args: - auth_service (AuthService): The authentication service. Ret...
stack_v2_sparse_classes_36k_train_021258
2,127
no_license
[ { "docstring": "Handles the GET requests to the login endpoint. Args: - auth_service (AuthService): The authentication service. Returns: - Union[Response,Text]: The generated response to the request.", "name": "get_login", "signature": "def get_login(auth_service: AuthService) -> Union[Response, Text]" ...
3
stack_v2_sparse_classes_30k_train_009119
Implement the Python class `SessionEndpoints` described below. Class description: Monostate class responsible of handling the session web endpoint requests. Method signatures and docstrings: - def get_login(auth_service: AuthService) -> Union[Response, Text]: Handles the GET requests to the login endpoint. Args: - au...
Implement the Python class `SessionEndpoints` described below. Class description: Monostate class responsible of handling the session web endpoint requests. Method signatures and docstrings: - def get_login(auth_service: AuthService) -> Union[Response, Text]: Handles the GET requests to the login endpoint. Args: - au...
d7d50f84e93914d388ccd084b3bee7e02c9e717b
<|skeleton|> class SessionEndpoints: """Monostate class responsible of handling the session web endpoint requests.""" def get_login(auth_service: AuthService) -> Union[Response, Text]: """Handles the GET requests to the login endpoint. Args: - auth_service (AuthService): The authentication service. Ret...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionEndpoints: """Monostate class responsible of handling the session web endpoint requests.""" def get_login(auth_service: AuthService) -> Union[Response, Text]: """Handles the GET requests to the login endpoint. Args: - auth_service (AuthService): The authentication service. Returns: - Union...
the_stack_v2_python_sparse
components/dms2122frontend/dms2122frontend/presentation/web/sessionendpoints.py
Kencho/practica-dms-2021-2022
train
0
af0fba043a7e50bd180b3f40a83c7678d9147fb9
[ "self.key = k\nself.parent = parent\nself.left = None\nself.right = None", "if self.key == k:\n return self\nif k > self.key:\n if self.right is None:\n return None\n else:\n return self.right.find(k)\nelif self.left is None:\n return None\nelse:\n return self.left.find(k)", "cur_no...
<|body_start_0|> self.key = k self.parent = parent self.left = None self.right = None <|end_body_0|> <|body_start_1|> if self.key == k: return self if k > self.key: if self.right is None: return None else: ...
A node in the vanilla BST tree.
BSTNode
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSTNode: """A node in the vanilla BST tree.""" def __init__(self, parent, k): """Creates a node. :param parent: node's parent :param k: node's key""" <|body_0|> def find(self, k): """Find and return the node with key k from the subtree rooted at this :param k: no...
stack_v2_sparse_classes_36k_train_021259
4,503
no_license
[ { "docstring": "Creates a node. :param parent: node's parent :param k: node's key", "name": "__init__", "signature": "def __init__(self, parent, k)" }, { "docstring": "Find and return the node with key k from the subtree rooted at this :param k: nodes with key k :return: node", "name": "find...
6
null
Implement the Python class `BSTNode` described below. Class description: A node in the vanilla BST tree. Method signatures and docstrings: - def __init__(self, parent, k): Creates a node. :param parent: node's parent :param k: node's key - def find(self, k): Find and return the node with key k from the subtree rooted...
Implement the Python class `BSTNode` described below. Class description: A node in the vanilla BST tree. Method signatures and docstrings: - def __init__(self, parent, k): Creates a node. :param parent: node's parent :param k: node's key - def find(self, k): Find and return the node with key k from the subtree rooted...
e16702d2b3ec4e5054baad56f4320bc3b31676ad
<|skeleton|> class BSTNode: """A node in the vanilla BST tree.""" def __init__(self, parent, k): """Creates a node. :param parent: node's parent :param k: node's key""" <|body_0|> def find(self, k): """Find and return the node with key k from the subtree rooted at this :param k: no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BSTNode: """A node in the vanilla BST tree.""" def __init__(self, parent, k): """Creates a node. :param parent: node's parent :param k: node's key""" self.key = k self.parent = parent self.left = None self.right = None def find(self, k): """Find and re...
the_stack_v2_python_sparse
CLRS/BST/BST_struct.py
SuperMartinYang/learning_algorithm
train
0
0f5b66ea01ab3465d24c9e5dad991f469ce9f6e6
[ "dict.__init__(self)\nself.setdefault('Name', None)\nself.setdefault('Size', None)\nself.setdefault('NumEvents', None)\nself.setdefault('NumFiles', None)\nself.update(args)", "block = Block()\nblock['Name'] = blockInfo[0]['name']\nblock['NumFiles'] = blockInfo[0]['num_files']\nblock['NumEvents'] = blockInfo[0]['n...
<|body_start_0|> dict.__init__(self) self.setdefault('Name', None) self.setdefault('Size', None) self.setdefault('NumEvents', None) self.setdefault('NumFiles', None) self.update(args) <|end_body_0|> <|body_start_1|> block = Block() block['Name'] = blockIn...
_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles
Block
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Block: """_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles""" def __init__(self, **args): """___init___ Initialize all attributes.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_021260
1,071
permissive
[ { "docstring": "___init___ Initialize all attributes.", "name": "__init__", "signature": "def __init__(self, **args)" }, { "docstring": "convert to the Block structure from db column format", "name": "getBlock", "signature": "def getBlock(blockInfo)" } ]
2
null
Implement the Python class `Block` described below. Class description: _Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles Method signatures and docstrings: - def __init__(self, **args): ___ini...
Implement the Python class `Block` described below. Class description: _Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles Method signatures and docstrings: - def __init__(self, **args): ___ini...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class Block: """_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles""" def __init__(self, **args): """___init___ Initialize all attributes.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Block: """_Block_ A dictionary based object meant to represent subset of dbs block. Which will just need for workQueue update. It contains the following keys: Name Size NumEvent NumFiles""" def __init__(self, **args): """___init___ Initialize all attributes.""" dict.__init__(self) ...
the_stack_v2_python_sparse
src/python/WMCore/WorkQueue/DataStructs/Block.py
vkuznet/WMCore
train
0
bc40cfc7bc8f8753a4e3cedc59275d134f924416
[ "rsp = apply(Response, [], kwargs)\nrsp['community'] = self['community']\npdu = self['pdu'].values()[0]\nif hasattr(pdu, 'reply'):\n rsp['pdu']['response'] = pdu.reply()\nreturn rsp", "if not isinstance(rsp, Response):\n raise error.BadArgumentError('Incompatible types for comparation %s with %s' % (self.__...
<|body_start_0|> rsp = apply(Response, [], kwargs) rsp['community'] = self['community'] pdu = self['pdu'].values()[0] if hasattr(pdu, 'reply'): rsp['pdu']['response'] = pdu.reply() return rsp <|end_body_0|> <|body_start_1|> if not isinstance(rsp, Response): ...
Request-specific methods
_RequestSpecifics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _RequestSpecifics: """Request-specific methods""" def reply(self, **kwargs): """Create v.2c RESPONSE message from this request message""" <|body_0|> def match(self, rsp): """Return true if response message matches this request message""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_021261
10,163
no_license
[ { "docstring": "Create v.2c RESPONSE message from this request message", "name": "reply", "signature": "def reply(self, **kwargs)" }, { "docstring": "Return true if response message matches this request message", "name": "match", "signature": "def match(self, rsp)" } ]
2
null
Implement the Python class `_RequestSpecifics` described below. Class description: Request-specific methods Method signatures and docstrings: - def reply(self, **kwargs): Create v.2c RESPONSE message from this request message - def match(self, rsp): Return true if response message matches this request message
Implement the Python class `_RequestSpecifics` described below. Class description: Request-specific methods Method signatures and docstrings: - def reply(self, **kwargs): Create v.2c RESPONSE message from this request message - def match(self, rsp): Return true if response message matches this request message <|skel...
256401ac313df2e45c516af1a4d5398f54703b9c
<|skeleton|> class _RequestSpecifics: """Request-specific methods""" def reply(self, **kwargs): """Create v.2c RESPONSE message from this request message""" <|body_0|> def match(self, rsp): """Return true if response message matches this request message""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _RequestSpecifics: """Request-specific methods""" def reply(self, **kwargs): """Create v.2c RESPONSE message from this request message""" rsp = apply(Response, [], kwargs) rsp['community'] = self['community'] pdu = self['pdu'].values()[0] if hasattr(pdu, 'reply'): ...
the_stack_v2_python_sparse
pre/python/lib/python2.7/dist-packages/pysnmp/proto/v2c.py
ag1455/OpenPLi-PC
train
27
1b35840c85755524de2b13c94d529569683f53cf
[ "tree_node_list = []\nfor i in range(len(tree_data)):\n if tree_data[i] != 'null':\n tree_node_list.append(TreeNode(tree_data[i]))\n else:\n tree_node_list.append(None)\nfor i in range(len(tree_data)):\n if tree_node_list[i]:\n if 2 * i + 2 < len(tree_data):\n tree_node_list...
<|body_start_0|> tree_node_list = [] for i in range(len(tree_data)): if tree_data[i] != 'null': tree_node_list.append(TreeNode(tree_data[i])) else: tree_node_list.append(None) for i in range(len(tree_data)): if tree_node_list[i]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def buildTree(self, tree_data): """:type tree_data: list :rtype: TreeNode""" <|body_0|> def maxDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> tree_node_list = [] for i in rang...
stack_v2_sparse_classes_36k_train_021262
1,354
no_license
[ { "docstring": ":type tree_data: list :rtype: TreeNode", "name": "buildTree", "signature": "def buildTree(self, tree_data)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "maxDepth", "signature": "def maxDepth(self, root)" } ]
2
stack_v2_sparse_classes_30k_test_000711
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, tree_data): :type tree_data: list :rtype: TreeNode - def maxDepth(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, tree_data): :type tree_data: list :rtype: TreeNode - def maxDepth(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: def buildTr...
37ece0a8e92a41ced2b4ce0f2d8dda3826b915ae
<|skeleton|> class Solution: def buildTree(self, tree_data): """:type tree_data: list :rtype: TreeNode""" <|body_0|> def maxDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def buildTree(self, tree_data): """:type tree_data: list :rtype: TreeNode""" tree_node_list = [] for i in range(len(tree_data)): if tree_data[i] != 'null': tree_node_list.append(TreeNode(tree_data[i])) else: tree_node_li...
the_stack_v2_python_sparse
Q104MaximumDepthofBinaryTree.py
ShenTonyM/LeetCode-Learn
train
0
69f67fad47f8148b6a6b0f7e6369809ebf81f3c3
[ "ans = []\n\ndef dfs(node):\n if not node:\n ans.append('null')\n return\n ans.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn ','.join(ans)", "data = data.split(',')\n\ndef dfs(nodes):\n rootV = nodes.pop(0)\n if rootV == 'null':\n return None\n ...
<|body_start_0|> ans = [] def dfs(node): if not node: ans.append('null') return ans.append(str(node.val)) dfs(node.left) dfs(node.right) dfs(root) return ','.join(ans) <|end_body_0|> <|body_start_1|> ...
前序模式
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: """前序模式""" def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_021263
1,465
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
stack_v2_sparse_classes_30k_test_000495
Implement the Python class `Codec` described below. Class description: 前序模式 Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: 前序模式 Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Codec: """前序模式""" ...
aa3be0350424aab2412f57f402e20e7cabe35747
<|skeleton|> class Codec: """前序模式""" def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: """前序模式""" def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" ans = [] def dfs(node): if not node: ans.append('null') return ans.append(str(node.val)) dfs(node.left) ...
the_stack_v2_python_sparse
algorithm/leetCode_xx/297.二叉树的序列化与反序列化.py
aizigao/keepTraining
train
0
fd1cafbca35b3026054116724fe72df449990ba6
[ "web.header('X-Frame-Options', 'SAMEORIGIN')\nweb.header('X-Content-Type-Options', 'nosniff')\nweb.header('X-XSS-Protection', '1')\nif not session.validate_session():\n raise web.seeother('/login')\nelse:\n input_data = model.validate_input(web.input(), ['code'])\n module_code = input_data.code.upper()\n ...
<|body_start_0|> web.header('X-Frame-Options', 'SAMEORIGIN') web.header('X-Content-Type-Options', 'nosniff') web.header('X-XSS-Protection', '1') if not session.validate_session(): raise web.seeother('/login') else: input_data = model.validate_input(web.inp...
This class handles the editing of a module's preclusions.
EditModulePreclusions
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EditModulePreclusions: """This class handles the editing of a module's preclusions.""" def GET(self): """Handles the loading of the 'Edit Module Preclusions' page.""" <|body_0|> def POST(self): """Handles the submission of updated module preclusions for a target ...
stack_v2_sparse_classes_36k_train_021264
1,749
permissive
[ { "docstring": "Handles the loading of the 'Edit Module Preclusions' page.", "name": "GET", "signature": "def GET(self)" }, { "docstring": "Handles the submission of updated module preclusions for a target module.", "name": "POST", "signature": "def POST(self)" } ]
2
stack_v2_sparse_classes_30k_train_011218
Implement the Python class `EditModulePreclusions` described below. Class description: This class handles the editing of a module's preclusions. Method signatures and docstrings: - def GET(self): Handles the loading of the 'Edit Module Preclusions' page. - def POST(self): Handles the submission of updated module prec...
Implement the Python class `EditModulePreclusions` described below. Class description: This class handles the editing of a module's preclusions. Method signatures and docstrings: - def GET(self): Handles the loading of the 'Edit Module Preclusions' page. - def POST(self): Handles the submission of updated module prec...
02b52871a34f580b779ede08750f2d4e887bcf65
<|skeleton|> class EditModulePreclusions: """This class handles the editing of a module's preclusions.""" def GET(self): """Handles the loading of the 'Edit Module Preclusions' page.""" <|body_0|> def POST(self): """Handles the submission of updated module preclusions for a target ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EditModulePreclusions: """This class handles the editing of a module's preclusions.""" def GET(self): """Handles the loading of the 'Edit Module Preclusions' page.""" web.header('X-Frame-Options', 'SAMEORIGIN') web.header('X-Content-Type-Options', 'nosniff') web.header('X-...
the_stack_v2_python_sparse
components/handlers/module_edit_preclusions.py
nus-mtp/cs-modify
train
1
ea093afaa701764af59c22faa4b370b07d7b3bd4
[ "args = args.split()\nif _debug:\n ReadWriteBBMDConsoleClient._debug('do_readbdt %r', args)\nread_bdt = ReadBroadcastDistributionTable(destination=Address(args[0]))\nif _debug:\n ReadWriteBBMDConsoleClient._debug(' - read_bdt: %r', read_bdt)\nself.request(read_bdt)", "args = args.split()\nif _debug:\n ...
<|body_start_0|> args = args.split() if _debug: ReadWriteBBMDConsoleClient._debug('do_readbdt %r', args) read_bdt = ReadBroadcastDistributionTable(destination=Address(args[0])) if _debug: ReadWriteBBMDConsoleClient._debug(' - read_bdt: %r', read_bdt) se...
ReadWriteBBMDConsoleClient
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReadWriteBBMDConsoleClient: def do_readbdt(self, args): """readbdt <addr>""" <|body_0|> def do_readfdt(self, args): """readfdt <addr>""" <|body_1|> def do_writebdt(self, args): """writebdt <addr> <entry> ...""" <|body_2|> def confirm...
stack_v2_sparse_classes_36k_train_021265
3,791
permissive
[ { "docstring": "readbdt <addr>", "name": "do_readbdt", "signature": "def do_readbdt(self, args)" }, { "docstring": "readfdt <addr>", "name": "do_readfdt", "signature": "def do_readfdt(self, args)" }, { "docstring": "writebdt <addr> <entry> ...", "name": "do_writebdt", "si...
4
stack_v2_sparse_classes_30k_train_002121
Implement the Python class `ReadWriteBBMDConsoleClient` described below. Class description: Implement the ReadWriteBBMDConsoleClient class. Method signatures and docstrings: - def do_readbdt(self, args): readbdt <addr> - def do_readfdt(self, args): readfdt <addr> - def do_writebdt(self, args): writebdt <addr> <entry>...
Implement the Python class `ReadWriteBBMDConsoleClient` described below. Class description: Implement the ReadWriteBBMDConsoleClient class. Method signatures and docstrings: - def do_readbdt(self, args): readbdt <addr> - def do_readfdt(self, args): readfdt <addr> - def do_writebdt(self, args): writebdt <addr> <entry>...
a5be2ad5ac69821c12299716b167dd52041b5342
<|skeleton|> class ReadWriteBBMDConsoleClient: def do_readbdt(self, args): """readbdt <addr>""" <|body_0|> def do_readfdt(self, args): """readfdt <addr>""" <|body_1|> def do_writebdt(self, args): """writebdt <addr> <entry> ...""" <|body_2|> def confirm...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReadWriteBBMDConsoleClient: def do_readbdt(self, args): """readbdt <addr>""" args = args.split() if _debug: ReadWriteBBMDConsoleClient._debug('do_readbdt %r', args) read_bdt = ReadBroadcastDistributionTable(destination=Address(args[0])) if _debug: ...
the_stack_v2_python_sparse
samples/ReadWriteBBMD.py
JoelBender/bacpypes
train
284
1cf6b4db235a6f269be8f1ee3c8410d0dae769cf
[ "super().__init__()\nself.iterable = iterable\nself.start = start\nself.end = end", "ret = []\nif isinstance(self.iterable, dict):\n sorted_keys = sorted(self.iterable.keys())\n for key in sorted_keys[self.start:self.end]:\n ret.append((key, self.iterable[key]))\nelif isinstance(self.iterable, list):...
<|body_start_0|> super().__init__() self.iterable = iterable self.start = start self.end = end <|end_body_0|> <|body_start_1|> ret = [] if isinstance(self.iterable, dict): sorted_keys = sorted(self.iterable.keys()) for key in sorted_keys[self.star...
Iterator Loader.
IteratorLoader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IteratorLoader: """Iterator Loader.""" def __init__(self, iterable, start, end): """Create new IteratorLoader object. :param iterable: Iterable object. :param start: Start position. :param end: End Position. :returns: None.""" <|body_0|> def retrieve_data(self): ...
stack_v2_sparse_classes_36k_train_021266
6,375
permissive
[ { "docstring": "Create new IteratorLoader object. :param iterable: Iterable object. :param start: Start position. :param end: End Position. :returns: None.", "name": "__init__", "signature": "def __init__(self, iterable, start, end)" }, { "docstring": "Divide and retrieve the next partition. :re...
2
null
Implement the Python class `IteratorLoader` described below. Class description: Iterator Loader. Method signatures and docstrings: - def __init__(self, iterable, start, end): Create new IteratorLoader object. :param iterable: Iterable object. :param start: Start position. :param end: End Position. :returns: None. - d...
Implement the Python class `IteratorLoader` described below. Class description: Iterator Loader. Method signatures and docstrings: - def __init__(self, iterable, start, end): Create new IteratorLoader object. :param iterable: Iterable object. :param start: Start position. :param end: End Position. :returns: None. - d...
5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092
<|skeleton|> class IteratorLoader: """Iterator Loader.""" def __init__(self, iterable, start, end): """Create new IteratorLoader object. :param iterable: Iterable object. :param start: Start position. :param end: End Position. :returns: None.""" <|body_0|> def retrieve_data(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IteratorLoader: """Iterator Loader.""" def __init__(self, iterable, start, end): """Create new IteratorLoader object. :param iterable: Iterable object. :param start: Start position. :param end: End Position. :returns: None.""" super().__init__() self.iterable = iterable se...
the_stack_v2_python_sparse
compss/programming_model/bindings/python/src/pycompss/dds/partition_generators.py
bsc-wdc/compss
train
39
14b0ec57320083bc44b3a228ac206941b7b9e587
[ "super(MoveItemsForm, self).__init__(project, *args, **kwargs)\nif subdir is not None:\n choices = [(d.name, d.name) for d in display_dirs]\n if subdir:\n choices.insert(0, ('../', '(Parent directory)'))\n self.fields['destination_folder'].widget.choices = choices", "cleaned_data = super(MoveItems...
<|body_start_0|> super(MoveItemsForm, self).__init__(project, *args, **kwargs) if subdir is not None: choices = [(d.name, d.name) for d in display_dirs] if subdir: choices.insert(0, ('../', '(Parent directory)')) self.fields['destination_folder'].widge...
Form for moving items into a target folder
MoveItemsForm
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MoveItemsForm: """Form for moving items into a target folder""" def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): """Set the choices for the destination folder""" <|body_0|> def clean(self): """Selected destination folder: - May only b...
stack_v2_sparse_classes_36k_train_021267
39,361
permissive
[ { "docstring": "Set the choices for the destination folder", "name": "__init__", "signature": "def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs)" }, { "docstring": "Selected destination folder: - May only be '..' if subdir is not the top level - Must not be one of the ...
3
stack_v2_sparse_classes_30k_train_012447
Implement the Python class `MoveItemsForm` described below. Class description: Form for moving items into a target folder Method signatures and docstrings: - def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): Set the choices for the destination folder - def clean(self): Selected destination...
Implement the Python class `MoveItemsForm` described below. Class description: Form for moving items into a target folder Method signatures and docstrings: - def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): Set the choices for the destination folder - def clean(self): Selected destination...
e7c8ed0b07a4c9a1b4007f6089f59aafa6a3ac57
<|skeleton|> class MoveItemsForm: """Form for moving items into a target folder""" def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): """Set the choices for the destination folder""" <|body_0|> def clean(self): """Selected destination folder: - May only b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MoveItemsForm: """Form for moving items into a target folder""" def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): """Set the choices for the destination folder""" super(MoveItemsForm, self).__init__(project, *args, **kwargs) if subdir is not None: ...
the_stack_v2_python_sparse
physionet-django/project/forms.py
tompollard/physionet-build
train
0
1437c9583dbb261184023f7ca5008c03ae81243e
[ "graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges)\ntested_pass = AddIsCyclicAttribute()\ntested_pass.find_and_replace_pattern(graph)\nassert graph.graph['is_cyclic'] is False", "graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, new_edg...
<|body_start_0|> graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges) tested_pass = AddIsCyclicAttribute() tested_pass.find_and_replace_pattern(graph) assert graph.graph['is_cyclic'] is False <|end_body_0|> <|body_start_1|> graph = build_graph...
AddIsCyclicAttributeTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddIsCyclicAttributeTest: def test_1(self): """Acyclic case => graph.graph['is_cyclic'] should be False.""" <|body_0|> def test_2(self): """Cyclic case => graph.graph['is_cyclic'] should be True. :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_021268
1,771
permissive
[ { "docstring": "Acyclic case => graph.graph['is_cyclic'] should be False.", "name": "test_1", "signature": "def test_1(self)" }, { "docstring": "Cyclic case => graph.graph['is_cyclic'] should be True. :return:", "name": "test_2", "signature": "def test_2(self)" } ]
2
stack_v2_sparse_classes_30k_train_015859
Implement the Python class `AddIsCyclicAttributeTest` described below. Class description: Implement the AddIsCyclicAttributeTest class. Method signatures and docstrings: - def test_1(self): Acyclic case => graph.graph['is_cyclic'] should be False. - def test_2(self): Cyclic case => graph.graph['is_cyclic'] should be ...
Implement the Python class `AddIsCyclicAttributeTest` described below. Class description: Implement the AddIsCyclicAttributeTest class. Method signatures and docstrings: - def test_1(self): Acyclic case => graph.graph['is_cyclic'] should be False. - def test_2(self): Cyclic case => graph.graph['is_cyclic'] should be ...
2e6c95f389b195f6d3ff8597147d1f817433cfb3
<|skeleton|> class AddIsCyclicAttributeTest: def test_1(self): """Acyclic case => graph.graph['is_cyclic'] should be False.""" <|body_0|> def test_2(self): """Cyclic case => graph.graph['is_cyclic'] should be True. :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddIsCyclicAttributeTest: def test_1(self): """Acyclic case => graph.graph['is_cyclic'] should be False.""" graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges) tested_pass = AddIsCyclicAttribute() tested_pass.find_and_replace_pattern(graph) ...
the_stack_v2_python_sparse
model-optimizer/extensions/middle/AddIsCyclicAttribute_test.py
0xF6/openvino
train
2
2e207a2e04ca9743aa32fdc2bd3ade823c896893
[ "print('重写创建方法', validated_data)\ninstance = Category.objects.create(**validated_data)\nprint('创建模型实例', instance)\nreturn instance", "print('重写更新方法', validated_data, instance.name)\ninstance.name = validated_data.get('name', instance.name)\nprint(instance.name)\ninstance.save()\nreturn instance" ]
<|body_start_0|> print('重写创建方法', validated_data) instance = Category.objects.create(**validated_data) print('创建模型实例', instance) return instance <|end_body_0|> <|body_start_1|> print('重写更新方法', validated_data, instance.name) instance.name = validated_data.get('name', insta...
序列化类 决定了模型序列化细节
CategorySerizlizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CategorySerizlizer: """序列化类 决定了模型序列化细节""" def create(self, validated_data): """通过重写create方法 来定义模型创建方式 :param validated_data: :return:""" <|body_0|> def update(self, instance, validated_data): """通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 :param validated_data...
stack_v2_sparse_classes_36k_train_021269
7,088
no_license
[ { "docstring": "通过重写create方法 来定义模型创建方式 :param validated_data: :return:", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 :param validated_data: 更改参数 :return: 返回的新实例", "name": "update", "signature": "def u...
2
null
Implement the Python class `CategorySerizlizer` described below. Class description: 序列化类 决定了模型序列化细节 Method signatures and docstrings: - def create(self, validated_data): 通过重写create方法 来定义模型创建方式 :param validated_data: :return: - def update(self, instance, validated_data): 通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 ...
Implement the Python class `CategorySerizlizer` described below. Class description: 序列化类 决定了模型序列化细节 Method signatures and docstrings: - def create(self, validated_data): 通过重写create方法 来定义模型创建方式 :param validated_data: :return: - def update(self, instance, validated_data): 通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 ...
80eb5175cd0e5b3c6c5e2ebb906bb78d9a8f9e0d
<|skeleton|> class CategorySerizlizer: """序列化类 决定了模型序列化细节""" def create(self, validated_data): """通过重写create方法 来定义模型创建方式 :param validated_data: :return:""" <|body_0|> def update(self, instance, validated_data): """通过重写update,来定义模型的更新方法 :param instance: 更改之前的实例 :param validated_data...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CategorySerizlizer: """序列化类 决定了模型序列化细节""" def create(self, validated_data): """通过重写create方法 来定义模型创建方式 :param validated_data: :return:""" print('重写创建方法', validated_data) instance = Category.objects.create(**validated_data) print('创建模型实例', instance) return instance ...
the_stack_v2_python_sparse
end/shop-end/drfend/shop/serializers.py
1987617587/lsh_py
train
2
910897d88113ab288cdb465e40036e3a92f90c45
[ "coord_name = 'air_temperature status_flag'\ntry:\n coord = cube.coord(coord_name)\nexcept CoordinateNotFoundError:\n coord = None\nif coord:\n if coord.attributes != {'flag_meanings': 'above_surface_pressure below_surface_pressure', 'flag_values': np.array([0, 1], dtype='int8')}:\n raise ValueError...
<|body_start_0|> coord_name = 'air_temperature status_flag' try: coord = cube.coord(coord_name) except CoordinateNotFoundError: coord = None if coord: if coord.attributes != {'flag_meanings': 'above_surface_pressure below_surface_pressure', 'flag_value...
Plugin to standardise cube metadata
StandardiseMetadata
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StandardiseMetadata: """Plugin to standardise cube metadata""" def _rm_air_temperature_status_flag(cube: Cube) -> Cube: """Remove air_temperature status_flag coord by applying as NaN to cube data. See https://github.com/metoppv/improver/pull/1839 for further details.""" <|bod...
stack_v2_sparse_classes_36k_train_021270
8,621
permissive
[ { "docstring": "Remove air_temperature status_flag coord by applying as NaN to cube data. See https://github.com/metoppv/improver/pull/1839 for further details.", "name": "_rm_air_temperature_status_flag", "signature": "def _rm_air_temperature_status_flag(cube: Cube) -> Cube" }, { "docstring": "...
6
stack_v2_sparse_classes_30k_train_015795
Implement the Python class `StandardiseMetadata` described below. Class description: Plugin to standardise cube metadata Method signatures and docstrings: - def _rm_air_temperature_status_flag(cube: Cube) -> Cube: Remove air_temperature status_flag coord by applying as NaN to cube data. See https://github.com/metoppv...
Implement the Python class `StandardiseMetadata` described below. Class description: Plugin to standardise cube metadata Method signatures and docstrings: - def _rm_air_temperature_status_flag(cube: Cube) -> Cube: Remove air_temperature status_flag coord by applying as NaN to cube data. See https://github.com/metoppv...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class StandardiseMetadata: """Plugin to standardise cube metadata""" def _rm_air_temperature_status_flag(cube: Cube) -> Cube: """Remove air_temperature status_flag coord by applying as NaN to cube data. See https://github.com/metoppv/improver/pull/1839 for further details.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StandardiseMetadata: """Plugin to standardise cube metadata""" def _rm_air_temperature_status_flag(cube: Cube) -> Cube: """Remove air_temperature status_flag coord by applying as NaN to cube data. See https://github.com/metoppv/improver/pull/1839 for further details.""" coord_name = 'air_...
the_stack_v2_python_sparse
improver/standardise.py
metoppv/improver
train
101
827e513f1feabd9e407948c1e3d04dc55405f898
[ "current_app.logger.info('<RoutingSlips.get')\ntry:\n response = RoutingSlipService.validate_and_find_by_number(routing_slip_number)\n if response:\n status = HTTPStatus.OK\n else:\n response, status = ({}, HTTPStatus.NO_CONTENT)\nexcept BusinessException as exception:\n return exception.r...
<|body_start_0|> current_app.logger.info('<RoutingSlips.get') try: response = RoutingSlipService.validate_and_find_by_number(routing_slip_number) if response: status = HTTPStatus.OK else: response, status = ({}, HTTPStatus.NO_CONTENT) ...
Endpoint resource update and return routing slip by number.
RoutingSlip
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoutingSlip: """Endpoint resource update and return routing slip by number.""" def get(routing_slip_number: str): """Get routing slip.""" <|body_0|> def patch(routing_slip_number: str): """Patch routing slip.""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_021271
10,127
permissive
[ { "docstring": "Get routing slip.", "name": "get", "signature": "def get(routing_slip_number: str)" }, { "docstring": "Patch routing slip.", "name": "patch", "signature": "def patch(routing_slip_number: str)" } ]
2
null
Implement the Python class `RoutingSlip` described below. Class description: Endpoint resource update and return routing slip by number. Method signatures and docstrings: - def get(routing_slip_number: str): Get routing slip. - def patch(routing_slip_number: str): Patch routing slip.
Implement the Python class `RoutingSlip` described below. Class description: Endpoint resource update and return routing slip by number. Method signatures and docstrings: - def get(routing_slip_number: str): Get routing slip. - def patch(routing_slip_number: str): Patch routing slip. <|skeleton|> class RoutingSlip: ...
0d71d37b0e08d11f6b6d9f59a4b202dfabc98fc1
<|skeleton|> class RoutingSlip: """Endpoint resource update and return routing slip by number.""" def get(routing_slip_number: str): """Get routing slip.""" <|body_0|> def patch(routing_slip_number: str): """Patch routing slip.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoutingSlip: """Endpoint resource update and return routing slip by number.""" def get(routing_slip_number: str): """Get routing slip.""" current_app.logger.info('<RoutingSlips.get') try: response = RoutingSlipService.validate_and_find_by_number(routing_slip_number) ...
the_stack_v2_python_sparse
pay-api/src/pay_api/resources/fas/routing_slip.py
bcgov/sbc-pay
train
6
71ac6e9debfe67d31456d98c384332719e0bc816
[ "parser = subparsers.add_parser('set', help=textwrap.fill('Set contents of pattoo DB.', width=width))\nself.subparsers = parser.add_subparsers(dest='qualifier')\nfor name in dir(self):\n attribute = getattr(self, name)\n if ismethod(attribute):\n if name.startswith('_'):\n continue\n ...
<|body_start_0|> parser = subparsers.add_parser('set', help=textwrap.fill('Set contents of pattoo DB.', width=width)) self.subparsers = parser.add_subparsers(dest='qualifier') for name in dir(self): attribute = getattr(self, name) if ismethod(attribute): i...
Class gathers all CLI 'set' information.
_Set
[ "GPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Set: """Class gathers all CLI 'set' information.""" def __init__(self, subparsers, width=80): """Intialize the class.""" <|body_0|> def language(self, width=80): """Process set language CLI commands. Args: width: Width of the help text string to STDIO before wra...
stack_v2_sparse_classes_36k_train_021272
14,703
permissive
[ { "docstring": "Intialize the class.", "name": "__init__", "signature": "def __init__(self, subparsers, width=80)" }, { "docstring": "Process set language CLI commands. Args: width: Width of the help text string to STDIO before wrapping Returns: None", "name": "language", "signature": "d...
3
stack_v2_sparse_classes_30k_train_005541
Implement the Python class `_Set` described below. Class description: Class gathers all CLI 'set' information. Method signatures and docstrings: - def __init__(self, subparsers, width=80): Intialize the class. - def language(self, width=80): Process set language CLI commands. Args: width: Width of the help text strin...
Implement the Python class `_Set` described below. Class description: Class gathers all CLI 'set' information. Method signatures and docstrings: - def __init__(self, subparsers, width=80): Intialize the class. - def language(self, width=80): Process set language CLI commands. Args: width: Width of the help text strin...
57bd3e82e49d51e3426b13ad53ed8326a735ce29
<|skeleton|> class _Set: """Class gathers all CLI 'set' information.""" def __init__(self, subparsers, width=80): """Intialize the class.""" <|body_0|> def language(self, width=80): """Process set language CLI commands. Args: width: Width of the help text string to STDIO before wra...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _Set: """Class gathers all CLI 'set' information.""" def __init__(self, subparsers, width=80): """Intialize the class.""" parser = subparsers.add_parser('set', help=textwrap.fill('Set contents of pattoo DB.', width=width)) self.subparsers = parser.add_subparsers(dest='qualifier') ...
the_stack_v2_python_sparse
pattoo/cli/cli.py
palisadoes/pattoo
train
0
09a14e54f163fa58acb6911b81fb11fccad20ff7
[ "if str(x) == str(x)[::-1]:\n return True\nelse:\n return False", "if x < 0 or (x % 10 == 0 and x != 0):\n return False\ni = 0\nwhile x > i:\n i = i * 10 + x % 10\n x /= 10\nreturn x == i or x == i / 10" ]
<|body_start_0|> if str(x) == str(x)[::-1]: return True else: return False <|end_body_0|> <|body_start_1|> if x < 0 or (x % 10 == 0 and x != 0): return False i = 0 while x > i: i = i * 10 + x % 10 x /= 10 return...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def isPalindromes(self, x): """:type x: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if str(x) == str(x)[::-1]: return True else:...
stack_v2_sparse_classes_36k_train_021273
744
no_license
[ { "docstring": ":type x: int :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, x)" }, { "docstring": ":type x: int :rtype: bool", "name": "isPalindromes", "signature": "def isPalindromes(self, x)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def isPalindromes(self, x): :type x: int :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def isPalindromes(self, x): :type x: int :rtype: bool <|skeleton|> class Solution: def isPalindrome(self, x): ...
069bb0b751ef7f469036b9897436eb5d138ffa24
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def isPalindromes(self, x): """:type x: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" if str(x) == str(x)[::-1]: return True else: return False def isPalindromes(self, x): """:type x: int :rtype: bool""" if x < 0 or (x % 10 == 0 and x != 0): retu...
the_stack_v2_python_sparse
算法/4、回文数.py
RichieSong/algorithm
train
0
5b466c63247fe1f17e39d4f876dd8a55b54e9de3
[ "self.operation_obj = operation_obj\nself.image = image\nself.name = name\nself.instance = instance\nself.flavor = flavor\nself.region = region\nself.bandwidth = bandwidth\nself.snapshot = snapshot\nself.size = size\nself.kwargs = kwargs", "if kwargs is None:\n return None\ncontext = ScaleContext('', '')\nfor ...
<|body_start_0|> self.operation_obj = operation_obj self.image = image self.name = name self.instance = instance self.flavor = flavor self.region = region self.bandwidth = bandwidth self.snapshot = snapshot self.size = size self.kwargs = kw...
ScaleContext
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScaleContext: def __init__(self, name='ali', operation_obj='instance', image=None, instance=None, flavor=None, region=None, bandwidth=None, snapshot=None, size=None, **kwargs): """:param instance: id of instance :param name :the name of cloud :param operation_obj:volume or instance :para...
stack_v2_sparse_classes_36k_train_021274
1,716
no_license
[ { "docstring": ":param instance: id of instance :param name :the name of cloud :param operation_obj:volume or instance :param image:image id :param flavor: flavor like small.tiny1 :param region: region :param bandwidth:400 :param snapshot: snapshot of volume :param size: size of volume :param kwargs: other args...
2
stack_v2_sparse_classes_30k_train_015900
Implement the Python class `ScaleContext` described below. Class description: Implement the ScaleContext class. Method signatures and docstrings: - def __init__(self, name='ali', operation_obj='instance', image=None, instance=None, flavor=None, region=None, bandwidth=None, snapshot=None, size=None, **kwargs): :param ...
Implement the Python class `ScaleContext` described below. Class description: Implement the ScaleContext class. Method signatures and docstrings: - def __init__(self, name='ali', operation_obj='instance', image=None, instance=None, flavor=None, region=None, bandwidth=None, snapshot=None, size=None, **kwargs): :param ...
d26ddb2fe7aaecdff4c1dfcd495b53c4086c5360
<|skeleton|> class ScaleContext: def __init__(self, name='ali', operation_obj='instance', image=None, instance=None, flavor=None, region=None, bandwidth=None, snapshot=None, size=None, **kwargs): """:param instance: id of instance :param name :the name of cloud :param operation_obj:volume or instance :para...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScaleContext: def __init__(self, name='ali', operation_obj='instance', image=None, instance=None, flavor=None, region=None, bandwidth=None, snapshot=None, size=None, **kwargs): """:param instance: id of instance :param name :the name of cloud :param operation_obj:volume or instance :param image:image ...
the_stack_v2_python_sparse
scaling/_scaling/context.py
wjybluse/cloudsdk
train
0
1af32c233fa1289e2541dbf6607a6f358cef0859
[ "try:\n search = request.GET.get('search')\n out_of_stock = request.GET.get('out_of_stock')\n spare = self.get_filter_objects(Spare, brand_model=brand_model_id, store=store_id)\n if search:\n spare = spare.filter(Q(spare_id__icontains=search) | Q(spare_name__icontains=search))\n if out_of_stoc...
<|body_start_0|> try: search = request.GET.get('search') out_of_stock = request.GET.get('out_of_stock') spare = self.get_filter_objects(Spare, brand_model=brand_model_id, store=store_id) if search: spare = spare.filter(Q(spare_id__icontains=search)...
SpareList
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpareList: def get(self, request, store_id, brand_model_id): """return a list of spares for particular model :param request: @query_param search=search_text - to search the spares out_of_stock=true - to get only out of stock Note - we can use both at same time :) :param store_id :param b...
stack_v2_sparse_classes_36k_train_021275
23,745
permissive
[ { "docstring": "return a list of spares for particular model :param request: @query_param search=search_text - to search the spares out_of_stock=true - to get only out of stock Note - we can use both at same time :) :param store_id :param brand_model_id: :return:", "name": "get", "signature": "def get(s...
2
stack_v2_sparse_classes_30k_train_012385
Implement the Python class `SpareList` described below. Class description: Implement the SpareList class. Method signatures and docstrings: - def get(self, request, store_id, brand_model_id): return a list of spares for particular model :param request: @query_param search=search_text - to search the spares out_of_sto...
Implement the Python class `SpareList` described below. Class description: Implement the SpareList class. Method signatures and docstrings: - def get(self, request, store_id, brand_model_id): return a list of spares for particular model :param request: @query_param search=search_text - to search the spares out_of_sto...
1e31affddf60d2de72445a85dd2055bdeba6f670
<|skeleton|> class SpareList: def get(self, request, store_id, brand_model_id): """return a list of spares for particular model :param request: @query_param search=search_text - to search the spares out_of_stock=true - to get only out of stock Note - we can use both at same time :) :param store_id :param b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpareList: def get(self, request, store_id, brand_model_id): """return a list of spares for particular model :param request: @query_param search=search_text - to search the spares out_of_stock=true - to get only out of stock Note - we can use both at same time :) :param store_id :param brand_model_id:...
the_stack_v2_python_sparse
the_mechanic_backend/v0/stock/views.py
muthukumar4999/the-mechanic-backend
train
0
76ce83894187cfc171dc9f92cbb72c68ebc74cb5
[ "self.listedQValuesDict = {}\nself.inputFiles = inputFiles\nself.pertQValuesDict = self.scientificNotation(pertDict)\nself.fileReconstruction()\nself.printInput(workingDir)", "for key, value in pertDict.items():\n pertDict[key] = '%.3E' % Decimal(str(value))\nreturn pertDict", "for line in lines:\n line =...
<|body_start_0|> self.listedQValuesDict = {} self.inputFiles = inputFiles self.pertQValuesDict = self.scientificNotation(pertDict) self.fileReconstruction() self.printInput(workingDir) <|end_body_0|> <|body_start_1|> for key, value in pertDict.items(): pertDi...
Parses the PHISICS Qvalues library and replaces the nominal values by the perturbed values.
QValuesParser
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QValuesParser: """Parses the PHISICS Qvalues library and replaces the nominal values by the perturbed values.""" def __init__(self, inputFiles, workingDir, **pertDict): """Constructor. @ In, inputFiles, string, Qvalues library file. @ In, workingDir, string, path to working directory...
stack_v2_sparse_classes_36k_train_021276
4,140
permissive
[ { "docstring": "Constructor. @ In, inputFiles, string, Qvalues library file. @ In, workingDir, string, path to working directory @ In, pertDict, dictionary, dictionary of perturbed variables @ Out, None", "name": "__init__", "signature": "def __init__(self, inputFiles, workingDir, **pertDict)" }, { ...
6
stack_v2_sparse_classes_30k_train_012267
Implement the Python class `QValuesParser` described below. Class description: Parses the PHISICS Qvalues library and replaces the nominal values by the perturbed values. Method signatures and docstrings: - def __init__(self, inputFiles, workingDir, **pertDict): Constructor. @ In, inputFiles, string, Qvalues library ...
Implement the Python class `QValuesParser` described below. Class description: Parses the PHISICS Qvalues library and replaces the nominal values by the perturbed values. Method signatures and docstrings: - def __init__(self, inputFiles, workingDir, **pertDict): Constructor. @ In, inputFiles, string, Qvalues library ...
2b16e7aa3325fe84cab2477947a951414c635381
<|skeleton|> class QValuesParser: """Parses the PHISICS Qvalues library and replaces the nominal values by the perturbed values.""" def __init__(self, inputFiles, workingDir, **pertDict): """Constructor. @ In, inputFiles, string, Qvalues library file. @ In, workingDir, string, path to working directory...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QValuesParser: """Parses the PHISICS Qvalues library and replaces the nominal values by the perturbed values.""" def __init__(self, inputFiles, workingDir, **pertDict): """Constructor. @ In, inputFiles, string, Qvalues library file. @ In, workingDir, string, path to working directory @ In, pertDi...
the_stack_v2_python_sparse
ravenframework/CodeInterfaceClasses/PHISICS/QValuesParser.py
idaholab/raven
train
201
62f41e4977bc52946955b633e57b6b0cd6cf7743
[ "self.cast = cast\nself.delimiter = delimiter\nself.strip = strip", "transform = lambda s: self.cast(s.strip(self.strip))\nsplitter = shlex(value, posix=True)\nsplitter.whitespace = self.delimiter\nsplitter.whitespace_split = True\nreturn [transform(s) for s in splitter]" ]
<|body_start_0|> self.cast = cast self.delimiter = delimiter self.strip = strip <|end_body_0|> <|body_start_1|> transform = lambda s: self.cast(s.strip(self.strip)) splitter = shlex(value, posix=True) splitter.whitespace = self.delimiter splitter.whitespace_split...
Produces a csv parser that return a list of transformed elements.
Csv
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Csv: """Produces a csv parser that return a list of transformed elements.""" def __init__(self, cast=text_type, delimiter=',', strip=string.whitespace): """Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters char...
stack_v2_sparse_classes_36k_train_021277
5,980
permissive
[ { "docstring": "Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters chars passed to shlex. strip -- string of non-relevant characters to be passed to str.strip after the split.", "name": "__init__", "signature": "def __init__(self, ...
2
null
Implement the Python class `Csv` described below. Class description: Produces a csv parser that return a list of transformed elements. Method signatures and docstrings: - def __init__(self, cast=text_type, delimiter=',', strip=string.whitespace): Parameters: cast -- callable that transforms the item just before it's ...
Implement the Python class `Csv` described below. Class description: Produces a csv parser that return a list of transformed elements. Method signatures and docstrings: - def __init__(self, cast=text_type, delimiter=',', strip=string.whitespace): Parameters: cast -- callable that transforms the item just before it's ...
c87fdf49ae040668323d1a034aa407cfe23c4a1d
<|skeleton|> class Csv: """Produces a csv parser that return a list of transformed elements.""" def __init__(self, cast=text_type, delimiter=',', strip=string.whitespace): """Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters char...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Csv: """Produces a csv parser that return a list of transformed elements.""" def __init__(self, cast=text_type, delimiter=',', strip=string.whitespace): """Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters chars passed to s...
the_stack_v2_python_sparse
jvbhw/Lib/site-packages/decouple.py
wahello/jvb
train
0
78d1e8eadfe6d7ee15745ffb7d2119c3a8c76c63
[ "super(AppIdentityExternalStub, self).__init__(service_name)\nself._location = location\nself._max_request_size = apiproxy_stub.MAX_REQUEST_SIZE\nself._service_name = service_name", "assert service == self._service_name, 'Expected \"%s\" service name, was \"%s\"' % (self._service_name, service)\nif request.ByteSi...
<|body_start_0|> super(AppIdentityExternalStub, self).__init__(service_name) self._location = location self._max_request_size = apiproxy_stub.MAX_REQUEST_SIZE self._service_name = service_name <|end_body_0|> <|body_start_1|> assert service == self._service_name, 'Expected "%s" s...
A proxy for the AppIdentityService API.
AppIdentityExternalStub
[ "Apache-2.0", "LGPL-2.1-or-later", "BSD-3-Clause", "MIT", "GPL-2.0-or-later", "MPL-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppIdentityExternalStub: """A proxy for the AppIdentityService API.""" def __init__(self, location, service_name='app_identity_service'): """Constructor. Args: location: The location of a server that handles App Identity requests.""" <|body_0|> def MakeSyncCall(self, ser...
stack_v2_sparse_classes_36k_train_021278
2,773
permissive
[ { "docstring": "Constructor. Args: location: The location of a server that handles App Identity requests.", "name": "__init__", "signature": "def __init__(self, location, service_name='app_identity_service')" }, { "docstring": "The main RPC entry point. Args: service: Must be name as provided to...
2
null
Implement the Python class `AppIdentityExternalStub` described below. Class description: A proxy for the AppIdentityService API. Method signatures and docstrings: - def __init__(self, location, service_name='app_identity_service'): Constructor. Args: location: The location of a server that handles App Identity reques...
Implement the Python class `AppIdentityExternalStub` described below. Class description: A proxy for the AppIdentityService API. Method signatures and docstrings: - def __init__(self, location, service_name='app_identity_service'): Constructor. Args: location: The location of a server that handles App Identity reques...
be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f
<|skeleton|> class AppIdentityExternalStub: """A proxy for the AppIdentityService API.""" def __init__(self, location, service_name='app_identity_service'): """Constructor. Args: location: The location of a server that handles App Identity requests.""" <|body_0|> def MakeSyncCall(self, ser...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AppIdentityExternalStub: """A proxy for the AppIdentityService API.""" def __init__(self, location, service_name='app_identity_service'): """Constructor. Args: location: The location of a server that handles App Identity requests.""" super(AppIdentityExternalStub, self).__init__(service_n...
the_stack_v2_python_sparse
AppServer/google/appengine/api/app_identity/app_identity_external_stub.py
obino/appscale
train
1
79bbafce1f0cc501924a33fd47d599bfc9859d0f
[ "self.id = id\nself.server_relativeurl = server_relativeurl\nself.title = title\nself.url = url\nself.webid = webid", "if dictionary is None:\n return None\nid = dictionary.get('id')\nserver_relativeurl = dictionary.get('serverRelativeurl')\ntitle = dictionary.get('title')\nurl = dictionary.get('url')\nwebid =...
<|body_start_0|> self.id = id self.server_relativeurl = server_relativeurl self.title = title self.url = url self.webid = webid <|end_body_0|> <|body_start_1|> if dictionary is None: return None id = dictionary.get('id') server_relativeurl = d...
Implementation of the 'SiteIdentity' model. O365 Sharepoint online Site Identity. These may be obtained by Graph/REST or PnP cmdlets. All fields are case insensitive. Attributes: id (string): Unique guid for the site in SPO. This is a unqiue identifier that can be used to compare sites. server_relativeurl (string): Opt...
SiteIdentity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SiteIdentity: """Implementation of the 'SiteIdentity' model. O365 Sharepoint online Site Identity. These may be obtained by Graph/REST or PnP cmdlets. All fields are case insensitive. Attributes: id (string): Unique guid for the site in SPO. This is a unqiue identifier that can be used to compare...
stack_v2_sparse_classes_36k_train_021279
2,543
permissive
[ { "docstring": "Constructor for the SiteIdentity class", "name": "__init__", "signature": "def __init__(self, id=None, server_relativeurl=None, title=None, url=None, webid=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary re...
2
stack_v2_sparse_classes_30k_train_016419
Implement the Python class `SiteIdentity` described below. Class description: Implementation of the 'SiteIdentity' model. O365 Sharepoint online Site Identity. These may be obtained by Graph/REST or PnP cmdlets. All fields are case insensitive. Attributes: id (string): Unique guid for the site in SPO. This is a unqiue...
Implement the Python class `SiteIdentity` described below. Class description: Implementation of the 'SiteIdentity' model. O365 Sharepoint online Site Identity. These may be obtained by Graph/REST or PnP cmdlets. All fields are case insensitive. Attributes: id (string): Unique guid for the site in SPO. This is a unqiue...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class SiteIdentity: """Implementation of the 'SiteIdentity' model. O365 Sharepoint online Site Identity. These may be obtained by Graph/REST or PnP cmdlets. All fields are case insensitive. Attributes: id (string): Unique guid for the site in SPO. This is a unqiue identifier that can be used to compare...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SiteIdentity: """Implementation of the 'SiteIdentity' model. O365 Sharepoint online Site Identity. These may be obtained by Graph/REST or PnP cmdlets. All fields are case insensitive. Attributes: id (string): Unique guid for the site in SPO. This is a unqiue identifier that can be used to compare sites. serve...
the_stack_v2_python_sparse
cohesity_management_sdk/models/site_identity.py
cohesity/management-sdk-python
train
24
5a5b61ac7be37418920c7208dc317f8df84c9461
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
A set of methods for managing Service resources.
ServiceServiceServicer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceServiceServicer: """A set of methods for managing Service resources.""" def Get(self, request, context): """Returns the specified service.""" <|body_0|> def List(self, request, context): """Retrieves the list of services.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_36k_train_021280
4,669
permissive
[ { "docstring": "Returns the specified service.", "name": "Get", "signature": "def Get(self, request, context)" }, { "docstring": "Retrieves the list of services.", "name": "List", "signature": "def List(self, request, context)" } ]
2
null
Implement the Python class `ServiceServiceServicer` described below. Class description: A set of methods for managing Service resources. Method signatures and docstrings: - def Get(self, request, context): Returns the specified service. - def List(self, request, context): Retrieves the list of services.
Implement the Python class `ServiceServiceServicer` described below. Class description: A set of methods for managing Service resources. Method signatures and docstrings: - def Get(self, request, context): Returns the specified service. - def List(self, request, context): Retrieves the list of services. <|skeleton|>...
b906a014dd893e2697864e1e48e814a8d9fbc48c
<|skeleton|> class ServiceServiceServicer: """A set of methods for managing Service resources.""" def Get(self, request, context): """Returns the specified service.""" <|body_0|> def List(self, request, context): """Retrieves the list of services.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServiceServiceServicer: """A set of methods for managing Service resources.""" def Get(self, request, context): """Returns the specified service.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Me...
the_stack_v2_python_sparse
yandex/cloud/billing/v1/service_service_pb2_grpc.py
yandex-cloud/python-sdk
train
63
6f0a1161c58a38699e3b31b86f68831b24bc9c89
[ "def dfs(node):\n if not node:\n return 0\n count = 1\n for child in (node.left, node.right):\n if not child:\n continue\n count_child = dfs(child)\n if child.val == node.val + 1:\n count = max(count, count_child + 1)\n self.max_count = max(self.max_coun...
<|body_start_0|> def dfs(node): if not node: return 0 count = 1 for child in (node.left, node.right): if not child: continue count_child = dfs(child) if child.val == node.val + 1: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def longestConsecutive_verbose(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> def dfs(node): ...
stack_v2_sparse_classes_36k_train_021281
2,981
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "longestConsecutive", "signature": "def longestConsecutive(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "longestConsecutive_verbose", "signature": "def longestConsecutive_verbose(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive(self, root): :type root: TreeNode :rtype: int - def longestConsecutive_verbose(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive(self, root): :type root: TreeNode :rtype: int - def longestConsecutive_verbose(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: ...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def longestConsecutive_verbose(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" def dfs(node): if not node: return 0 count = 1 for child in (node.left, node.right): if not child: continue ...
the_stack_v2_python_sparse
src/lt_298.py
oxhead/CodingYourWay
train
0
14f1b321a066ecbd3d8f22edc6677cb6b51d98b4
[ "input_statistics_generator = math_utils.InputStatisticsFromMiniBatch(dtype=model.dtype, num_features=model.num_features)\nif state_manager is None:\n state_manager = state_management.PassthroughStateManager()\nif optimizer is None:\n optimizer = train.AdamOptimizer(0.02)\nself._model = model\nmodel_fn = ts_h...
<|body_start_0|> input_statistics_generator = math_utils.InputStatisticsFromMiniBatch(dtype=model.dtype, num_features=model.num_features) if state_manager is None: state_manager = state_management.PassthroughStateManager() if optimizer is None: optimizer = train.AdamOptim...
An Estimator to fit and evaluate a time series model.
TimeSeriesRegressor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeSeriesRegressor: """An Estimator to fit and evaluate a time series model.""" def __init__(self, model, state_manager=None, optimizer=None, model_dir=None, config=None): """Initialize the Estimator. Args: model: The time series model to wrap (inheriting from TimeSeriesModel). stat...
stack_v2_sparse_classes_36k_train_021282
19,271
permissive
[ { "docstring": "Initialize the Estimator. Args: model: The time series model to wrap (inheriting from TimeSeriesModel). state_manager: The state manager to use, or (by default) PassthroughStateManager if none is needed. optimizer: The optimization algorithm to use when training, inheriting from tf.train.Optimiz...
2
null
Implement the Python class `TimeSeriesRegressor` described below. Class description: An Estimator to fit and evaluate a time series model. Method signatures and docstrings: - def __init__(self, model, state_manager=None, optimizer=None, model_dir=None, config=None): Initialize the Estimator. Args: model: The time ser...
Implement the Python class `TimeSeriesRegressor` described below. Class description: An Estimator to fit and evaluate a time series model. Method signatures and docstrings: - def __init__(self, model, state_manager=None, optimizer=None, model_dir=None, config=None): Initialize the Estimator. Args: model: The time ser...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class TimeSeriesRegressor: """An Estimator to fit and evaluate a time series model.""" def __init__(self, model, state_manager=None, optimizer=None, model_dir=None, config=None): """Initialize the Estimator. Args: model: The time series model to wrap (inheriting from TimeSeriesModel). stat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TimeSeriesRegressor: """An Estimator to fit and evaluate a time series model.""" def __init__(self, model, state_manager=None, optimizer=None, model_dir=None, config=None): """Initialize the Estimator. Args: model: The time series model to wrap (inheriting from TimeSeriesModel). state_manager: Th...
the_stack_v2_python_sparse
Tensorflow_Pandas_Numpy/source3.6/tensorflow/contrib/timeseries/python/timeseries/estimators.py
ryfeus/lambda-packs
train
1,283
6a11fa2b594760e959360175ceb659e17c5c0439
[ "record = []\nsq_sum = 0\nse_n = n\nwhile se_n != 1:\n sq_sum = 0\n while se_n > 0:\n sq_sum += se_n % 10 * (se_n % 10)\n se_n = se_n / 10\n if sq_sum in record:\n return False\n record.append(sq_sum)\n se_n = sq_sum\nreturn True", "nStr = str(n)\nlength = len(nStr)\nsum = 0\ni...
<|body_start_0|> record = [] sq_sum = 0 se_n = n while se_n != 1: sq_sum = 0 while se_n > 0: sq_sum += se_n % 10 * (se_n % 10) se_n = se_n / 10 if sq_sum in record: return False record.append(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isHappy(self, n): """:type n: int :rtype: bool""" <|body_0|> def isHappy1(self, n): """:type n: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> record = [] sq_sum = 0 se_n = n while se_n != 1: ...
stack_v2_sparse_classes_36k_train_021283
1,464
no_license
[ { "docstring": ":type n: int :rtype: bool", "name": "isHappy", "signature": "def isHappy(self, n)" }, { "docstring": ":type n: int :rtype: bool", "name": "isHappy1", "signature": "def isHappy1(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_011279
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isHappy(self, n): :type n: int :rtype: bool - def isHappy1(self, n): :type n: int :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isHappy(self, n): :type n: int :rtype: bool - def isHappy1(self, n): :type n: int :rtype: bool <|skeleton|> class Solution: def isHappy(self, n): """:type n: in...
8793e0f58a0e586f89cd26f477a8d7288389a080
<|skeleton|> class Solution: def isHappy(self, n): """:type n: int :rtype: bool""" <|body_0|> def isHappy1(self, n): """:type n: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isHappy(self, n): """:type n: int :rtype: bool""" record = [] sq_sum = 0 se_n = n while se_n != 1: sq_sum = 0 while se_n > 0: sq_sum += se_n % 10 * (se_n % 10) se_n = se_n / 10 if sq_sum i...
the_stack_v2_python_sparse
python-leetcode/src/number/happyNumber.py
zcg741/leetcode
train
0
76c4b640cd166fce2fdf6f5fffb67a2c972497d8
[ "acl.enforce('cron_triggers:get', context.ctx())\nLOG.debug('Fetch cron trigger [identifier=%s]', identifier)\nif fields and 'id' not in fields:\n fields.insert(0, 'id')\ndb_model = rest_utils.rest_retry_on_db_error(db_api.get_cron_trigger)(identifier, fields=fields)\nif fields:\n return resources.CronTrigger...
<|body_start_0|> acl.enforce('cron_triggers:get', context.ctx()) LOG.debug('Fetch cron trigger [identifier=%s]', identifier) if fields and 'id' not in fields: fields.insert(0, 'id') db_model = rest_utils.rest_retry_on_db_error(db_api.get_cron_trigger)(identifier, fields=field...
CronTriggersController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CronTriggersController: def get(self, identifier, fields=''): """Returns the named cron_trigger. :param identifier: Id or name of cron trigger to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if ...
stack_v2_sparse_classes_36k_train_021284
8,745
permissive
[ { "docstring": "Returns the named cron_trigger. :param identifier: Id or name of cron trigger to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's not provided.", "name": "get", "signature": "def get(self, i...
4
stack_v2_sparse_classes_30k_train_005583
Implement the Python class `CronTriggersController` described below. Class description: Implement the CronTriggersController class. Method signatures and docstrings: - def get(self, identifier, fields=''): Returns the named cron_trigger. :param identifier: Id or name of cron trigger to retrieve :param fields: Optiona...
Implement the Python class `CronTriggersController` described below. Class description: Implement the CronTriggersController class. Method signatures and docstrings: - def get(self, identifier, fields=''): Returns the named cron_trigger. :param identifier: Id or name of cron trigger to retrieve :param fields: Optiona...
7baff017d0cf01d19c44055ad201ca59131b9f94
<|skeleton|> class CronTriggersController: def get(self, identifier, fields=''): """Returns the named cron_trigger. :param identifier: Id or name of cron trigger to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CronTriggersController: def get(self, identifier, fields=''): """Returns the named cron_trigger. :param identifier: Id or name of cron trigger to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's not provi...
the_stack_v2_python_sparse
mistral/api/controllers/v2/cron_trigger.py
openstack/mistral
train
214
76c2520b0dcf2244178ab216bd453ee86868cecc
[ "super().__init__()\nself.accuracy = torchmetrics.Accuracy()\nself.roc_auc = torchmetrics.AUROC(num_classes=2)\nself.auc_score = torchmetrics.AUC()\nself.precision = torchmetrics.Precision()\nself.recall = torchmetrics.Recall()\nself.f1 = torchmetrics.F1()\nself.hamming_distance = torchmetrics.HammingDistance()\nse...
<|body_start_0|> super().__init__() self.accuracy = torchmetrics.Accuracy() self.roc_auc = torchmetrics.AUROC(num_classes=2) self.auc_score = torchmetrics.AUC() self.precision = torchmetrics.Precision() self.recall = torchmetrics.Recall() self.f1 = torchmetrics.F1...
MetricLogger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricLogger: def __init__(self): """Initialize the metrics.""" <|body_0|> def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: """Update the metrics given the predictions and the ground truth.""" <|body_1|> def compute(self) -> dict: ...
stack_v2_sparse_classes_36k_train_021285
1,953
permissive
[ { "docstring": "Initialize the metrics.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Update the metrics given the predictions and the ground truth.", "name": "update", "signature": "def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None" }, ...
3
stack_v2_sparse_classes_30k_train_020265
Implement the Python class `MetricLogger` described below. Class description: Implement the MetricLogger class. Method signatures and docstrings: - def __init__(self): Initialize the metrics. - def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: Update the metrics given the predictions and the groun...
Implement the Python class `MetricLogger` described below. Class description: Implement the MetricLogger class. Method signatures and docstrings: - def __init__(self): Initialize the metrics. - def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: Update the metrics given the predictions and the groun...
a5880c1e4051603d65672996b7c8ff204dabbe37
<|skeleton|> class MetricLogger: def __init__(self): """Initialize the metrics.""" <|body_0|> def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: """Update the metrics given the predictions and the ground truth.""" <|body_1|> def compute(self) -> dict: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetricLogger: def __init__(self): """Initialize the metrics.""" super().__init__() self.accuracy = torchmetrics.Accuracy() self.roc_auc = torchmetrics.AUROC(num_classes=2) self.auc_score = torchmetrics.AUC() self.precision = torchmetrics.Precision() self...
the_stack_v2_python_sparse
care_nl_ica/metrics/metric_logger.py
rpatrik96/nl-causal-representations
train
9
52766b63250e46f75fe96371732b49b2efd7345b
[ "kwargs = super().get_form_kwargs()\nif hasattr(self, 'object'):\n kwargs.update({'instance': self.object})\nkwargs.update({'user': self.request.user})\nreturn kwargs", "self.object = form.save()\nself.object.save()\nfor permission in permissions:\n for item in permission['permissions']:\n if item[0]...
<|body_start_0|> kwargs = super().get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) kwargs.update({'user': self.request.user}) return kwargs <|end_body_0|> <|body_start_1|> self.object = form.save() self.object.save() ...
Edit account profile details
Edit
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Edit: """Edit account profile details""" def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" <|body_0|> def form_valid(self, form): """Valid form method""" <|body_1|> def get_context_data(self, *, object_list=Non...
stack_v2_sparse_classes_36k_train_021286
20,739
permissive
[ { "docstring": "Return the keyword arguments for instantiating the form.", "name": "get_form_kwargs", "signature": "def get_form_kwargs(self)" }, { "docstring": "Valid form method", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "Get the context...
4
stack_v2_sparse_classes_30k_train_015629
Implement the Python class `Edit` described below. Class description: Edit account profile details Method signatures and docstrings: - def get_form_kwargs(self): Return the keyword arguments for instantiating the form. - def form_valid(self, form): Valid form method - def get_context_data(self, *, object_list=None, *...
Implement the Python class `Edit` described below. Class description: Edit account profile details Method signatures and docstrings: - def get_form_kwargs(self): Return the keyword arguments for instantiating the form. - def form_valid(self, form): Valid form method - def get_context_data(self, *, object_list=None, *...
f3f8354bf164fcfe86d597cdbc28b0e3b7b73bd1
<|skeleton|> class Edit: """Edit account profile details""" def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" <|body_0|> def form_valid(self, form): """Valid form method""" <|body_1|> def get_context_data(self, *, object_list=Non...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Edit: """Edit account profile details""" def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" kwargs = super().get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) kwargs.update({'user': sel...
the_stack_v2_python_sparse
seshat/account/views.py
XecusM/SESHAT
train
0
763ef10f4ff65d3949f6b6c54dd3afaf4695e5fa
[ "permissions = list(self.own_permissions.all())\nfor parent in self.parents.all():\n permissions += list(parent.permissions.all())\nself.permissions.set(permissions)\nfor sub in self.sub_groups.all():\n sub.update_permissions()", "subs = self.sub_groups.all()\nfor sub in self.sub_groups.all():\n subs = s...
<|body_start_0|> permissions = list(self.own_permissions.all()) for parent in self.parents.all(): permissions += list(parent.permissions.all()) self.permissions.set(permissions) for sub in self.sub_groups.all(): sub.update_permissions() <|end_body_0|> <|body_star...
A group that allow inheritance of permissions. The groups that a group will inherit from is given by the `parents` field. The permissions that this group has independently from its parents are given by the `own_permissions` field. The standard `permissions` field will contain the groups own permissions, and those it ha...
InheritanceGroup
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InheritanceGroup: """A group that allow inheritance of permissions. The groups that a group will inherit from is given by the `parents` field. The permissions that this group has independently from its parents are given by the `own_permissions` field. The standard `permissions` field will contain...
stack_v2_sparse_classes_36k_train_021287
16,403
no_license
[ { "docstring": "Update the permissions of this and all sub groups.", "name": "update_permissions", "signature": "def update_permissions(self)" }, { "docstring": "Return a queryset of all groups that inherits from this group.", "name": "get_sub_groups", "signature": "def get_sub_groups(se...
4
stack_v2_sparse_classes_30k_train_013298
Implement the Python class `InheritanceGroup` described below. Class description: A group that allow inheritance of permissions. The groups that a group will inherit from is given by the `parents` field. The permissions that this group has independently from its parents are given by the `own_permissions` field. The st...
Implement the Python class `InheritanceGroup` described below. Class description: A group that allow inheritance of permissions. The groups that a group will inherit from is given by the `parents` field. The permissions that this group has independently from its parents are given by the `own_permissions` field. The st...
708071d144b06ab289abdea6046437c40a81d230
<|skeleton|> class InheritanceGroup: """A group that allow inheritance of permissions. The groups that a group will inherit from is given by the `parents` field. The permissions that this group has independently from its parents are given by the `own_permissions` field. The standard `permissions` field will contain...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InheritanceGroup: """A group that allow inheritance of permissions. The groups that a group will inherit from is given by the `parents` field. The permissions that this group has independently from its parents are given by the `own_permissions` field. The standard `permissions` field will contain the groups o...
the_stack_v2_python_sparse
members/models.py
kalkins/buk-django
train
4
cc95fc34723ddc51a7162f768f2b4cae9ab980bd
[ "assert isinstance(errors, int) or errors in ('raise', 'ignore', 'report')\nself.function = function\nself.errors = errors\nself.error_count = 0", "try:\n return self.function(*args, **kwds)\nexcept Exception as e:\n self.error_count += 1\n if self.errors == 'raise':\n raise\n if self.errors ==...
<|body_start_0|> assert isinstance(errors, int) or errors in ('raise', 'ignore', 'report') self.function = function self.errors = errors self.error_count = 0 <|end_body_0|> <|body_start_1|> try: return self.function(*args, **kwds) except Exception as e: ...
Wraps a function call to catch and report exceptions.
LogErrors
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogErrors: """Wraps a function call to catch and report exceptions.""" def __init__(self, function, errors): """:param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning t...
stack_v2_sparse_classes_36k_train_021288
1,450
permissive
[ { "docstring": ":param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning to raise an exception 'ignore', meaning to ignore all errors 'report', meaning to report all errors", "name": "__init__",...
2
stack_v2_sparse_classes_30k_train_016935
Implement the Python class `LogErrors` described below. Class description: Wraps a function call to catch and report exceptions. Method signatures and docstrings: - def __init__(self, function, errors): :param function: the function to wrap :param errors: either a number, indicating how many errors to report before i...
Implement the Python class `LogErrors` described below. Class description: Wraps a function call to catch and report exceptions. Method signatures and docstrings: - def __init__(self, function, errors): :param function: the function to wrap :param errors: either a number, indicating how many errors to report before i...
fd97e6c651a4bbcade64733847f4eec8f7704b7c
<|skeleton|> class LogErrors: """Wraps a function call to catch and report exceptions.""" def __init__(self, function, errors): """:param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogErrors: """Wraps a function call to catch and report exceptions.""" def __init__(self, function, errors): """:param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning to raise an ex...
the_stack_v2_python_sparse
bibliopixel/util/log_errors.py
dr-aryone/BiblioPixel
train
2
acf96567c208484480fd8826de0a8cc841135fb1
[ "cardholder_name = card.name\ntransarmor_token = card.ta_token\ncredit_card_type = card.card_type\ncc_expiry = card.period\ntransaction = firstdata.FirstData(self.FIRST_DATA_KEY_ID, self.FIRST_DATA_HMAC_KEY, gateway_id=self.FIRST_DATA_GATEWAY_ID, password=self.FIRST_DATA_PASSWORD, transaction_type='00', cardholder_...
<|body_start_0|> cardholder_name = card.name transarmor_token = card.ta_token credit_card_type = card.card_type cc_expiry = card.period transaction = firstdata.FirstData(self.FIRST_DATA_KEY_ID, self.FIRST_DATA_HMAC_KEY, gateway_id=self.FIRST_DATA_GATEWAY_ID, password=self.FIRST_D...
TransArmorOperations
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransArmorOperations: def ta_purchase(self, card, amount, reference_no='', customer_ref='', reference_3=''): """# Purchase - # The method by which an amount of funds moving from clients credit card to merchants account # Supports "Refund transaction", "Void transaction". # # :param cardh...
stack_v2_sparse_classes_36k_train_021289
22,151
no_license
[ { "docstring": "# Purchase - # The method by which an amount of funds moving from clients credit card to merchants account # Supports \"Refund transaction\", \"Void transaction\". # # :param cardholder_name: The customer's name. The following characters will be stripped from this field: # ; ` \" / % as well as ...
3
null
Implement the Python class `TransArmorOperations` described below. Class description: Implement the TransArmorOperations class. Method signatures and docstrings: - def ta_purchase(self, card, amount, reference_no='', customer_ref='', reference_3=''): # Purchase - # The method by which an amount of funds moving from c...
Implement the Python class `TransArmorOperations` described below. Class description: Implement the TransArmorOperations class. Method signatures and docstrings: - def ta_purchase(self, card, amount, reference_no='', customer_ref='', reference_3=''): # Purchase - # The method by which an amount of funds moving from c...
a27cb847ea7698872b64f9c58e43ebf5aad5590d
<|skeleton|> class TransArmorOperations: def ta_purchase(self, card, amount, reference_no='', customer_ref='', reference_3=''): """# Purchase - # The method by which an amount of funds moving from clients credit card to merchants account # Supports "Refund transaction", "Void transaction". # # :param cardh...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransArmorOperations: def ta_purchase(self, card, amount, reference_no='', customer_ref='', reference_3=''): """# Purchase - # The method by which an amount of funds moving from clients credit card to merchants account # Supports "Refund transaction", "Void transaction". # # :param cardholder_name: Th...
the_stack_v2_python_sparse
payments/payment_operations.py
adam1978828/webapp1
train
1
5f95cbe2c79e6d95f0ab39ef3c8c52e4c136ae90
[ "transformations = getattr(config, transformation, [])\nif post_transformation:\n transformations += getattr(config, post_transformation, [])\nself.transformations = [image_transformer(name, config) for name in transformations]\nlogger.info(f'Creating ImageTransformations {transformations}')", "for transformer...
<|body_start_0|> transformations = getattr(config, transformation, []) if post_transformation: transformations += getattr(config, post_transformation, []) self.transformations = [image_transformer(name, config) for name in transformations] logger.info(f'Creating ImageTransfor...
ImageTransformations
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageTransformations: def __init__(self, config: Config, transformation: str, post_transformation: str=None) -> object: """Part that constructs a list of image transformers and run them in sequence to produce a transformed image""" <|body_0|> def run(self, image): ""...
stack_v2_sparse_classes_36k_train_021290
19,545
permissive
[ { "docstring": "Part that constructs a list of image transformers and run them in sequence to produce a transformed image", "name": "__init__", "signature": "def __init__(self, config: Config, transformation: str, post_transformation: str=None) -> object" }, { "docstring": "Run the list of tranf...
2
null
Implement the Python class `ImageTransformations` described below. Class description: Implement the ImageTransformations class. Method signatures and docstrings: - def __init__(self, config: Config, transformation: str, post_transformation: str=None) -> object: Part that constructs a list of image transformers and ru...
Implement the Python class `ImageTransformations` described below. Class description: Implement the ImageTransformations class. Method signatures and docstrings: - def __init__(self, config: Config, transformation: str, post_transformation: str=None) -> object: Part that constructs a list of image transformers and ru...
9f91ad1aaff054522b24c2c1e727d1a111e266f4
<|skeleton|> class ImageTransformations: def __init__(self, config: Config, transformation: str, post_transformation: str=None) -> object: """Part that constructs a list of image transformers and run them in sequence to produce a transformed image""" <|body_0|> def run(self, image): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageTransformations: def __init__(self, config: Config, transformation: str, post_transformation: str=None) -> object: """Part that constructs a list of image transformers and run them in sequence to produce a transformed image""" transformations = getattr(config, transformation, []) ...
the_stack_v2_python_sparse
donkeycar/parts/image_transformations.py
autorope/donkeycar
train
1,861
4b6949d3a58653779a2bdf2df0005703fda8f682
[ "result = self.validate_data(challenge_pk=kwargs.get('challenge_pk'), submission_pk=kwargs.get('pk'))\nif isinstance(result, Response):\n return result\nreturn super().retrieve(request, *args, **kwargs)", "try:\n challenge = Challenge.objects.get(id=challenge_pk)\nexcept Challenge.DoesNotExist:\n return ...
<|body_start_0|> result = self.validate_data(challenge_pk=kwargs.get('challenge_pk'), submission_pk=kwargs.get('pk')) if isinstance(result, Response): return result return super().retrieve(request, *args, **kwargs) <|end_body_0|> <|body_start_1|> try: challenge =...
Returns information about a specific Submission Normally used for when we want to open a page with the solution's code We want to give access to this submission only if: a) the requester is the author of the submission b) the requester has solved the associated challenge with max score
SubmissionDetailView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubmissionDetailView: """Returns information about a specific Submission Normally used for when we want to open a page with the solution's code We want to give access to this submission only if: a) the requester is the author of the submission b) the requester has solved the associated challenge ...
stack_v2_sparse_classes_36k_train_021291
24,750
no_license
[ { "docstring": "Get the submission", "name": "retrieve", "signature": "def retrieve(self, request, *args, **kwargs)" }, { "docstring": "Validate the given challenge_id, submission_id and their association", "name": "validate_data", "signature": "def validate_data(self, challenge_pk, subm...
2
null
Implement the Python class `SubmissionDetailView` described below. Class description: Returns information about a specific Submission Normally used for when we want to open a page with the solution's code We want to give access to this submission only if: a) the requester is the author of the submission b) the request...
Implement the Python class `SubmissionDetailView` described below. Class description: Returns information about a specific Submission Normally used for when we want to open a page with the solution's code We want to give access to this submission only if: a) the requester is the author of the submission b) the request...
d32a534a5ab248ffaae3697a25a453108c8d3f53
<|skeleton|> class SubmissionDetailView: """Returns information about a specific Submission Normally used for when we want to open a page with the solution's code We want to give access to this submission only if: a) the requester is the author of the submission b) the requester has solved the associated challenge ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubmissionDetailView: """Returns information about a specific Submission Normally used for when we want to open a page with the solution's code We want to give access to this submission only if: a) the requester is the author of the submission b) the requester has solved the associated challenge with max scor...
the_stack_v2_python_sparse
deadline_/challenges/views.py
two-man-army/deadline
train
18
c8d2327ba45c30d7f94e5db69adb649ece479fc4
[ "test = test_method()\ninput_str = 'test'\nself.assertEqual(test.check_palindrome(input_str), False)", "test = test_method()\ninput_str = 'racecar'\nself.assertEqual(test.check_palindrome(input_str), True)", "test = test_method()\ninput_str = 'deed'\nself.assertEqual(test.check_palindrome(input_str), True)", ...
<|body_start_0|> test = test_method() input_str = 'test' self.assertEqual(test.check_palindrome(input_str), False) <|end_body_0|> <|body_start_1|> test = test_method() input_str = 'racecar' self.assertEqual(test.check_palindrome(input_str), True) <|end_body_1|> <|body_s...
Test_Cases_ArraySet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_Cases_ArraySet: def test_1(self): """Test to verify working check_palindrome method""" <|body_0|> def test_2(self): """Test to verify working check_palindrome method""" <|body_1|> def test_3(self): """Test to verify working check_palindrome ...
stack_v2_sparse_classes_36k_train_021292
1,775
no_license
[ { "docstring": "Test to verify working check_palindrome method", "name": "test_1", "signature": "def test_1(self)" }, { "docstring": "Test to verify working check_palindrome method", "name": "test_2", "signature": "def test_2(self)" }, { "docstring": "Test to verify working check...
5
stack_v2_sparse_classes_30k_train_000395
Implement the Python class `Test_Cases_ArraySet` described below. Class description: Implement the Test_Cases_ArraySet class. Method signatures and docstrings: - def test_1(self): Test to verify working check_palindrome method - def test_2(self): Test to verify working check_palindrome method - def test_3(self): Test...
Implement the Python class `Test_Cases_ArraySet` described below. Class description: Implement the Test_Cases_ArraySet class. Method signatures and docstrings: - def test_1(self): Test to verify working check_palindrome method - def test_2(self): Test to verify working check_palindrome method - def test_3(self): Test...
31b182184e00dda5efba515824a6a3551fbd5870
<|skeleton|> class Test_Cases_ArraySet: def test_1(self): """Test to verify working check_palindrome method""" <|body_0|> def test_2(self): """Test to verify working check_palindrome method""" <|body_1|> def test_3(self): """Test to verify working check_palindrome ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_Cases_ArraySet: def test_1(self): """Test to verify working check_palindrome method""" test = test_method() input_str = 'test' self.assertEqual(test.check_palindrome(input_str), False) def test_2(self): """Test to verify working check_palindrome method""" ...
the_stack_v2_python_sparse
Lab 5/Test Cases.py
bryanee23/Advanced-Python-Programming
train
0
a6ca8abea8b7cba03a96189a05c45d3faacf2f22
[ "bound_clusters = []\nself.bound_cluster_vertices = []\nerasure_bound = []\nfor layer in self.graph.B.values():\n for bound in layer.values():\n for vertex, edge in bound.neighbors.values():\n if edge.qubit.erasure:\n cluster = self.graph.get_cluster(self.graph.cID, bound)\n ...
<|body_start_0|> bound_clusters = [] self.bound_cluster_vertices = [] erasure_bound = [] for layer in self.graph.B.values(): for bound in layer.values(): for vertex, edge in bound.neighbors.values(): if edge.qubit.erasure: ...
Union-Find Balanced Bloom-integrated decoder for the toric lattice (2D and 3D) Inherits all the class variables and methods of uf.planar and toric objects. Method resolution order: planar -> uf.planar -> toric -> uf.toric Initilized using the toric.__init__() function. And therefore has the addditions and replacements ...
planar
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class planar: """Union-Find Balanced Bloom-integrated decoder for the toric lattice (2D and 3D) Inherits all the class variables and methods of uf.planar and toric objects. Method resolution order: planar -> uf.planar -> toric -> uf.toric Initilized using the toric.__init__() function. And therefore ha...
stack_v2_sparse_classes_36k_train_021293
21,992
no_license
[ { "docstring": "For the planar lattice, in the case of erasures connected to the boundary, clusters need to be formed from the boundary, such that the shortest path from an anyon to the boundary is formed within the cluster tree. We loop over all edges connected to the boundary to find erasures and initate clus...
3
stack_v2_sparse_classes_30k_train_019144
Implement the Python class `planar` described below. Class description: Union-Find Balanced Bloom-integrated decoder for the toric lattice (2D and 3D) Inherits all the class variables and methods of uf.planar and toric objects. Method resolution order: planar -> uf.planar -> toric -> uf.toric Initilized using the tori...
Implement the Python class `planar` described below. Class description: Union-Find Balanced Bloom-integrated decoder for the toric lattice (2D and 3D) Inherits all the class variables and methods of uf.planar and toric objects. Method resolution order: planar -> uf.planar -> toric -> uf.toric Initilized using the tori...
8d952fc8d8d728086360e1718f43c0bc445f26b1
<|skeleton|> class planar: """Union-Find Balanced Bloom-integrated decoder for the toric lattice (2D and 3D) Inherits all the class variables and methods of uf.planar and toric objects. Method resolution order: planar -> uf.planar -> toric -> uf.toric Initilized using the toric.__init__() function. And therefore ha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class planar: """Union-Find Balanced Bloom-integrated decoder for the toric lattice (2D and 3D) Inherits all the class variables and methods of uf.planar and toric objects. Method resolution order: planar -> uf.planar -> toric -> uf.toric Initilized using the toric.__init__() function. And therefore has the addditi...
the_stack_v2_python_sparse
oopsc/decoder/ufbb.py
Poeloe/oop_surface_code
train
3
5c8bf7b8334da03f4bbc466cfe9538442c47deb2
[ "SparkReaderWriter.__init__(self, spark_session, None)\nDataFrameReader._jreader = HiveContext(sparkContext=spark_session.sparkContext)._ssql_ctx.read()\nDataFrameReader._spark = spark_session", "db_func = CommonDBFunc()\ndriver = db_func.get_db_driver(db_name)\ngp_config = ConfigInit().read_python_properties(f'{...
<|body_start_0|> SparkReaderWriter.__init__(self, spark_session, None) DataFrameReader._jreader = HiveContext(sparkContext=spark_session.sparkContext)._ssql_ctx.read() DataFrameReader._spark = spark_session <|end_body_0|> <|body_start_1|> db_func = CommonDBFunc() driver = db_fun...
兼容原始read函数
SparkReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SparkReader: """兼容原始read函数""" def __init__(self, spark_session): """初始化 :param spark_session: SparkSession""" <|body_0|> def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): """:param db_name: :param database_env: :param datab...
stack_v2_sparse_classes_36k_train_021294
1,366
no_license
[ { "docstring": "初始化 :param spark_session: SparkSession", "name": "__init__", "signature": "def __init__(self, spark_session)" }, { "docstring": ":param db_name: :param database_env: :param databases: :param query_sql_or_table: :param options: :return:", "name": "relational_db", "signatur...
2
stack_v2_sparse_classes_30k_train_004861
Implement the Python class `SparkReader` described below. Class description: 兼容原始read函数 Method signatures and docstrings: - def __init__(self, spark_session): 初始化 :param spark_session: SparkSession - def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): :param db_name: :param datab...
Implement the Python class `SparkReader` described below. Class description: 兼容原始read函数 Method signatures and docstrings: - def __init__(self, spark_session): 初始化 :param spark_session: SparkSession - def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): :param db_name: :param datab...
e883217e27a44699064c30e386379dea049af30d
<|skeleton|> class SparkReader: """兼容原始read函数""" def __init__(self, spark_session): """初始化 :param spark_session: SparkSession""" <|body_0|> def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): """:param db_name: :param database_env: :param datab...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SparkReader: """兼容原始read函数""" def __init__(self, spark_session): """初始化 :param spark_session: SparkSession""" SparkReaderWriter.__init__(self, spark_session, None) DataFrameReader._jreader = HiveContext(sparkContext=spark_session.sparkContext)._ssql_ctx.read() DataFrameRea...
the_stack_v2_python_sparse
mavenimportant/python/jobs/common/spark_reader.py
liProject/importantProject
train
0
ffd4f8b36a784daea7c45f271e23b5d030621c20
[ "self.shape = shape\nself.topk = topk\nself.upto = equiv_len\nif topk is not None:\n if equiv_len is None:\n self.upto = topk\n if self.upto > self.topk:\n raise ValueError(f'Equiv length {equiv_len} cannot exceed topk={topk}.')\nself.gumbel_noise = Gumbel(0, 1.0 / shape)\nself.log_scores = log_...
<|body_start_0|> self.shape = shape self.topk = topk self.upto = equiv_len if topk is not None: if equiv_len is None: self.upto = topk if self.upto > self.topk: raise ValueError(f'Equiv length {equiv_len} cannot exceed topk={topk}.'...
FrechetSort
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrechetSort: def __init__(self, shape: float=1.0, topk: Optional[int]=None, equiv_len: Optional[int]=None, log_scores: bool=False): """FréchetSort is a softer version of descending sort which samples all possible orderings of items favoring orderings which resemble descending sort. This ...
stack_v2_sparse_classes_36k_train_021295
6,759
permissive
[ { "docstring": "FréchetSort is a softer version of descending sort which samples all possible orderings of items favoring orderings which resemble descending sort. This can be used to convert descending sort by rank score into a differentiable, stochastic policy amenable to policy gradient algorithms. :param sh...
3
null
Implement the Python class `FrechetSort` described below. Class description: Implement the FrechetSort class. Method signatures and docstrings: - def __init__(self, shape: float=1.0, topk: Optional[int]=None, equiv_len: Optional[int]=None, log_scores: bool=False): FréchetSort is a softer version of descending sort wh...
Implement the Python class `FrechetSort` described below. Class description: Implement the FrechetSort class. Method signatures and docstrings: - def __init__(self, shape: float=1.0, topk: Optional[int]=None, equiv_len: Optional[int]=None, log_scores: bool=False): FréchetSort is a softer version of descending sort wh...
c5f1a8371a677b4f8fb0882b600bf331eba5259d
<|skeleton|> class FrechetSort: def __init__(self, shape: float=1.0, topk: Optional[int]=None, equiv_len: Optional[int]=None, log_scores: bool=False): """FréchetSort is a softer version of descending sort which samples all possible orderings of items favoring orderings which resemble descending sort. This ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrechetSort: def __init__(self, shape: float=1.0, topk: Optional[int]=None, equiv_len: Optional[int]=None, log_scores: bool=False): """FréchetSort is a softer version of descending sort which samples all possible orderings of items favoring orderings which resemble descending sort. This can be used to...
the_stack_v2_python_sparse
reagent/samplers/frechet.py
facebookresearch/ReAgent
train
1,480
3fbdc4d7d84e152e0a793a7072c55f06037c7743
[ "pre_node = head\nnode = head\nwhile node:\n cur_node = node\n i = 0\n while cur_node and i < n:\n cur_node = cur_node.next\n i += 1\n if i == n and (not cur_node):\n if pre_node == node and n == 1:\n return None\n elif pre_node == node:\n return head.ne...
<|body_start_0|> pre_node = head node = head while node: cur_node = node i = 0 while cur_node and i < n: cur_node = cur_node.next i += 1 if i == n and (not cur_node): if pre_node == node and n == 1: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: """使用双指针,判断当前节点是否为倒数第n个节点 :param head: :param n: :return:""" <|body_0|> def removeNthFromEnd1(self, head: ListNode, n: int) -> ListNode: """使用dummy,快慢指针,让快指针先走n,然后和慢指针一起遍历,当快指针为None时,慢指针当前节点就是倒...
stack_v2_sparse_classes_36k_train_021296
2,264
no_license
[ { "docstring": "使用双指针,判断当前节点是否为倒数第n个节点 :param head: :param n: :return:", "name": "removeNthFromEnd", "signature": "def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode" }, { "docstring": "使用dummy,快慢指针,让快指针先走n,然后和慢指针一起遍历,当快指针为None时,慢指针当前节点就是倒数第N个节点 :param head: :param n: :return:", ...
2
stack_v2_sparse_classes_30k_train_019111
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 使用双指针,判断当前节点是否为倒数第n个节点 :param head: :param n: :return: - def removeNthFromEnd1(self, head: ListNode, n: int) -> Li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 使用双指针,判断当前节点是否为倒数第n个节点 :param head: :param n: :return: - def removeNthFromEnd1(self, head: ListNode, n: int) -> Li...
9acba92695c06406f12f997a720bfe1deb9464a8
<|skeleton|> class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: """使用双指针,判断当前节点是否为倒数第n个节点 :param head: :param n: :return:""" <|body_0|> def removeNthFromEnd1(self, head: ListNode, n: int) -> ListNode: """使用dummy,快慢指针,让快指针先走n,然后和慢指针一起遍历,当快指针为None时,慢指针当前节点就是倒...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: """使用双指针,判断当前节点是否为倒数第n个节点 :param head: :param n: :return:""" pre_node = head node = head while node: cur_node = node i = 0 while cur_node and i < n: cur...
the_stack_v2_python_sparse
datastructure/linked_list/RemoveNthFromEnd.py
yinhuax/leet_code
train
0
d230f880423499e578e40dcfab704351d44ec71b
[ "try:\n return config_parser.get(section_name, value_name)\nexcept configparser.NoOptionError:\n return None", "config_parser = configparser.ConfigParser(interpolation=None)\nconfig_parser.read_file(file_object)\nfor section_name in config_parser.sections():\n dependency_definition = DependencyDefinition...
<|body_start_0|> try: return config_parser.get(section_name, value_name) except configparser.NoOptionError: return None <|end_body_0|> <|body_start_1|> config_parser = configparser.ConfigParser(interpolation=None) config_parser.read_file(file_object) for ...
Dependency definition reader.
DependencyDefinitionReader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DependencyDefinitionReader: """Dependency definition reader.""" def _GetConfigValue(self, config_parser, section_name, value_name): """Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that cont...
stack_v2_sparse_classes_36k_train_021297
11,583
permissive
[ { "docstring": "Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: object: configuration value or None if the value does not exists.", "name": "_Get...
2
null
Implement the Python class `DependencyDefinitionReader` described below. Class description: Dependency definition reader. Method signatures and docstrings: - def _GetConfigValue(self, config_parser, section_name, value_name): Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration ...
Implement the Python class `DependencyDefinitionReader` described below. Class description: Dependency definition reader. Method signatures and docstrings: - def _GetConfigValue(self, config_parser, section_name, value_name): Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration ...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class DependencyDefinitionReader: """Dependency definition reader.""" def _GetConfigValue(self, config_parser, section_name, value_name): """Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that cont...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DependencyDefinitionReader: """Dependency definition reader.""" def _GetConfigValue(self, config_parser, section_name, value_name): """Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the valu...
the_stack_v2_python_sparse
utils/dependencies.py
log2timeline/plaso
train
1,506
62cd124f08b9516cf83502ba93e95dedd1e1094b
[ "stack = []\nfor num in arr:\n if stack and num < stack[-1]:\n max_value = stack.pop()\n while stack and stack[-1] > num:\n stack.pop()\n stack.append(max_value)\n else:\n stack.append(num)\nreturn len(stack)", "count = 0\nsorted_array = sorted(arr)\ns1 = s2 = 0\nfor n...
<|body_start_0|> stack = [] for num in arr: if stack and num < stack[-1]: max_value = stack.pop() while stack and stack[-1] > num: stack.pop() stack.append(max_value) else: stack.append(num) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: """monotonous non-decreasing stack""" <|body_0|> def maxChunksToSorted(self, arr: List[int]) -> int: """sorting and compare sum""" <|body_1|> <|end_skeleton|> <|body_start_0|> stack = [] ...
stack_v2_sparse_classes_36k_train_021298
1,171
no_license
[ { "docstring": "monotonous non-decreasing stack", "name": "maxChunksToSorted", "signature": "def maxChunksToSorted(self, arr: List[int]) -> int" }, { "docstring": "sorting and compare sum", "name": "maxChunksToSorted", "signature": "def maxChunksToSorted(self, arr: List[int]) -> int" }...
2
stack_v2_sparse_classes_30k_train_000917
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxChunksToSorted(self, arr: List[int]) -> int: monotonous non-decreasing stack - def maxChunksToSorted(self, arr: List[int]) -> int: sorting and compare sum
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxChunksToSorted(self, arr: List[int]) -> int: monotonous non-decreasing stack - def maxChunksToSorted(self, arr: List[int]) -> int: sorting and compare sum <|skeleton|> cl...
fce451090ecaf5471aab5a9413ac0675639ace5d
<|skeleton|> class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: """monotonous non-decreasing stack""" <|body_0|> def maxChunksToSorted(self, arr: List[int]) -> int: """sorting and compare sum""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: """monotonous non-decreasing stack""" stack = [] for num in arr: if stack and num < stack[-1]: max_value = stack.pop() while stack and stack[-1] > num: stack.po...
the_stack_v2_python_sparse
array_stack_queue/768MaxChunksToMakeSortedII.py
kidexp/91leetcode
train
0
e9d5f911db466574d83bbbdff41d017b178f8281
[ "if not isinstance(rotation_range, (list, tuple)) or len(rotation_range) != 2:\n raise ValueError('rotation_range argument must be list/tuple with two values!')\nself.rotation_range = rotation_range\nself.reference = reference\nself.lazy = lazy", "rotation = random.gauss(self.rotation_range[0], self.rotation_r...
<|body_start_0|> if not isinstance(rotation_range, (list, tuple)) or len(rotation_range) != 2: raise ValueError('rotation_range argument must be list/tuple with two values!') self.rotation_range = rotation_range self.reference = reference self.lazy = lazy <|end_body_0|> <|bo...
Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
RandomRotate2D
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomRotate2D: """Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.""" def __init__(self, rotation_ran...
stack_v2_sparse_classes_36k_train_021299
21,674
permissive
[ { "docstring": "Initialize a RandomRotate2D object Arguments --------- rotation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. rotation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but re...
2
null
Implement the Python class `RandomRotate2D` described below. Class description: Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ...
Implement the Python class `RandomRotate2D` described below. Class description: Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ...
41f2dd3fcf72654f284dac1a9448033e963f0afb
<|skeleton|> class RandomRotate2D: """Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.""" def __init__(self, rotation_ran...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomRotate2D: """Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.""" def __init__(self, rotation_range, reference...
the_stack_v2_python_sparse
ants/contrib/sampling/affine2d.py
ANTsX/ANTsPy
train
483