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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3a90de517da9199757efad8a7b2b029e182f8c73 | [
"out = {'type': type, 'content': content}\nif id:\n out['id'] = id\nif in_response:\n out['in_response'] = in_response\ntry:\n await super().send_json(out)\nexcept (ConnectionClosed, RuntimeError) as e:\n if not silence_errors:\n raise e",
"try:\n jsonschema.validate(content, schema)\nexcept... | <|body_start_0|>
out = {'type': type, 'content': content}
if id:
out['id'] = id
if in_response:
out['in_response'] = in_response
try:
await super().send_json(out)
except (ConnectionClosed, RuntimeError) as e:
if not silence_errors:
... | Mixin for JSONWebsocketConsumers, that speaks the a special protocol. | ProtocollAsyncJsonWebsocketConsumer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtocollAsyncJsonWebsocketConsumer:
"""Mixin for JSONWebsocketConsumers, that speaks the a special protocol."""
async def send_json(self, type: str, content: Any, id: Optional[str]=None, in_response: Optional[str]=None, silence_errors: Optional[bool]=True) -> None:
"""Sends the data... | stack_v2_sparse_classes_36k_train_029700 | 6,258 | permissive | [
{
"docstring": "Sends the data with the type. If silence_errors is True (default), all ConnectionClosed and runtime errors during sending will be ignored.",
"name": "send_json",
"signature": "async def send_json(self, type: str, content: Any, id: Optional[str]=None, in_response: Optional[str]=None, sile... | 2 | stack_v2_sparse_classes_30k_train_014499 | Implement the Python class `ProtocollAsyncJsonWebsocketConsumer` described below.
Class description:
Mixin for JSONWebsocketConsumers, that speaks the a special protocol.
Method signatures and docstrings:
- async def send_json(self, type: str, content: Any, id: Optional[str]=None, in_response: Optional[str]=None, sil... | Implement the Python class `ProtocollAsyncJsonWebsocketConsumer` described below.
Class description:
Mixin for JSONWebsocketConsumers, that speaks the a special protocol.
Method signatures and docstrings:
- async def send_json(self, type: str, content: Any, id: Optional[str]=None, in_response: Optional[str]=None, sil... | 4495985d4c752d9e56d1011a4396a7cb444070a6 | <|skeleton|>
class ProtocollAsyncJsonWebsocketConsumer:
"""Mixin for JSONWebsocketConsumers, that speaks the a special protocol."""
async def send_json(self, type: str, content: Any, id: Optional[str]=None, in_response: Optional[str]=None, silence_errors: Optional[bool]=True) -> None:
"""Sends the data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtocollAsyncJsonWebsocketConsumer:
"""Mixin for JSONWebsocketConsumers, that speaks the a special protocol."""
async def send_json(self, type: str, content: Any, id: Optional[str]=None, in_response: Optional[str]=None, silence_errors: Optional[bool]=True) -> None:
"""Sends the data with the typ... | the_stack_v2_python_sparse | openslides/utils/websocket.py | Intevation/OpenSlides | train | 0 |
0b8f4d5b15b4ca4d3e916f74620692fbd7d98bb4 | [
"total = 0\nm = {}\nfor w in worker:\n x = 0\n if w in m:\n x = m[w]\n else:\n for d, p in zip(difficulty, profit):\n if w >= d:\n x = max(x, p)\n m[w] = x\n total += x\nreturn total",
"dp = [[i, j] for i, j in zip(difficulty, profit)]\ndp = sorted(dp, ke... | <|body_start_0|>
total = 0
m = {}
for w in worker:
x = 0
if w in m:
x = m[w]
else:
for d, p in zip(difficulty, profit):
if w >= d:
x = max(x, p)
m[w] = x
to... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfitAssignment1(self, difficulty, profit, worker):
""":type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int"""
<|body_0|>
def maxProfitAssignment(self, difficulty, profit, worker):
""":type difficulty: List[int] :t... | stack_v2_sparse_classes_36k_train_029701 | 1,717 | no_license | [
{
"docstring": ":type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int",
"name": "maxProfitAssignment1",
"signature": "def maxProfitAssignment1(self, difficulty, profit, worker)"
},
{
"docstring": ":type difficulty: List[int] :type profit: List[int] :type worker:... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfitAssignment1(self, difficulty, profit, worker): :type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int
- def maxProfitAssignment(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfitAssignment1(self, difficulty, profit, worker): :type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int
- def maxProfitAssignment(self... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def maxProfitAssignment1(self, difficulty, profit, worker):
""":type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int"""
<|body_0|>
def maxProfitAssignment(self, difficulty, profit, worker):
""":type difficulty: List[int] :t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfitAssignment1(self, difficulty, profit, worker):
""":type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int"""
total = 0
m = {}
for w in worker:
x = 0
if w in m:
x = m[w]
el... | the_stack_v2_python_sparse | most-profit-assigning-work/solution.py | uxlsl/leetcode_practice | train | 0 | |
36d121cf4ab8c4a21fac3cad275776852e5ea7a7 | [
"super().__init__()\nself._stft = Stft(fps, window, n_perseg, n_overlap)\nif pp_params:\n self._ppkr = FilterPeakPicker(**pp_params)\nelse:\n self._ppkr = FilterPeakPicker()",
"sxx = self._stft.transform(inp)\nflux = features.spectral_flux(sxx.abs, total=True)\ntimes = sxx.times.squeeze()\nodf = {'frame': (... | <|body_start_0|>
super().__init__()
self._stft = Stft(fps, window, n_perseg, n_overlap)
if pp_params:
self._ppkr = FilterPeakPicker(**pp_params)
else:
self._ppkr = FilterPeakPicker()
<|end_body_0|>
<|body_start_1|>
sxx = self._stft.transform(inp)
... | Onset detection based on spectral flux. | FluxOnsetDetector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FluxOnsetDetector:
"""Onset detection based on spectral flux."""
def __init__(self, fps: int, window: str='hamming', n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None:
"""Detect onsets as local maxima in the energy difference of consecutive stft time ste... | stack_v2_sparse_classes_36k_train_029702 | 8,907 | permissive | [
{
"docstring": "Detect onsets as local maxima in the energy difference of consecutive stft time steps. Args: fps: Sample rate. window: Name of window function. n_perseg: Samples per segment. n_overlap: Numnber of overlapping samples per segment. pp_params: Keyword args for peak picking.",
"name": "__init__"... | 2 | stack_v2_sparse_classes_30k_train_013618 | Implement the Python class `FluxOnsetDetector` described below.
Class description:
Onset detection based on spectral flux.
Method signatures and docstrings:
- def __init__(self, fps: int, window: str='hamming', n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None: Detect onsets as local max... | Implement the Python class `FluxOnsetDetector` described below.
Class description:
Onset detection based on spectral flux.
Method signatures and docstrings:
- def __init__(self, fps: int, window: str='hamming', n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None: Detect onsets as local max... | c733591240f3a4d3825d61385bd19262bd76b43b | <|skeleton|>
class FluxOnsetDetector:
"""Onset detection based on spectral flux."""
def __init__(self, fps: int, window: str='hamming', n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None:
"""Detect onsets as local maxima in the energy difference of consecutive stft time ste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FluxOnsetDetector:
"""Onset detection based on spectral flux."""
def __init__(self, fps: int, window: str='hamming', n_perseg: int=1024, n_overlap: int=512, pp_params: Optional[dict]=None) -> None:
"""Detect onsets as local maxima in the energy difference of consecutive stft time steps. Args: fps... | the_stack_v2_python_sparse | src/apollon/onsets.py | TimZiemer/apollon | train | 0 |
be9e5709153f2ad6984388b3e761927d4611f4fc | [
"super().__init__()\nassert use_sigmoid is True, 'Only sigmoid varifocal loss supported now.'\nassert alpha >= 0.0\nself.use_sigmoid = use_sigmoid\nself.alpha = alpha\nself.gamma = gamma\nself.iou_weighted = iou_weighted\nself.reduction = reduction\nself.loss_weight = loss_weight",
"assert reduction_override in (... | <|body_start_0|>
super().__init__()
assert use_sigmoid is True, 'Only sigmoid varifocal loss supported now.'
assert alpha >= 0.0
self.use_sigmoid = use_sigmoid
self.alpha = alpha
self.gamma = gamma
self.iou_weighted = iou_weighted
self.reduction = reductio... | VarifocalLoss | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VarifocalLoss:
def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None:
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the predicti... | stack_v2_sparse_classes_36k_train_029703 | 5,749 | permissive | [
{
"docstring": "`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for sigmoid or softmax. Defaults to True. alpha (float, optional): A balance factor for the negative part of Varifocal Loss, which is different from the alpha of Focal Loss. De... | 2 | null | Implement the Python class `VarifocalLoss` described below.
Class description:
Implement the VarifocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None: `Varifo... | Implement the Python class `VarifocalLoss` described below.
Class description:
Implement the VarifocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None: `Varifo... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class VarifocalLoss:
def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None:
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the predicti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VarifocalLoss:
def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None:
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/losses/varifocal_loss.py | alldatacenter/alldata | train | 774 | |
e2c8848e6a38d5fa79d023184cbd3dadb5e8b857 | [
"self.seq = self.ssm(step_rescale=self.step_rescale)\nif self.activation in ['full_glu']:\n self.out1 = nn.Dense(self.d_model)\n self.out2 = nn.Dense(self.d_model)\nelif self.activation in ['half_glu1', 'half_glu2']:\n self.out2 = nn.Dense(self.d_model)\nif self.batchnorm:\n self.norm = nn.BatchNorm(use... | <|body_start_0|>
self.seq = self.ssm(step_rescale=self.step_rescale)
if self.activation in ['full_glu']:
self.out1 = nn.Dense(self.d_model)
self.out2 = nn.Dense(self.d_model)
elif self.activation in ['half_glu1', 'half_glu2']:
self.out2 = nn.Dense(self.d_model... | Defines a single S5 layer, with S5 SSM, nonlinearity, dropout, batch/layer norm, etc. Args: ssm (nn.Module): the SSM to be used (i.e. S5 ssm) dropout (float32): dropout rate d_model (int32): this is the feature size of the layer inputs and outputs we usually refer to this size as H activation (string): Type of activati... | SequenceLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceLayer:
"""Defines a single S5 layer, with S5 SSM, nonlinearity, dropout, batch/layer norm, etc. Args: ssm (nn.Module): the SSM to be used (i.e. S5 ssm) dropout (float32): dropout rate d_model (int32): this is the feature size of the layer inputs and outputs we usually refer to this size a... | stack_v2_sparse_classes_36k_train_029704 | 3,323 | permissive | [
{
"docstring": "Initializes the ssm, batch/layer norm and dropout",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Compute the LxH output of S5 layer given an LxH input. Args: x (float32): input sequence (L, d_model) Returns: output sequence (float32): (L, d_model)",
"nam... | 2 | stack_v2_sparse_classes_30k_train_014556 | Implement the Python class `SequenceLayer` described below.
Class description:
Defines a single S5 layer, with S5 SSM, nonlinearity, dropout, batch/layer norm, etc. Args: ssm (nn.Module): the SSM to be used (i.e. S5 ssm) dropout (float32): dropout rate d_model (int32): this is the feature size of the layer inputs and ... | Implement the Python class `SequenceLayer` described below.
Class description:
Defines a single S5 layer, with S5 SSM, nonlinearity, dropout, batch/layer norm, etc. Args: ssm (nn.Module): the SSM to be used (i.e. S5 ssm) dropout (float32): dropout rate d_model (int32): this is the feature size of the layer inputs and ... | 3c18fdb6b06414da35e77b94b9cd855f6a95ef17 | <|skeleton|>
class SequenceLayer:
"""Defines a single S5 layer, with S5 SSM, nonlinearity, dropout, batch/layer norm, etc. Args: ssm (nn.Module): the SSM to be used (i.e. S5 ssm) dropout (float32): dropout rate d_model (int32): this is the feature size of the layer inputs and outputs we usually refer to this size a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceLayer:
"""Defines a single S5 layer, with S5 SSM, nonlinearity, dropout, batch/layer norm, etc. Args: ssm (nn.Module): the SSM to be used (i.e. S5 ssm) dropout (float32): dropout rate d_model (int32): this is the feature size of the layer inputs and outputs we usually refer to this size as H activatio... | the_stack_v2_python_sparse | s5/layers.py | lindermanlab/S5 | train | 150 |
ffe0928618cff1540f508fcba61d7a2de920ddd7 | [
"super(ScatterVisualizer, self).__init__(ax=ax, features=features, classes=classes, color=color, colormap=colormap, **kwargs)\nself.x = x\nself.y = y\nself.alpha = alpha\nself.markers = itertools.cycle(kwargs.pop('markers', (',', '+', 'o', '*', 'v', 'h', 'd')))\nself.color = color\nself.colormap = colormap\nif self... | <|body_start_0|>
super(ScatterVisualizer, self).__init__(ax=ax, features=features, classes=classes, color=color, colormap=colormap, **kwargs)
self.x = x
self.y = y
self.alpha = alpha
self.markers = itertools.cycle(kwargs.pop('markers', (',', '+', 'o', '*', 'v', 'h', 'd')))
... | ScatterVisualizer is a bivariate feature data visualization algorithm that plots using the Cartesian coordinates of each point. Parameters ---------- ax : a matplotlib plot, default: None The axis to plot the figure on. x : string, default: None The feature name that corresponds to a column name or index postion in the... | ScatterVisualizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScatterVisualizer:
"""ScatterVisualizer is a bivariate feature data visualization algorithm that plots using the Cartesian coordinates of each point. Parameters ---------- ax : a matplotlib plot, default: None The axis to plot the figure on. x : string, default: None The feature name that corresp... | stack_v2_sparse_classes_36k_train_029705 | 11,862 | permissive | [
{
"docstring": "Initialize the base scatter with many of the options required in order to make the visualization work.",
"name": "__init__",
"signature": "def __init__(self, ax=None, x=None, y=None, features=None, classes=None, color=None, colormap=None, markers=None, alpha=1.0, **kwargs)"
},
{
... | 4 | null | Implement the Python class `ScatterVisualizer` described below.
Class description:
ScatterVisualizer is a bivariate feature data visualization algorithm that plots using the Cartesian coordinates of each point. Parameters ---------- ax : a matplotlib plot, default: None The axis to plot the figure on. x : string, defa... | Implement the Python class `ScatterVisualizer` described below.
Class description:
ScatterVisualizer is a bivariate feature data visualization algorithm that plots using the Cartesian coordinates of each point. Parameters ---------- ax : a matplotlib plot, default: None The axis to plot the figure on. x : string, defa... | f7a8e950bd31452ea2f5d402a1c5d519cd163fd5 | <|skeleton|>
class ScatterVisualizer:
"""ScatterVisualizer is a bivariate feature data visualization algorithm that plots using the Cartesian coordinates of each point. Parameters ---------- ax : a matplotlib plot, default: None The axis to plot the figure on. x : string, default: None The feature name that corresp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScatterVisualizer:
"""ScatterVisualizer is a bivariate feature data visualization algorithm that plots using the Cartesian coordinates of each point. Parameters ---------- ax : a matplotlib plot, default: None The axis to plot the figure on. x : string, default: None The feature name that corresponds to a col... | the_stack_v2_python_sparse | yellowbrick/contrib/scatter.py | DistrictDataLabs/yellowbrick | train | 4,242 |
e538e26a3316f7b60fd55e220443cb05870a4bb3 | [
"if not s:\n return ''\nif len(s) == 1:\n return s\nret = ''\nfor i in range(len(s)):\n l = r = i\n while r < len(s) and s[l] == s[r]:\n r += 1\n if len(ret) < r - l:\n ret = s[l:r]\n l -= 1\n while l >= 0 and r < len(s) and (s[l] == s[r]):\n l -= 1\n r += 1\n if ... | <|body_start_0|>
if not s:
return ''
if len(s) == 1:
return s
ret = ''
for i in range(len(s)):
l = r = i
while r < len(s) and s[l] == s[r]:
r += 1
if len(ret) < r - l:
ret = s[l:r]
l -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""Time complexity:O(N*N) Spave complexity:O(N) 验证通过,性能不错 Runtime: 728 ms, faster than 91.18% of Python3 online submissions for Longest Palindromic Substring. Memory Usage: 14.1 MB, less than 76.49% of Python3 online submissions for Longest Palin... | stack_v2_sparse_classes_36k_train_029706 | 3,775 | no_license | [
{
"docstring": "Time complexity:O(N*N) Spave complexity:O(N) 验证通过,性能不错 Runtime: 728 ms, faster than 91.18% of Python3 online submissions for Longest Palindromic Substring. Memory Usage: 14.1 MB, less than 76.49% of Python3 online submissions for Longest Palindromic Substring. :param s: :return:",
"name": "l... | 2 | stack_v2_sparse_classes_30k_test_000956 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): Time complexity:O(N*N) Spave complexity:O(N) 验证通过,性能不错 Runtime: 728 ms, faster than 91.18% of Python3 online submissions for Longest Palindromic S... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): Time complexity:O(N*N) Spave complexity:O(N) 验证通过,性能不错 Runtime: 728 ms, faster than 91.18% of Python3 online submissions for Longest Palindromic S... | 6a7267b8b784283a760de7775089b936a0e97617 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""Time complexity:O(N*N) Spave complexity:O(N) 验证通过,性能不错 Runtime: 728 ms, faster than 91.18% of Python3 online submissions for Longest Palindromic Substring. Memory Usage: 14.1 MB, less than 76.49% of Python3 online submissions for Longest Palin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
"""Time complexity:O(N*N) Spave complexity:O(N) 验证通过,性能不错 Runtime: 728 ms, faster than 91.18% of Python3 online submissions for Longest Palindromic Substring. Memory Usage: 14.1 MB, less than 76.49% of Python3 online submissions for Longest Palindromic Substri... | the_stack_v2_python_sparse | leetcode/5_longest_palindromic_substring/longest_palindromic_substring.py | liuyanhui/leetcode-py | train | 0 | |
669d87757f3be036c1f9421489221e332c9a2d63 | [
"try:\n inst = Tenant.objects.get(pk=inst_id)\nexcept Tenant.DoesNotExist:\n return api_error(code=404, msg=_('Tenant not existed.'))\ninst_admins = [x.user for x in TenantAdmin.objects.filter(tenant=inst)]\nusernames = [x.user for x in Profile.objects.filter(tenant=inst.name)]\nusers = [User.objects.get(x) f... | <|body_start_0|>
try:
inst = Tenant.objects.get(pk=inst_id)
except Tenant.DoesNotExist:
return api_error(code=404, msg=_('Tenant not existed.'))
inst_admins = [x.user for x in TenantAdmin.objects.filter(tenant=inst)]
usernames = [x.user for x in Profile.objects.fi... | AdminTenant | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminTenant:
def get(self, request, inst_id):
"""Get tenant details"""
<|body_0|>
def put(self, request, inst_id):
"""Update tenant quota"""
<|body_1|>
def delete(self, request, inst_id):
"""Delete a tenant"""
<|body_2|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_029707 | 34,523 | permissive | [
{
"docstring": "Get tenant details",
"name": "get",
"signature": "def get(self, request, inst_id)"
},
{
"docstring": "Update tenant quota",
"name": "put",
"signature": "def put(self, request, inst_id)"
},
{
"docstring": "Delete a tenant",
"name": "delete",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_007067 | Implement the Python class `AdminTenant` described below.
Class description:
Implement the AdminTenant class.
Method signatures and docstrings:
- def get(self, request, inst_id): Get tenant details
- def put(self, request, inst_id): Update tenant quota
- def delete(self, request, inst_id): Delete a tenant | Implement the Python class `AdminTenant` described below.
Class description:
Implement the AdminTenant class.
Method signatures and docstrings:
- def get(self, request, inst_id): Get tenant details
- def put(self, request, inst_id): Update tenant quota
- def delete(self, request, inst_id): Delete a tenant
<|skeleton... | 13b3ed26a04248211ef91ca70dccc617be27a3c3 | <|skeleton|>
class AdminTenant:
def get(self, request, inst_id):
"""Get tenant details"""
<|body_0|>
def put(self, request, inst_id):
"""Update tenant quota"""
<|body_1|>
def delete(self, request, inst_id):
"""Delete a tenant"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminTenant:
def get(self, request, inst_id):
"""Get tenant details"""
try:
inst = Tenant.objects.get(pk=inst_id)
except Tenant.DoesNotExist:
return api_error(code=404, msg=_('Tenant not existed.'))
inst_admins = [x.user for x in TenantAdmin.objects.filt... | the_stack_v2_python_sparse | fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/admin/tenants.py | syncwerk/syncwerk-server-restapi | train | 0 | |
de99b9d246dbcb67f9fd433fe045eb21fe5cd0bd | [
"self._config = CONFIG\nself._device_dict = {}\nself._devicename = devicename\nlog_message = 'Starting port idle times for device {}.'.format(devicename)\nlog.log2debug(1034, log_message)\nfilepath = self._config.temp_topology_device_file(devicename)\nif os.path.isfile(filepath) is True:\n self._device_dict = ge... | <|body_start_0|>
self._config = CONFIG
self._device_dict = {}
self._devicename = devicename
log_message = 'Starting port idle times for device {}.'.format(devicename)
log.log2debug(1034, log_message)
filepath = self._config.temp_topology_device_file(devicename)
if... | Process device port idle times. | IdleTimes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdleTimes:
"""Process device port idle times."""
def __init__(self, devicename):
"""Initialize class. Args: devicename: Name of device to calculate idle times Returns: None"""
<|body_0|>
def save(self):
"""Save the idle times to file. Args: None Returns: None"""
... | stack_v2_sparse_classes_36k_train_029708 | 20,081 | permissive | [
{
"docstring": "Initialize class. Args: devicename: Name of device to calculate idle times Returns: None",
"name": "__init__",
"signature": "def __init__(self, devicename)"
},
{
"docstring": "Save the idle times to file. Args: None Returns: None",
"name": "save",
"signature": "def save(s... | 2 | null | Implement the Python class `IdleTimes` described below.
Class description:
Process device port idle times.
Method signatures and docstrings:
- def __init__(self, devicename): Initialize class. Args: devicename: Name of device to calculate idle times Returns: None
- def save(self): Save the idle times to file. Args: N... | Implement the Python class `IdleTimes` described below.
Class description:
Process device port idle times.
Method signatures and docstrings:
- def __init__(self, devicename): Initialize class. Args: devicename: Name of device to calculate idle times Returns: None
- def save(self): Save the idle times to file. Args: N... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class IdleTimes:
"""Process device port idle times."""
def __init__(self, devicename):
"""Initialize class. Args: devicename: Name of device to calculate idle times Returns: None"""
<|body_0|>
def save(self):
"""Save the idle times to file. Args: None Returns: None"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdleTimes:
"""Process device port idle times."""
def __init__(self, devicename):
"""Initialize class. Args: devicename: Name of device to calculate idle times Returns: None"""
self._config = CONFIG
self._device_dict = {}
self._devicename = devicename
log_message = ... | the_stack_v2_python_sparse | switchmap/process/device.py | PalisadoesFoundation/switchmap-ng | train | 8 |
863692089d6ba0188cd989751005fa26eef018b4 | [
"self.detector = detector\nself.learner = ObjectTracking2DDeepSortLearner(device=device, temp_path=temp_dir)\nif not os.path.exists(os.path.join(temp_dir, model_name)):\n ObjectTracking2DDeepSortLearner.download(model_name, temp_dir)\nself.learner.load(os.path.join(temp_dir, model_name), verbose=True)\nself.brid... | <|body_start_0|>
self.detector = detector
self.learner = ObjectTracking2DDeepSortLearner(device=device, temp_path=temp_dir)
if not os.path.exists(os.path.join(temp_dir, model_name)):
ObjectTracking2DDeepSortLearner.download(model_name, temp_dir)
self.learner.load(os.path.join... | ObjectTracking2DDeepSortNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectTracking2DDeepSortNode:
def __init__(self, detector=None, input_rgb_image_topic='/usb_cam/image_raw', output_detection_topic='/opendr/objects', output_tracking_id_topic='/opendr/objects_tracking_id', output_rgb_image_topic='/opendr/image_objects_annotated', device='cuda:0', model_name='dee... | stack_v2_sparse_classes_36k_train_029709 | 9,139 | permissive | [
{
"docstring": "Creates a ROS Node for 2D object tracking :param detector: Learner to generate object detections :type detector: Learner :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_rgb_image_topic: Topic to which we are publishing ... | 3 | stack_v2_sparse_classes_30k_train_018383 | Implement the Python class `ObjectTracking2DDeepSortNode` described below.
Class description:
Implement the ObjectTracking2DDeepSortNode class.
Method signatures and docstrings:
- def __init__(self, detector=None, input_rgb_image_topic='/usb_cam/image_raw', output_detection_topic='/opendr/objects', output_tracking_id... | Implement the Python class `ObjectTracking2DDeepSortNode` described below.
Class description:
Implement the ObjectTracking2DDeepSortNode class.
Method signatures and docstrings:
- def __init__(self, detector=None, input_rgb_image_topic='/usb_cam/image_raw', output_detection_topic='/opendr/objects', output_tracking_id... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class ObjectTracking2DDeepSortNode:
def __init__(self, detector=None, input_rgb_image_topic='/usb_cam/image_raw', output_detection_topic='/opendr/objects', output_tracking_id_topic='/opendr/objects_tracking_id', output_rgb_image_topic='/opendr/image_objects_annotated', device='cuda:0', model_name='dee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectTracking2DDeepSortNode:
def __init__(self, detector=None, input_rgb_image_topic='/usb_cam/image_raw', output_detection_topic='/opendr/objects', output_tracking_id_topic='/opendr/objects_tracking_id', output_rgb_image_topic='/opendr/image_objects_annotated', device='cuda:0', model_name='deep_sort', temp_... | the_stack_v2_python_sparse | projects/opendr_ws/src/opendr_perception/scripts/object_tracking_2d_deep_sort_node.py | opendr-eu/opendr | train | 535 | |
47cd03935e70b3a8e3233d9cde6b530864dca5ce | [
"super().__init__()\nself.unbiased_pcnt = unbiased_pcnt\nself.mixing_factors = mixing_factors\nself.seed = seed\nself.fixed_unbiased = fixed_unbiased",
"mixing_factor = self.mixing_factors[split_id]\nbiased, unbiased = get_biased_and_debiased_subsets(data, mixing_factor, self.unbiased_pcnt, self.seed, self.fixed_... | <|body_start_0|>
super().__init__()
self.unbiased_pcnt = unbiased_pcnt
self.mixing_factors = mixing_factors
self.seed = seed
self.fixed_unbiased = fixed_unbiased
<|end_body_0|>
<|body_start_1|>
mixing_factor = self.mixing_factors[split_id]
biased, unbiased = get_... | Split the given data into a biased subset and a debiased subset. | BiasedDebiasedSubsets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiasedDebiasedSubsets:
"""Split the given data into a biased subset and a debiased subset."""
def __init__(self, unbiased_pcnt: float, mixing_factors: Sequence[float]=(0,), seed: int=42, fixed_unbiased: bool=True):
"""The constructor takes the following arguments. Args: mixing_factor... | stack_v2_sparse_classes_36k_train_029710 | 10,886 | no_license | [
{
"docstring": "The constructor takes the following arguments. Args: mixing_factors: List of mixing factors; they are chosen based on the split ID unbiased_pcnt: how much of the data should be reserved for the unbiased subset seed: random seed for the splitting fixed_unbiased: if True, then the unbiased dataset... | 2 | null | Implement the Python class `BiasedDebiasedSubsets` described below.
Class description:
Split the given data into a biased subset and a debiased subset.
Method signatures and docstrings:
- def __init__(self, unbiased_pcnt: float, mixing_factors: Sequence[float]=(0,), seed: int=42, fixed_unbiased: bool=True): The const... | Implement the Python class `BiasedDebiasedSubsets` described below.
Class description:
Split the given data into a biased subset and a debiased subset.
Method signatures and docstrings:
- def __init__(self, unbiased_pcnt: float, mixing_factors: Sequence[float]=(0,), seed: int=42, fixed_unbiased: bool=True): The const... | 3aecb7642d9611ae0a61cd47948931f8f47b6f76 | <|skeleton|>
class BiasedDebiasedSubsets:
"""Split the given data into a biased subset and a debiased subset."""
def __init__(self, unbiased_pcnt: float, mixing_factors: Sequence[float]=(0,), seed: int=42, fixed_unbiased: bool=True):
"""The constructor takes the following arguments. Args: mixing_factor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiasedDebiasedSubsets:
"""Split the given data into a biased subset and a debiased subset."""
def __init__(self, unbiased_pcnt: float, mixing_factors: Sequence[float]=(0,), seed: int=42, fixed_unbiased: bool=True):
"""The constructor takes the following arguments. Args: mixing_factors: List of mi... | the_stack_v2_python_sparse | ethicml/preprocessing/biased_split.py | anonymous-iclr-3518/code-for-submission | train | 0 |
a4ac8be9c867a8b47f6a7f025a5bed327b6e6dc9 | [
"s = sum((i for i in A if i % 2 == 0))\nres = []\nfor val, index in queries:\n if A[index] % 2 == 0:\n s -= A[index]\n A[index] += val\n if A[index] % 2 == 0:\n s += A[index]\n res.append(s)\nreturn res",
"nsum = sum((i for i in A if i & 1 == 0))\nres = []\nfor value, key in queries:\n ... | <|body_start_0|>
s = sum((i for i in A if i % 2 == 0))
res = []
for val, index in queries:
if A[index] % 2 == 0:
s -= A[index]
A[index] += val
if A[index] % 2 == 0:
s += A[index]
res.append(s)
return res
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumEvenAfterQueries(self, A, queries):
""":type A: List[int] :type queries: List[List[int]] :rtype: List[int]"""
<|body_0|>
def sumEvenAfterQueries(self, A, queries):
""":type A: List[int] :type queries: List[List[int]] :rtype: List[int]"""
<|bo... | stack_v2_sparse_classes_36k_train_029711 | 2,334 | no_license | [
{
"docstring": ":type A: List[int] :type queries: List[List[int]] :rtype: List[int]",
"name": "sumEvenAfterQueries",
"signature": "def sumEvenAfterQueries(self, A, queries)"
},
{
"docstring": ":type A: List[int] :type queries: List[List[int]] :rtype: List[int]",
"name": "sumEvenAfterQueries"... | 3 | stack_v2_sparse_classes_30k_train_014600 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumEvenAfterQueries(self, A, queries): :type A: List[int] :type queries: List[List[int]] :rtype: List[int]
- def sumEvenAfterQueries(self, A, queries): :type A: List[int] :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumEvenAfterQueries(self, A, queries): :type A: List[int] :type queries: List[List[int]] :rtype: List[int]
- def sumEvenAfterQueries(self, A, queries): :type A: List[int] :ty... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def sumEvenAfterQueries(self, A, queries):
""":type A: List[int] :type queries: List[List[int]] :rtype: List[int]"""
<|body_0|>
def sumEvenAfterQueries(self, A, queries):
""":type A: List[int] :type queries: List[List[int]] :rtype: List[int]"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumEvenAfterQueries(self, A, queries):
""":type A: List[int] :type queries: List[List[int]] :rtype: List[int]"""
s = sum((i for i in A if i % 2 == 0))
res = []
for val, index in queries:
if A[index] % 2 == 0:
s -= A[index]
A... | the_stack_v2_python_sparse | 0985_Sum_of_Even_Numbers_After_Queries.py | bingli8802/leetcode | train | 0 | |
061576d4adab94e9f4606f26c9a21a6fa1a4bf98 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Printer()",
"from .print_connector import PrintConnector\nfrom .printer_base import PrinterBase\nfrom .printer_share import PrinterShare\nfrom .print_task_trigger import PrintTaskTrigger\nfrom .print_connector import PrintConnector\nfr... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Printer()
<|end_body_0|>
<|body_start_1|>
from .print_connector import PrintConnector
from .printer_base import PrinterBase
from .printer_share import PrinterShare
from .... | Printer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Printer:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Printer:
"""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: Printer"""... | stack_v2_sparse_classes_36k_train_029712 | 4,504 | 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: Printer",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse... | 3 | null | Implement the Python class `Printer` described below.
Class description:
Implement the Printer class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Printer: Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | Implement the Python class `Printer` described below.
Class description:
Implement the Printer class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Printer: Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Printer:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Printer:
"""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: Printer"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Printer:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Printer:
"""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: Printer"""
if no... | the_stack_v2_python_sparse | msgraph/generated/models/printer.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b8b44bbc21030299c36498186edf206ff715cb75 | [
"if isinstance(cls, six.class_types):\n init = cls.__init__\n\n def wrapped(*args, **kwargs):\n try:\n warp_self = args[0]\n warp_self.df = None\n init(*args, **kwargs)\n symbol = args[1]\n self._gen_warp_df(warp_self, symbol)\n except Excep... | <|body_start_0|>
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
warp_self.df = None
init(*args, **kwargs)
symbol = args[1]
... | 做为类装饰器封装替换解析数据统一操作,装饰替换init | AbuDataParseWrap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbuDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:"... | stack_v2_sparse_classes_36k_train_029713 | 14,108 | permissive | [
{
"docstring": "只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程",
"name": "__call__",
"signature": "def __call__(self, cls)"
},
{
"docstring": "封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:",
"name": "_gen_warp_df",
"signature": "def _gen_warp_df(self, warp_s... | 2 | stack_v2_sparse_classes_30k_train_011513 | Implement the Python class `AbuDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的s... | Implement the Python class `AbuDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的s... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class AbuDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbuDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
... | the_stack_v2_python_sparse | abupy/MarketBu/ABuDataParser.py | luqin/firefly | train | 1 |
c7d4d9c555f6a4d6ea6c1d92f47256ba6f4e935d | [
"self.mode = mode\nself.ids_rulesets = ids_rulesets\nself.protected_networks = protected_networks",
"if dictionary is None:\n return None\nmode = dictionary.get('mode')\nids_rulesets = dictionary.get('idsRulesets')\nprotected_networks = meraki_sdk.models.protected_networks_model.ProtectedNetworksModel.from_dic... | <|body_start_0|>
self.mode = mode
self.ids_rulesets = ids_rulesets
self.protected_networks = protected_networks
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
mode = dictionary.get('mode')
ids_rulesets = dictionary.get('idsRulesets')
... | Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_rulesets (string): Set the detection ruleset 'connectivity'/'balanced'/'securi... | UpdateNetworkSecurityIntrusionSettingsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkSecurityIntrusionSettingsModel:
"""Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_ruleset... | stack_v2_sparse_classes_36k_train_029714 | 2,701 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkSecurityIntrusionSettingsModel class",
"name": "__init__",
"signature": "def __init__(self, mode=None, ids_rulesets=None, protected_networks=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary... | 2 | stack_v2_sparse_classes_30k_train_011302 | Implement the Python class `UpdateNetworkSecurityIntrusionSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leav... | Implement the Python class `UpdateNetworkSecurityIntrusionSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leav... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkSecurityIntrusionSettingsModel:
"""Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_ruleset... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNetworkSecurityIntrusionSettingsModel:
"""Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_rulesets (string): S... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_security_intrusion_settings_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
2f822b306f083dd100852e90bd0ce7b8022ac1b5 | [
"if '_read' not in data and '_seen' not in data:\n raise ValidationError('Please provide at least one field to update. Valid fields to update are: read, seen')\nreturn data",
"unwanted_fields = ['resource_type']\nfor field in unwanted_fields:\n if field in data:\n data.pop(field)\nreturn data"
] | <|body_start_0|>
if '_read' not in data and '_seen' not in data:
raise ValidationError('Please provide at least one field to update. Valid fields to update are: read, seen')
return data
<|end_body_0|>
<|body_start_1|>
unwanted_fields = ['resource_type']
for field in unwanted... | Class to serialize and deserialize notification models. | NotificationSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationSchema:
"""Class to serialize and deserialize notification models."""
def validate_read_and_seen(self, data, **kwargs):
"""Raise a ValidationError if both read and seen aren't present in the data on load."""
<|body_0|>
def strip_unwanted_fields(self, data, ma... | stack_v2_sparse_classes_36k_train_029715 | 1,963 | no_license | [
{
"docstring": "Raise a ValidationError if both read and seen aren't present in the data on load.",
"name": "validate_read_and_seen",
"signature": "def validate_read_and_seen(self, data, **kwargs)"
},
{
"docstring": "Remove unwanted fields from the input data before deserialization.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_009327 | Implement the Python class `NotificationSchema` described below.
Class description:
Class to serialize and deserialize notification models.
Method signatures and docstrings:
- def validate_read_and_seen(self, data, **kwargs): Raise a ValidationError if both read and seen aren't present in the data on load.
- def stri... | Implement the Python class `NotificationSchema` described below.
Class description:
Class to serialize and deserialize notification models.
Method signatures and docstrings:
- def validate_read_and_seen(self, data, **kwargs): Raise a ValidationError if both read and seen aren't present in the data on load.
- def stri... | 55ce20945bea8a6348bea64726aaf209936723c2 | <|skeleton|>
class NotificationSchema:
"""Class to serialize and deserialize notification models."""
def validate_read_and_seen(self, data, **kwargs):
"""Raise a ValidationError if both read and seen aren't present in the data on load."""
<|body_0|>
def strip_unwanted_fields(self, data, ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationSchema:
"""Class to serialize and deserialize notification models."""
def validate_read_and_seen(self, data, **kwargs):
"""Raise a ValidationError if both read and seen aren't present in the data on load."""
if '_read' not in data and '_seen' not in data:
raise Val... | the_stack_v2_python_sparse | api/app/schemas/notification.py | EricMontague/Flask-Chat-Server | train | 0 |
7c6d76770d0d071e709b48c64093a601d3cba771 | [
"self.ndims = ndims\nself.W_init = W_init\nself.W0 = None\nif W_init == 'zeros':\n self.W0 = tf.zeros([self.ndims + 1, 1])\nelif W_init == 'ones':\n self.W0 = tf.ones([self.ndims + 1, 1])\nelif W_init == 'uniform':\n self.W0 = tf.random_uniform([self.ndims + 1, 1], maxval=1)\nelif W_init == 'gaussian':\n ... | <|body_start_0|>
self.ndims = ndims
self.W_init = W_init
self.W0 = None
if W_init == 'zeros':
self.W0 = tf.zeros([self.ndims + 1, 1])
elif W_init == 'ones':
self.W0 = tf.ones([self.ndims + 1, 1])
elif W_init == 'uniform':
self.W0 = tf.r... | LogisticModel_TF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias t... | stack_v2_sparse_classes_36k_train_029716 | 5,037 | no_license | [
{
"docstring": "Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias term, Weight = [Bias, W1, W2, W3, ...] where Wi correspnds to each featur... | 3 | stack_v2_sparse_classes_30k_train_000399 | Implement the Python class `LogisticModel_TF` described below.
Class description:
Implement the LogisticModel_TF class.
Method signatures and docstrings:
- def __init__(self, ndims, W_init='zeros'): Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector... | Implement the Python class `LogisticModel_TF` described below.
Class description:
Implement the LogisticModel_TF class.
Method signatures and docstrings:
- def __init__(self, ndims, W_init='zeros'): Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector... | 9caaad9a923e9a9c02d1784f416b0623313c6faa | <|skeleton|>
class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias term, Weight = ... | the_stack_v2_python_sparse | mp3/codefromtf/logistic_model.py | handsomeboy/CS446-3 | train | 0 | |
fd8a281c394fb18221b4dbefea17e82c93c6ecf8 | [
"self.id = id\nself.abbrv_name = abbrv_name\nself.logo_url = logo_url\nself.decryption_key_activated = decryption_key_activated\nself.created_date = created_date\nself.last_modified_date = last_modified_date\nself.status = status\nself.additional_properties = additional_properties",
"if dictionary is None:\n r... | <|body_start_0|>
self.id = id
self.abbrv_name = abbrv_name
self.logo_url = logo_url
self.decryption_key_activated = decryption_key_activated
self.created_date = created_date
self.last_modified_date = last_modified_date
self.status = status
self.additional_... | Implementation of the 'App FI Status' model. The registration status fields for each specific OAuth financial institution Attributes: id (long|int): The finicity financial institution id abbrv_name (string): The applications abbreviated name logo_url (string): Logo URL for stored logo file decryption_key_activated (boo... | AppFIStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppFIStatus:
"""Implementation of the 'App FI Status' model. The registration status fields for each specific OAuth financial institution Attributes: id (long|int): The finicity financial institution id abbrv_name (string): The applications abbreviated name logo_url (string): Logo URL for stored ... | stack_v2_sparse_classes_36k_train_029717 | 3,550 | permissive | [
{
"docstring": "Constructor for the AppFIStatus class",
"name": "__init__",
"signature": "def __init__(self, id=None, decryption_key_activated=None, created_date=None, last_modified_date=None, status=None, abbrv_name=None, logo_url=None, additional_properties={})"
},
{
"docstring": "Creates an i... | 2 | null | Implement the Python class `AppFIStatus` described below.
Class description:
Implementation of the 'App FI Status' model. The registration status fields for each specific OAuth financial institution Attributes: id (long|int): The finicity financial institution id abbrv_name (string): The applications abbreviated name ... | Implement the Python class `AppFIStatus` described below.
Class description:
Implementation of the 'App FI Status' model. The registration status fields for each specific OAuth financial institution Attributes: id (long|int): The finicity financial institution id abbrv_name (string): The applications abbreviated name ... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class AppFIStatus:
"""Implementation of the 'App FI Status' model. The registration status fields for each specific OAuth financial institution Attributes: id (long|int): The finicity financial institution id abbrv_name (string): The applications abbreviated name logo_url (string): Logo URL for stored ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppFIStatus:
"""Implementation of the 'App FI Status' model. The registration status fields for each specific OAuth financial institution Attributes: id (long|int): The finicity financial institution id abbrv_name (string): The applications abbreviated name logo_url (string): Logo URL for stored logo file dec... | the_stack_v2_python_sparse | finicityapi/models/app_fi_status.py | monarchmoney/finicity-python | train | 0 |
4649d5dafa9bc70f584568c36bdbfbe865c8a5b6 | [
"self.count = features.shape[0]\nself.features = np.copy(features)\nself.features_dim = features.shape[1]\nif isinstance(idx, np.ndarray):\n self.idx = idx\nelse:\n self.idx = np.arange(self.count)\nself.labels = np.array(labels)\nself.labels_dim = 1",
"fl_store = []\nskf = KFold(n_splits=k_folds, shuffle=s... | <|body_start_0|>
self.count = features.shape[0]
self.features = np.copy(features)
self.features_dim = features.shape[1]
if isinstance(idx, np.ndarray):
self.idx = idx
else:
self.idx = np.arange(self.count)
self.labels = np.array(labels)
sel... | Features_labels_grid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Features_labels_grid:
def __init__(self, features, labels, idx=None):
"""Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performin... | stack_v2_sparse_classes_36k_train_029718 | 16,885 | no_license | [
{
"docstring": "Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performing k-fold cv",
"name": "__init__",
"signature": "def __init__(self, featur... | 2 | stack_v2_sparse_classes_30k_train_012652 | Implement the Python class `Features_labels_grid` described below.
Class description:
Implement the Features_labels_grid class.
Method signatures and docstrings:
- def __init__(self, features, labels, idx=None): Creates fl class with a lot useful attributes for grid data classification :param features: :param labels:... | Implement the Python class `Features_labels_grid` described below.
Class description:
Implement the Features_labels_grid class.
Method signatures and docstrings:
- def __init__(self, features, labels, idx=None): Creates fl class with a lot useful attributes for grid data classification :param features: :param labels:... | e19037a75b2a077c40c16f8794a3777f3928a356 | <|skeleton|>
class Features_labels_grid:
def __init__(self, features, labels, idx=None):
"""Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Features_labels_grid:
def __init__(self, features, labels, idx=None):
"""Creates fl class with a lot useful attributes for grid data classification :param features: :param labels: Labels as np array, no. of examples x dim :param idx: Used to keep track of the example index when performing k-fold cv"""... | the_stack_v2_python_sparse | own_package/features_labels_setup.py | liqiaofeng1990/Automatic_Strain_Sensor_Design | train | 0 | |
d7bd1eaba6692bb27e656f69cd56fb4627683498 | [
"self.pool_size = pool_size\nif self.pool_size > 0:\n self.num_imgs = 0\n self.images = []\nself.device, self.on_cpu = (device, on_cpu)",
"if self.pool_size == 0:\n return images\nreturn_images = []\nfor image in images:\n image = torch.unsqueeze(image.data, 0)\n if self.num_imgs < self.pool_size:\... | <|body_start_0|>
self.pool_size = pool_size
if self.pool_size > 0:
self.num_imgs = 0
self.images = []
self.device, self.on_cpu = (device, on_cpu)
<|end_body_0|>
<|body_start_1|>
if self.pool_size == 0:
return images
return_images = []
... | This class implements an image buffer that stores previously generated images. Adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/image_pool.py This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. | ImagePool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePool:
"""This class implements an image buffer that stores previously generated images. Adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/image_pool.py This buffer enables us to update discriminators using a history of generated images rather than the ones... | stack_v2_sparse_classes_36k_train_029719 | 15,023 | permissive | [
{
"docstring": "Initialize the ImagePool class Args: pool_size (int): the size of image buffer, if pool_size=0, no buffer will be created device (torch.device): model running device. GPUs are recommended for model training and inference. on_cpu (bool): whether to save image buffer on cpu to reduce GPU memory us... | 2 | stack_v2_sparse_classes_30k_train_012112 | Implement the Python class `ImagePool` described below.
Class description:
This class implements an image buffer that stores previously generated images. Adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/image_pool.py This buffer enables us to update discriminators using a history o... | Implement the Python class `ImagePool` described below.
Class description:
This class implements an image buffer that stores previously generated images. Adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/image_pool.py This buffer enables us to update discriminators using a history o... | 5c29c0ad388281e64f210003ba93740e28e02550 | <|skeleton|>
class ImagePool:
"""This class implements an image buffer that stores previously generated images. Adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/image_pool.py This buffer enables us to update discriminators using a history of generated images rather than the ones... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImagePool:
"""This class implements an image buffer that stores previously generated images. Adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/image_pool.py This buffer enables us to update discriminators using a history of generated images rather than the ones produced by ... | the_stack_v2_python_sparse | connectomics/model/utils/misc.py | zudi-lin/pytorch_connectomics | train | 149 |
67a73320bcec5dabe5f7f5919ea4e7df3aa0289f | [
"super().__init__()\nassert len(bitmap) <= window_size, 'You cannot specified more bitmap than windows'\nself.bitmap = bitmap\nself.window_size = window_size\nself.size = len(bitmap)\nreturn",
"out = ''\nfor bit in self.bitmap:\n if bit:\n out += '1'\n else:\n out += '0'\nreturn out",
"if se... | <|body_start_0|>
super().__init__()
assert len(bitmap) <= window_size, 'You cannot specified more bitmap than windows'
self.bitmap = bitmap
self.window_size = window_size
self.size = len(bitmap)
return
<|end_body_0|>
<|body_start_1|>
out = ''
for bit in s... | Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization | CompressedBitmap | [
"LicenseRef-scancode-ietf-trust",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompressedBitmap:
"""Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization"""
def __init__(self, bitmap, window_size):
"""Compressed Bitmap constructor Parameters ---------- bitmap : Lis... | stack_v2_sparse_classes_36k_train_029720 | 2,011 | permissive | [
{
"docstring": "Compressed Bitmap constructor Parameters ---------- bitmap : List[bool] Bitmap, it has to have a length of at most window size window_size : int Size of window",
"name": "__init__",
"signature": "def __init__(self, bitmap, window_size)"
},
{
"docstring": "Returns the bytes repres... | 3 | stack_v2_sparse_classes_30k_train_014012 | Implement the Python class `CompressedBitmap` described below.
Class description:
Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization
Method signatures and docstrings:
- def __init__(self, bitmap, window_size): Compres... | Implement the Python class `CompressedBitmap` described below.
Class description:
Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization
Method signatures and docstrings:
- def __init__(self, bitmap, window_size): Compres... | 2b1d9ed7d7c9857cbb362bdee5c77f7234838ddd | <|skeleton|>
class CompressedBitmap:
"""Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization"""
def __init__(self, bitmap, window_size):
"""Compressed Bitmap constructor Parameters ---------- bitmap : Lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompressedBitmap:
"""Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization"""
def __init__(self, bitmap, window_size):
"""Compressed Bitmap constructor Parameters ---------- bitmap : List[bool] Bitma... | the_stack_v2_python_sparse | fragmentation_layer/code/schc_messages/schc_header/compressed_bitmap.py | CristianWulfing/PySCHC | train | 0 |
f8a0c9d13bf87f17ea19e39fa8289049ed4ef75f | [
"if 'configuration' not in kwargs:\n kwargs['configuration'] = {}\nScript.__init__(self, **kwargs)\nself._camera = camera\nself._count = count\nself._binning = binning\nself._exptime = exptime\nif self._exptime == 0:\n self._ImageType = ImageType.BIAS\nelse:\n self._ImageType = ImageType.DARK",
"try:\n ... | <|body_start_0|>
if 'configuration' not in kwargs:
kwargs['configuration'] = {}
Script.__init__(self, **kwargs)
self._camera = camera
self._count = count
self._binning = binning
self._exptime = exptime
if self._exptime == 0:
self._ImageType... | Script for running darks or biases. | DarkBias | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkBias:
"""Script for running darks or biases."""
def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any):
"""Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed ... | stack_v2_sparse_classes_36k_train_029721 | 3,168 | permissive | [
{
"docstring": "Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed number of darks or biases exptime: exposure time [s], exptime=0 -> Bias binning: binning for dark or bias",
"name": "__init__",
"signature": "def __init__(self, camera: Union[str, ICamera],... | 3 | null | Implement the Python class `DarkBias` described below.
Class description:
Script for running darks or biases.
Method signatures and docstrings:
- def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any): Init a new DarkBias script. Args: camera: ... | Implement the Python class `DarkBias` described below.
Class description:
Script for running darks or biases.
Method signatures and docstrings:
- def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any): Init a new DarkBias script. Args: camera: ... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class DarkBias:
"""Script for running darks or biases."""
def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any):
"""Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DarkBias:
"""Script for running darks or biases."""
def __init__(self, camera: Union[str, ICamera], count: int=20, exptime: float=0, binning: Tuple[int, int]=(1, 1), **kwargs: Any):
"""Init a new DarkBias script. Args: camera: name of ICamera that takes the dark or bias count: aimed number of dar... | the_stack_v2_python_sparse | pyobs/robotic/scripts/darkbias.py | pyobs/pyobs-core | train | 9 |
7e5c75cca57193dceb1fad2f58015debc04dd8df | [
"for envname, envtree in self.envs.items():\n if not isinstance(envtree, SaltEnv):\n if isinstance(envtree, str):\n envtree = [envtree]\n self.envs[envname] = SaltEnv(name=envname, paths=envtree)\n setattr(self, envname, self.envs[envname])",
"config = {}\nfor env in self.envs.value... | <|body_start_0|>
for envname, envtree in self.envs.items():
if not isinstance(envtree, SaltEnv):
if isinstance(envtree, str):
envtree = [envtree]
self.envs[envname] = SaltEnv(name=envname, paths=envtree)
setattr(self, envname, self.envs... | This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.SaltEnv` or a list of strings(paths). I... | SaltEnvs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaltEnvs:
"""This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.Sal... | stack_v2_sparse_classes_36k_train_029722 | 14,449 | permissive | [
{
"docstring": "Post attrs initialization routines.",
"name": "__attrs_post_init__",
"signature": "def __attrs_post_init__(self)"
},
{
"docstring": "Returns a dictionary of the right types to update the salt configuration. :return dict:",
"name": "as_dict",
"signature": "def as_dict(self... | 2 | stack_v2_sparse_classes_30k_test_000566 | Implement the Python class `SaltEnvs` described below.
Class description:
This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:cl... | Implement the Python class `SaltEnvs` described below.
Class description:
This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:cl... | 7440e0923afabc9837537c3871dc7f16cf83a1de | <|skeleton|>
class SaltEnvs:
"""This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.Sal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaltEnvs:
"""This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.SaltEnv` or a li... | the_stack_v2_python_sparse | src/saltfactories/utils/tempfiles.py | s0undt3ch/pytest-salt-factories | train | 0 |
aaf7c34461cc0698fb7ba5dc26f5cac0d682ff3b | [
"node = self.Node(name, index)\nif not itemsStack:\n topologyNode.addChild(node)\ntopNodeIndex = topNode and topNode.index or -1\nwhile not index > topNodeIndex:\n itemsStack.pop()\n topNode = itemsStack and itemsStack[-1]\n topNodeIndex = topNode.index\nitemsStack.append(node)\ntopNode.children.append(... | <|body_start_0|>
node = self.Node(name, index)
if not itemsStack:
topologyNode.addChild(node)
topNodeIndex = topNode and topNode.index or -1
while not index > topNodeIndex:
itemsStack.pop()
topNode = itemsStack and itemsStack[-1]
topNodeInd... | Topology configuration is stored in topology.ini file as flat representation of the tree Part of file content: n1>host n2>ls2725 n3>cruiser n4>30008 n5>activated_at=2012-01-05 12:20:41.149 d1>active=yes n5>pid=31897 n5>read_accesscounter=0 That is actually a such tree host -> ls2725 -> cruiser -> 30008 [activated_at = ... | TopologyConfigParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyConfigParser:
"""Topology configuration is stored in topology.ini file as flat representation of the tree Part of file content: n1>host n2>ls2725 n3>cruiser n4>30008 n5>activated_at=2012-01-05 12:20:41.149 d1>active=yes n5>pid=31897 n5>read_accesscounter=0 That is actually a such tree hos... | stack_v2_sparse_classes_36k_train_029723 | 22,285 | no_license | [
{
"docstring": "@types: str, int, list[Node], Node, Node -> Node",
"name": "__createNewNode",
"signature": "def __createNewNode(self, name, index, itemsStack, topologyNode, topNode)"
},
{
"docstring": "@types: str -> TopologyConfigParser.Node @return: root node for the topology that contains sub... | 2 | null | Implement the Python class `TopologyConfigParser` described below.
Class description:
Topology configuration is stored in topology.ini file as flat representation of the tree Part of file content: n1>host n2>ls2725 n3>cruiser n4>30008 n5>activated_at=2012-01-05 12:20:41.149 d1>active=yes n5>pid=31897 n5>read_accesscou... | Implement the Python class `TopologyConfigParser` described below.
Class description:
Topology configuration is stored in topology.ini file as flat representation of the tree Part of file content: n1>host n2>ls2725 n3>cruiser n4>30008 n5>activated_at=2012-01-05 12:20:41.149 d1>active=yes n5>pid=31897 n5>read_accesscou... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class TopologyConfigParser:
"""Topology configuration is stored in topology.ini file as flat representation of the tree Part of file content: n1>host n2>ls2725 n3>cruiser n4>30008 n5>activated_at=2012-01-05 12:20:41.149 d1>active=yes n5>pid=31897 n5>read_accesscounter=0 That is actually a such tree hos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopologyConfigParser:
"""Topology configuration is stored in topology.ini file as flat representation of the tree Part of file content: n1>host n2>ls2725 n3>cruiser n4>30008 n5>activated_at=2012-01-05 12:20:41.149 d1>active=yes n5>pid=31897 n5>read_accesscounter=0 That is actually a such tree host -> ls2725 -... | the_stack_v2_python_sparse | reference/ucmdb/discovery/sap_trex_discoverer.py | madmonkyang/cda-record | train | 0 |
68be0addbbfa6028ee5563b40867015e28294bea | [
"if 'page' in self.request.POST:\n try:\n location = 'dashboard'\n kwargs = {'page': int(self.request.POST.get('page'))}\n if 'tag' in self.request.POST:\n kwargs.update({'tag': self.request.POST.get('tag')})\n location += '_tag'\n return redirect(reverse(locatio... | <|body_start_0|>
if 'page' in self.request.POST:
try:
location = 'dashboard'
kwargs = {'page': int(self.request.POST.get('page'))}
if 'tag' in self.request.POST:
kwargs.update({'tag': self.request.POST.get('tag')})
... | This view shows the dashboard of the logged in user. | DashboardView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardView:
"""This view shows the dashboard of the logged in user."""
def post(self, request, *args, **kwargs):
"""Redirect to display a certain page when jumping towards one."""
<|body_0|>
def get_model_queryset(self, list_name, model):
"""Return the five ne... | stack_v2_sparse_classes_36k_train_029724 | 25,887 | no_license | [
{
"docstring": "Redirect to display a certain page when jumping towards one.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Return the five newest objects for Accounts and Contacts. Paginate objects for BlogEntry later.",
"name": "get_model_query... | 3 | stack_v2_sparse_classes_30k_train_013027 | Implement the Python class `DashboardView` described below.
Class description:
This view shows the dashboard of the logged in user.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Redirect to display a certain page when jumping towards one.
- def get_model_queryset(self, list_name, model... | Implement the Python class `DashboardView` described below.
Class description:
This view shows the dashboard of the logged in user.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Redirect to display a certain page when jumping towards one.
- def get_model_queryset(self, list_name, model... | 0a284e2aae3ca08955215418a76bb70ad9af1f81 | <|skeleton|>
class DashboardView:
"""This view shows the dashboard of the logged in user."""
def post(self, request, *args, **kwargs):
"""Redirect to display a certain page when jumping towards one."""
<|body_0|>
def get_model_queryset(self, list_name, model):
"""Return the five ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DashboardView:
"""This view shows the dashboard of the logged in user."""
def post(self, request, *args, **kwargs):
"""Redirect to display a certain page when jumping towards one."""
if 'page' in self.request.POST:
try:
location = 'dashboard'
kw... | the_stack_v2_python_sparse | lily/users/views.py | rmoorman/hellolily | train | 0 |
6441ee22c37547ec7cb3d98ccdeef6f469932343 | [
"self.TannerObj = Tanner(netlist, wave_names)\nself.netlist = self.TannerObj.netlist\nself.waves = self.TannerObj.waves\npass",
"self.assertIsInstance(self.netlist, str)\nself.assertIsInstance(self.waves, dict)\npass"
] | <|body_start_0|>
self.TannerObj = Tanner(netlist, wave_names)
self.netlist = self.TannerObj.netlist
self.waves = self.TannerObj.waves
pass
<|end_body_0|>
<|body_start_1|>
self.assertIsInstance(self.netlist, str)
self.assertIsInstance(self.waves, dict)
pass
<|end_... | TestTannerTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTannerTypes:
def setUp(self):
"""Setup function TestTypes for class Tanner"""
<|body_0|>
def test_types(self):
"""Function to test data types for class Tanner"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.TannerObj = Tanner(netlist, wave_... | stack_v2_sparse_classes_36k_train_029725 | 943 | permissive | [
{
"docstring": "Setup function TestTypes for class Tanner",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Function to test data types for class Tanner",
"name": "test_types",
"signature": "def test_types(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011831 | Implement the Python class `TestTannerTypes` described below.
Class description:
Implement the TestTannerTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class Tanner
- def test_types(self): Function to test data types for class Tanner | Implement the Python class `TestTannerTypes` described below.
Class description:
Implement the TestTannerTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class Tanner
- def test_types(self): Function to test data types for class Tanner
<|skeleton|>
class TestTannerTypes:... | 825a0eab64be709efe161b9a48eb54c4bc5c1bef | <|skeleton|>
class TestTannerTypes:
def setUp(self):
"""Setup function TestTypes for class Tanner"""
<|body_0|>
def test_types(self):
"""Function to test data types for class Tanner"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTannerTypes:
def setUp(self):
"""Setup function TestTypes for class Tanner"""
self.TannerObj = Tanner(netlist, wave_names)
self.netlist = self.TannerObj.netlist
self.waves = self.TannerObj.waves
pass
def test_types(self):
"""Function to test data types ... | the_stack_v2_python_sparse | VLC_devel/class_structure/__auto_gen__/test_Tanner.py | wenh81/vlc_simulator | train | 0 | |
38b4ce6452eaa575cd1264358a54edd6e7a3b74f | [
"engine = db_connect()\ncreate_items_table(engine)\nself.Session = sessionmaker(bind=engine)",
"session = self.Session()\ninstance = session.query(Items).filter_by(**item).one_or_none()\nif instance:\n return instance\nzelda_item = Items(**item)\ntry:\n session.add(zelda_item)\n session.commit()\nexcept:... | <|body_start_0|>
engine = db_connect()
create_items_table(engine)
self.Session = sessionmaker(bind=engine)
<|end_body_0|>
<|body_start_1|>
session = self.Session()
instance = session.query(Items).filter_by(**item).one_or_none()
if instance:
return instance
... | CrawlPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrawlPipeline:
def __init__(self):
"""Initializes database connection and sessionmaker. Creates items table."""
<|body_0|>
def process_item(self, item, spider):
"""Process the item and store to database."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029726 | 921 | no_license | [
{
"docstring": "Initializes database connection and sessionmaker. Creates items table.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Process the item and store to database.",
"name": "process_item",
"signature": "def process_item(self, item, spider)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000159 | Implement the Python class `CrawlPipeline` described below.
Class description:
Implement the CrawlPipeline class.
Method signatures and docstrings:
- def __init__(self): Initializes database connection and sessionmaker. Creates items table.
- def process_item(self, item, spider): Process the item and store to databas... | Implement the Python class `CrawlPipeline` described below.
Class description:
Implement the CrawlPipeline class.
Method signatures and docstrings:
- def __init__(self): Initializes database connection and sessionmaker. Creates items table.
- def process_item(self, item, spider): Process the item and store to databas... | 0d7ba4cb394edc2f228a67200b5d9b69123025ea | <|skeleton|>
class CrawlPipeline:
def __init__(self):
"""Initializes database connection and sessionmaker. Creates items table."""
<|body_0|>
def process_item(self, item, spider):
"""Process the item and store to database."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrawlPipeline:
def __init__(self):
"""Initializes database connection and sessionmaker. Creates items table."""
engine = db_connect()
create_items_table(engine)
self.Session = sessionmaker(bind=engine)
def process_item(self, item, spider):
"""Process the item and s... | the_stack_v2_python_sparse | data-retrieval/crawl/pipelines.py | jitsejan/architecture-patterns-with-python | train | 5 | |
37b571283b0f2d61c9f32f32a8f34a9f617b3cef | [
"super(AvatarServicesForm, self).__init__(*args, **kwargs)\ndefault_choices = [('none', 'None')]\nenable_choices = []\nfor service in avatar_services:\n default_choices.append((service.avatar_service_id, service.name))\n enable_choices.append((service.avatar_service_id, service.name))\ndefault_service_field =... | <|body_start_0|>
super(AvatarServicesForm, self).__init__(*args, **kwargs)
default_choices = [('none', 'None')]
enable_choices = []
for service in avatar_services:
default_choices.append((service.avatar_service_id, service.name))
enable_choices.append((service.ava... | A form for managing avatar services. | AvatarServicesForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvatarServicesForm:
"""A form for managing avatar services."""
def __init__(self, *args, **kwargs):
"""Initialize the settings form. This will populate the choices and initial values for the form fields based on the current avatar configuration. Args: *args (tuple): Additional positi... | stack_v2_sparse_classes_36k_train_029727 | 5,362 | permissive | [
{
"docstring": "Initialize the settings form. This will populate the choices and initial values for the form fields based on the current avatar configuration. Args: *args (tuple): Additional positional arguments for the parent class. **kwargs (dict): Additional keyword arguments for the parent class.",
"nam... | 4 | null | Implement the Python class `AvatarServicesForm` described below.
Class description:
A form for managing avatar services.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the settings form. This will populate the choices and initial values for the form fields based on the current ava... | Implement the Python class `AvatarServicesForm` described below.
Class description:
A form for managing avatar services.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the settings form. This will populate the choices and initial values for the form fields based on the current ava... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class AvatarServicesForm:
"""A form for managing avatar services."""
def __init__(self, *args, **kwargs):
"""Initialize the settings form. This will populate the choices and initial values for the form fields based on the current avatar configuration. Args: *args (tuple): Additional positi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvatarServicesForm:
"""A form for managing avatar services."""
def __init__(self, *args, **kwargs):
"""Initialize the settings form. This will populate the choices and initial values for the form fields based on the current avatar configuration. Args: *args (tuple): Additional positional argument... | the_stack_v2_python_sparse | reviewboard/admin/forms/avatar_settings.py | reviewboard/reviewboard | train | 1,141 |
337b79b58615d2f18d864d7a01cb1dfa0641c68a | [
"self.middleman = middleman\nself.items = items\nself.keys = items\nself.data = {}\nself.tick = 0\nself.data['tick'] = 0\nfor i, key in enumerate(self.keys):\n self.data[key] = 0",
"for key, val in self.data.items():\n self.data[key] = val + 0.2 * (random() - 0.5)\n if key == 'tick':\n self.data[k... | <|body_start_0|>
self.middleman = middleman
self.items = items
self.keys = items
self.data = {}
self.tick = 0
self.data['tick'] = 0
for i, key in enumerate(self.keys):
self.data[key] = 0
<|end_body_0|>
<|body_start_1|>
for key, val in self.dat... | Market | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Market:
def __init__(self, items, middleman):
"""Dummy market emulator Args: items : List of item keys middleman : A Middleman object"""
<|body_0|>
def update(self):
"""Updates market data and propagates to Bokeh server Note: best to update all at once. Current versi... | stack_v2_sparse_classes_36k_train_029728 | 6,993 | permissive | [
{
"docstring": "Dummy market emulator Args: items : List of item keys middleman : A Middleman object",
"name": "__init__",
"signature": "def __init__(self, items, middleman)"
},
{
"docstring": "Updates market data and propagates to Bokeh server Note: best to update all at once. Current version m... | 2 | stack_v2_sparse_classes_30k_train_016762 | Implement the Python class `Market` described below.
Class description:
Implement the Market class.
Method signatures and docstrings:
- def __init__(self, items, middleman): Dummy market emulator Args: items : List of item keys middleman : A Middleman object
- def update(self): Updates market data and propagates to B... | Implement the Python class `Market` described below.
Class description:
Implement the Market class.
Method signatures and docstrings:
- def __init__(self, items, middleman): Dummy market emulator Args: items : List of item keys middleman : A Middleman object
- def update(self): Updates market data and propagates to B... | 42a5e8b20591f0e4789201b02cbbaf3837352881 | <|skeleton|>
class Market:
def __init__(self, items, middleman):
"""Dummy market emulator Args: items : List of item keys middleman : A Middleman object"""
<|body_0|>
def update(self):
"""Updates market data and propagates to Bokeh server Note: best to update all at once. Current versi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Market:
def __init__(self, items, middleman):
"""Dummy market emulator Args: items : List of item keys middleman : A Middleman object"""
self.middleman = middleman
self.items = items
self.keys = items
self.data = {}
self.tick = 0
self.data['tick'] = 0
... | the_stack_v2_python_sparse | neural_mmo/forge/blade/core/market/new_visualizer.py | alirezanobakht13/neural-mmo | train | 0 | |
255b0b02cbe3d272868465c5f9a189f682c298a1 | [
"to_date = datetime.now()\nfrom_date = to_date - timedelta(7)\ntry:\n results = shopify.Order().find(status='any', updated_at_min=from_date, updated_at_max=to_date, fields=['gateway'], limit=250)\nexcept ClientError as error:\n if hasattr(error, 'response'):\n if error.response.code == 429 and error.re... | <|body_start_0|>
to_date = datetime.now()
from_date = to_date - timedelta(7)
try:
results = shopify.Order().find(status='any', updated_at_min=from_date, updated_at_max=to_date, fields=['gateway'], limit=250)
except ClientError as error:
if hasattr(error, 'response... | ShopifyPaymentGateway | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShopifyPaymentGateway:
def import_payment_gateway(self, instance):
"""This method import payment gateway through Order API. @param instance: Shopify Instance @author: Hardik Dhankecha on Date 15-Dec-2020."""
<|body_0|>
def search_or_create_payment_gateway(self, instance, gat... | stack_v2_sparse_classes_36k_train_029729 | 5,923 | no_license | [
{
"docstring": "This method import payment gateway through Order API. @param instance: Shopify Instance @author: Hardik Dhankecha on Date 15-Dec-2020.",
"name": "import_payment_gateway",
"signature": "def import_payment_gateway(self, instance)"
},
{
"docstring": "This method searches for payment... | 3 | stack_v2_sparse_classes_30k_train_019827 | Implement the Python class `ShopifyPaymentGateway` described below.
Class description:
Implement the ShopifyPaymentGateway class.
Method signatures and docstrings:
- def import_payment_gateway(self, instance): This method import payment gateway through Order API. @param instance: Shopify Instance @author: Hardik Dhan... | Implement the Python class `ShopifyPaymentGateway` described below.
Class description:
Implement the ShopifyPaymentGateway class.
Method signatures and docstrings:
- def import_payment_gateway(self, instance): This method import payment gateway through Order API. @param instance: Shopify Instance @author: Hardik Dhan... | dd439232589631b3c59387ef22f21b5d8e724163 | <|skeleton|>
class ShopifyPaymentGateway:
def import_payment_gateway(self, instance):
"""This method import payment gateway through Order API. @param instance: Shopify Instance @author: Hardik Dhankecha on Date 15-Dec-2020."""
<|body_0|>
def search_or_create_payment_gateway(self, instance, gat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShopifyPaymentGateway:
def import_payment_gateway(self, instance):
"""This method import payment gateway through Order API. @param instance: Shopify Instance @author: Hardik Dhankecha on Date 15-Dec-2020."""
to_date = datetime.now()
from_date = to_date - timedelta(7)
try:
... | the_stack_v2_python_sparse | shopify_ept/models/payment_gateway.py | Darkmanzoro/nectarbeautyhub | train | 0 | |
12aa9b8b04d1fb31bc5a3b595a96e7f6f3cff27d | [
"self.iterable = iterable\nself.dataset_kwargs = dict(auto_gpu=auto_gpu, transform=transform, suffix=suffix, input_name=input_name, target_name=target_name, **kwargs)\nself.is_split = False\nself.dataset_method = dataset_method",
"assert self.split, 'must run {self}.split(**kwargs)'\ntest_dataset_kwargs = self.da... | <|body_start_0|>
self.iterable = iterable
self.dataset_kwargs = dict(auto_gpu=auto_gpu, transform=transform, suffix=suffix, input_name=input_name, target_name=target_name, **kwargs)
self.is_split = False
self.dataset_method = dataset_method
<|end_body_0|>
<|body_start_1|>
assert... | TrainValidationTestSplit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainValidationTestSplit:
def __init__(self, iterable: Iterable, auto_gpu=True, transform=None, suffix='*.npy', input_name=None, target_name=None, dataset_method=DictDataset, **kwargs):
"""__init__ Split an iterable into a train validation test split Args: iterable (Iterable): some itera... | stack_v2_sparse_classes_36k_train_029730 | 16,117 | no_license | [
{
"docstring": "__init__ Split an iterable into a train validation test split Args: iterable (Iterable): some iterable to divide into a train validation, test split auto_gpu (bool, optional): specify whether or not to automatically place the data onto the gpu Defaults to True. transform ([Iterable], optional): ... | 3 | null | Implement the Python class `TrainValidationTestSplit` described below.
Class description:
Implement the TrainValidationTestSplit class.
Method signatures and docstrings:
- def __init__(self, iterable: Iterable, auto_gpu=True, transform=None, suffix='*.npy', input_name=None, target_name=None, dataset_method=DictDatase... | Implement the Python class `TrainValidationTestSplit` described below.
Class description:
Implement the TrainValidationTestSplit class.
Method signatures and docstrings:
- def __init__(self, iterable: Iterable, auto_gpu=True, transform=None, suffix='*.npy', input_name=None, target_name=None, dataset_method=DictDatase... | dbb5e6a58b0ecfdb4ed3b05e5ca1841a321bd11b | <|skeleton|>
class TrainValidationTestSplit:
def __init__(self, iterable: Iterable, auto_gpu=True, transform=None, suffix='*.npy', input_name=None, target_name=None, dataset_method=DictDataset, **kwargs):
"""__init__ Split an iterable into a train validation test split Args: iterable (Iterable): some itera... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainValidationTestSplit:
def __init__(self, iterable: Iterable, auto_gpu=True, transform=None, suffix='*.npy', input_name=None, target_name=None, dataset_method=DictDataset, **kwargs):
"""__init__ Split an iterable into a train validation test split Args: iterable (Iterable): some iterable to divide ... | the_stack_v2_python_sparse | myTorch/Data/DataLoaders.py | cubayang/DeepLearningForWallShearStressPredictionAndImageSegmentation | train | 0 | |
1cb7e12870b02736a70ac0bc4dc678eea4cf5a88 | [
"self.stack = []\nself.max_size = 5\nself.top = 0",
"if self.top == self.max_size:\n print('Stack Overflow\\n')\nelse:\n self.stack.append(item)\n self.top += 1",
"if self.top == 0:\n print('Stack Underflow\\n')\nelse:\n self.stack.pop()\n self.top -= 1",
"if self.top == 0:\n print('Stack... | <|body_start_0|>
self.stack = []
self.max_size = 5
self.top = 0
<|end_body_0|>
<|body_start_1|>
if self.top == self.max_size:
print('Stack Overflow\n')
else:
self.stack.append(item)
self.top += 1
<|end_body_1|>
<|body_start_2|>
if sel... | The class Stack contains all the helper functions for stack implementation. | Stack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stack:
"""The class Stack contains all the helper functions for stack implementation."""
def __init__(self):
"""Arguments: self -- reference to the object."""
<|body_0|>
def push(self, item):
"""The function will push the required item to the stack. Arguments: se... | stack_v2_sparse_classes_36k_train_029731 | 1,815 | no_license | [
{
"docstring": "Arguments: self -- reference to the object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "The function will push the required item to the stack. Arguments: self -- reference to the object. item -- item to be pushed.",
"name": "push",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_010412 | Implement the Python class `Stack` described below.
Class description:
The class Stack contains all the helper functions for stack implementation.
Method signatures and docstrings:
- def __init__(self): Arguments: self -- reference to the object.
- def push(self, item): The function will push the required item to the... | Implement the Python class `Stack` described below.
Class description:
The class Stack contains all the helper functions for stack implementation.
Method signatures and docstrings:
- def __init__(self): Arguments: self -- reference to the object.
- def push(self, item): The function will push the required item to the... | 6870426104aef417086788221dad29e887ddfe3f | <|skeleton|>
class Stack:
"""The class Stack contains all the helper functions for stack implementation."""
def __init__(self):
"""Arguments: self -- reference to the object."""
<|body_0|>
def push(self, item):
"""The function will push the required item to the stack. Arguments: se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stack:
"""The class Stack contains all the helper functions for stack implementation."""
def __init__(self):
"""Arguments: self -- reference to the object."""
self.stack = []
self.max_size = 5
self.top = 0
def push(self, item):
"""The function will push the re... | the_stack_v2_python_sparse | Data Structure/02. Stack/01. Stack Implementation/py_code.py | Slothfulwave612/Coding-Problems | train | 5 |
3807016ed672917df96312c928fe15f7e923bb2b | [
"def recursive(root):\n if root is None:\n self.ret.append('#,')\n return\n self.ret.append(str(root.val) + ',')\n recursive(root.left)\n recursive(root.right)\nself.ret = []\nrecursive(root)\nreturn ''.join(self.ret)",
"nodes = data.split(',')\n\ndef recursive(nodes):\n if not nodes:... | <|body_start_0|>
def recursive(root):
if root is None:
self.ret.append('#,')
return
self.ret.append(str(root.val) + ',')
recursive(root.left)
recursive(root.right)
self.ret = []
recursive(root)
return ''.join... | 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_029732 | 1,693 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_016071 | 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:... | 82132065ae1b4964a1e0ef913912f382471f4eb5 | <|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 recursive(root):
if root is None:
self.ret.append('#,')
return
self.ret.append(str(root.val) + ',')
recursive(root... | the_stack_v2_python_sparse | 449.serialize-and-deserialize-bst.py | mrgrant/LeetCode | train | 0 | |
04295c02a91de6178cb7dbea7dd23c3ae98b3991 | [
"if not root:\n return []\nqueue = [root]\nres = []\nwhile queue:\n child = []\n node = []\n for q in queue:\n if q:\n child.append(q.val)\n if q.left:\n node.append(q.left)\n if q.right:\n node.append(q.right)\n queue = node\n ... | <|body_start_0|>
if not root:
return []
queue = [root]
res = []
while queue:
child = []
node = []
for q in queue:
if q:
child.append(q.val)
if q.left:
node.appe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBfs(self, root: TreeNode) -> List[List[int]]:
"""bfs"""
<|body_0|>
def levelOrder(self, root: TreeNode) -> List[List[int]]:
"""dfs :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_029733 | 1,746 | no_license | [
{
"docstring": "bfs",
"name": "levelOrderBfs",
"signature": "def levelOrderBfs(self, root: TreeNode) -> List[List[int]]"
},
{
"docstring": "dfs :param root: :return:",
"name": "levelOrder",
"signature": "def levelOrder(self, root: TreeNode) -> List[List[int]]"
}
] | 2 | stack_v2_sparse_classes_30k_train_006371 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: bfs
- def levelOrder(self, root: TreeNode) -> List[List[int]]: dfs :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBfs(self, root: TreeNode) -> List[List[int]]: bfs
- def levelOrder(self, root: TreeNode) -> List[List[int]]: dfs :param root: :return:
<|skeleton|>
class Solution:... | 1a1abf5aabdd23755769efaa6c33579bc5b0917b | <|skeleton|>
class Solution:
def levelOrderBfs(self, root: TreeNode) -> List[List[int]]:
"""bfs"""
<|body_0|>
def levelOrder(self, root: TreeNode) -> List[List[int]]:
"""dfs :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBfs(self, root: TreeNode) -> List[List[int]]:
"""bfs"""
if not root:
return []
queue = [root]
res = []
while queue:
child = []
node = []
for q in queue:
if q:
chi... | the_stack_v2_python_sparse | Week_03/G20190343020041/LeetCode_102_0041.py | algorithm005-class02/algorithm005-class02 | train | 45 | |
3123aad781f1a9807f44a457bcb363888ba070e3 | [
"if not head or not head.next:\n return head\ndummy = cur = ListNode(0, head)\nwhile head and head.next:\n if head.val == head.next.val:\n while head and head.next and (head.val == head.next.val):\n head = head.next\n head = head.next\n cur.next = head\n else:\n cur =... | <|body_start_0|>
if not head or not head.next:
return head
dummy = cur = ListNode(0, head)
while head and head.next:
if head.val == head.next.val:
while head and head.next and (head.val == head.next.val):
head = head.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.ne... | stack_v2_sparse_classes_36k_train_029734 | 1,636 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates1",
"signature": "def deleteDuplicates1(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012924 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates1(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates1(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
dummy = cur = ListNode(0, head)
while head and head.next:
if head.val == head.next.val:
while head and head... | the_stack_v2_python_sparse | out/production/leetcode/82.删除排序链表中的重复元素-ii.py | yangyuxiang1996/leetcode | train | 0 | |
5b94ebd13b85d1440fad8b56014f12a3610b795d | [
"self.directory = directory\nself.hist_name = hist_name\nunique_tag = ''.join((random.choice(string.ascii_lowercase) for x in xrange(5)))\nself.unique_name = '%s__%s__%s' % (directory, hist_name, unique_tag)\nself.hist_info = hist_info\nself.hist_type = None\nself.hist_handles = {}\nself.hist_handles_keys = []\nsel... | <|body_start_0|>
self.directory = directory
self.hist_name = hist_name
unique_tag = ''.join((random.choice(string.ascii_lowercase) for x in xrange(5)))
self.unique_name = '%s__%s__%s' % (directory, hist_name, unique_tag)
self.hist_info = hist_info
self.hist_type = None
... | docstring | HistMerger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistMerger:
"""docstring"""
def __init__(self, directory, hist_name, hist_handle_dict, hist_handle_key_list, hist_info):
"""constructor"""
<|body_0|>
def __del__(self):
"""destructor"""
<|body_1|>
def addHistHandle(self, hist_handle, label):
... | stack_v2_sparse_classes_36k_train_029735 | 5,788 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, directory, hist_name, hist_handle_dict, hist_handle_key_list, hist_info)"
},
{
"docstring": "destructor",
"name": "__del__",
"signature": "def __del__(self)"
},
{
"docstring": "docstring",
"nam... | 5 | null | Implement the Python class `HistMerger` described below.
Class description:
docstring
Method signatures and docstrings:
- def __init__(self, directory, hist_name, hist_handle_dict, hist_handle_key_list, hist_info): constructor
- def __del__(self): destructor
- def addHistHandle(self, hist_handle, label): docstring
- ... | Implement the Python class `HistMerger` described below.
Class description:
docstring
Method signatures and docstrings:
- def __init__(self, directory, hist_name, hist_handle_dict, hist_handle_key_list, hist_info): constructor
- def __del__(self): destructor
- def addHistHandle(self, hist_handle, label): docstring
- ... | 41303b163dbc05451b22c19b00b436cc25440cf6 | <|skeleton|>
class HistMerger:
"""docstring"""
def __init__(self, directory, hist_name, hist_handle_dict, hist_handle_key_list, hist_info):
"""constructor"""
<|body_0|>
def __del__(self):
"""destructor"""
<|body_1|>
def addHistHandle(self, hist_handle, label):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HistMerger:
"""docstring"""
def __init__(self, directory, hist_name, hist_handle_dict, hist_handle_key_list, hist_info):
"""constructor"""
self.directory = directory
self.hist_name = hist_name
unique_tag = ''.join((random.choice(string.ascii_lowercase) for x in xrange(5)))... | the_stack_v2_python_sparse | Plotting/HistHandle/Merger.py | UPenn-SUSY/PennSUSYFrame | train | 2 |
27277f8c1551285e40fb2bd12d8e7414d908481b | [
"if key < currentNode.key:\n if currentNode.hasLeftChild():\n self._put(key, val, currentNode.leftChild)\n else:\n currentNode.leftChild = TreeNode(key, val)\n self.updateBalance(currentNode.leftChild)\nelif currentNode.hasRightChild():\n self._put(key, val, currentNode.rightChild)\nel... | <|body_start_0|>
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key, val, currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(key, val)
self.updateBalance(currentNode.leftChild)
elif currentNode.hasRigh... | BalancedTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BalancedTree:
def _put(self, key, val, currentNode: TreeNode):
"""Similar to BST, also update parent balance factor"""
<|body_0|>
def updateBalance(self, node):
"""Update balance factor of parents node. 1) check if node is out of balance >1 or <-1, if so rebalance an... | stack_v2_sparse_classes_36k_train_029736 | 4,166 | no_license | [
{
"docstring": "Similar to BST, also update parent balance factor",
"name": "_put",
"signature": "def _put(self, key, val, currentNode: TreeNode)"
},
{
"docstring": "Update balance factor of parents node. 1) check if node is out of balance >1 or <-1, if so rebalance and return 2) check whether c... | 5 | null | Implement the Python class `BalancedTree` described below.
Class description:
Implement the BalancedTree class.
Method signatures and docstrings:
- def _put(self, key, val, currentNode: TreeNode): Similar to BST, also update parent balance factor
- def updateBalance(self, node): Update balance factor of parents node.... | Implement the Python class `BalancedTree` described below.
Class description:
Implement the BalancedTree class.
Method signatures and docstrings:
- def _put(self, key, val, currentNode: TreeNode): Similar to BST, also update parent balance factor
- def updateBalance(self, node): Update balance factor of parents node.... | 19b040360b03c883c2e3ff6dd5c836ff40124137 | <|skeleton|>
class BalancedTree:
def _put(self, key, val, currentNode: TreeNode):
"""Similar to BST, also update parent balance factor"""
<|body_0|>
def updateBalance(self, node):
"""Update balance factor of parents node. 1) check if node is out of balance >1 or <-1, if so rebalance an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BalancedTree:
def _put(self, key, val, currentNode: TreeNode):
"""Similar to BST, also update parent balance factor"""
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key, val, currentNode.leftChild)
else:
currentNode.l... | the_stack_v2_python_sparse | datastructures/AVLTree.py | kapitsa2811/leetcode-algos-python | train | 0 | |
23c84408a54a3675d5438be265381b7ca081466a | [
"if not fields:\n raise ValueError('At least one field must be provided')\nif not fields:\n raise ValueError('At least one field must be provided')\nselects = []\nfor field in fields:\n if isinstance(field, list):\n selects.append(','.join(field))\n else:\n selects.append(field)\nself._req... | <|body_start_0|>
if not fields:
raise ValueError('At least one field must be provided')
if not fields:
raise ValueError('At least one field must be provided')
selects = []
for field in fields:
if isinstance(field, list):
selects.append(... | Represent a search suggestion query again an Azure Search index. | SuggestQuery | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuggestQuery:
"""Represent a search suggestion query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: Va... | stack_v2_sparse_classes_36k_train_029737 | 4,488 | permissive | [
{
"docstring": "Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueError",
"name": "order_by",
"signature": "def order_by(self, *fields: str) -> None"
},
{
"docstring": "Update the `select` ... | 2 | stack_v2_sparse_classes_30k_val_000316 | Implement the Python class `SuggestQuery` described below.
Class description:
Represent a search suggestion query again an Azure Search index.
Method signatures and docstrings:
- def order_by(self, *fields: str) -> None: Update the `orderby` property for the search results. :param fields: A list of fields for the que... | Implement the Python class `SuggestQuery` described below.
Class description:
Represent a search suggestion query again an Azure Search index.
Method signatures and docstrings:
- def order_by(self, *fields: str) -> None: Update the `orderby` property for the search results. :param fields: A list of fields for the que... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class SuggestQuery:
"""Represent a search suggestion query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: Va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuggestQuery:
"""Represent a search suggestion query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueError"""
... | the_stack_v2_python_sparse | sdk/search/azure-search-documents/azure/search/documents/_queries.py | Azure/azure-sdk-for-python | train | 4,046 |
7800f605df3594d34514037b2dc687591114871b | [
"def traverse(arr, start, path, seen):\n if len(path) >= 2 and path not in self.res and (path == sorted(path)):\n self.res.append(path[:])\n for i in range(start, len(arr)):\n if i not in seen:\n path.append(arr[i])\n seen.add(i)\n traverse(arr, i + 1, path, seen... | <|body_start_0|>
def traverse(arr, start, path, seen):
if len(path) >= 2 and path not in self.res and (path == sorted(path)):
self.res.append(path[:])
for i in range(start, len(arr)):
if i not in seen:
path.append(arr[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
"""Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order."""
<|body_0|>
def findSubsequences1(self, nums... | stack_v2_sparse_classes_36k_train_029738 | 1,854 | no_license | [
{
"docstring": "Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order.",
"name": "findSubsequences",
"signature": "def findSubsequences(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "I... | 3 | stack_v2_sparse_classes_30k_val_000497 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubsequences(self, nums: List[int]) -> List[List[int]]: Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubsequences(self, nums: List[int]) -> List[List[int]]: Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note:... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
"""Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order."""
<|body_0|>
def findSubsequences1(self, nums... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
"""Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order."""
def traverse(arr, start, path, seen):
if len(path)... | the_stack_v2_python_sparse | backtrackIncSubseq.py | tashakim/puzzles_python | train | 8 | |
ae36c0c8ee5f9ee6c9d882cb856bf9f71e940051 | [
"Inventory.__init__(self, inventory_item.product_code, inventory_item.description, inventory_item.market_price, inventory_item.rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = {}\noutput_dict['product_code'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict[... | <|body_start_0|>
Inventory.__init__(self, inventory_item.product_code, inventory_item.description, inventory_item.market_price, inventory_item.rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['product_code'] = s... | electrical appliance class | ElecAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElecAppliances:
"""electrical appliance class"""
def __init__(self, inventory_item, brand, voltage):
"""initializes electrical appliance item"""
<|body_0|>
def return_as_dictionary(self):
"""returns electrical appliances as a dictionary"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_029739 | 1,047 | no_license | [
{
"docstring": "initializes electrical appliance item",
"name": "__init__",
"signature": "def __init__(self, inventory_item, brand, voltage)"
},
{
"docstring": "returns electrical appliances as a dictionary",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)"
... | 2 | stack_v2_sparse_classes_30k_train_014596 | Implement the Python class `ElecAppliances` described below.
Class description:
electrical appliance class
Method signatures and docstrings:
- def __init__(self, inventory_item, brand, voltage): initializes electrical appliance item
- def return_as_dictionary(self): returns electrical appliances as a dictionary | Implement the Python class `ElecAppliances` described below.
Class description:
electrical appliance class
Method signatures and docstrings:
- def __init__(self, inventory_item, brand, voltage): initializes electrical appliance item
- def return_as_dictionary(self): returns electrical appliances as a dictionary
<|sk... | 99271cd60485bd2e54f8d133c9057a2ccd6c91c2 | <|skeleton|>
class ElecAppliances:
"""electrical appliance class"""
def __init__(self, inventory_item, brand, voltage):
"""initializes electrical appliance item"""
<|body_0|>
def return_as_dictionary(self):
"""returns electrical appliances as a dictionary"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElecAppliances:
"""electrical appliance class"""
def __init__(self, inventory_item, brand, voltage):
"""initializes electrical appliance item"""
Inventory.__init__(self, inventory_item.product_code, inventory_item.description, inventory_item.market_price, inventory_item.rental_price)
... | the_stack_v2_python_sparse | students/ZackConnaughton/lesson01/assignment/inventory_management/elec_appliances_class.py | zconn/PythonCert220Assign | train | 2 |
987b76f2084919423927f2222d0e817e9a19bc46 | [
"logger.info('Overriding class: Space -> BooleanSpace.')\nn_dimensions = 1\nlower_bound = np.zeros(n_variables)\nupper_bound = np.ones(n_variables)\nsuper(BooleanSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)\nself.build()\nlogger.info('Class overrided.')",
"for agen... | <|body_start_0|>
logger.info('Overriding class: Space -> BooleanSpace.')
n_dimensions = 1
lower_bound = np.zeros(n_variables)
upper_bound = np.ones(n_variables)
super(BooleanSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)
self... | A BooleanSpace class for agents, variables and methods related to the boolean search space. | BooleanSpace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BooleanSpace:
"""A BooleanSpace class for agents, variables and methods related to the boolean search space."""
def __init__(self, n_agents: int, n_variables: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args: n_agents: Number of agents. n_variables: Num... | stack_v2_sparse_classes_36k_train_029740 | 1,335 | permissive | [
{
"docstring": "Initialization method. Args: n_agents: Number of agents. n_variables: Number of decision variables. mapping: String-based identifiers for mapping variables' names.",
"name": "__init__",
"signature": "def __init__(self, n_agents: int, n_variables: int, mapping: Optional[List[str]]=None) -... | 2 | null | Implement the Python class `BooleanSpace` described below.
Class description:
A BooleanSpace class for agents, variables and methods related to the boolean search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, mapping: Optional[List[str]]=None) -> None: Initialization m... | Implement the Python class `BooleanSpace` described below.
Class description:
A BooleanSpace class for agents, variables and methods related to the boolean search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, mapping: Optional[List[str]]=None) -> None: Initialization m... | 7326a887ed8e3858bc99c8815048d56d02edf88c | <|skeleton|>
class BooleanSpace:
"""A BooleanSpace class for agents, variables and methods related to the boolean search space."""
def __init__(self, n_agents: int, n_variables: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args: n_agents: Number of agents. n_variables: Num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BooleanSpace:
"""A BooleanSpace class for agents, variables and methods related to the boolean search space."""
def __init__(self, n_agents: int, n_variables: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args: n_agents: Number of agents. n_variables: Number of decisi... | the_stack_v2_python_sparse | opytimizer/spaces/boolean.py | gugarosa/opytimizer | train | 602 |
61a04c4d382f5dfe80c3384ec7277519399addc6 | [
"self.load_date = load_date\nself.verbose = verbose\nif isinstance(self.load_date, str):\n self.load_date = pd.to_datetime(self.load_date)\nif isinstance(self.load_date, pd.Timestamp):\n doy = str(self.load_date.dayofyear).zfill(3)\nelif isinstance(self.load_date, (datetime, date)):\n doy = str(self.load_d... | <|body_start_0|>
self.load_date = load_date
self.verbose = verbose
if isinstance(self.load_date, str):
self.load_date = pd.to_datetime(self.load_date)
if isinstance(self.load_date, pd.Timestamp):
doy = str(self.load_date.dayofyear).zfill(3)
elif isinstance... | Load_SAMPEX_HILT | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Load_SAMPEX_HILT:
def __init__(self, load_date, extract=False, time_index=True, verbose=False):
"""Load the HILT data given a date. If this class will look for a file with the "hhrrYYYYDOY*" filename pattern and open the found csv file. If the file is zipped, it will first be unzipped. I... | stack_v2_sparse_classes_36k_train_029741 | 10,167 | permissive | [
{
"docstring": "Load the HILT data given a date. If this class will look for a file with the \"hhrrYYYYDOY*\" filename pattern and open the found csv file. If the file is zipped, it will first be unzipped. If you want to extract the file as well, set extract=True. time_index=True sets the time index of self.hil... | 5 | stack_v2_sparse_classes_30k_train_017642 | Implement the Python class `Load_SAMPEX_HILT` described below.
Class description:
Implement the Load_SAMPEX_HILT class.
Method signatures and docstrings:
- def __init__(self, load_date, extract=False, time_index=True, verbose=False): Load the HILT data given a date. If this class will look for a file with the "hhrrYY... | Implement the Python class `Load_SAMPEX_HILT` described below.
Class description:
Implement the Load_SAMPEX_HILT class.
Method signatures and docstrings:
- def __init__(self, load_date, extract=False, time_index=True, verbose=False): Load the HILT data given a date. If this class will look for a file with the "hhrrYY... | 916a24f072034fea4680ab13f98d967d2ecfcf5d | <|skeleton|>
class Load_SAMPEX_HILT:
def __init__(self, load_date, extract=False, time_index=True, verbose=False):
"""Load the HILT data given a date. If this class will look for a file with the "hhrrYYYYDOY*" filename pattern and open the found csv file. If the file is zipped, it will first be unzipped. I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Load_SAMPEX_HILT:
def __init__(self, load_date, extract=False, time_index=True, verbose=False):
"""Load the HILT data given a date. If this class will look for a file with the "hhrrYYYYDOY*" filename pattern and open the found csv file. If the file is zipped, it will first be unzipped. If you want to ... | the_stack_v2_python_sparse | sampex_microburst_widths/misc/load_hilt_data.py | mshumko/sampex_microburst_widths | train | 0 | |
a4240c08728bc439a12c239c4891ae41f16b164d | [
"if N == 0:\n return 0\nself.M = M\nself.nums = [x for x in range(1, N + 1)]\nself.res = 0\nself.dfs(1, [str(self.nums[0])])\nreturn self.res",
"if index == len(self.nums):\n if self.cal(path) == self.M:\n self.res += 1\n return\nfor op in '+-s':\n if op != 's':\n path.append(op)\n ... | <|body_start_0|>
if N == 0:
return 0
self.M = M
self.nums = [x for x in range(1, N + 1)]
self.res = 0
self.dfs(1, [str(self.nums[0])])
return self.res
<|end_body_0|>
<|body_start_1|>
if index == len(self.nums):
if self.cal(path) == self.M:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def func(self, N, M):
"""Args: N: int M: int Return: int"""
<|body_0|>
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
<|body_1|>
def cal(self, path):
"""Args: path: list[str] Return: int"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k_train_029742 | 1,922 | no_license | [
{
"docstring": "Args: N: int M: int Return: int",
"name": "func",
"signature": "def func(self, N, M)"
},
{
"docstring": "Args: index: int path: list[str]",
"name": "dfs",
"signature": "def dfs(self, index, path)"
},
{
"docstring": "Args: path: list[str] Return: int",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_002739 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, N, M): Args: N: int M: int Return: int
- def dfs(self, index, path): Args: index: int path: list[str]
- def cal(self, path): Args: path: list[str] Return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, N, M): Args: N: int M: int Return: int
- def dfs(self, index, path): Args: index: int path: list[str]
- def cal(self, path): Args: path: list[str] Return: int
<|s... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def func(self, N, M):
"""Args: N: int M: int Return: int"""
<|body_0|>
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
<|body_1|>
def cal(self, path):
"""Args: path: list[str] Return: int"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def func(self, N, M):
"""Args: N: int M: int Return: int"""
if N == 0:
return 0
self.M = M
self.nums = [x for x in range(1, N + 1)]
self.res = 0
self.dfs(1, [str(self.nums[0])])
return self.res
def dfs(self, index, path):
... | the_stack_v2_python_sparse | 秋招/小米/如何添加运算符.py | AiZhanghan/Leetcode | train | 0 | |
8450b240d02591891e5eaa9ecf7e66ef7a724a0c | [
"if 'debug' in kwargs:\n warnings.warn('Keyword debug has been deprecated.', DeprecationWarning)\nif device is None:\n from .pl_server.device import Device\n device = Device.active_device\nself.device = device\nif base_addr < 0 or length < 0:\n raise ValueError('Base address or length cannot be negative... | <|body_start_0|>
if 'debug' in kwargs:
warnings.warn('Keyword debug has been deprecated.', DeprecationWarning)
if device is None:
from .pl_server.device import Device
device = Device.active_device
self.device = device
if base_addr < 0 or length < 0:
... | This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A device that can interact with the... | MMIO | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMIO:
"""This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A d... | stack_v2_sparse_classes_36k_train_029743 | 5,926 | permissive | [
{
"docstring": "Return a new MMIO object. Parameters ---------- base_addr : int The base address of the MMIO. length : int The length in bytes; default is 4. device: Device The device that MMIO object is created for.",
"name": "__init__",
"signature": "def __init__(self, base_addr, length=4, device=None... | 4 | stack_v2_sparse_classes_30k_train_000738 | Implement the Python class `MMIO` described below.
Class description:
This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for e... | Implement the Python class `MMIO` described below.
Class description:
This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for e... | de6b6fc3a803945d59f8f06523addfe0d9b60a1c | <|skeleton|>
class MMIO:
"""This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MMIO:
"""This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A device that ca... | the_stack_v2_python_sparse | pynq/mmio.py | schelleg/PYNQ | train | 1 |
44ab080409a0baddac6e71cc84accb4bf5592c7f | [
"if root == None:\n return ''\nres = []\nqueue = deque()\nqueue.append(root)\nres.append(root.val)\nwhile queue:\n node = queue.popleft()\n if node == 'None':\n continue\n if node.left != None:\n queue.append(node.left)\n res.append(node.left.val)\n else:\n res.append('Non... | <|body_start_0|>
if root == None:
return ''
res = []
queue = deque()
queue.append(root)
res.append(root.val)
while queue:
node = queue.popleft()
if node == 'None':
continue
if node.left != None:
... | 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_029744 | 4,106 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006413 | 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:... | 56047a5058c6a20b356ab20e52eacb425ad45762 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return ''
res = []
queue = deque()
queue.append(root)
res.append(root.val)
while queue:
node = queue.popl... | the_stack_v2_python_sparse | Python/BinaryTree/297. Serialize and Deserialize Binary Tree.py | Leahxuliu/Data-Structure-And-Algorithm | train | 2 | |
f2e11f0b80f8c6848b9d3591d2fba976f04b32f1 | [
"M = len(matrix)\nN = len(matrix[0])\nF = [[0 for _ in xrange(N + 1)] for _ in xrange(M + 1)]\ngmax = 0\nfor i in xrange(1, M + 1):\n for j in xrange(1, N + 1):\n if matrix[i - 1][j - 1] == 1:\n F[i][j] = min(F[i - 1][j], F[i][j - 1], F[i - 1][j - 1]) + 1\n gmax = max(gmax, F[i][j])\... | <|body_start_0|>
M = len(matrix)
N = len(matrix[0])
F = [[0 for _ in xrange(N + 1)] for _ in xrange(M + 1)]
gmax = 0
for i in xrange(1, M + 1):
for j in xrange(1, N + 1):
if matrix[i - 1][j - 1] == 1:
F[i][j] = min(F[i - 1][j], F[i]... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSquare(self, matrix):
"""Algorithm: O(n^2) let F_{i, j} represents the max square's length ended at matrix_{i, j} (lower right corner). F_{i, j} = min{F_{i-1, j}, F_{i, j-1}, F_{i-1, j-1}}+1 // if matrix{i, j} == 1 F_{i, j} = 0 // otherwise O(n^3) sandwich approach :para... | stack_v2_sparse_classes_36k_train_029745 | 2,163 | permissive | [
{
"docstring": "Algorithm: O(n^2) let F_{i, j} represents the max square's length ended at matrix_{i, j} (lower right corner). F_{i, j} = min{F_{i-1, j}, F_{i, j-1}, F_{i-1, j-1}}+1 // if matrix{i, j} == 1 F_{i, j} = 0 // otherwise O(n^3) sandwich approach :param matrix: a matrix of 0 and 1 :return: an integer"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSquare(self, matrix): Algorithm: O(n^2) let F_{i, j} represents the max square's length ended at matrix_{i, j} (lower right corner). F_{i, j} = min{F_{i-1, j}, F_{i, j-1},... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSquare(self, matrix): Algorithm: O(n^2) let F_{i, j} represents the max square's length ended at matrix_{i, j} (lower right corner). F_{i, j} = min{F_{i-1, j}, F_{i, j-1},... | 4629a3857b2c57418b86a3b3a7180ecb15e763e3 | <|skeleton|>
class Solution:
def maxSquare(self, matrix):
"""Algorithm: O(n^2) let F_{i, j} represents the max square's length ended at matrix_{i, j} (lower right corner). F_{i, j} = min{F_{i-1, j}, F_{i, j-1}, F_{i-1, j-1}}+1 // if matrix{i, j} == 1 F_{i, j} = 0 // otherwise O(n^3) sandwich approach :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSquare(self, matrix):
"""Algorithm: O(n^2) let F_{i, j} represents the max square's length ended at matrix_{i, j} (lower right corner). F_{i, j} = min{F_{i-1, j}, F_{i, j-1}, F_{i-1, j-1}}+1 // if matrix{i, j} == 1 F_{i, j} = 0 // otherwise O(n^3) sandwich approach :param matrix: a ma... | the_stack_v2_python_sparse | Maximal Square.py | RijuDasgupta9116/LintCode | train | 0 | |
66268995fefabb36f90b8f7f19e7fd13a99945b5 | [
"self._name = name\nself._adapter = introspection_adapter\niface_id = InterfaceIdentifier('com.vmware.vapi.std.introspection.provider')\nmethod_defs = {}\nget_method_id = MethodIdentifier(iface_id, 'get')\noutput_def = StructDefinition('com.vmware.vapi.std.introspection.provider.info', [('id', StringDefinition()), ... | <|body_start_0|>
self._name = name
self._adapter = introspection_adapter
iface_id = InterfaceIdentifier('com.vmware.vapi.std.introspection.provider')
method_defs = {}
get_method_id = MethodIdentifier(iface_id, 'get')
output_def = StructDefinition('com.vmware.vapi.std.intr... | This service provides operations to retrieve information of a vAPI Provider. A provider represents a vAPI endpoint that is exposing a collection of vAPI services. | ProviderApiInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProviderApiInterface:
"""This service provides operations to retrieve information of a vAPI Provider. A provider represents a vAPI endpoint that is exposing a collection of vAPI services."""
def __init__(self, name, introspection_adapter):
"""Initialize ProviderApiInterface :type nam... | stack_v2_sparse_classes_36k_train_029746 | 27,765 | no_license | [
{
"docstring": "Initialize ProviderApiInterface :type name: :class:`str` :param name: Name of the provider :type introspection_adapter: :class:`vmware.vapi.provider.introspection.ApiProviderIntrospector` :param introspection_adapter: Adapter for fetching introspection information",
"name": "__init__",
"... | 2 | null | Implement the Python class `ProviderApiInterface` described below.
Class description:
This service provides operations to retrieve information of a vAPI Provider. A provider represents a vAPI endpoint that is exposing a collection of vAPI services.
Method signatures and docstrings:
- def __init__(self, name, introspe... | Implement the Python class `ProviderApiInterface` described below.
Class description:
This service provides operations to retrieve information of a vAPI Provider. A provider represents a vAPI endpoint that is exposing a collection of vAPI services.
Method signatures and docstrings:
- def __init__(self, name, introspe... | 5d395700ab3d0d1d45b497e48beab8c366fca9f5 | <|skeleton|>
class ProviderApiInterface:
"""This service provides operations to retrieve information of a vAPI Provider. A provider represents a vAPI endpoint that is exposing a collection of vAPI services."""
def __init__(self, name, introspection_adapter):
"""Initialize ProviderApiInterface :type nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProviderApiInterface:
"""This service provides operations to retrieve information of a vAPI Provider. A provider represents a vAPI endpoint that is exposing a collection of vAPI services."""
def __init__(self, name, introspection_adapter):
"""Initialize ProviderApiInterface :type name: :class:`st... | the_stack_v2_python_sparse | alexa-program/vmware/vapi/provider/introspection.py | taromurata/TDP2018_VMCAPI | train | 1 |
2c1b38dc6037f5386b94e0f348b8a24418166a86 | [
"super().__init__()\nself.multioutputWrapper = False\nimport sklearn\nimport sklearn.linear_model\nself.model = sklearn.linear_model.Ridge",
"specs = super(Ridge, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{Ridge} regressor also known as\\n \\\\textit{linear leas... | <|body_start_0|>
super().__init__()
self.multioutputWrapper = False
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.Ridge
<|end_body_0|>
<|body_start_1|>
specs = super(Ridge, cls).getInputSpecification()
specs.description = 'The \\xml... | Ridge Regressor | Ridge | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ridge:
"""Ridge Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input d... | stack_v2_sparse_classes_36k_train_029747 | 7,366 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | null | Implement the Python class `Ridge` described below.
Class description:
Ridge Regressor
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a reference to a class that ... | Implement the Python class `Ridge` described below.
Class description:
Ridge Regressor
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a reference to a class that ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class Ridge:
"""Ridge Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ridge:
"""Ridge Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
self.multioutputWrapper = False
import sklearn
import sklearn.linear_model
self.mode... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/LinearModel/Ridge.py | idaholab/raven | train | 201 |
9190df27fce86a01a474e84a82c0179ea9968817 | [
"name, *args = config.split(':')\navailable = []\nfor each in cls.mro():\n available.extend([name for k, name in cls._registry if k is each])\n if (each, name) in cls._registry:\n return validated_config(cls._registry[each, name](cls, *args))\nraise ValueError(f'{config} is not a valid config. Availabl... | <|body_start_0|>
name, *args = config.split(':')
available = []
for each in cls.mro():
available.extend([name for k, name in cls._registry if k is each])
if (each, name) in cls._registry:
return validated_config(cls._registry[each, name](cls, *args))
... | Base class for project configs. This class exists to simplify support of easily specifying complex configs from command line, by providing a registry of parameterized parsers to assign values to the entire nested config using simple preset values. For example config class: ``` from ml_collections import config_flags @d... | ProjectConfig | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectConfig:
"""Base class for project configs. This class exists to simplify support of easily specifying complex configs from command line, by providing a registry of parameterized parsers to assign values to the entire nested config using simple preset values. For example config class: ``` f... | stack_v2_sparse_classes_36k_train_029748 | 6,153 | permissive | [
{
"docstring": "Parses config and returns an instance of cls.",
"name": "parse_config",
"signature": "def parse_config(cls, config)"
},
{
"docstring": "Registers flag parser with a given name. This is a decorator that can be used to decorate functions that can parse configs. The parser will be i... | 2 | stack_v2_sparse_classes_30k_train_007279 | Implement the Python class `ProjectConfig` described below.
Class description:
Base class for project configs. This class exists to simplify support of easily specifying complex configs from command line, by providing a registry of parameterized parsers to assign values to the entire nested config using simple preset ... | Implement the Python class `ProjectConfig` described below.
Class description:
Base class for project configs. This class exists to simplify support of easily specifying complex configs from command line, by providing a registry of parameterized parsers to assign values to the entire nested config using simple preset ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ProjectConfig:
"""Base class for project configs. This class exists to simplify support of easily specifying complex configs from command line, by providing a registry of parameterized parsers to assign values to the entire nested config using simple preset values. For example config class: ``` f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectConfig:
"""Base class for project configs. This class exists to simplify support of easily specifying complex configs from command line, by providing a registry of parameterized parsers to assign values to the entire nested config using simple preset values. For example config class: ``` from ml_collec... | the_stack_v2_python_sparse | wildfire_perc_sim/config.py | Jimmy-INL/google-research | train | 1 |
9cbc33ce5507bc5e170d5d53435d107a91f1dea1 | [
"rental_data = [['Elisa Miles', 'LC04', 'Leather Chair', '12.0'], ['Edward Data', 'CT78', 'Coffee Table', '10.0'], ['Alex Gonzales', 'BR01', 'Bed Frame', '80.0']]\ninvoice_file = 'rental_data.csv'\nfor record in rental_data:\n add_furniture(invoice_file, record[0], record[1], record[2], record[3])\nwith open(inv... | <|body_start_0|>
rental_data = [['Elisa Miles', 'LC04', 'Leather Chair', '12.0'], ['Edward Data', 'CT78', 'Coffee Table', '10.0'], ['Alex Gonzales', 'BR01', 'Bed Frame', '80.0']]
invoice_file = 'rental_data.csv'
for record in rental_data:
add_furniture(invoice_file, record[0], record... | Unit tests for inventory functions | TestInventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInventory:
"""Unit tests for inventory functions"""
def test_add_furniture(self):
"""Tests function to add rental data to csv file"""
<|body_0|>
def test_single_customer(self):
"""Tests function to add multiple rental data for a single customer"""
<|b... | stack_v2_sparse_classes_36k_train_029749 | 1,574 | no_license | [
{
"docstring": "Tests function to add rental data to csv file",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self)"
},
{
"docstring": "Tests function to add multiple rental data for a single customer",
"name": "test_single_customer",
"signature": "def test_single_cu... | 2 | stack_v2_sparse_classes_30k_train_017250 | Implement the Python class `TestInventory` described below.
Class description:
Unit tests for inventory functions
Method signatures and docstrings:
- def test_add_furniture(self): Tests function to add rental data to csv file
- def test_single_customer(self): Tests function to add multiple rental data for a single cu... | Implement the Python class `TestInventory` described below.
Class description:
Unit tests for inventory functions
Method signatures and docstrings:
- def test_add_furniture(self): Tests function to add rental data to csv file
- def test_single_customer(self): Tests function to add multiple rental data for a single cu... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestInventory:
"""Unit tests for inventory functions"""
def test_add_furniture(self):
"""Tests function to add rental data to csv file"""
<|body_0|>
def test_single_customer(self):
"""Tests function to add multiple rental data for a single customer"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestInventory:
"""Unit tests for inventory functions"""
def test_add_furniture(self):
"""Tests function to add rental data to csv file"""
rental_data = [['Elisa Miles', 'LC04', 'Leather Chair', '12.0'], ['Edward Data', 'CT78', 'Coffee Table', '10.0'], ['Alex Gonzales', 'BR01', 'Bed Frame'... | the_stack_v2_python_sparse | students/joli-u/lesson08/test_inventory.py | JavaRod/SP_Python220B_2019 | train | 1 |
e6f3b3cfe120ccaa761d3edfa1f2339c4c5846b2 | [
"try:\n self.__genre = 'review'\n self.__task_elements_dict = {'priority': self.task.priority, 'level': self.task.level, 'last_updated_time': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'), 'pickup_date': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'), 'connector_instance_log_id': self... | <|body_start_0|>
try:
self.__genre = 'review'
self.__task_elements_dict = {'priority': self.task.priority, 'level': self.task.level, 'last_updated_time': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'), 'pickup_date': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'),... | This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America | CustomerServiceScoreBoardConnector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerServiceScoreBoardConnector:
"""This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America"""
def fetch(self):
"""Fetch of customerservicescoreboard.com"""
<|body_0|>
def __iteratePosts(self):
"""It will Iterate Ov... | stack_v2_sparse_classes_36k_train_029750 | 7,675 | no_license | [
{
"docstring": "Fetch of customerservicescoreboard.com",
"name": "fetch",
"signature": "def fetch(self)"
},
{
"docstring": "It will Iterate Over the links found in the Current URI",
"name": "__iteratePosts",
"signature": "def __iteratePosts(self)"
},
{
"docstring": "This will tak... | 5 | stack_v2_sparse_classes_30k_train_019117 | Implement the Python class `CustomerServiceScoreBoardConnector` described below.
Class description:
This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America
Method signatures and docstrings:
- def fetch(self): Fetch of customerservicescoreboard.com
- def __iteratePosts(self... | Implement the Python class `CustomerServiceScoreBoardConnector` described below.
Class description:
This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America
Method signatures and docstrings:
- def fetch(self): Fetch of customerservicescoreboard.com
- def __iteratePosts(self... | dbd14efb81b28be6340dfd00df9d31cc6a290b08 | <|skeleton|>
class CustomerServiceScoreBoardConnector:
"""This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America"""
def fetch(self):
"""Fetch of customerservicescoreboard.com"""
<|body_0|>
def __iteratePosts(self):
"""It will Iterate Ov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerServiceScoreBoardConnector:
"""This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America"""
def fetch(self):
"""Fetch of customerservicescoreboard.com"""
try:
self.__genre = 'review'
self.__task_elements_dict = {'p... | the_stack_v2_python_sparse | crawler/connectors/customerservicescoreboardconnector.py | jsyadav/CrawlerFramework | train | 1 |
868fe3a2b8e740366c0faa1f3952fa2af1758f3a | [
"if HA is not None:\n self.HA = HA\nelse:\n self.HA = A\nself.A = np.mat(A)\nself.HA = np.mat(self.HA)\nself.d = np.mat(d)\nself.E = np.mat(E)\nself.ndim, self.nens = A.shape\nself.nobs = len(d)\nself.R = np.mat(np.diag(np.diag(1.0 / (self.nens - 1) * self.E * self.E.T)))",
"Dp = self.d + np.mean(self.E, ax... | <|body_start_0|>
if HA is not None:
self.HA = HA
else:
self.HA = A
self.A = np.mat(A)
self.HA = np.mat(self.HA)
self.d = np.mat(d)
self.E = np.mat(E)
self.ndim, self.nens = A.shape
self.nobs = len(d)
self.R = np.mat(np.diag(... | ENKF | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ENKF:
def __init__(self, A, HA, d, E):
"""Initialize Ensemble Kalman Filter object using a state matrix *A*, a predicted measurement matrix *HA*, an observation vector *d*, and an observation error covariance matrix *R*."""
<|body_0|>
def analysis(self, dists):
"""Pe... | stack_v2_sparse_classes_36k_train_029751 | 4,032 | permissive | [
{
"docstring": "Initialize Ensemble Kalman Filter object using a state matrix *A*, a predicted measurement matrix *HA*, an observation vector *d*, and an observation error covariance matrix *R*.",
"name": "__init__",
"signature": "def __init__(self, A, HA, d, E)"
},
{
"docstring": "Perform the a... | 2 | stack_v2_sparse_classes_30k_train_006394 | Implement the Python class `ENKF` described below.
Class description:
Implement the ENKF class.
Method signatures and docstrings:
- def __init__(self, A, HA, d, E): Initialize Ensemble Kalman Filter object using a state matrix *A*, a predicted measurement matrix *HA*, an observation vector *d*, and an observation err... | Implement the Python class `ENKF` described below.
Class description:
Implement the ENKF class.
Method signatures and docstrings:
- def __init__(self, A, HA, d, E): Initialize Ensemble Kalman Filter object using a state matrix *A*, a predicted measurement matrix *HA*, an observation vector *d*, and an observation err... | 27d0abcaeefd8760ce68e05e52905aea5f8f3a51 | <|skeleton|>
class ENKF:
def __init__(self, A, HA, d, E):
"""Initialize Ensemble Kalman Filter object using a state matrix *A*, a predicted measurement matrix *HA*, an observation vector *d*, and an observation error covariance matrix *R*."""
<|body_0|>
def analysis(self, dists):
"""Pe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ENKF:
def __init__(self, A, HA, d, E):
"""Initialize Ensemble Kalman Filter object using a state matrix *A*, a predicted measurement matrix *HA*, an observation vector *d*, and an observation error covariance matrix *R*."""
if HA is not None:
self.HA = HA
else:
... | the_stack_v2_python_sparse | src/kalman.py | nasa/RHEAS | train | 88 | |
df76d797c60cefe8bfb44bcbaf67ca2c5725bb74 | [
"self.name = name\nself.function = function\nself.hindcast = hindcast\nself.probabilistic = probabilistic\nself.long_name = long_name\nself.aliases = aliases",
"summary = '----- Comparison metadata -----\\n'\nsummary += f'Name: {self.name}\\n'\nif not self.probabilistic:\n summary += 'Kind: deterministic\\n'\n... | <|body_start_0|>
self.name = name
self.function = function
self.hindcast = hindcast
self.probabilistic = probabilistic
self.long_name = long_name
self.aliases = aliases
<|end_body_0|>
<|body_start_1|>
summary = '----- Comparison metadata -----\n'
summary ... | Master class for all comparisons. See :ref:`comparisons`. | Comparison | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
... | stack_v2_sparse_classes_36k_train_029752 | 11,669 | permissive | [
{
"docstring": "Comparison initialization See :ref:`comparisons`. Args: name: name of comparison. function: comparison function. hindcast: Can comparison be used in :py:class:`.HindcastEnsemble`? ``False`` means only :py:class:`.PerfectModelEnsemble` probabilistic: Can this comparison be used for probabilistic ... | 2 | stack_v2_sparse_classes_30k_train_021014 | Implement the Python class `Comparison` described below.
Class description:
Master class for all comparisons. See :ref:`comparisons`.
Method signatures and docstrings:
- def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Op... | Implement the Python class `Comparison` described below.
Class description:
Master class for all comparisons. See :ref:`comparisons`.
Method signatures and docstrings:
- def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Op... | 1424e89e9bdf3eb1ae47d581be2953ede0b98996 | <|skeleton|>
class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
"""Comparis... | the_stack_v2_python_sparse | climpred/comparisons.py | pangeo-data/climpred | train | 164 |
b9cd4e1ab9cb30bf63b8487027b548f0388e16b0 | [
"super().__init__()\nself.norm = nn.LayerNorm(query_dim)\nself.att = SelfAttention(name=name, how=how, query_dim=query_dim, cross_attention_dim=cross_attention_dim, head_dim=head_dim, num_heads=num_heads, dropout=dropout, bias=bias, slice_size=slice_size, **kwargs)",
"residual = x\nx = self.norm(x)\nx = self.att(... | <|body_start_0|>
super().__init__()
self.norm = nn.LayerNorm(query_dim)
self.att = SelfAttention(name=name, how=how, query_dim=query_dim, cross_attention_dim=cross_attention_dim, head_dim=head_dim, num_heads=num_heads, dropout=dropout, bias=bias, slice_size=slice_size, **kwargs)
<|end_body_0|>
... | SelfAttentionBlock | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttentionBlock:
def __init__(self, how: str, query_dim: int, name: str='exact', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None:
"""Singular self-attention block. These can be stacked to for... | stack_v2_sparse_classes_36k_train_029753 | 10,093 | permissive | [
{
"docstring": "Singular self-attention block. These can be stacked to form a tranformer block. NOTE: Can be used as a cross-attention block if `cross_attention_dim` is given. Input Shape: (B, H'*W', query_dim). Output Shape: (B, H'*W', query_dim). Parameters ---------- name : str Name of the attention method. ... | 2 | stack_v2_sparse_classes_30k_train_019927 | Implement the Python class `SelfAttentionBlock` described below.
Class description:
Implement the SelfAttentionBlock class.
Method signatures and docstrings:
- def __init__(self, how: str, query_dim: int, name: str='exact', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: b... | Implement the Python class `SelfAttentionBlock` described below.
Class description:
Implement the SelfAttentionBlock class.
Method signatures and docstrings:
- def __init__(self, how: str, query_dim: int, name: str='exact', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: b... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class SelfAttentionBlock:
def __init__(self, how: str, query_dim: int, name: str='exact', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None:
"""Singular self-attention block. These can be stacked to for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttentionBlock:
def __init__(self, how: str, query_dim: int, name: str='exact', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None:
"""Singular self-attention block. These can be stacked to form a tranformer... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/self_attention_modules.py | okunator/cellseg_models.pytorch | train | 43 | |
32b8a91260344dd21ca3b33011301a97298708e2 | [
"if '@' in username:\n kw = 'email'\nelse:\n kw = 'username'\nuser_kwargs = {kw: username}\ntry:\n user = User.objects.get(**user_kwargs)\n if user.check_password(raw_password=password):\n return user\nexcept User.DoesNotExist:\n return None",
"try:\n return User.objects.get(pk=pk)\nexcep... | <|body_start_0|>
if '@' in username:
kw = 'email'
else:
kw = 'username'
user_kwargs = {kw: username}
try:
user = User.objects.get(**user_kwargs)
if user.check_password(raw_password=password):
return user
except User.... | This model backend class utilized user email or username for authentication | EmailOrUsernameModelBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailOrUsernameModelBackend:
"""This model backend class utilized user email or username for authentication"""
def authenticate(self, request, username=None, password=None, **kwargs):
"""Authentication method"""
<|body_0|>
def get_user(self, pk):
"""Getting the u... | stack_v2_sparse_classes_36k_train_029754 | 938 | no_license | [
{
"docstring": "Authentication method",
"name": "authenticate",
"signature": "def authenticate(self, request, username=None, password=None, **kwargs)"
},
{
"docstring": "Getting the user via the Primary Key",
"name": "get_user",
"signature": "def get_user(self, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001803 | Implement the Python class `EmailOrUsernameModelBackend` described below.
Class description:
This model backend class utilized user email or username for authentication
Method signatures and docstrings:
- def authenticate(self, request, username=None, password=None, **kwargs): Authentication method
- def get_user(sel... | Implement the Python class `EmailOrUsernameModelBackend` described below.
Class description:
This model backend class utilized user email or username for authentication
Method signatures and docstrings:
- def authenticate(self, request, username=None, password=None, **kwargs): Authentication method
- def get_user(sel... | 6f0f9e3b7e2e544a4fe3a9bfa2451712e1dd1307 | <|skeleton|>
class EmailOrUsernameModelBackend:
"""This model backend class utilized user email or username for authentication"""
def authenticate(self, request, username=None, password=None, **kwargs):
"""Authentication method"""
<|body_0|>
def get_user(self, pk):
"""Getting the u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailOrUsernameModelBackend:
"""This model backend class utilized user email or username for authentication"""
def authenticate(self, request, username=None, password=None, **kwargs):
"""Authentication method"""
if '@' in username:
kw = 'email'
else:
kw = '... | the_stack_v2_python_sparse | app/authentication/backend/authentication.py | fuadaghazada/fampact-backend | train | 1 |
a589c8b107a55883312bab4be41c957b2b572709 | [
"features = np.concatenate([self.one_hot_sequence, self.one_hot_sequence, np.zeros_like(self.one_hot_sequence)], axis=1)\nlogits = np.expand_dims(np.array([1.0, 2.0, 3.0, 4.0, 5.0]), axis=0)\nwith self.test_session():\n inputs = {DataKeys.FEATURES: tf.convert_to_tensor(features, dtype=tf.float32), DataKeys.LOGIT... | <|body_start_0|>
features = np.concatenate([self.one_hot_sequence, self.one_hot_sequence, np.zeros_like(self.one_hot_sequence)], axis=1)
logits = np.expand_dims(np.array([1.0, 2.0, 3.0, 4.0, 5.0]), axis=0)
with self.test_session():
inputs = {DataKeys.FEATURES: tf.convert_to_tensor(fe... | NormalizationTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizationTests:
def test_logit_normalization(self):
"""test standard normalization"""
<|body_0|>
def test_shuf_logit_normalization(self):
"""test standard normalization"""
<|body_1|>
def test_masked_normalization(self):
"""test masking for df... | stack_v2_sparse_classes_36k_train_029755 | 4,948 | permissive | [
{
"docstring": "test standard normalization",
"name": "test_logit_normalization",
"signature": "def test_logit_normalization(self)"
},
{
"docstring": "test standard normalization",
"name": "test_shuf_logit_normalization",
"signature": "def test_shuf_logit_normalization(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_010694 | Implement the Python class `NormalizationTests` described below.
Class description:
Implement the NormalizationTests class.
Method signatures and docstrings:
- def test_logit_normalization(self): test standard normalization
- def test_shuf_logit_normalization(self): test standard normalization
- def test_masked_norma... | Implement the Python class `NormalizationTests` described below.
Class description:
Implement the NormalizationTests class.
Method signatures and docstrings:
- def test_logit_normalization(self): test standard normalization
- def test_shuf_logit_normalization(self): test standard normalization
- def test_masked_norma... | 59654a958f6debb5be150e383e96997f1982359d | <|skeleton|>
class NormalizationTests:
def test_logit_normalization(self):
"""test standard normalization"""
<|body_0|>
def test_shuf_logit_normalization(self):
"""test standard normalization"""
<|body_1|>
def test_masked_normalization(self):
"""test masking for df... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizationTests:
def test_logit_normalization(self):
"""test standard normalization"""
features = np.concatenate([self.one_hot_sequence, self.one_hot_sequence, np.zeros_like(self.one_hot_sequence)], axis=1)
logits = np.expand_dims(np.array([1.0, 2.0, 3.0, 4.0, 5.0]), axis=0)
... | the_stack_v2_python_sparse | tronn/nets/normalization_nets_test.py | mbrannon88/tronn | train | 0 | |
4b730d3e38b819b3c47d559efddf8d6c464e81a6 | [
"test = '2\\n><\\n1 2'\nd = Gh(test)\nself.assertEqual(d.n, 2)\nself.assertEqual(d.numa, [1, 0])\nself.assertEqual(d.numb, [1, 2])\nself.assertEqual(Gh(test).calculate(), 'FINITE')\ntest = '3\\n>><\\n2 1 1'\nself.assertEqual(Gh(test).calculate(), 'INFINITE')\ntest = '4\\n>>><\\n1 1 1 4'\nself.assertEqual(Gh(test).c... | <|body_start_0|>
test = '2\n><\n1 2'
d = Gh(test)
self.assertEqual(d.n, 2)
self.assertEqual(d.numa, [1, 0])
self.assertEqual(d.numb, [1, 2])
self.assertEqual(Gh(test).calculate(), 'FINITE')
test = '3\n>><\n2 1 1'
self.assertEqual(Gh(test).calculate(), 'INF... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Gh class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '2\n><\n1 2'
d = Gh(test)
self.assertEqual(d.n, 2)
... | stack_v2_sparse_classes_36k_train_029756 | 3,180 | permissive | [
{
"docstring": "Gh class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003030 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Gh class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Gh class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""Gh ... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Gh class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Gh class testing"""
test = '2\n><\n1 2'
d = Gh(test)
self.assertEqual(d.n, 2)
self.assertEqual(d.numa, [1, 0])
self.assertEqual(d.numb, [1, 2])
self.assertEqual(Gh(test).calculate(), 'FINITE')
test = '3\n... | the_stack_v2_python_sparse | codeforces/669B_gh.py | snsokolov/contests | train | 1 | |
b3407ded89cf05171a3270d349cd8938e6d9867a | [
"split = line.strip().split(delimiter)\nself.fam, self.ind_id, self.fa, self.mo, self.sex = split[0:5]\nself.aff = split[5] if len(split) > 5 else None\nself.data = split[6:] if len(split) > 6 else None",
"temp_id = (self.fam, self.ind_id)\nind = Individual(population, temp_id, self.fa, self.mo, sex_codes[self.se... | <|body_start_0|>
split = line.strip().split(delimiter)
self.fam, self.ind_id, self.fa, self.mo, self.sex = split[0:5]
self.aff = split[5] if len(split) > 5 else None
self.data = split[6:] if len(split) > 6 else None
<|end_body_0|>
<|body_start_1|>
temp_id = (self.fam, self.ind_i... | PEDRecord | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PEDRecord:
def __init__(self, line, delimiter=' '):
"""Creates pedigree record from line :param line: a line in the pedigree file :param delmiter: field separator :type line: string :type delimiter: string"""
<|body_0|>
def create_individual(self, population=None):
"... | stack_v2_sparse_classes_36k_train_029757 | 10,859 | permissive | [
{
"docstring": "Creates pedigree record from line :param line: a line in the pedigree file :param delmiter: field separator :type line: string :type delimiter: string",
"name": "__init__",
"signature": "def __init__(self, line, delimiter=' ')"
},
{
"docstring": "Creates an Individual object from... | 2 | stack_v2_sparse_classes_30k_train_011711 | Implement the Python class `PEDRecord` described below.
Class description:
Implement the PEDRecord class.
Method signatures and docstrings:
- def __init__(self, line, delimiter=' '): Creates pedigree record from line :param line: a line in the pedigree file :param delmiter: field separator :type line: string :type de... | Implement the Python class `PEDRecord` described below.
Class description:
Implement the PEDRecord class.
Method signatures and docstrings:
- def __init__(self, line, delimiter=' '): Creates pedigree record from line :param line: a line in the pedigree file :param delmiter: field separator :type line: string :type de... | 67436d73a90a1f38f014857ea5ab5f6948d100a3 | <|skeleton|>
class PEDRecord:
def __init__(self, line, delimiter=' '):
"""Creates pedigree record from line :param line: a line in the pedigree file :param delmiter: field separator :type line: string :type delimiter: string"""
<|body_0|>
def create_individual(self, population=None):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PEDRecord:
def __init__(self, line, delimiter=' '):
"""Creates pedigree record from line :param line: a line in the pedigree file :param delmiter: field separator :type line: string :type delimiter: string"""
split = line.strip().split(delimiter)
self.fam, self.ind_id, self.fa, self.mo... | the_stack_v2_python_sparse | pydigree/io/base.py | lucventurini/pydigree | train | 0 | |
0cf55d839fdc00177395aa24ece36a78426c8a0e | [
"files = validated_data.pop('files', [])\ninstance = self.Meta.model.objects.create(**validated_data)\nfor file in files:\n File.objects.create(file=S3Object.objects.get(pk=file['id']), room=instance)\nreturn instance",
"files = validated_data.pop('files', [])\nfor file in files:\n try:\n file = File... | <|body_start_0|>
files = validated_data.pop('files', [])
instance = self.Meta.model.objects.create(**validated_data)
for file in files:
File.objects.create(file=S3Object.objects.get(pk=file['id']), room=instance)
return instance
<|end_body_0|>
<|body_start_1|>
files ... | RoomSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomSerializer:
def create(self, validated_data):
"""Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room"""
<|body_0|>
def update(self, instance, validated_data):
"""Implementi... | stack_v2_sparse_classes_36k_train_029758 | 16,085 | no_license | [
{
"docstring": "Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Implementing the update method We extract the file... | 3 | stack_v2_sparse_classes_30k_train_014613 | Implement the Python class `RoomSerializer` described below.
Class description:
Implement the RoomSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files wit... | Implement the Python class `RoomSerializer` described below.
Class description:
Implement the RoomSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files wit... | bef520659a7316c861933f9609b6b9ca7d9f47ac | <|skeleton|>
class RoomSerializer:
def create(self, validated_data):
"""Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room"""
<|body_0|>
def update(self, instance, validated_data):
"""Implementi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoomSerializer:
def create(self, validated_data):
"""Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room"""
files = validated_data.pop('files', [])
instance = self.Meta.model.objects.create(**val... | the_stack_v2_python_sparse | projects/serializers.py | charliephairoj/backend | train | 0 | |
58a62510157ae8189fac9f571aea0fc80a19d56a | [
"Leaf.__init__(self, scope=scope)\nself.unique_vals = unique_vals\nself.mean = mean\nself.inverted_mean = inverted_mean\nself.square_mean = square_mean\nself.inverted_square_mean = inverted_square_mean\nself.prob_sum = prob_sum\nself.null_value_prob = null_value_prob",
"col = self.scope[0]\nnumber_null_values = r... | <|body_start_0|>
Leaf.__init__(self, scope=scope)
self.unique_vals = unique_vals
self.mean = mean
self.inverted_mean = inverted_mean
self.square_mean = square_mean
self.inverted_square_mean = inverted_square_mean
self.prob_sum = prob_sum
self.null_value_pr... | IdentityNumericLeaf | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityNumericLeaf:
def __init__(self, unique_vals, mean, inverted_mean, square_mean, inverted_square_mean, prob_sum, null_value_prob, scope=None):
"""Instead of histogram remember individual values. :param unique_vals: all possible values in leaf :param mean: mean of not null values :p... | stack_v2_sparse_classes_36k_train_029759 | 15,472 | permissive | [
{
"docstring": "Instead of histogram remember individual values. :param unique_vals: all possible values in leaf :param mean: mean of not null values :param inverted_mean: inverted mean of not null values :param square_mean: mean of squared not null values :param inverted_square_mean: mean of 1/squared not null... | 2 | stack_v2_sparse_classes_30k_train_007220 | Implement the Python class `IdentityNumericLeaf` described below.
Class description:
Implement the IdentityNumericLeaf class.
Method signatures and docstrings:
- def __init__(self, unique_vals, mean, inverted_mean, square_mean, inverted_square_mean, prob_sum, null_value_prob, scope=None): Instead of histogram remembe... | Implement the Python class `IdentityNumericLeaf` described below.
Class description:
Implement the IdentityNumericLeaf class.
Method signatures and docstrings:
- def __init__(self, unique_vals, mean, inverted_mean, square_mean, inverted_square_mean, prob_sum, null_value_prob, scope=None): Instead of histogram remembe... | a8989bfadcf551ee1dee2aec57ef6b2709c9f85d | <|skeleton|>
class IdentityNumericLeaf:
def __init__(self, unique_vals, mean, inverted_mean, square_mean, inverted_square_mean, prob_sum, null_value_prob, scope=None):
"""Instead of histogram remember individual values. :param unique_vals: all possible values in leaf :param mean: mean of not null values :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityNumericLeaf:
def __init__(self, unique_vals, mean, inverted_mean, square_mean, inverted_square_mean, prob_sum, null_value_prob, scope=None):
"""Instead of histogram remember individual values. :param unique_vals: all possible values in leaf :param mean: mean of not null values :param inverted_... | the_stack_v2_python_sparse | CardinalityEstimationTestbed/Synthetic/deepdb/deepdb_job_ranges/aqp_spn/aqp_leaves.py | TsinghuaDatabaseGroup/AI4DBCode | train | 53 | |
4cd47ccda052bd21ddb821da7d775c334df3098f | [
"self._vertex = vertex\nself._edges = edges\nself._building_block = building_block",
"position_matrix = self._vertex.place_building_block(building_block=self._building_block, edges=self._edges)\nposition_matrix.setflags(write=False)\nbuilding_block = self._building_block.with_position_matrix(position_matrix=posit... | <|body_start_0|>
self._vertex = vertex
self._edges = edges
self._building_block = building_block
<|end_body_0|>
<|body_start_1|>
position_matrix = self._vertex.place_building_block(building_block=self._building_block, edges=self._edges)
position_matrix.setflags(write=False)
... | Represents placement of a building block on a vertex. It represents a computation which carries out the placement of the building block on the vertex and the mapping of its functional group to edges. | _Placement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Placement:
"""Represents placement of a building block on a vertex. It represents a computation which carries out the placement of the building block on the vertex and the mapping of its functional group to edges."""
def __init__(self, vertex, edges, building_block):
"""Initialize a... | stack_v2_sparse_classes_36k_train_029760 | 2,570 | permissive | [
{
"docstring": "Initialize a :class:`._Placement`. Parameters ---------- vertex : :class:`.Vertex` The vertex which does the placement. edges : :class:`tuple` of :class:`.Edge` The edges connected to `vertex`. building_block : :class:`.BuildingBlock` The building block to be placed on `vertex`.",
"name": "_... | 2 | null | Implement the Python class `_Placement` described below.
Class description:
Represents placement of a building block on a vertex. It represents a computation which carries out the placement of the building block on the vertex and the mapping of its functional group to edges.
Method signatures and docstrings:
- def __... | Implement the Python class `_Placement` described below.
Class description:
Represents placement of a building block on a vertex. It represents a computation which carries out the placement of the building block on the vertex and the mapping of its functional group to edges.
Method signatures and docstrings:
- def __... | 46f70cd000890ca7c2312cc0fdbab306565f1400 | <|skeleton|>
class _Placement:
"""Represents placement of a building block on a vertex. It represents a computation which carries out the placement of the building block on the vertex and the mapping of its functional group to edges."""
def __init__(self, vertex, edges, building_block):
"""Initialize a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Placement:
"""Represents placement of a building block on a vertex. It represents a computation which carries out the placement of the building block on the vertex and the mapping of its functional group to edges."""
def __init__(self, vertex, edges, building_block):
"""Initialize a :class:`._Pl... | the_stack_v2_python_sparse | src/stk/molecular/topology_graphs/topology_graph/topology_graph/implementations/utilities.py | supramolecular-toolkit/stk | train | 22 |
5928d867f9dcaec1bec5798217cd30f325263229 | [
"for k, v in phenotypes.items():\n assert type(k) is str, 'phenotype keys must be strings'\n assert v[1] > v[0], 'upper bound of ' + k + ' must be greater than the lower bound'\n assert type(v[1]) is int and type(v[0]) is int, ' (!) recent change means bounds need to be in ints now: https://github.com/zafa... | <|body_start_0|>
for k, v in phenotypes.items():
assert type(k) is str, 'phenotype keys must be strings'
assert v[1] > v[0], 'upper bound of ' + k + ' must be greater than the lower bound'
assert type(v[1]) is int and type(v[0]) is int, ' (!) recent change means bounds need t... | PhenotypeEvaluator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhenotypeEvaluator:
def __init__(self, phenotypes):
"""PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dicti... | stack_v2_sparse_classes_36k_train_029761 | 3,310 | no_license | [
{
"docstring": "PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dictionary [mandatory] must contain entries akin to { 'phenotype-nam... | 2 | stack_v2_sparse_classes_30k_train_020234 | Implement the Python class `PhenotypeEvaluator` described below.
Class description:
Implement the PhenotypeEvaluator class.
Method signatures and docstrings:
- def __init__(self, phenotypes): PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. I... | Implement the Python class `PhenotypeEvaluator` described below.
Class description:
Implement the PhenotypeEvaluator class.
Method signatures and docstrings:
- def __init__(self, phenotypes): PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. I... | a01c36ddaaf72d04608ad1a848a24864b73e95bf | <|skeleton|>
class PhenotypeEvaluator:
def __init__(self, phenotypes):
"""PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dicti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhenotypeEvaluator:
def __init__(self, phenotypes):
"""PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dictionary [mandato... | the_stack_v2_python_sparse | cc3dtools/Phenotype.py | ibrahim85/metastasis | train | 0 | |
b92cfcd02a639f8d00ee8806c67415a63e09dccc | [
"username = getpass.getuser()\nself.root_directory = general.root_directory()\nself.infoset_user_exists = True\nself.infoset_user = None\nself.running_as_root = False\nif username == 'root':\n self.running_as_root = True\n try:\n self.infoset_user = input('Please enter the username under which infoset-... | <|body_start_0|>
username = getpass.getuser()
self.root_directory = general.root_directory()
self.infoset_user_exists = True
self.infoset_user = None
self.running_as_root = False
if username == 'root':
self.running_as_root = True
try:
... | Class to setup infoset-ng daemon. | _Daemon | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Daemon:
"""Class to setup infoset-ng daemon."""
def __init__(self):
"""Function for intializing the class. Args: None Returns: None"""
<|body_0|>
def setup(self):
"""Setup daemon scripts and file permissions. Args: None Returns: None"""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_029762 | 20,450 | permissive | [
{
"docstring": "Function for intializing the class. Args: None Returns: None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Setup daemon scripts and file permissions. Args: None Returns: None",
"name": "setup",
"signature": "def setup(self)"
},
{
"docs... | 5 | stack_v2_sparse_classes_30k_train_013160 | Implement the Python class `_Daemon` described below.
Class description:
Class to setup infoset-ng daemon.
Method signatures and docstrings:
- def __init__(self): Function for intializing the class. Args: None Returns: None
- def setup(self): Setup daemon scripts and file permissions. Args: None Returns: None
- def _... | Implement the Python class `_Daemon` described below.
Class description:
Class to setup infoset-ng daemon.
Method signatures and docstrings:
- def __init__(self): Function for intializing the class. Args: None Returns: None
- def setup(self): Setup daemon scripts and file permissions. Args: None Returns: None
- def _... | bac6f7e2157bea76ce882e8dab320d24b66bb718 | <|skeleton|>
class _Daemon:
"""Class to setup infoset-ng daemon."""
def __init__(self):
"""Function for intializing the class. Args: None Returns: None"""
<|body_0|>
def setup(self):
"""Setup daemon scripts and file permissions. Args: None Returns: None"""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Daemon:
"""Class to setup infoset-ng daemon."""
def __init__(self):
"""Function for intializing the class. Args: None Returns: None"""
username = getpass.getuser()
self.root_directory = general.root_directory()
self.infoset_user_exists = True
self.infoset_user = N... | the_stack_v2_python_sparse | setup.py | Quantum99/infoset-ng | train | 1 |
efce05504735d6df03bb1f6dd2e5defe1cc32cfa | [
"try:\n payload = {'exp': datetime.datetime.utcnow() + config.JWT_SET.get('expiration'), 'iat': datetime.datetime.utcnow(), 'iss': 'ken', 'data': {'id': userid}}\n return jwt.encode(payload, config.JWT_SET.get('secret'), algorithm='HS256')\nexcept Exception as e:\n return e",
"try:\n payload = jwt.dec... | <|body_start_0|>
try:
payload = {'exp': datetime.datetime.utcnow() + config.JWT_SET.get('expiration'), 'iat': datetime.datetime.utcnow(), 'iss': 'ken', 'data': {'id': userid}}
return jwt.encode(payload, config.JWT_SET.get('secret'), algorithm='HS256')
except Exception as e:
... | Authority | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Authority:
def encode_jwt(userid):
"""生成jwt"""
<|body_0|>
def decode_jwt(auth_token):
"""解析jwt"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
payload = {'exp': datetime.datetime.utcnow() + config.JWT_SET.get('expiration'), 'iat': d... | stack_v2_sparse_classes_36k_train_029763 | 1,081 | no_license | [
{
"docstring": "生成jwt",
"name": "encode_jwt",
"signature": "def encode_jwt(userid)"
},
{
"docstring": "解析jwt",
"name": "decode_jwt",
"signature": "def decode_jwt(auth_token)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000812 | Implement the Python class `Authority` described below.
Class description:
Implement the Authority class.
Method signatures and docstrings:
- def encode_jwt(userid): 生成jwt
- def decode_jwt(auth_token): 解析jwt | Implement the Python class `Authority` described below.
Class description:
Implement the Authority class.
Method signatures and docstrings:
- def encode_jwt(userid): 生成jwt
- def decode_jwt(auth_token): 解析jwt
<|skeleton|>
class Authority:
def encode_jwt(userid):
"""生成jwt"""
<|body_0|>
def de... | b0c237425e7147879da4dd336af4c4c31cfdcfde | <|skeleton|>
class Authority:
def encode_jwt(userid):
"""生成jwt"""
<|body_0|>
def decode_jwt(auth_token):
"""解析jwt"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Authority:
def encode_jwt(userid):
"""生成jwt"""
try:
payload = {'exp': datetime.datetime.utcnow() + config.JWT_SET.get('expiration'), 'iat': datetime.datetime.utcnow(), 'iss': 'ken', 'data': {'id': userid}}
return jwt.encode(payload, config.JWT_SET.get('secret'), algorit... | the_stack_v2_python_sparse | Server/app/ServerView/Authority/Authority.py | vaststar/Blog | train | 1 | |
36a5f4a4e171ab61e5ff83028a4dd5b390fbb07c | [
"self.maxDiff = None\nindexer = Indexer()\nfor text in self.texts:\n text = text.strip()\n bag = BagOfWords(text, enable_stemming=False, filter_stopwords=False)\n indexer.index(bag)\nself.assertSequenceEqual(self.expected['docs_index'], indexer.docs_index)\nself.assertDictEqual(self.expected['words_index']... | <|body_start_0|>
self.maxDiff = None
indexer = Indexer()
for text in self.texts:
text = text.strip()
bag = BagOfWords(text, enable_stemming=False, filter_stopwords=False)
indexer.index(bag)
self.assertSequenceEqual(self.expected['docs_index'], indexer.... | Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf | TestIndexer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIndexer:
"""Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf"""
def test_index_creation(self):
"""Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf... | stack_v2_sparse_classes_36k_train_029764 | 7,596 | permissive | [
{
"docstring": "Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf",
"name": "test_index_creation",
"signature": "def test_index_creation(self)"
},
{
"docstring": "Prueba los scores de una palabra ... | 3 | stack_v2_sparse_classes_30k_train_010095 | Implement the Python class `TestIndexer` described below.
Class description:
Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf
Method signatures and docstrings:
- def test_index_creation(self): Prueba la creación del indice Esta prueba usa el sigui... | Implement the Python class `TestIndexer` described below.
Class description:
Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf
Method signatures and docstrings:
- def test_index_creation(self): Prueba la creación del indice Esta prueba usa el sigui... | d3f24952cc0bd0f3f6ab7bae7428836511b3d67e | <|skeleton|>
class TestIndexer:
"""Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf"""
def test_index_creation(self):
"""Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestIndexer:
"""Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf"""
def test_index_creation(self):
"""Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#... | the_stack_v2_python_sparse | tfidf_index/TFIDF/tests.py | sankosk/SIW | train | 0 |
1b5caaf8edd93e3f28dbdee27db9e5d5714030ca | [
"super().__init__()\nlayers: list[Module] = [nn.modules.Sequential(nn.modules.Conv2d(in_channels, inner_channels, 3, 1, 1), nn.modules.BatchNorm2d(inner_channels), nn.modules.ReLU(True))]\nlayers += [nn.modules.Sequential(nn.modules.Conv2d(inner_channels, inner_channels, 3, 1, 1), nn.modules.BatchNorm2d(inner_chann... | <|body_start_0|>
super().__init__()
layers: list[Module] = [nn.modules.Sequential(nn.modules.Conv2d(in_channels, inner_channels, 3, 1, 1), nn.modules.BatchNorm2d(inner_channels), nn.modules.ReLU(True))]
layers += [nn.modules.Sequential(nn.modules.Conv2d(inner_channels, inner_channels, 3, 1, 1), ... | This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002 | ChangeMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeMixin:
"""This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002"""
... | stack_v2_sparse_classes_36k_train_029765 | 7,715 | permissive | [
{
"docstring": "Initializes a new ChangeMixin module. Args: in_channels: sum of channels of bitemporal feature maps inner_channels: number of channels of inner feature maps num_convs: number of convolution blocks scale_factor: number of upsampling factor",
"name": "__init__",
"signature": "def __init__(... | 2 | stack_v2_sparse_classes_30k_train_003829 | Implement the Python class `ChangeMixin` described below.
Class description:
This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * ... | Implement the Python class `ChangeMixin` described below.
Class description:
This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * ... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class ChangeMixin:
"""This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangeMixin:
"""This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002"""
def __init_... | the_stack_v2_python_sparse | torchgeo/models/changestar.py | microsoft/torchgeo | train | 1,724 |
b70e73edb101e6303b655e31f58aa1ebc22cac70 | [
"super(SDNet, self).__init__(parameters)\nself.anatomy_factors = 8\nself.modality_factors = 8\nif parameters['patch_size'] != [224, 224, 1]:\n print('WARNING: The patch size is not 224x224, which is required for sdnet. Using default patch size instead', file=sys.stderr)\n parameters['patch_size'] = [224, 224,... | <|body_start_0|>
super(SDNet, self).__init__(parameters)
self.anatomy_factors = 8
self.modality_factors = 8
if parameters['patch_size'] != [224, 224, 1]:
print('WARNING: The patch size is not 224x224, which is required for sdnet. Using default patch size instead', file=sys.st... | SDNet | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SDNet:
def __init__(self, parameters: dict):
"""SDNet (Structure-Disentangled Network) module. Args: parameters (dict): A dictionary containing model parameters. Attributes: anatomy_factors (int): The number of anatomical factors to be considered. modality_factors (int): The number of mo... | stack_v2_sparse_classes_36k_train_029766 | 14,834 | permissive | [
{
"docstring": "SDNet (Structure-Disentangled Network) module. Args: parameters (dict): A dictionary containing model parameters. Attributes: anatomy_factors (int): The number of anatomical factors to be considered. modality_factors (int): The number of modality factors to be considered. cencoder (unet): U-Net ... | 3 | stack_v2_sparse_classes_30k_train_018053 | Implement the Python class `SDNet` described below.
Class description:
Implement the SDNet class.
Method signatures and docstrings:
- def __init__(self, parameters: dict): SDNet (Structure-Disentangled Network) module. Args: parameters (dict): A dictionary containing model parameters. Attributes: anatomy_factors (int... | Implement the Python class `SDNet` described below.
Class description:
Implement the SDNet class.
Method signatures and docstrings:
- def __init__(self, parameters: dict): SDNet (Structure-Disentangled Network) module. Args: parameters (dict): A dictionary containing model parameters. Attributes: anatomy_factors (int... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class SDNet:
def __init__(self, parameters: dict):
"""SDNet (Structure-Disentangled Network) module. Args: parameters (dict): A dictionary containing model parameters. Attributes: anatomy_factors (int): The number of anatomical factors to be considered. modality_factors (int): The number of mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SDNet:
def __init__(self, parameters: dict):
"""SDNet (Structure-Disentangled Network) module. Args: parameters (dict): A dictionary containing model parameters. Attributes: anatomy_factors (int): The number of anatomical factors to be considered. modality_factors (int): The number of modality factors... | the_stack_v2_python_sparse | GANDLF/models/sdnet.py | mlcommons/GaNDLF | train | 45 | |
b2c8849b114ffbfe4722b43a1884203fb935c767 | [
"self._num_classes = num_classes\nself._level = level\nself._num_convs = num_convs\nself._upsample_factor = upsample_factor\nself._upsample_num_filters = upsample_num_filters\nif activation == 'relu':\n self._activation = tf.nn.relu\nelif activation == 'swish':\n self._activation = tf.nn.swish\nelse:\n rai... | <|body_start_0|>
self._num_classes = num_classes
self._level = level
self._num_convs = num_convs
self._upsample_factor = upsample_factor
self._upsample_num_filters = upsample_num_filters
if activation == 'relu':
self._activation = tf.nn.relu
elif activ... | Semantic segmentation head. | SegmentationHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationHead:
"""Semantic segmentation head."""
def __init__(self, num_classes, level, num_convs=2, upsample_factor=1, upsample_num_filters=256, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu')):
"""Initialize params to b... | stack_v2_sparse_classes_36k_train_029767 | 46,218 | permissive | [
{
"docstring": "Initialize params to build segmentation head. Args: num_classes: `int` number of mask classification categories. The number of classes does not include background class. level: `int` feature level used for prediction. num_convs: `int` number of stacked convolution before the last prediction laye... | 2 | null | Implement the Python class `SegmentationHead` described below.
Class description:
Semantic segmentation head.
Method signatures and docstrings:
- def __init__(self, num_classes, level, num_convs=2, upsample_factor=1, upsample_num_filters=256, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchN... | Implement the Python class `SegmentationHead` described below.
Class description:
Semantic segmentation head.
Method signatures and docstrings:
- def __init__(self, num_classes, level, num_convs=2, upsample_factor=1, upsample_num_filters=256, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchN... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class SegmentationHead:
"""Semantic segmentation head."""
def __init__(self, num_classes, level, num_convs=2, upsample_factor=1, upsample_num_filters=256, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu')):
"""Initialize params to b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentationHead:
"""Semantic segmentation head."""
def __init__(self, num_classes, level, num_convs=2, upsample_factor=1, upsample_num_filters=256, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu')):
"""Initialize params to build segmenta... | the_stack_v2_python_sparse | models/official/detection/modeling/architecture/heads.py | tensorflow/tpu | train | 5,627 |
dc4dfbe73ea869dcd0b2c8946b7c53a6fb66c814 | [
"form_valid = isinstance(response, HttpResponseRedirect)\nif request.POST.get('_save') and form_valid:\n return redirect('admin:index')\nreturn response",
"try:\n singleton = self.model.objects.get()\nexcept (self.model.DoesNotExist, self.model.MultipleObjectsReturned):\n kwargs.setdefault('extra_context... | <|body_start_0|>
form_valid = isinstance(response, HttpResponseRedirect)
if request.POST.get('_save') and form_valid:
return redirect('admin:index')
return response
<|end_body_0|>
<|body_start_1|>
try:
singleton = self.model.objects.get()
except (self.mod... | Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. | SingletonAdmin | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't."""
def handle_save(self, request, response):
"""Handles redirect back to the dash... | stack_v2_sparse_classes_36k_train_029768 | 2,498 | permissive | [
{
"docstring": "Handles redirect back to the dashboard when save is clicked (eg not save and continue editing), by checking for a redirect response, which only occurs if the form is valid.",
"name": "handle_save",
"signature": "def handle_save(self, request, response)"
},
{
"docstring": "Redirec... | 4 | stack_v2_sparse_classes_30k_train_004568 | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't.
Method signatures and docstrings:
- def handle_save(se... | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't.
Method signatures and docstrings:
- def handle_save(se... | 29203de1d111a6d94d576a89430b37edd24cef55 | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't."""
def handle_save(self, request, response):
"""Handles redirect back to the dash... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't."""
def handle_save(self, request, response):
"""Handles redirect back to the dashboard when sa... | the_stack_v2_python_sparse | mezzanine/utils/admin.py | fermorltd/mezzanine | train | 6 |
d9af9ade7ca949b474b107f1120b00e38e2f9c53 | [
"self.initialize(**params)\ncfgcmd = 'smt configure -d {datadir}'.format(**params)\nself.exec(cfgcmd, params['rundir'])\nself.exec(cmd, params['rundir'])\nerr = self.last_sc.stderr\nif err.startswith('WARNING:root:Returned:'):\n parts = self.last_sc.stderr.split()\n if parts[1] != '0':\n raise RuntimeE... | <|body_start_0|>
self.initialize(**params)
cfgcmd = 'smt configure -d {datadir}'.format(**params)
self.exec(cfgcmd, params['rundir'])
self.exec(cmd, params['rundir'])
err = self.last_sc.stderr
if err.startswith('WARNING:root:Returned:'):
parts = self.last_sc.s... | A SumatraRunner runs a program as governed by a parameter set under Sumatra. The canonical parameters: - `rundir` specifies the current working directory to use when calling the program. This is also the Sumatra workdir and repository. - `datadir` specifies where output data files should appear and any found there will... | SumatraRunner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumatraRunner:
"""A SumatraRunner runs a program as governed by a parameter set under Sumatra. The canonical parameters: - `rundir` specifies the current working directory to use when calling the program. This is also the Sumatra workdir and repository. - `datadir` specifies where output data fil... | stack_v2_sparse_classes_36k_train_029769 | 13,942 | no_license | [
{
"docstring": "Run for Sumatra, needs potentially to initialize .smt and .git directories and call 'smt configure' before finally 'smt run'.",
"name": "run",
"signature": "def run(self, cmd, **params)"
},
{
"docstring": "Return a command line from the parameters",
"name": "cmdline",
"si... | 3 | stack_v2_sparse_classes_30k_train_001313 | Implement the Python class `SumatraRunner` described below.
Class description:
A SumatraRunner runs a program as governed by a parameter set under Sumatra. The canonical parameters: - `rundir` specifies the current working directory to use when calling the program. This is also the Sumatra workdir and repository. - `d... | Implement the Python class `SumatraRunner` described below.
Class description:
A SumatraRunner runs a program as governed by a parameter set under Sumatra. The canonical parameters: - `rundir` specifies the current working directory to use when calling the program. This is also the Sumatra workdir and repository. - `d... | 50bf5ccc9ea9527d4032e0992fb70f598c236d37 | <|skeleton|>
class SumatraRunner:
"""A SumatraRunner runs a program as governed by a parameter set under Sumatra. The canonical parameters: - `rundir` specifies the current working directory to use when calling the program. This is also the Sumatra workdir and repository. - `datadir` specifies where output data fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SumatraRunner:
"""A SumatraRunner runs a program as governed by a parameter set under Sumatra. The canonical parameters: - `rundir` specifies the current working directory to use when calling the program. This is also the Sumatra workdir and repository. - `datadir` specifies where output data files should app... | the_stack_v2_python_sparse | femb_python/runpolicy.py | DUNE/femb_python | train | 3 |
71e69b29ec2990c6c94e3bab610583e199762c6f | [
"self.num_reduce_shards = num_reduce_shards\nself.output_dir = output_dir\nself.partition_id = partition_id\nself.reduce_output_prefix = reduce_output_prefix\nself.view_box_id = view_box_id\nself.view_name = view_name",
"if dictionary is None:\n return None\nnum_reduce_shards = dictionary.get('numReduceShards'... | <|body_start_0|>
self.num_reduce_shards = num_reduce_shards
self.output_dir = output_dir
self.partition_id = partition_id
self.reduce_output_prefix = reduce_output_prefix
self.view_box_id = view_box_id
self.view_name = view_name
<|end_body_0|>
<|body_start_1|>
if... | Implementation of the 'OutputSpec' model. TODO: type description here. Attributes: num_reduce_shards (int): Number of reduce shards. output_dir (string): Name of output directory. partition_id (long|int): Partition id where output will go. reduce_output_prefix (string): Prefix of the reduce output files. File names wil... | OutputSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputSpec:
"""Implementation of the 'OutputSpec' model. TODO: type description here. Attributes: num_reduce_shards (int): Number of reduce shards. output_dir (string): Name of output directory. partition_id (long|int): Partition id where output will go. reduce_output_prefix (string): Prefix of t... | stack_v2_sparse_classes_36k_train_029770 | 2,942 | permissive | [
{
"docstring": "Constructor for the OutputSpec class",
"name": "__init__",
"signature": "def __init__(self, num_reduce_shards=None, output_dir=None, partition_id=None, reduce_output_prefix=None, view_box_id=None, view_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictio... | 2 | null | Implement the Python class `OutputSpec` described below.
Class description:
Implementation of the 'OutputSpec' model. TODO: type description here. Attributes: num_reduce_shards (int): Number of reduce shards. output_dir (string): Name of output directory. partition_id (long|int): Partition id where output will go. red... | Implement the Python class `OutputSpec` described below.
Class description:
Implementation of the 'OutputSpec' model. TODO: type description here. Attributes: num_reduce_shards (int): Number of reduce shards. output_dir (string): Name of output directory. partition_id (long|int): Partition id where output will go. red... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OutputSpec:
"""Implementation of the 'OutputSpec' model. TODO: type description here. Attributes: num_reduce_shards (int): Number of reduce shards. output_dir (string): Name of output directory. partition_id (long|int): Partition id where output will go. reduce_output_prefix (string): Prefix of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputSpec:
"""Implementation of the 'OutputSpec' model. TODO: type description here. Attributes: num_reduce_shards (int): Number of reduce shards. output_dir (string): Name of output directory. partition_id (long|int): Partition id where output will go. reduce_output_prefix (string): Prefix of the reduce out... | the_stack_v2_python_sparse | cohesity_management_sdk/models/output_spec.py | cohesity/management-sdk-python | train | 24 |
b5345a93d0ebb46fc005f8549fadef242564c0c3 | [
"_, ext = os.path.splitext(post_file.name)\next = ext[1:] if ext.startswith('.') else ext\nhashes = generate_hashes(post_file)\npost_file.seek(0)\nexisting = Object.objects.filter(sha512=hashes.get('sha512'))\nif existing.exists():\n LOGGER.debug('De-duped existing upload %s', existing.first().filename)\n ret... | <|body_start_0|>
_, ext = os.path.splitext(post_file.name)
ext = ext[1:] if ext.startswith('.') else ext
hashes = generate_hashes(post_file)
post_file.seek(0)
existing = Object.objects.filter(sha512=hashes.get('sha512'))
if existing.exists():
LOGGER.debug('De-... | Handle uploads from browser | BrowserObjectView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserObjectView:
"""Handle uploads from browser"""
def handle_post_file(self, post_file) -> Tuple[Object, bool]:
"""Handle upload of a single file, computes hashes and returns existing Upload instance and False as tuple if file was uploaded already. Otherwise, new Upload instance i... | stack_v2_sparse_classes_36k_train_029771 | 8,125 | permissive | [
{
"docstring": "Handle upload of a single file, computes hashes and returns existing Upload instance and False as tuple if file was uploaded already. Otherwise, new Upload instance is created and returned in a tuple with True.",
"name": "handle_post_file",
"signature": "def handle_post_file(self, post_f... | 2 | stack_v2_sparse_classes_30k_train_015695 | Implement the Python class `BrowserObjectView` described below.
Class description:
Handle uploads from browser
Method signatures and docstrings:
- def handle_post_file(self, post_file) -> Tuple[Object, bool]: Handle upload of a single file, computes hashes and returns existing Upload instance and False as tuple if fi... | Implement the Python class `BrowserObjectView` described below.
Class description:
Handle uploads from browser
Method signatures and docstrings:
- def handle_post_file(self, post_file) -> Tuple[Object, bool]: Handle upload of a single file, computes hashes and returns existing Upload instance and False as tuple if fi... | 84bf18262af59e45502a9e862d1a85c5cecd63ac | <|skeleton|>
class BrowserObjectView:
"""Handle uploads from browser"""
def handle_post_file(self, post_file) -> Tuple[Object, bool]:
"""Handle upload of a single file, computes hashes and returns existing Upload instance and False as tuple if file was uploaded already. Otherwise, new Upload instance i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowserObjectView:
"""Handle uploads from browser"""
def handle_post_file(self, post_file) -> Tuple[Object, bool]:
"""Handle upload of a single file, computes hashes and returns existing Upload instance and False as tuple if file was uploaded already. Otherwise, new Upload instance is created and... | the_stack_v2_python_sparse | pyazo/core/views/upload.py | BeryJu/pyazo | train | 5 |
f06127212106e69f06c23064438adecf9284cf30 | [
"super(HeartbeatListener, self).__init__()\nself._heartbeat_queue = Queue(maxsize=1)\nself._cache_store = cache_store\ntime_delay = 0.5\nself._period = period + time_delay if period else 15\nself._running = threading.Event()\nself._running.clear()",
"self._running.set()\nlog.info('Start listening for heartbeat.')... | <|body_start_0|>
super(HeartbeatListener, self).__init__()
self._heartbeat_queue = Queue(maxsize=1)
self._cache_store = cache_store
time_delay = 0.5
self._period = period + time_delay if period else 15
self._running = threading.Event()
self._running.clear()
<|end_... | Heartbeat listener. | HeartbeatListener | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeartbeatListener:
"""Heartbeat listener."""
def __init__(self, cache_store, period=None):
"""Initialize Heartbeat listener object. Args: cache_store (DebuggerCacheStore): Cache store for debugger server. period (int): The max waiting seconds for each period."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_029772 | 31,395 | permissive | [
{
"docstring": "Initialize Heartbeat listener object. Args: cache_store (DebuggerCacheStore): Cache store for debugger server. period (int): The max waiting seconds for each period.",
"name": "__init__",
"signature": "def __init__(self, cache_store, period=None)"
},
{
"docstring": "Function that... | 4 | null | Implement the Python class `HeartbeatListener` described below.
Class description:
Heartbeat listener.
Method signatures and docstrings:
- def __init__(self, cache_store, period=None): Initialize Heartbeat listener object. Args: cache_store (DebuggerCacheStore): Cache store for debugger server. period (int): The max ... | Implement the Python class `HeartbeatListener` described below.
Class description:
Heartbeat listener.
Method signatures and docstrings:
- def __init__(self, cache_store, period=None): Initialize Heartbeat listener object. Args: cache_store (DebuggerCacheStore): Cache store for debugger server. period (int): The max ... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class HeartbeatListener:
"""Heartbeat listener."""
def __init__(self, cache_store, period=None):
"""Initialize Heartbeat listener object. Args: cache_store (DebuggerCacheStore): Cache store for debugger server. period (int): The max waiting seconds for each period."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeartbeatListener:
"""Heartbeat listener."""
def __init__(self, cache_store, period=None):
"""Initialize Heartbeat listener object. Args: cache_store (DebuggerCacheStore): Cache store for debugger server. period (int): The max waiting seconds for each period."""
super(HeartbeatListener, s... | the_stack_v2_python_sparse | mindinsight/debugger/debugger_services/debugger_grpc_server.py | mindspore-ai/mindinsight | train | 224 |
386944c551752756a5a6e41d24667ee644b64353 | [
"self.surface = pygame.Surface(dim)\nself.color = color\nself.objects = [get_circle_points(100, 1.0, 1.0, (80, 100)), get_circle_points(100, 2.0, 4.0, (240, 100))]\nself.points = list(self.objects[0])\nself.framecount = 0",
"self.surface.fill((0, 0, 0))\ntarget = self.objects[1]\nmax_distance = 0\nfor index in ra... | <|body_start_0|>
self.surface = pygame.Surface(dim)
self.color = color
self.objects = [get_circle_points(100, 1.0, 1.0, (80, 100)), get_circle_points(100, 2.0, 4.0, (240, 100))]
self.points = list(self.objects[0])
self.framecount = 0
<|end_body_0|>
<|body_start_1|>
self.... | Morph/move point in a set to another place | MorphingPixels | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MorphingPixels:
"""Morph/move point in a set to another place"""
def __init__(self, dim: tuple, color=(255, 255, 255, 255)):
""":param dim: <tuple> dimension of surface to draw on like (x, y)"""
<|body_0|>
def update(self):
"""draw something"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_029773 | 3,368 | no_license | [
{
"docstring": ":param dim: <tuple> dimension of surface to draw on like (x, y)",
"name": "__init__",
"signature": "def __init__(self, dim: tuple, color=(255, 255, 255, 255))"
},
{
"docstring": "draw something",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003680 | Implement the Python class `MorphingPixels` described below.
Class description:
Morph/move point in a set to another place
Method signatures and docstrings:
- def __init__(self, dim: tuple, color=(255, 255, 255, 255)): :param dim: <tuple> dimension of surface to draw on like (x, y)
- def update(self): draw something | Implement the Python class `MorphingPixels` described below.
Class description:
Morph/move point in a set to another place
Method signatures and docstrings:
- def __init__(self, dim: tuple, color=(255, 255, 255, 255)): :param dim: <tuple> dimension of surface to draw on like (x, y)
- def update(self): draw something
... | 1fd421195a2888c0588a49f5a043a1110eedcdbf | <|skeleton|>
class MorphingPixels:
"""Morph/move point in a set to another place"""
def __init__(self, dim: tuple, color=(255, 255, 255, 255)):
""":param dim: <tuple> dimension of surface to draw on like (x, y)"""
<|body_0|>
def update(self):
"""draw something"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MorphingPixels:
"""Morph/move point in a set to another place"""
def __init__(self, dim: tuple, color=(255, 255, 255, 255)):
""":param dim: <tuple> dimension of surface to draw on like (x, y)"""
self.surface = pygame.Surface(dim)
self.color = color
self.objects = [get_circ... | the_stack_v2_python_sparse | effects/MorphingPixels.py | gunny26/pygame | train | 5 |
aa494614b6b283dc0f5a81a5deb921e9765ce505 | [
"if not isinstance(generator, list):\n generator = [generator]\nfor index, item in enumerate(generator):\n if not isinstance(item, tuple) and isinstance(item, types.FunctionType):\n generator[index] = (item, [], {})\n elif isinstance(item, tuple) and isinstance(item[0], types.FunctionType):\n ... | <|body_start_0|>
if not isinstance(generator, list):
generator = [generator]
for index, item in enumerate(generator):
if not isinstance(item, tuple) and isinstance(item, types.FunctionType):
generator[index] = (item, [], {})
elif isinstance(item, tuple... | DataTransformer wrapper for DataFrames | DFDataTransformer | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DFDataTransformer:
"""DataTransformer wrapper for DataFrames"""
def __init__(self, generator, resource_id=None, name=None, description=None):
"""Receives the function or list of functions to be applied on the input DataFrame Optional parameters are: :param resource_id: unique ID for ... | stack_v2_sparse_classes_36k_train_029774 | 11,498 | permissive | [
{
"docstring": "Receives the function or list of functions to be applied on the input DataFrame Optional parameters are: :param resource_id: unique ID for the DataTransformer :type resource_id: str :param name: DataTransformer name :type name: str :param description: Description for the transformations. :type d... | 2 | stack_v2_sparse_classes_30k_val_000892 | Implement the Python class `DFDataTransformer` described below.
Class description:
DataTransformer wrapper for DataFrames
Method signatures and docstrings:
- def __init__(self, generator, resource_id=None, name=None, description=None): Receives the function or list of functions to be applied on the input DataFrame Op... | Implement the Python class `DFDataTransformer` described below.
Class description:
DataTransformer wrapper for DataFrames
Method signatures and docstrings:
- def __init__(self, generator, resource_id=None, name=None, description=None): Receives the function or list of functions to be applied on the input DataFrame Op... | 22698904f9b54234272fe2fea91a0eed692ca48a | <|skeleton|>
class DFDataTransformer:
"""DataTransformer wrapper for DataFrames"""
def __init__(self, generator, resource_id=None, name=None, description=None):
"""Receives the function or list of functions to be applied on the input DataFrame Optional parameters are: :param resource_id: unique ID for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DFDataTransformer:
"""DataTransformer wrapper for DataFrames"""
def __init__(self, generator, resource_id=None, name=None, description=None):
"""Receives the function or list of functions to be applied on the input DataFrame Optional parameters are: :param resource_id: unique ID for the DataTrans... | the_stack_v2_python_sparse | bigml/pipeline/transformer.py | jaor/python | train | 0 |
61fb61379af3f23f6e053eaf8d7c1e5904a72afa | [
"super().__init__(coll_name, code, qc_spec, **kwargs)\nself.coll.set_default_units('hartree / angstrom ** 2')\nself.coll.set_default_driver('hessian')\nself.coll.save()",
"records = self.get_complete_records()\nmols = self.get_geometries(records)\noutput = {}\nfor label, record in records.items():\n inchi, sta... | <|body_start_0|>
super().__init__(coll_name, code, qc_spec, **kwargs)
self.coll.set_default_units('hartree / angstrom ** 2')
self.coll.set_default_driver('hessian')
self.coll.save()
<|end_body_0|>
<|body_start_1|>
records = self.get_complete_records()
mols = self.get_geo... | Compute Hessians for a certain dataset | HessianDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HessianDataset:
"""Compute Hessians for a certain dataset"""
def __init__(self, coll_name: str, code: str, qc_spec: str, **kwargs):
"""Args: coll_name: Collection name. code: Which code to use qc_spec: Name of the specification **kwargs"""
<|body_0|>
def get_zpe(self, sc... | stack_v2_sparse_classes_36k_train_029775 | 29,582 | no_license | [
{
"docstring": "Args: coll_name: Collection name. code: Which code to use qc_spec: Name of the specification **kwargs",
"name": "__init__",
"signature": "def __init__(self, coll_name: str, code: str, qc_spec: str, **kwargs)"
},
{
"docstring": "Get the zero point energy contributions to all molec... | 2 | stack_v2_sparse_classes_30k_train_011098 | Implement the Python class `HessianDataset` described below.
Class description:
Compute Hessians for a certain dataset
Method signatures and docstrings:
- def __init__(self, coll_name: str, code: str, qc_spec: str, **kwargs): Args: coll_name: Collection name. code: Which code to use qc_spec: Name of the specification... | Implement the Python class `HessianDataset` described below.
Class description:
Compute Hessians for a certain dataset
Method signatures and docstrings:
- def __init__(self, coll_name: str, code: str, qc_spec: str, **kwargs): Args: coll_name: Collection name. code: Which code to use qc_spec: Name of the specification... | ef9e586e89053d1f6bea541717db8be43dbce0a4 | <|skeleton|>
class HessianDataset:
"""Compute Hessians for a certain dataset"""
def __init__(self, coll_name: str, code: str, qc_spec: str, **kwargs):
"""Args: coll_name: Collection name. code: Which code to use qc_spec: Name of the specification **kwargs"""
<|body_0|>
def get_zpe(self, sc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HessianDataset:
"""Compute Hessians for a certain dataset"""
def __init__(self, coll_name: str, code: str, qc_spec: str, **kwargs):
"""Args: coll_name: Collection name. code: Which code to use qc_spec: Name of the specification **kwargs"""
super().__init__(coll_name, code, qc_spec, **kwar... | the_stack_v2_python_sparse | moldesign/simulate/qcfractal.py | exalearn/electrolyte-design | train | 4 |
c87aaa361366c270e80a0ae3d95f29cb706b9868 | [
"if self.l_s_save.get(longUrl):\n return 'http://tinyurl.com/' + self.l_s_save[longUrl]\nrand_str = ''.join(random.choices(self.dlu, k=6))\nwhile self.s_l_save.get(rand_str):\n rand_str = ''.join(random.choices(self.dlu, k=6))\nself.l_s_save[longUrl] = rand_str\nself.s_l_save[rand_str] = longUrl\nreturn 'http... | <|body_start_0|>
if self.l_s_save.get(longUrl):
return 'http://tinyurl.com/' + self.l_s_save[longUrl]
rand_str = ''.join(random.choices(self.dlu, k=6))
while self.s_l_save.get(rand_str):
rand_str = ''.join(random.choices(self.dlu, k=6))
self.l_s_save[longUrl] = ra... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_029776 | 1,233 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | 826907f270f3345661b0dfe991cec1b52c5a42bd | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
if self.l_s_save.get(longUrl):
return 'http://tinyurl.com/' + self.l_s_save[longUrl]
rand_str = ''.join(random.choices(self.dlu, k=6))
while self.s_l_save.get(ra... | the_stack_v2_python_sparse | py/encode-and-decode.py | ghxuan/leetcode | train | 2 | |
b904de1bbda8fd5640b337ff04fb528cc3f2ec38 | [
"self.id = id\nself.value = value\nself.discount_type = discount_type\nself.status = status\nself.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None\nself.cycles = cycles\nself.deleted_at = APIHelper.RFC3339DateTime(deleted_at) if deleted_at else None\nself.description = description\nself.su... | <|body_start_0|>
self.id = id
self.value = value
self.discount_type = discount_type
self.status = status
self.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None
self.cycles = cycles
self.deleted_at = APIHelper.RFC3339DateTime(deleted_at) if... | Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (string): TODO: type description here. created_at (datetime): T... | SubscriptionsDiscountsResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionsDiscountsResponse:
"""Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (stri... | stack_v2_sparse_classes_36k_train_029777 | 4,408 | permissive | [
{
"docstring": "Constructor for the SubscriptionsDiscountsResponse class",
"name": "__init__",
"signature": "def __init__(self, id=None, value=None, discount_type=None, status=None, created_at=None, cycles=None, deleted_at=None, description=None, subscription=None, subscription_item=None)"
},
{
... | 2 | null | Implement the Python class `SubscriptionsDiscountsResponse` described below.
Class description:
Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TO... | Implement the Python class `SubscriptionsDiscountsResponse` described below.
Class description:
Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TO... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class SubscriptionsDiscountsResponse:
"""Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (stri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubscriptionsDiscountsResponse:
"""Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (string): TODO: ty... | the_stack_v2_python_sparse | mundiapi/models/subscriptions_discounts_response.py | mundipagg/MundiAPI-PYTHON | train | 10 |
4b653de11fba1d6aa8bfc0f0e14ea998358939b0 | [
"super(RandomHorizontalFlip, self).__init__()\nself.prob = prob\nif not isinstance(self.prob, float):\n raise TypeError('{}: input type is invalid.'.format(self))",
"samples = sample\nbatch_input = True\nif not isinstance(samples, Sequence):\n batch_input = False\n samples = [samples]\nfor sample in samp... | <|body_start_0|>
super(RandomHorizontalFlip, self).__init__()
self.prob = prob
if not isinstance(self.prob, float):
raise TypeError('{}: input type is invalid.'.format(self))
<|end_body_0|>
<|body_start_1|>
samples = sample
batch_input = True
if not isinstanc... | RandomHorizontalFlip | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomHorizontalFlip:
def __init__(self, prob=0.5):
"""Args: prob (float): the probability of flipping image is_normalized (bool): whether the bbox scale to [0,1] is_mask_flip (bool): whether flip the segmentation"""
<|body_0|>
def __call__(self, sample, context=None):
... | stack_v2_sparse_classes_36k_train_029778 | 19,057 | permissive | [
{
"docstring": "Args: prob (float): the probability of flipping image is_normalized (bool): whether the bbox scale to [0,1] is_mask_flip (bool): whether flip the segmentation",
"name": "__init__",
"signature": "def __init__(self, prob=0.5)"
},
{
"docstring": "Filp the image and bounding box. Ope... | 2 | stack_v2_sparse_classes_30k_test_000978 | Implement the Python class `RandomHorizontalFlip` described below.
Class description:
Implement the RandomHorizontalFlip class.
Method signatures and docstrings:
- def __init__(self, prob=0.5): Args: prob (float): the probability of flipping image is_normalized (bool): whether the bbox scale to [0,1] is_mask_flip (bo... | Implement the Python class `RandomHorizontalFlip` described below.
Class description:
Implement the RandomHorizontalFlip class.
Method signatures and docstrings:
- def __init__(self, prob=0.5): Args: prob (float): the probability of flipping image is_normalized (bool): whether the bbox scale to [0,1] is_mask_flip (bo... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class RandomHorizontalFlip:
def __init__(self, prob=0.5):
"""Args: prob (float): the probability of flipping image is_normalized (bool): whether the bbox scale to [0,1] is_mask_flip (bool): whether flip the segmentation"""
<|body_0|>
def __call__(self, sample, context=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomHorizontalFlip:
def __init__(self, prob=0.5):
"""Args: prob (float): the probability of flipping image is_normalized (bool): whether the bbox scale to [0,1] is_mask_flip (bool): whether flip the segmentation"""
super(RandomHorizontalFlip, self).__init__()
self.prob = prob
... | the_stack_v2_python_sparse | CV/PaddleReid/reid/data/transform/operators.py | sserdoubleh/Research | train | 10 | |
1c2587e2e11a60265619963bdf60ef9e0b94f7ca | [
"import random\nimport string\ns = ''\nletterCount = random.randint(3, 5)\nnumberCount = random.randint(3, 5)\nsuffleCount = random.randint(1, 10)\nfor _ in range(letterCount):\n s += str(random.choice(string.ascii_letters))\nfor _ in range(numberCount):\n s += str(random.choice(string.digits))\nlt = list(s)\... | <|body_start_0|>
import random
import string
s = ''
letterCount = random.randint(3, 5)
numberCount = random.randint(3, 5)
suffleCount = random.randint(1, 10)
for _ in range(letterCount):
s += str(random.choice(string.ascii_letters))
for _ in ra... | Get the joincode, To join in a admin group | GetJoinCodeAPIView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetJoinCodeAPIView:
"""Get the joincode, To join in a admin group"""
def _generateUniqueJoinCode(self):
"""Get unique code"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""didn't allow to generate newcode ,if a joincode is generated already Returns exist... | stack_v2_sparse_classes_36k_train_029779 | 15,595 | permissive | [
{
"docstring": "Get unique code",
"name": "_generateUniqueJoinCode",
"signature": "def _generateUniqueJoinCode(self)"
},
{
"docstring": "didn't allow to generate newcode ,if a joincode is generated already Returns existing joincode for the requested admin, if all codes were used for joining, gen... | 2 | stack_v2_sparse_classes_30k_train_018521 | Implement the Python class `GetJoinCodeAPIView` described below.
Class description:
Get the joincode, To join in a admin group
Method signatures and docstrings:
- def _generateUniqueJoinCode(self): Get unique code
- def get(self, request, *args, **kwargs): didn't allow to generate newcode ,if a joincode is generated ... | Implement the Python class `GetJoinCodeAPIView` described below.
Class description:
Get the joincode, To join in a admin group
Method signatures and docstrings:
- def _generateUniqueJoinCode(self): Get unique code
- def get(self, request, *args, **kwargs): didn't allow to generate newcode ,if a joincode is generated ... | 82820d93876a2c3e6caec2725b1c6078e79e3bfb | <|skeleton|>
class GetJoinCodeAPIView:
"""Get the joincode, To join in a admin group"""
def _generateUniqueJoinCode(self):
"""Get unique code"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""didn't allow to generate newcode ,if a joincode is generated already Returns exist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetJoinCodeAPIView:
"""Get the joincode, To join in a admin group"""
def _generateUniqueJoinCode(self):
"""Get unique code"""
import random
import string
s = ''
letterCount = random.randint(3, 5)
numberCount = random.randint(3, 5)
suffleCount = rand... | the_stack_v2_python_sparse | grocery/shopowner/views.py | DeepakDk04/bigbasketClone | train | 0 |
032505289b688c7a1c1558d4c5e43acf538f7c86 | [
"self.category = category\nself.dataset = dataset\nself.silent = True\n'Quite console'\nsuper().__init__(*args, **kwargs)",
"imgs = [x for x in _voc.get_image_url_list(self.category, self.dataset)]\nfor fname in imgs:\n if pathonly:\n yield (None, fname, None)\n else:\n try:\n img =... | <|body_start_0|>
self.category = category
self.dataset = dataset
self.silent = True
'Quite console'
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
imgs = [x for x in _voc.get_image_url_list(self.category, self.dataset)]
for fname in imgs:
... | Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' filters: Keyword argument containi... | VOC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VOC:
"""Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' fil... | stack_v2_sparse_classes_36k_train_029780 | 47,799 | no_license | [
{
"docstring": "(str, str) -> void",
"name": "__init__",
"signature": "def __init__(self, category, *args, dataset='train', **kwargs)"
},
{
"docstring": "(cv2.imread option, bool, bool) -> ndarray|None, str, dict|None Yields the images with the bounding boxes and category name of all objects in ... | 2 | null | Implement the Python class `VOC` described below.
Class description:
Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 't... | Implement the Python class `VOC` described below.
Class description:
Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 't... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class VOC:
"""Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VOC:
"""Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' filters: Keyword... | the_stack_v2_python_sparse | opencvlib/imgpipes/generators.py | gmonkman/python | train | 0 |
8b65546e0921706d76ff03285aaf646194255e69 | [
"if self.current_user == team.owner:\n return True\nraise ApiException(403, '无权修改俱乐部')",
"obj = Team.get_or_404(id=team_id)\ninfo = TeamSerializer(instance=obj, request=self).data\nif self.current_user and TeamFollower.select().where(TeamFollower.user_id == self.current_user.id, TeamFollower.team_id == obj.id)... | <|body_start_0|>
if self.current_user == team.owner:
return True
raise ApiException(403, '无权修改俱乐部')
<|end_body_0|>
<|body_start_1|>
obj = Team.get_or_404(id=team_id)
info = TeamSerializer(instance=obj, request=self).data
if self.current_user and TeamFollower.select()... | TeamObjectHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamObjectHandler:
def has_update_permission(self, team):
"""是否具有修改权限 目前只有俱乐部所有者可以修改 :param team: Team"""
<|body_0|>
def get(self, team_id):
"""获取俱乐部详情"""
<|body_1|>
def patch(self, team_id):
"""修改俱乐部信息; 俱乐部徽标额外接口修改"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_029781 | 13,604 | no_license | [
{
"docstring": "是否具有修改权限 目前只有俱乐部所有者可以修改 :param team: Team",
"name": "has_update_permission",
"signature": "def has_update_permission(self, team)"
},
{
"docstring": "获取俱乐部详情",
"name": "get",
"signature": "def get(self, team_id)"
},
{
"docstring": "修改俱乐部信息; 俱乐部徽标额外接口修改",
"name"... | 3 | stack_v2_sparse_classes_30k_train_004819 | Implement the Python class `TeamObjectHandler` described below.
Class description:
Implement the TeamObjectHandler class.
Method signatures and docstrings:
- def has_update_permission(self, team): 是否具有修改权限 目前只有俱乐部所有者可以修改 :param team: Team
- def get(self, team_id): 获取俱乐部详情
- def patch(self, team_id): 修改俱乐部信息; 俱乐部徽标额外接... | Implement the Python class `TeamObjectHandler` described below.
Class description:
Implement the TeamObjectHandler class.
Method signatures and docstrings:
- def has_update_permission(self, team): 是否具有修改权限 目前只有俱乐部所有者可以修改 :param team: Team
- def get(self, team_id): 获取俱乐部详情
- def patch(self, team_id): 修改俱乐部信息; 俱乐部徽标额外接... | 49c31d9cce6ca451ff069697913b33fe55028a46 | <|skeleton|>
class TeamObjectHandler:
def has_update_permission(self, team):
"""是否具有修改权限 目前只有俱乐部所有者可以修改 :param team: Team"""
<|body_0|>
def get(self, team_id):
"""获取俱乐部详情"""
<|body_1|>
def patch(self, team_id):
"""修改俱乐部信息; 俱乐部徽标额外接口修改"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamObjectHandler:
def has_update_permission(self, team):
"""是否具有修改权限 目前只有俱乐部所有者可以修改 :param team: Team"""
if self.current_user == team.owner:
return True
raise ApiException(403, '无权修改俱乐部')
def get(self, team_id):
"""获取俱乐部详情"""
obj = Team.get_or_404(id=t... | the_stack_v2_python_sparse | PaiDuiGuanJia/yiyun/handlers/rest/team.py | haoweiking/image_tesseract_private | train | 0 | |
d1396d8f37d16491d769f52d25607550baa12aad | [
"i = max_profit = 0\nwhile i < len(prices) - 1:\n while i < len(prices) - 1 and prices[i] >= prices[i + 1]:\n i += 1\n valley = prices[i]\n while i < len(prices) - 1 and prices[i] <= prices[i + 1]:\n i += 1\n peak = prices[i]\n max_profit += peak - valley\nreturn max_profit",
"max_pro... | <|body_start_0|>
i = max_profit = 0
while i < len(prices) - 1:
while i < len(prices) - 1 and prices[i] >= prices[i + 1]:
i += 1
valley = prices[i]
while i < len(prices) - 1 and prices[i] <= prices[i + 1]:
i += 1
peak = price... | Stock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stock:
def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int:
"""Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:"""
<|body_0|>
def get_max_profit_for_multiple_transaction(self, prices: List[int]) -> int:
... | stack_v2_sparse_classes_36k_train_029782 | 1,758 | no_license | [
{
"docstring": "Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:",
"name": "get_max_profit_for_multiple_transactions_",
"signature": "def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int"
},
{
"docstring": "Approach: One Pass Tim... | 3 | stack_v2_sparse_classes_30k_val_000163 | Implement the Python class `Stock` described below.
Class description:
Implement the Stock class.
Method signatures and docstrings:
- def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int: Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:
- def get_max_... | Implement the Python class `Stock` described below.
Class description:
Implement the Stock class.
Method signatures and docstrings:
- def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int: Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:
- def get_max_... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Stock:
def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int:
"""Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:"""
<|body_0|>
def get_max_profit_for_multiple_transaction(self, prices: List[int]) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stock:
def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int:
"""Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:"""
i = max_profit = 0
while i < len(prices) - 1:
while i < len(prices) - 1 and prices[i] >= pr... | the_stack_v2_python_sparse | revisited/greedy/best_time_to_buy_stock.py | Shiv2157k/leet_code | train | 1 | |
abde901041a1b1a07ff26611696ac92de9320277 | [
"Editeur.__init__(self, pere, objet, attribut)\nself.ajouter_option('n', self.opt_ajouter_periode)\nself.ajouter_option('d', self.opt_supprimer_periode)",
"cycle = self.objet\narguments = arguments.strip()\nif not arguments:\n self.pere << '|err|Précisez le nom de la période.|ff|'\n return\nnom = arguments\... | <|body_start_0|>
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('n', self.opt_ajouter_periode)
self.ajouter_option('d', self.opt_supprimer_periode)
<|end_body_0|>
<|body_start_1|>
cycle = self.objet
arguments = arguments.strip()
if not arguments:
... | Contexte-éditeur d'édition des périodes du cycle. | EdtPeriodes | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdtPeriodes:
"""Contexte-éditeur d'édition des périodes du cycle."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def opt_ajouter_periode(self, arguments):
"""Ajout d'une période. Syntaxe : /n <age> <nom de la pé... | stack_v2_sparse_classes_36k_train_029783 | 4,711 | permissive | [
{
"docstring": "Constructeur de l'éditeur",
"name": "__init__",
"signature": "def __init__(self, pere, objet=None, attribut=None)"
},
{
"docstring": "Ajout d'une période. Syntaxe : /n <age> <nom de la période>",
"name": "opt_ajouter_periode",
"signature": "def opt_ajouter_periode(self, a... | 5 | null | Implement the Python class `EdtPeriodes` described below.
Class description:
Contexte-éditeur d'édition des périodes du cycle.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def opt_ajouter_periode(self, arguments): Ajout d'une période. Syntaxe : /... | Implement the Python class `EdtPeriodes` described below.
Class description:
Contexte-éditeur d'édition des périodes du cycle.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def opt_ajouter_periode(self, arguments): Ajout d'une période. Syntaxe : /... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class EdtPeriodes:
"""Contexte-éditeur d'édition des périodes du cycle."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def opt_ajouter_periode(self, arguments):
"""Ajout d'une période. Syntaxe : /n <age> <nom de la pé... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdtPeriodes:
"""Contexte-éditeur d'édition des périodes du cycle."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('n', self.opt_ajouter_periode)
self.ajouter_option('d... | the_stack_v2_python_sparse | src/secondaires/botanique/editeurs/vegedit/edt_periodes.py | vincent-lg/tsunami | train | 5 |
822eb5bf5de3caf42952a0e36b3b7e1ae794eb48 | [
"same = True\nfor _ in range(n - 1):\n if not k % 2:\n same = not same\n k /= 2\n else:\n k = (k + 1) / 2\nreturn 0 if same else 1",
"moves, k = ([False] * (n - 1), k - 1)\nfor i in range(n - 1):\n moves[i] = bool(k % 2)\n k //= 2\nres = False\nfor right_branch in moves[::-1]:\n ... | <|body_start_0|>
same = True
for _ in range(n - 1):
if not k % 2:
same = not same
k /= 2
else:
k = (k + 1) / 2
return 0 if same else 1
<|end_body_0|>
<|body_start_1|>
moves, k = ([False] * (n - 1), k - 1)
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
"""Track if the current node is the same as parent node. Time: O(n) Space: O(1)"""
<|body_0|>
def kthGrammar2(self, n: int, k: int) -> int:
"""Backtrack from nth row to root to find the path. This way we don't ha... | stack_v2_sparse_classes_36k_train_029784 | 976 | no_license | [
{
"docstring": "Track if the current node is the same as parent node. Time: O(n) Space: O(1)",
"name": "kthGrammar",
"signature": "def kthGrammar(self, n: int, k: int) -> int"
},
{
"docstring": "Backtrack from nth row to root to find the path. This way we don't have to unnecessarily find all num... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthGrammar(self, n: int, k: int) -> int: Track if the current node is the same as parent node. Time: O(n) Space: O(1)
- def kthGrammar2(self, n: int, k: int) -> int: Backtrac... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthGrammar(self, n: int, k: int) -> int: Track if the current node is the same as parent node. Time: O(n) Space: O(1)
- def kthGrammar2(self, n: int, k: int) -> int: Backtrac... | c14d8829c95f61ff6691816e8c0de76b9319f389 | <|skeleton|>
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
"""Track if the current node is the same as parent node. Time: O(n) Space: O(1)"""
<|body_0|>
def kthGrammar2(self, n: int, k: int) -> int:
"""Backtrack from nth row to root to find the path. This way we don't ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
"""Track if the current node is the same as parent node. Time: O(n) Space: O(1)"""
same = True
for _ in range(n - 1):
if not k % 2:
same = not same
k /= 2
else:
... | the_stack_v2_python_sparse | medium/k-th-symbol-in-grammar/solution.py | hsuanhauliu/leetcode-solutions | train | 0 | |
ae5e204a7420278872d56d00fa5cb9e111b6d063 | [
"frame_rate, T, ftest, bandwidth = (1000, 1, 100, 10)\nm = sin(2 * pi * ftest * linspace(0, T, T * frame_rate, endpoint=False))\nlow, high, filtered = loudest_band(m, frame_rate, bandwidth)\nself.assertEqual(m.shape, filtered.shape)\nself.assertLessEqual(low, ftest, msg='low of band incorrect')\nself.assertLessEqua... | <|body_start_0|>
frame_rate, T, ftest, bandwidth = (1000, 1, 100, 10)
m = sin(2 * pi * ftest * linspace(0, T, T * frame_rate, endpoint=False))
low, high, filtered = loudest_band(m, frame_rate, bandwidth)
self.assertEqual(m.shape, filtered.shape)
self.assertLessEqual(low, ftest, m... | loudestTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class loudestTestCase:
def test_find_band(self):
"""a. sine wave at 100 Hz, 1 kHz frame rate"""
<|body_0|>
def test_find_energy(self):
"""b. cosines at 10 11 12 and 30"""
<|body_1|>
def test_find_band_split(self):
"""d. two sines 80% of bw apart"""
... | stack_v2_sparse_classes_36k_train_029785 | 4,240 | no_license | [
{
"docstring": "a. sine wave at 100 Hz, 1 kHz frame rate",
"name": "test_find_band",
"signature": "def test_find_band(self)"
},
{
"docstring": "b. cosines at 10 11 12 and 30",
"name": "test_find_energy",
"signature": "def test_find_energy(self)"
},
{
"docstring": "d. two sines 80... | 5 | stack_v2_sparse_classes_30k_train_009497 | Implement the Python class `loudestTestCase` described below.
Class description:
Implement the loudestTestCase class.
Method signatures and docstrings:
- def test_find_band(self): a. sine wave at 100 Hz, 1 kHz frame rate
- def test_find_energy(self): b. cosines at 10 11 12 and 30
- def test_find_band_split(self): d. ... | Implement the Python class `loudestTestCase` described below.
Class description:
Implement the loudestTestCase class.
Method signatures and docstrings:
- def test_find_band(self): a. sine wave at 100 Hz, 1 kHz frame rate
- def test_find_energy(self): b. cosines at 10 11 12 and 30
- def test_find_band_split(self): d. ... | 0c3afbbaf714d3a57e6347ea386f5cf86e4abb3c | <|skeleton|>
class loudestTestCase:
def test_find_band(self):
"""a. sine wave at 100 Hz, 1 kHz frame rate"""
<|body_0|>
def test_find_energy(self):
"""b. cosines at 10 11 12 and 30"""
<|body_1|>
def test_find_band_split(self):
"""d. two sines 80% of bw apart"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class loudestTestCase:
def test_find_band(self):
"""a. sine wave at 100 Hz, 1 kHz frame rate"""
frame_rate, T, ftest, bandwidth = (1000, 1, 100, 10)
m = sin(2 * pi * ftest * linspace(0, T, T * frame_rate, endpoint=False))
low, high, filtered = loudest_band(m, frame_rate, bandwidth)
... | the_stack_v2_python_sparse | Homework7/loudest_checker.py | Jasmine424/EC602-DesignBySoftware | train | 1 | |
21bc82e3fce68ab8f4202d1197bdd5ff9593bbc2 | [
"cumset = []\ncumset.append(0)\nmaxsum = -1 << 32\ncursum = 0\nfor i in range(len(nums)):\n cursum += nums[i]\n idx = bisect.bisect_left(cumset, cursum - k)\n if 0 <= idx < len(cumset):\n maxsum = max(maxsum, cursum - cumset[idx])\n bisect.insort(cumset, cursum)\nreturn maxsum",
"\"\"\"\n ... | <|body_start_0|>
cumset = []
cumset.append(0)
maxsum = -1 << 32
cursum = 0
for i in range(len(nums)):
cursum += nums[i]
idx = bisect.bisect_left(cumset, cursum - k)
if 0 <= idx < len(cumset):
maxsum = max(maxsum, cursum - cumset... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def maxSubArraylessK(self, nums, k):
"""we need to find the sum[right]-sum[left]<=k since the bitsect return the index of the sorted value we can't directly pop the nums[idx] we should use insort from the bisect"""
<|body_0|>
def maxSumSubmatrix(self, matrix, k):
... | stack_v2_sparse_classes_36k_train_029786 | 3,790 | no_license | [
{
"docstring": "we need to find the sum[right]-sum[left]<=k since the bitsect return the index of the sorted value we can't directly pop the nums[idx] we should use insort from the bisect",
"name": "maxSubArraylessK",
"signature": "def maxSubArraylessK(self, nums, k)"
},
{
"docstring": ":type ma... | 2 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def maxSubArraylessK(self, nums, k): we need to find the sum[right]-sum[left]<=k since the bitsect return the index of the sorted value we can't directly pop the nums[idx] we s... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def maxSubArraylessK(self, nums, k): we need to find the sum[right]-sum[left]<=k since the bitsect return the index of the sorted value we can't directly pop the nums[idx] we s... | 3e50f6a936b98ad75c47d7c1719e69163c648235 | <|skeleton|>
class Solution1:
def maxSubArraylessK(self, nums, k):
"""we need to find the sum[right]-sum[left]<=k since the bitsect return the index of the sorted value we can't directly pop the nums[idx] we should use insort from the bisect"""
<|body_0|>
def maxSumSubmatrix(self, matrix, k):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def maxSubArraylessK(self, nums, k):
"""we need to find the sum[right]-sum[left]<=k since the bitsect return the index of the sorted value we can't directly pop the nums[idx] we should use insort from the bisect"""
cumset = []
cumset.append(0)
maxsum = -1 << 32
... | the_stack_v2_python_sparse | LeetcodeNew/BinarySearch/LC_363_Max_Sum_of_Rectangle_No_Larger_Than_K.py | Taoge123/OptimizedLeetcode | train | 9 | |
d2cc412e30fb8ab6432776ebfa83e70e630a5bec | [
"super().__init__(cv)\nself._nextrocket = 0\nself._time = 0\nself._cv = cv\nself._pos = pos",
"super().update(dt)\nself._time = self._time + dt\nif self._time > self._nextrocket:\n r = RocketRocket(self._cv, self._pos, 1000, ['red', 'blue', 'yellow', 'chartreuse2'], [500, 500], 3, 3)\n entities.append(r)\n ... | <|body_start_0|>
super().__init__(cv)
self._nextrocket = 0
self._time = 0
self._cv = cv
self._pos = pos
<|end_body_0|>
<|body_start_1|>
super().update(dt)
self._time = self._time + dt
if self._time > self._nextrocket:
r = RocketRocket(self._cv... | RocketRocketLauncher | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RocketRocketLauncher:
def __init__(self, cv, pos):
"""Barrages the skies with a relentless series of badass explosions. (repetadly executes RocketRocket) Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old roc... | stack_v2_sparse_classes_36k_train_029787 | 16,427 | permissive | [
{
"docstring": "Barrages the skies with a relentless series of badass explosions. (repetadly executes RocketRocket) Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old rocket",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_train_015529 | Implement the Python class `RocketRocketLauncher` described below.
Class description:
Implement the RocketRocketLauncher class.
Method signatures and docstrings:
- def __init__(self, cv, pos): Barrages the skies with a relentless series of badass explosions. (repetadly executes RocketRocket) Arguments: cv {idontknow}... | Implement the Python class `RocketRocketLauncher` described below.
Class description:
Implement the RocketRocketLauncher class.
Method signatures and docstrings:
- def __init__(self, cv, pos): Barrages the skies with a relentless series of badass explosions. (repetadly executes RocketRocket) Arguments: cv {idontknow}... | c6b6d80e9d59f5d115ca8b8fc020fcd6cb030af8 | <|skeleton|>
class RocketRocketLauncher:
def __init__(self, cv, pos):
"""Barrages the skies with a relentless series of badass explosions. (repetadly executes RocketRocket) Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old roc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RocketRocketLauncher:
def __init__(self, cv, pos):
"""Barrages the skies with a relentless series of badass explosions. (repetadly executes RocketRocket) Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old rocket"""
... | the_stack_v2_python_sparse | scripts/sheet9/9.2.py | LennartElbe/PythOnline | train | 0 | |
6952ebfe248b78162e74b270b8b18351304d1116 | [
"if not height:\n return 0\nres = 0\nmax_hight = max(height)\nfor m in range(max_hight):\n left, right = (0, 0)\n for i in range(len(height)):\n if height[i] > 0:\n left = i\n break\n for k in reversed(range(len(height))):\n if height[k] > 0:\n right = k\n ... | <|body_start_0|>
if not height:
return 0
res = 0
max_hight = max(height)
for m in range(max_hight):
left, right = (0, 0)
for i in range(len(height)):
if height[i] > 0:
left = i
break
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap2(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not height:
return 0
res = ... | stack_v2_sparse_classes_36k_train_029788 | 1,538 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap2",
"signature": "def trap2(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trap2(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trap2(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def trap(self, heigh... | a4c7a868f01ed2c571b57ddc17de36e49cc6c63f | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap2(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
if not height:
return 0
res = 0
max_hight = max(height)
for m in range(max_hight):
left, right = (0, 0)
for i in range(len(height)):
if height... | the_stack_v2_python_sparse | leetcode/n41-50/trapping-rain-water.py | allenair/pystudy | train | 0 | |
4ae1bfd0f4ffa051b92d3188993bb0d667edc03a | [
"info = {}\ntry:\n if obj.teacher:\n info['teacher'] = obj.teacher.pen_name\nexcept Sensei.DoesNotExist as e:\n info['teacher'] = str(e)\ntry:\n info_problems = OrderedDict({})\n for index, value in enumerate(obj.problems.all()):\n info_problems[value.pk] = value.get_data()\n info['prob... | <|body_start_0|>
info = {}
try:
if obj.teacher:
info['teacher'] = obj.teacher.pen_name
except Sensei.DoesNotExist as e:
info['teacher'] = str(e)
try:
info_problems = OrderedDict({})
for index, value in enumerate(obj.problems... | Serialize the Exam Problem with link and info. | ExamProblemsSerializers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamProblemsSerializers:
"""Serialize the Exam Problem with link and info."""
def get_info_data(self, obj, *args, **kwargs):
"""Get information data. :param obj: :param args: :param kwargs: :return:"""
<|body_0|>
def get_links_url(self, obj, *args, **kwargs):
"""... | stack_v2_sparse_classes_36k_train_029789 | 7,433 | no_license | [
{
"docstring": "Get information data. :param obj: :param args: :param kwargs: :return:",
"name": "get_info_data",
"signature": "def get_info_data(self, obj, *args, **kwargs)"
},
{
"docstring": "Get link url :param obj: :param args: :param kwargs: :return:",
"name": "get_links_url",
"sign... | 2 | stack_v2_sparse_classes_30k_test_000222 | Implement the Python class `ExamProblemsSerializers` described below.
Class description:
Serialize the Exam Problem with link and info.
Method signatures and docstrings:
- def get_info_data(self, obj, *args, **kwargs): Get information data. :param obj: :param args: :param kwargs: :return:
- def get_links_url(self, ob... | Implement the Python class `ExamProblemsSerializers` described below.
Class description:
Serialize the Exam Problem with link and info.
Method signatures and docstrings:
- def get_info_data(self, obj, *args, **kwargs): Get information data. :param obj: :param args: :param kwargs: :return:
- def get_links_url(self, ob... | acd31a2f43d7ea83fc9bb34627f5dca94763eade | <|skeleton|>
class ExamProblemsSerializers:
"""Serialize the Exam Problem with link and info."""
def get_info_data(self, obj, *args, **kwargs):
"""Get information data. :param obj: :param args: :param kwargs: :return:"""
<|body_0|>
def get_links_url(self, obj, *args, **kwargs):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExamProblemsSerializers:
"""Serialize the Exam Problem with link and info."""
def get_info_data(self, obj, *args, **kwargs):
"""Get information data. :param obj: :param args: :param kwargs: :return:"""
info = {}
try:
if obj.teacher:
info['teacher'] = ob... | the_stack_v2_python_sparse | classroom/serializers.py | JoenyBui/mywaterbuffalo | train | 0 |
cd8bef09dad13b5d09caf15c25b217c00d78559d | [
"user = self.get_user_from_session()\nupload_url_string = blobstore.create_upload_url('/api/photos')\nself.send_success(model.UploadUrl(url=upload_url_string))",
"photo_id = self.request.get('id')\nphoto = model.Photo.all().filter('id=', photo_id).get()\nself.response.headers['Content-Type'] = 'image/png'\nself.r... | <|body_start_0|>
user = self.get_user_from_session()
upload_url_string = blobstore.create_upload_url('/api/photos')
self.send_success(model.UploadUrl(url=upload_url_string))
<|end_body_0|>
<|body_start_1|>
photo_id = self.request.get('id')
photo = model.Photo.all().filter('id=',... | Provides an API for creating and retrieving URLs to which photo images can be uploaded. This handler provides the /api/images end-point, and exposes the following operations: POST /api/images | ImageHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageHandler:
"""Provides an API for creating and retrieving URLs to which photo images can be uploaded. This handler provides the /api/images end-point, and exposes the following operations: POST /api/images"""
def post(self):
"""Exposed as `POST /api/images`. Creates and returns a ... | stack_v2_sparse_classes_36k_train_029790 | 32,317 | no_license | [
{
"docstring": "Exposed as `POST /api/images`. Creates and returns a URL that can be used to upload an image for a photo. Returned URL, after receiving an upload, will fire a callback (resend the entire HTTP request) to /api/photos. Takes no request payload. Returns the following JSON response representing an u... | 2 | stack_v2_sparse_classes_30k_train_021208 | Implement the Python class `ImageHandler` described below.
Class description:
Provides an API for creating and retrieving URLs to which photo images can be uploaded. This handler provides the /api/images end-point, and exposes the following operations: POST /api/images
Method signatures and docstrings:
- def post(sel... | Implement the Python class `ImageHandler` described below.
Class description:
Provides an API for creating and retrieving URLs to which photo images can be uploaded. This handler provides the /api/images end-point, and exposes the following operations: POST /api/images
Method signatures and docstrings:
- def post(sel... | f236a8cd20af89e889caf1049217fdbb5c45e536 | <|skeleton|>
class ImageHandler:
"""Provides an API for creating and retrieving URLs to which photo images can be uploaded. This handler provides the /api/images end-point, and exposes the following operations: POST /api/images"""
def post(self):
"""Exposed as `POST /api/images`. Creates and returns a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageHandler:
"""Provides an API for creating and retrieving URLs to which photo images can be uploaded. This handler provides the /api/images end-point, and exposes the following operations: POST /api/images"""
def post(self):
"""Exposed as `POST /api/images`. Creates and returns a URL that can ... | the_stack_v2_python_sparse | handlers.py | creationexus/django-x | train | 0 |
8bb727379c55d713997ece11dc926255177042b3 | [
"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 ResourcePreset resources. | ResourcePresetServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourcePresetServiceServicer:
"""A set of methods for managing ResourcePreset resources."""
def Get(self, request, context):
"""Returns the specified ResourcePreset resource. To get the list of available ResourcePreset resources, make a [List] request."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_029791 | 5,129 | permissive | [
{
"docstring": "Returns the specified ResourcePreset resource. To get the list of available ResourcePreset resources, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of available ResourcePreset resources.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_010855 | Implement the Python class `ResourcePresetServiceServicer` described below.
Class description:
A set of methods for managing ResourcePreset resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified ResourcePreset resource. To get the list of available ResourcePreset resourc... | Implement the Python class `ResourcePresetServiceServicer` described below.
Class description:
A set of methods for managing ResourcePreset resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified ResourcePreset resource. To get the list of available ResourcePreset resourc... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class ResourcePresetServiceServicer:
"""A set of methods for managing ResourcePreset resources."""
def Get(self, request, context):
"""Returns the specified ResourcePreset resource. To get the list of available ResourcePreset resources, make a [List] request."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourcePresetServiceServicer:
"""A set of methods for managing ResourcePreset resources."""
def Get(self, request, context):
"""Returns the specified ResourcePreset resource. To get the list of available ResourcePreset resources, make a [List] request."""
context.set_code(grpc.StatusCode... | the_stack_v2_python_sparse | yandex/cloud/dataproc/v1/resource_preset_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
46387d7f47da692898cc02ef9a31660e46dc86dc | [
"device = get_object_or_404(Device, slug=slug)\nself.check_object_permissions(request, device)\nserializer = DeviceRetrieveUpdateDestroySerializer(device, many=False)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)",
"device = get_object_or_404(Device, slug=slug)\nself.check_object_permissions(r... | <|body_start_0|>
device = get_object_or_404(Device, slug=slug)
self.check_object_permissions(request, device)
serializer = DeviceRetrieveUpdateDestroySerializer(device, many=False)
return Response(data=serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
d... | DeviceRetrieveUpdateDestroyAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceRetrieveUpdateDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, slug=None):
"""Update"""
<|body_1|>
def delete(self, request, slug=None):
"""Delete"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_029792 | 5,225 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, slug=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, slug=None)"
},
{
"docstring": "Delete",
"name": "delete",
"signature": "def delete(self, request, slu... | 3 | stack_v2_sparse_classes_30k_train_016626 | Implement the Python class `DeviceRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the DeviceRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, slug=None): Update
- def delete(self, request, slug=None)... | Implement the Python class `DeviceRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the DeviceRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, slug=None): Update
- def delete(self, request, slug=None)... | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | <|skeleton|>
class DeviceRetrieveUpdateDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, slug=None):
"""Update"""
<|body_1|>
def delete(self, request, slug=None):
"""Delete"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceRetrieveUpdateDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
device = get_object_or_404(Device, slug=slug)
self.check_object_permissions(request, device)
serializer = DeviceRetrieveUpdateDestroySerializer(device, many=False)
return Response(data... | the_stack_v2_python_sparse | mikaponics/device/views/resources/device_crud_api_views.py | mikaponics/mikaponics-back | train | 4 | |
d35f50816bd0d8a711828000ae442009b465bfc8 | [
"assert len(input_list) > 0\nassert target_sum > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.input_list = input_list\nself.target_sum = target_sum",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nself.input_list.sort()\nclosest_sum = sys.maxsize\nfor i in range(len(self.input_list) - 2):\n ptr1 =... | <|body_start_0|>
assert len(input_list) > 0
assert target_sum > 0
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
self.target_sum = target_sum
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
self.input_li... | Three Sum | ThreeSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeSum:
"""Three Sum"""
def __init__(self, input_list, target_sum):
"""Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the ... | stack_v2_sparse_classes_36k_train_029793 | 2,041 | no_license | [
{
"docstring": "Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_list, target_sum)"
},
{
"docstring": "Solve the problem Note: There are o... | 2 | null | Implement the Python class `ThreeSum` described below.
Class description:
Three Sum
Method signatures and docstrings:
- def __init__(self, input_list, target_sum): Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None
- def so... | Implement the Python class `ThreeSum` described below.
Class description:
Three Sum
Method signatures and docstrings:
- def __init__(self, input_list, target_sum): Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None
- def so... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class ThreeSum:
"""Three Sum"""
def __init__(self, input_list, target_sum):
"""Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreeSum:
"""Three Sum"""
def __init__(self, input_list, target_sum):
"""Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None"""
assert len(input_list) > 0
assert target_sum > 0
su... | the_stack_v2_python_sparse | python/problems/array/three_sum.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
3733e3552366139eaa276f01fcf12ba402b615d2 | [
"self.hass = hass\nself.webhook_id = webhook_id\nself.support_confirm = support_confirm\nself._send_message = send_message\nself.on_teardown = on_teardown\nself.pending_confirms: dict[str, dict] = {}",
"if not self.support_confirm:\n self._send_message(data)\n return\nconfirm_id = random_uuid_hex()\ndata['h... | <|body_start_0|>
self.hass = hass
self.webhook_id = webhook_id
self.support_confirm = support_confirm
self._send_message = send_message
self.on_teardown = on_teardown
self.pending_confirms: dict[str, dict] = {}
<|end_body_0|>
<|body_start_1|>
if not self.support_... | Class that represents a push channel. | PushChannel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PushChannel:
"""Class that represents a push channel."""
def __init__(self, hass: HomeAssistant, webhook_id: str, support_confirm: bool, send_message: Callable[[dict], None], on_teardown: Callable[[], None]) -> None:
"""Initialize a local push channel."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_029794 | 2,897 | permissive | [
{
"docstring": "Initialize a local push channel.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, webhook_id: str, support_confirm: bool, send_message: Callable[[dict], None], on_teardown: Callable[[], None]) -> None"
},
{
"docstring": "Send a push notification.",
... | 4 | null | Implement the Python class `PushChannel` described below.
Class description:
Class that represents a push channel.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, webhook_id: str, support_confirm: bool, send_message: Callable[[dict], None], on_teardown: Callable[[], None]) -> None: Initial... | Implement the Python class `PushChannel` described below.
Class description:
Class that represents a push channel.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, webhook_id: str, support_confirm: bool, send_message: Callable[[dict], None], on_teardown: Callable[[], None]) -> None: Initial... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class PushChannel:
"""Class that represents a push channel."""
def __init__(self, hass: HomeAssistant, webhook_id: str, support_confirm: bool, send_message: Callable[[dict], None], on_teardown: Callable[[], None]) -> None:
"""Initialize a local push channel."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PushChannel:
"""Class that represents a push channel."""
def __init__(self, hass: HomeAssistant, webhook_id: str, support_confirm: bool, send_message: Callable[[dict], None], on_teardown: Callable[[], None]) -> None:
"""Initialize a local push channel."""
self.hass = hass
self.web... | the_stack_v2_python_sparse | homeassistant/components/mobile_app/push_notification.py | home-assistant/core | train | 35,501 |
e00d6c369bcfcecdd10a257d4e9da71a74ec6b10 | [
"self.RF = listOfTrees\nself.h = header\nself.FC = listOfFeaturesChoosen\nself.featureColumn = originalFeatureColumn",
"prediction = {}\nresults = []\nfor i in range(len(self.RF)):\n dp = trimDatapoint(datapoint, self.FC[i], self.h, self.featureColumn)\n results.append(classify(self.RF[i], dp))\nfor result ... | <|body_start_0|>
self.RF = listOfTrees
self.h = header
self.FC = listOfFeaturesChoosen
self.featureColumn = originalFeatureColumn
<|end_body_0|>
<|body_start_1|>
prediction = {}
results = []
for i in range(len(self.RF)):
dp = trimDatapoint(datapoint, ... | A RandomForest Object. | RandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
"""A RandomForest Object."""
def __init__(self, listOfTrees, header, listOfFeaturesChoosen, originalFeatureColumn):
"""the constructor for the Random Forest Object Keyword Argument: listOfTrees: A list containing each random tree in the RandomForest header: All the feat... | stack_v2_sparse_classes_36k_train_029795 | 15,954 | no_license | [
{
"docstring": "the constructor for the Random Forest Object Keyword Argument: listOfTrees: A list containing each random tree in the RandomForest header: All the features in order of how they appear in each datapoint listOfFeaturesChoosen: An ordered list of random features choosen for randomForest originalFea... | 3 | stack_v2_sparse_classes_30k_train_000140 | Implement the Python class `RandomForest` described below.
Class description:
A RandomForest Object.
Method signatures and docstrings:
- def __init__(self, listOfTrees, header, listOfFeaturesChoosen, originalFeatureColumn): the constructor for the Random Forest Object Keyword Argument: listOfTrees: A list containing ... | Implement the Python class `RandomForest` described below.
Class description:
A RandomForest Object.
Method signatures and docstrings:
- def __init__(self, listOfTrees, header, listOfFeaturesChoosen, originalFeatureColumn): the constructor for the Random Forest Object Keyword Argument: listOfTrees: A list containing ... | 0022c0bee14cdc3a773c0fe60d196cb12a0dd9f0 | <|skeleton|>
class RandomForest:
"""A RandomForest Object."""
def __init__(self, listOfTrees, header, listOfFeaturesChoosen, originalFeatureColumn):
"""the constructor for the Random Forest Object Keyword Argument: listOfTrees: A list containing each random tree in the RandomForest header: All the feat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomForest:
"""A RandomForest Object."""
def __init__(self, listOfTrees, header, listOfFeaturesChoosen, originalFeatureColumn):
"""the constructor for the Random Forest Object Keyword Argument: listOfTrees: A list containing each random tree in the RandomForest header: All the features in order... | the_stack_v2_python_sparse | random forest tree/InsuranceClaimPrediction.py | ShaaficiAli/PersonalProjects | train | 0 |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"self.column_names: List = kargs.pop('column_names')\nself.action: Action = kargs.pop('action')\nsuper().__init__(*args, **kargs)\nself.set_fields_from_dict(['item_column', 'user_fname_column', 'file_suffix', 'zip_for_moodle', 'confirm_items'])\nuser_fname_column = self.fields['user_fname_column'].initial\nitem_col... | <|body_start_0|>
self.column_names: List = kargs.pop('column_names')
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
self.set_fields_from_dict(['item_column', 'user_fname_column', 'file_suffix', 'zip_for_moodle', 'confirm_items'])
user_fname_column = se... | Form to create a ZIP. | ZipActionForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
<|body_0|>
def clean(self):
"""Detect uniques values in one column, and different column names."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_029796 | 20,237 | permissive | [
{
"docstring": "Store column names, action and payload, adjust fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Detect uniques values in one column, and different column names.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005113 | Implement the Python class `ZipActionForm` described below.
Class description:
Form to create a ZIP.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names, action and payload, adjust fields.
- def clean(self): Detect uniques values in one column, and different column names. | Implement the Python class `ZipActionForm` described below.
Class description:
Form to create a ZIP.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names, action and payload, adjust fields.
- def clean(self): Detect uniques values in one column, and different column names.
<|ske... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
<|body_0|>
def clean(self):
"""Detect uniques values in one column, and different column names."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
self.column_names: List = kargs.pop('column_names')
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
10e3c0973160752fda3677e997ae911da3e2e731 | [
"splitified = toParse.split('--------')\nsequence = list(splitified[0].rstrip().strip())\nsequence.insert(0, 'source')\nsequence.append('sink')\navailableStates = splitified[2].rstrip().strip().split()\ntransMatrix = splitified[3].rstrip().strip().splitlines()\nemissionMatrix = splitified[4].rstrip().strip().splitl... | <|body_start_0|>
splitified = toParse.split('--------')
sequence = list(splitified[0].rstrip().strip())
sequence.insert(0, 'source')
sequence.append('sink')
availableStates = splitified[2].rstrip().strip().split()
transMatrix = splitified[3].rstrip().strip().splitlines()
... | Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state) | HMM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HMM:
"""Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)"""
def parseInput(self, toParse):
"""Takes the input file and parses it the sequence and stat... | stack_v2_sparse_classes_36k_train_029797 | 3,029 | no_license | [
{
"docstring": "Takes the input file and parses it the sequence and states into lists and the transition and emission matrices into dictionaries",
"name": "parseInput",
"signature": "def parseInput(self, toParse)"
},
{
"docstring": "Constructs a graph as a dictionary of transition edges with the... | 2 | stack_v2_sparse_classes_30k_train_010492 | Implement the Python class `HMM` described below.
Class description:
Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)
Method signatures and docstrings:
- def parseInput(self, toParse):... | Implement the Python class `HMM` described below.
Class description:
Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)
Method signatures and docstrings:
- def parseInput(self, toParse):... | 93d0d0194341dd5a6cd6877fdd8b664a50bd9734 | <|skeleton|>
class HMM:
"""Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)"""
def parseInput(self, toParse):
"""Takes the input file and parses it the sequence and stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HMM:
"""Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)"""
def parseInput(self, toParse):
"""Takes the input file and parses it the sequence and states into lists... | the_stack_v2_python_sparse | Bioinformatics-Algorithms/HiddenStates-6/forwardp19.py | ajmak/Bioinformatics-Algorithms | train | 0 |
8c16098949430a781a03906f3a133e045bc48283 | [
"threading.Thread.__init__(self)\nself.threadName = name\nself.people = people",
"print('开始线程:' + self.threadName)\nchi(self.people)\nprint('结束线程:' + self.name)"
] | <|body_start_0|>
threading.Thread.__init__(self)
self.threadName = name
self.people = people
<|end_body_0|>
<|body_start_1|>
print('开始线程:' + self.threadName)
chi(self.people)
print('结束线程:' + self.name)
<|end_body_1|>
| myThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
<|body_0|>
def run(self):
"""重写run方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threading.Thread.__init__(self)
self.threadName = name
self.people = peopl... | stack_v2_sparse_classes_36k_train_029798 | 1,105 | no_license | [
{
"docstring": "重写threading.Thread初始化内容",
"name": "__init__",
"signature": "def __init__(self, people, name)"
},
{
"docstring": "重写run方法",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015009 | Implement the Python class `myThread` described below.
Class description:
Implement the myThread class.
Method signatures and docstrings:
- def __init__(self, people, name): 重写threading.Thread初始化内容
- def run(self): 重写run方法 | Implement the Python class `myThread` described below.
Class description:
Implement the myThread class.
Method signatures and docstrings:
- def __init__(self, people, name): 重写threading.Thread初始化内容
- def run(self): 重写run方法
<|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thr... | 56197668482f3f776e97258b845ec80adbe8e6cc | <|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
<|body_0|>
def run(self):
"""重写run方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
threading.Thread.__init__(self)
self.threadName = name
self.people = people
def run(self):
"""重写run方法"""
print('开始线程:' + self.threadName)
chi(self.people)
print('结束线程:... | the_stack_v2_python_sparse | Script/threading/case_threading_02.py | gentle-yu/PythonProject | train | 0 | |
f16d81baf4333c89d5510fb5bcba976b0c2da8ab | [
"X = {}\nfor i, v in enumerate(A):\n X[v] = i\nmax_len = 0\nfor i in range(len(A)):\n for j in range(i + 1, len(A)):\n x, y = (i, j)\n cur = 2\n while True:\n v = A[x] + A[y]\n if v in X and X[v] > y:\n x, y = (y, X[v])\n cur += 1\n ... | <|body_start_0|>
X = {}
for i, v in enumerate(A):
X[v] = i
max_len = 0
for i in range(len(A)):
for j in range(i + 1, len(A)):
x, y = (i, j)
cur = 2
while True:
v = A[x] + A[y]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
X = {}
for i, v in enumerate(A):
... | stack_v2_sparse_classes_36k_train_029799 | 1,349 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq",
"signature": "def lenLongestFibSubseq(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq",
"signature": "def lenLongestFibSubseq(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
<|skeleton|>
class Solution:
def lenLong... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
X = {}
for i, v in enumerate(A):
X[v] = i
max_len = 0
for i in range(len(A)):
for j in range(i + 1, len(A)):
x, y = (i, j)
cur = 2
... | the_stack_v2_python_sparse | length-of-longest-fibonacci-subsequence/solution.py | uxlsl/leetcode_practice | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.