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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dea8d6f747138b93eb4c7f9a135e45c5146a4551 | [
"if self._return_code != 0:\n return None\nreturn self._body.get(IPROTO_VERSION)",
"if self._return_code != 0:\n return []\nreturn self._body.get(IPROTO_FEATURES)",
"if self._return_code != 0:\n return None\nreturn to_unicode(self._body.get(IPROTO_AUTH_TYPE))"
] | <|body_start_0|>
if self._return_code != 0:
return None
return self._body.get(IPROTO_VERSION)
<|end_body_0|>
<|body_start_1|>
if self._return_code != 0:
return []
return self._body.get(IPROTO_FEATURES)
<|end_body_1|>
<|body_start_2|>
if self._return_code... | Represents an ID request response: information about server protocol version and features it supports. | ResponseProtocolVersion | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseProtocolVersion:
"""Represents an ID request response: information about server protocol version and features it supports."""
def protocol_version(self):
"""Server protocol version. :rtype: :obj:`int` or :obj:`None`"""
<|body_0|>
def features(self):
"""Se... | stack_v2_sparse_classes_36k_train_008300 | 10,967 | permissive | [
{
"docstring": "Server protocol version. :rtype: :obj:`int` or :obj:`None`",
"name": "protocol_version",
"signature": "def protocol_version(self)"
},
{
"docstring": "Server supported features. :rtype: :obj:`list`",
"name": "features",
"signature": "def features(self)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_021549 | Implement the Python class `ResponseProtocolVersion` described below.
Class description:
Represents an ID request response: information about server protocol version and features it supports.
Method signatures and docstrings:
- def protocol_version(self): Server protocol version. :rtype: :obj:`int` or :obj:`None`
- d... | Implement the Python class `ResponseProtocolVersion` described below.
Class description:
Represents an ID request response: information about server protocol version and features it supports.
Method signatures and docstrings:
- def protocol_version(self): Server protocol version. :rtype: :obj:`int` or :obj:`None`
- d... | 66e53bca472fec0efacd690ebe6c54c33a7df3f9 | <|skeleton|>
class ResponseProtocolVersion:
"""Represents an ID request response: information about server protocol version and features it supports."""
def protocol_version(self):
"""Server protocol version. :rtype: :obj:`int` or :obj:`None`"""
<|body_0|>
def features(self):
"""Se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResponseProtocolVersion:
"""Represents an ID request response: information about server protocol version and features it supports."""
def protocol_version(self):
"""Server protocol version. :rtype: :obj:`int` or :obj:`None`"""
if self._return_code != 0:
return None
ret... | the_stack_v2_python_sparse | tarantool/response.py | tarantool/tarantool-python | train | 80 |
3e9a70f2bb3186f5131a38c2b73f67a7b582a5f0 | [
"super(Recorder, self).__init__()\nself.symbols = symbols\nself.timer_frequency = SNAPSHOT_RATE\nself.workers = dict()\nself.current_time = dt.now()\nself.daemon = False",
"coinbase, bitfinex = self.symbols\nself.workers[coinbase] = CoinbaseClient(sym=coinbase)\nself.workers[bitfinex] = BitfinexClient(sym=bitfine... | <|body_start_0|>
super(Recorder, self).__init__()
self.symbols = symbols
self.timer_frequency = SNAPSHOT_RATE
self.workers = dict()
self.current_time = dt.now()
self.daemon = False
<|end_body_0|>
<|body_start_1|>
coinbase, bitfinex = self.symbols
self.wor... | Recorder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Recorder:
def __init__(self, symbols):
"""Constructor of Recorder. :param symbols: basket of securities to record... Example: symbols = [('BTC-USD, 'tBTCUSD')]"""
<|body_0|>
def run(self) -> None:
"""New process created to instantiate limit order books for (1) Coinba... | stack_v2_sparse_classes_36k_train_008301 | 4,752 | no_license | [
{
"docstring": "Constructor of Recorder. :param symbols: basket of securities to record... Example: symbols = [('BTC-USD, 'tBTCUSD')]",
"name": "__init__",
"signature": "def __init__(self, symbols)"
},
{
"docstring": "New process created to instantiate limit order books for (1) Coinbase Pro, and... | 3 | stack_v2_sparse_classes_30k_val_001052 | Implement the Python class `Recorder` described below.
Class description:
Implement the Recorder class.
Method signatures and docstrings:
- def __init__(self, symbols): Constructor of Recorder. :param symbols: basket of securities to record... Example: symbols = [('BTC-USD, 'tBTCUSD')]
- def run(self) -> None: New pr... | Implement the Python class `Recorder` described below.
Class description:
Implement the Recorder class.
Method signatures and docstrings:
- def __init__(self, symbols): Constructor of Recorder. :param symbols: basket of securities to record... Example: symbols = [('BTC-USD, 'tBTCUSD')]
- def run(self) -> None: New pr... | 078081e5715cadeae9c798a3d759c9d59d2041bc | <|skeleton|>
class Recorder:
def __init__(self, symbols):
"""Constructor of Recorder. :param symbols: basket of securities to record... Example: symbols = [('BTC-USD, 'tBTCUSD')]"""
<|body_0|>
def run(self) -> None:
"""New process created to instantiate limit order books for (1) Coinba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Recorder:
def __init__(self, symbols):
"""Constructor of Recorder. :param symbols: basket of securities to record... Example: symbols = [('BTC-USD, 'tBTCUSD')]"""
super(Recorder, self).__init__()
self.symbols = symbols
self.timer_frequency = SNAPSHOT_RATE
self.workers =... | the_stack_v2_python_sparse | recorder.py | sadighian/crypto-rl | train | 676 | |
54dcc8891439a5350d8ec44525b64eda8554423c | [
"n = len(s)\nm = len(t)\ndp = [[0] * (m + 1) for _ in range(n + 1)]\ni = 0\nwhile i <= n:\n j = 0\n while j <= m:\n if i == j == 0:\n dp[i][j] = 0\n elif s[i - 1] == t[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = min([dp[i - 1][j - 1] + 1, dp... | <|body_start_0|>
n = len(s)
m = len(t)
dp = [[0] * (m + 1) for _ in range(n + 1)]
i = 0
while i <= n:
j = 0
while j <= m:
if i == j == 0:
dp[i][j] = 0
elif s[i - 1] == t[j - 1]:
dp[i][... | @param s: a string @param t: a string @return: true if they are both one edit distance apart or false | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@param s: a string @param t: a string @return: true if they are both one edit distance apart or false"""
def isOneEditDistance(self, s, t):
"""Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/soluti... | stack_v2_sparse_classes_36k_train_008302 | 1,840 | no_license | [
{
"docstring": "Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/solution/edit-distance-by-ikaruga/",
"name": "isOneEditDistance",
"signature": "def isOneEditDistance(self, s, t)"
},
{
"docstring": "O(n) runtime, O(1) space... | 2 | stack_v2_sparse_classes_30k_test_000318 | Implement the Python class `Solution` described below.
Class description:
@param s: a string @param t: a string @return: true if they are both one edit distance apart or false
Method signatures and docstrings:
- def isOneEditDistance(self, s, t): Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) sp... | Implement the Python class `Solution` described below.
Class description:
@param s: a string @param t: a string @return: true if they are both one edit distance apart or false
Method signatures and docstrings:
- def isOneEditDistance(self, s, t): Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) sp... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution:
"""@param s: a string @param t: a string @return: true if they are both one edit distance apart or false"""
def isOneEditDistance(self, s, t):
"""Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/soluti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""@param s: a string @param t: a string @return: true if they are both one edit distance apart or false"""
def isOneEditDistance(self, s, t):
"""Dynamic Programming solution (not recommended): O(n2) runtime, O(n2) space https://leetcode-cn.com/problems/edit-distance/solution/edit-dista... | the_stack_v2_python_sparse | One_Edit_Distance_14.py | jay6413682/Leetcode | train | 0 |
8fe70f778074ee2ce032fe11375889317f383c57 | [
"super(HyperOptNoTraining, self).__init__(params, data)\nself.objective = None\nself.trial_losses = None\nself.best_trial = None\nself.trial_list = None",
"self.trial_list = trial_list\nif self.trial_list is None:\n raise Exception('Sorry, Hyperparameter optimization without training currently only works if a ... | <|body_start_0|>
super(HyperOptNoTraining, self).__init__(params, data)
self.objective = None
self.trial_losses = None
self.best_trial = None
self.trial_list = None
<|end_body_0|>
<|body_start_1|>
self.trial_list = trial_list
if self.trial_list is None:
... | Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian. | HyperOptNoTraining | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperOptNoTraining:
"""Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian."""
def __init__(self, params, data):
"""Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters us... | stack_v2_sparse_classes_36k_train_008303 | 2,999 | permissive | [
{
"docstring": "Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters used to create this hyperparameter optimizer. data : mala.datahandling.data_handler.DataHandler DataHandler holding the data for the hyperparameter optimization.",
"name": "__init__... | 3 | stack_v2_sparse_classes_30k_train_014278 | Implement the Python class `HyperOptNoTraining` described below.
Class description:
Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian.
Method signatures and docstrings:
- def __init__(self, params, data): Create a HyperOptNoTraining object. Parameters ---------... | Implement the Python class `HyperOptNoTraining` described below.
Class description:
Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian.
Method signatures and docstrings:
- def __init__(self, params, data): Create a HyperOptNoTraining object. Parameters ---------... | 9cc771b0cdc4178c7f66fd717684658abbb0d95c | <|skeleton|>
class HyperOptNoTraining:
"""Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian."""
def __init__(self, params, data):
"""Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HyperOptNoTraining:
"""Hyperparameter optimizer that does not require training networks. Networks are analysed using the Jacobian."""
def __init__(self, params, data):
"""Create a HyperOptNoTraining object. Parameters ---------- params : mala.common.parametes.Parameters Parameters used to create ... | the_stack_v2_python_sparse | mala/network/hyper_opt_notraining.py | icamps/mala | train | 0 |
dbf09a5b896f7769485c6dda3dfbdac6006e7531 | [
"self.subject = subject\nself.condition = condition\nself.effect = effect\nself.singleUse = singleUse\nself.parent = None",
"context = self.getTriggerContext(event)\nif self.condition is None or self.condition.evaluate(context):\n if self.singleUse:\n context.owner.unregisterTrigger(self)\n coroutine... | <|body_start_0|>
self.subject = subject
self.condition = condition
self.effect = effect
self.singleUse = singleUse
self.parent = None
<|end_body_0|>
<|body_start_1|>
context = self.getTriggerContext(event)
if self.condition is None or self.condition.evaluate(cont... | Represents a Triggerable Effect | Trigger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trigger:
"""Represents a Triggerable Effect"""
def __init__(self, subject, effect, condition=None, singleUse=False):
"""Initialize the Trigger"""
<|body_0|>
def receive(self, event):
"""Receive the event"""
<|body_1|>
def getTriggerContext(self, even... | stack_v2_sparse_classes_36k_train_008304 | 1,219 | no_license | [
{
"docstring": "Initialize the Trigger",
"name": "__init__",
"signature": "def __init__(self, subject, effect, condition=None, singleUse=False)"
},
{
"docstring": "Receive the event",
"name": "receive",
"signature": "def receive(self, event)"
},
{
"docstring": "Return the modifie... | 3 | stack_v2_sparse_classes_30k_train_011938 | Implement the Python class `Trigger` described below.
Class description:
Represents a Triggerable Effect
Method signatures and docstrings:
- def __init__(self, subject, effect, condition=None, singleUse=False): Initialize the Trigger
- def receive(self, event): Receive the event
- def getTriggerContext(self, event): ... | Implement the Python class `Trigger` described below.
Class description:
Represents a Triggerable Effect
Method signatures and docstrings:
- def __init__(self, subject, effect, condition=None, singleUse=False): Initialize the Trigger
- def receive(self, event): Receive the event
- def getTriggerContext(self, event): ... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class Trigger:
"""Represents a Triggerable Effect"""
def __init__(self, subject, effect, condition=None, singleUse=False):
"""Initialize the Trigger"""
<|body_0|>
def receive(self, event):
"""Receive the event"""
<|body_1|>
def getTriggerContext(self, even... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trigger:
"""Represents a Triggerable Effect"""
def __init__(self, subject, effect, condition=None, singleUse=False):
"""Initialize the Trigger"""
self.subject = subject
self.condition = condition
self.effect = effect
self.singleUse = singleUse
self.parent =... | the_stack_v2_python_sparse | src/Game/Effects/Triggers/trigger.py | dfwarden/DeckBuilding | train | 0 |
95a471991bc9e5dd14f77180b6e002b3a149a142 | [
"self.t = self.ctx.convert(t)\nif 'degree' in kwargs:\n self.degree = kwargs['degree']\n self.dps_goal = int(1.5 * self.degree)\nelse:\n self.dps_goal = int(self.ctx.dps * 1.74)\n self.degree = max(22, int(1.31 * self.dps_goal))\nM = self.degree + 1\nself.dps_orig = self.ctx.dps\nself.ctx.dps = self.dps... | <|body_start_0|>
self.t = self.ctx.convert(t)
if 'degree' in kwargs:
self.degree = kwargs['degree']
self.dps_goal = int(1.5 * self.degree)
else:
self.dps_goal = int(self.ctx.dps * 1.74)
self.degree = max(22, int(1.31 * self.dps_goal))
M = s... | Cohen | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cohen:
def calc_laplace_parameter(self, t, **kwargs):
"""The Cohen algorithm accelerates the convergence of the nearly alternating series resulting from the application of the trapezoidal rule to the Bromwich contour inversion integral. .. math :: p_k = \\frac{\\gamma}{2 t} + \\frac{\\pi... | stack_v2_sparse_classes_36k_train_008305 | 36,056 | permissive | [
{
"docstring": "The Cohen algorithm accelerates the convergence of the nearly alternating series resulting from the application of the trapezoidal rule to the Bromwich contour inversion integral. .. math :: p_k = \\\\frac{\\\\gamma}{2 t} + \\\\frac{\\\\pi i k}{t} \\\\qquad 0 \\\\le k < M where .. math :: \\\\ga... | 2 | null | Implement the Python class `Cohen` described below.
Class description:
Implement the Cohen class.
Method signatures and docstrings:
- def calc_laplace_parameter(self, t, **kwargs): The Cohen algorithm accelerates the convergence of the nearly alternating series resulting from the application of the trapezoidal rule t... | Implement the Python class `Cohen` described below.
Class description:
Implement the Cohen class.
Method signatures and docstrings:
- def calc_laplace_parameter(self, t, **kwargs): The Cohen algorithm accelerates the convergence of the nearly alternating series resulting from the application of the trapezoidal rule t... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class Cohen:
def calc_laplace_parameter(self, t, **kwargs):
"""The Cohen algorithm accelerates the convergence of the nearly alternating series resulting from the application of the trapezoidal rule to the Bromwich contour inversion integral. .. math :: p_k = \\frac{\\gamma}{2 t} + \\frac{\\pi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cohen:
def calc_laplace_parameter(self, t, **kwargs):
"""The Cohen algorithm accelerates the convergence of the nearly alternating series resulting from the application of the trapezoidal rule to the Bromwich contour inversion integral. .. math :: p_k = \\frac{\\gamma}{2 t} + \\frac{\\pi i k}{t} \\qqu... | the_stack_v2_python_sparse | contrib/python/mpmath/mpmath/calculus/inverselaplace.py | catboost/catboost | train | 8,012 | |
dec36a6ffecd6e3f8acf8aaa6191d412003c8a58 | [
"files = self._find(topdir)\ntags = self._read(files)\nreturn tags",
"matches = []\nfor root, dirnames, filenames in os.walk(topdir):\n for filename in fnmatch.filter(filenames, '*.mp3'):\n matches.append(os.path.join(root, filename))\nreturn matches",
"metadata = []\nfor mp3 in musicfiles:\n filed... | <|body_start_0|>
files = self._find(topdir)
tags = self._read(files)
return tags
<|end_body_0|>
<|body_start_1|>
matches = []
for root, dirnames, filenames in os.walk(topdir):
for filename in fnmatch.filter(filenames, '*.mp3'):
matches.append(os.path.... | A TagReader reads metadata from .mp3 files and returns it in a list of dictionaries. The only method used outside this file will be readtags(). | TagReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagReader:
"""A TagReader reads metadata from .mp3 files and returns it in a list of dictionaries. The only method used outside this file will be readtags()."""
def readtags(self, topdir):
"""Searches through the given directory for .mp3 files, reads the files' metadata, and returns ... | stack_v2_sparse_classes_36k_train_008306 | 2,103 | no_license | [
{
"docstring": "Searches through the given directory for .mp3 files, reads the files' metadata, and returns it in a list of dictionaries.",
"name": "readtags",
"signature": "def readtags(self, topdir)"
},
{
"docstring": "Searches through the given music directory for .mp3 files and returns an ar... | 3 | stack_v2_sparse_classes_30k_train_000097 | Implement the Python class `TagReader` described below.
Class description:
A TagReader reads metadata from .mp3 files and returns it in a list of dictionaries. The only method used outside this file will be readtags().
Method signatures and docstrings:
- def readtags(self, topdir): Searches through the given director... | Implement the Python class `TagReader` described below.
Class description:
A TagReader reads metadata from .mp3 files and returns it in a list of dictionaries. The only method used outside this file will be readtags().
Method signatures and docstrings:
- def readtags(self, topdir): Searches through the given director... | d903ea36887221032342349c90478ce331321e65 | <|skeleton|>
class TagReader:
"""A TagReader reads metadata from .mp3 files and returns it in a list of dictionaries. The only method used outside this file will be readtags()."""
def readtags(self, topdir):
"""Searches through the given directory for .mp3 files, reads the files' metadata, and returns ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagReader:
"""A TagReader reads metadata from .mp3 files and returns it in a list of dictionaries. The only method used outside this file will be readtags()."""
def readtags(self, topdir):
"""Searches through the given directory for .mp3 files, reads the files' metadata, and returns it in a list ... | the_stack_v2_python_sparse | project/tagreader.py | paperbackdragon/python-300 | train | 0 |
023d378c23d28f319c553c0e7587769e9a768a9d | [
"dummy = tail = ListNode(None)\nwhile head1 and head2:\n if head1.val <= head2.val:\n tail.next = head1\n head1 = head1.next\n else:\n tail.next = head2\n head2 = head2.next\n tail = tail.next\nif head1:\n tail.next = head1\nelif head2:\n tail.next = head2\nreturn dummy.ne... | <|body_start_0|>
dummy = tail = ListNode(None)
while head1 and head2:
if head1.val <= head2.val:
tail.next = head1
head1 = head1.next
else:
tail.next = head2
head2 = head2.next
tail = tail.next
if... | SolutionDivideAndConquer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionDivideAndConquer:
def merge(self, head1, head2):
"""Merges two sorted linked lists and returns head of a new list. Time complexity: O(m + n). Space complexity: O(1), m, n are lengths of linked lists."""
<|body_0|>
def mergeKLists(self, lists):
"""Merges sorte... | stack_v2_sparse_classes_36k_train_008307 | 5,297 | no_license | [
{
"docstring": "Merges two sorted linked lists and returns head of a new list. Time complexity: O(m + n). Space complexity: O(1), m, n are lengths of linked lists.",
"name": "merge",
"signature": "def merge(self, head1, head2)"
},
{
"docstring": "Merges sorted linked lists from array lists into ... | 2 | null | Implement the Python class `SolutionDivideAndConquer` described below.
Class description:
Implement the SolutionDivideAndConquer class.
Method signatures and docstrings:
- def merge(self, head1, head2): Merges two sorted linked lists and returns head of a new list. Time complexity: O(m + n). Space complexity: O(1), m... | Implement the Python class `SolutionDivideAndConquer` described below.
Class description:
Implement the SolutionDivideAndConquer class.
Method signatures and docstrings:
- def merge(self, head1, head2): Merges two sorted linked lists and returns head of a new list. Time complexity: O(m + n). Space complexity: O(1), m... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionDivideAndConquer:
def merge(self, head1, head2):
"""Merges two sorted linked lists and returns head of a new list. Time complexity: O(m + n). Space complexity: O(1), m, n are lengths of linked lists."""
<|body_0|>
def mergeKLists(self, lists):
"""Merges sorte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionDivideAndConquer:
def merge(self, head1, head2):
"""Merges two sorted linked lists and returns head of a new list. Time complexity: O(m + n). Space complexity: O(1), m, n are lengths of linked lists."""
dummy = tail = ListNode(None)
while head1 and head2:
if head1.v... | the_stack_v2_python_sparse | Linked_Lists/merge_k_sorted_lists.py | vladn90/Algorithms | train | 0 | |
a05cc41300b4ea6a33d01bec34f0b3d538212c46 | [
"self.arr = arr\ntotal = 0\nself.runningSum = [total]\nfor i in arr:\n total += i\n self.runningSum.append(total)",
"if i < 0 or len(self.arr) < j or j <= i:\n return None\nreturn self.runningSum[j] - self.runningSum[i]"
] | <|body_start_0|>
self.arr = arr
total = 0
self.runningSum = [total]
for i in arr:
total += i
self.runningSum.append(total)
<|end_body_0|>
<|body_start_1|>
if i < 0 or len(self.arr) < j or j <= i:
return None
return self.runningSum[j] -... | Optimized sub list. | SubListSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubListSum:
"""Optimized sub list."""
def __init__(self, arr):
"""Init."""
<|body_0|>
def sum(self, i, j):
"""Sum the sublist of arr from i (inc ) to j ( exc )."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.arr = arr
total = 0
... | stack_v2_sparse_classes_36k_train_008308 | 1,070 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, arr)"
},
{
"docstring": "Sum the sublist of arr from i (inc ) to j ( exc ).",
"name": "sum",
"signature": "def sum(self, i, j)"
}
] | 2 | null | Implement the Python class `SubListSum` described below.
Class description:
Optimized sub list.
Method signatures and docstrings:
- def __init__(self, arr): Init.
- def sum(self, i, j): Sum the sublist of arr from i (inc ) to j ( exc ). | Implement the Python class `SubListSum` described below.
Class description:
Optimized sub list.
Method signatures and docstrings:
- def __init__(self, arr): Init.
- def sum(self, i, j): Sum the sublist of arr from i (inc ) to j ( exc ).
<|skeleton|>
class SubListSum:
"""Optimized sub list."""
def __init__(s... | d3e1a6ab102c7af1eea4ab6b1282e4d44e5b80ba | <|skeleton|>
class SubListSum:
"""Optimized sub list."""
def __init__(self, arr):
"""Init."""
<|body_0|>
def sum(self, i, j):
"""Sum the sublist of arr from i (inc ) to j ( exc )."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubListSum:
"""Optimized sub list."""
def __init__(self, arr):
"""Init."""
self.arr = arr
total = 0
self.runningSum = [total]
for i in arr:
total += i
self.runningSum.append(total)
def sum(self, i, j):
"""Sum the sublist of arr ... | the_stack_v2_python_sparse | 149-sum-sublist.py | ericgarig/daily-coding-problem | train | 0 |
7c330d055d112f38e9faf2031180f17fa572f58c | [
"self.qname = qname\nself.attrs = attrs\nself.text = text or ''\nself.tail = None\nself.child_elements = []",
"elt = Element(qname, attrs, text)\nself.child_elements.append(elt)\nreturn elt",
"prefix, _ = split_qname(self.qname)\nif prefix:\n prefixes.add(prefix)\nelif '' in prefix_namespaces:\n prefixes.... | <|body_start_0|>
self.qname = qname
self.attrs = attrs
self.text = text or ''
self.tail = None
self.child_elements = []
<|end_body_0|>
<|body_start_1|>
elt = Element(qname, attrs, text)
self.child_elements.append(elt)
return elt
<|end_body_1|>
<|body_sta... | One element in a document. | Element | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Element:
"""One element in a document."""
def __init__(self, qname, attrs=None, text=None):
"""Create instance with this QName and attrs."""
<|body_0|>
def add_child(self, qname, attrs=None, text=None):
"""Create a new element and make it a child of this one."""
... | stack_v2_sparse_classes_36k_train_008309 | 4,900 | no_license | [
{
"docstring": "Create instance with this QName and attrs.",
"name": "__init__",
"signature": "def __init__(self, qname, attrs=None, text=None)"
},
{
"docstring": "Create a new element and make it a child of this one.",
"name": "add_child",
"signature": "def add_child(self, qname, attrs=... | 4 | null | Implement the Python class `Element` described below.
Class description:
One element in a document.
Method signatures and docstrings:
- def __init__(self, qname, attrs=None, text=None): Create instance with this QName and attrs.
- def add_child(self, qname, attrs=None, text=None): Create a new element and make it a c... | Implement the Python class `Element` described below.
Class description:
One element in a document.
Method signatures and docstrings:
- def __init__(self, qname, attrs=None, text=None): Create instance with this QName and attrs.
- def add_child(self, qname, attrs=None, text=None): Create a new element and make it a c... | 0075ea457f764cbb67acecb584e927bf58d2e7a8 | <|skeleton|>
class Element:
"""One element in a document."""
def __init__(self, qname, attrs=None, text=None):
"""Create instance with this QName and attrs."""
<|body_0|>
def add_child(self, qname, attrs=None, text=None):
"""Create a new element and make it a child of this one."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Element:
"""One element in a document."""
def __init__(self, qname, attrs=None, text=None):
"""Create instance with this QName and attrs."""
self.qname = qname
self.attrs = attrs
self.text = text or ''
self.tail = None
self.child_elements = []
def add_... | the_stack_v2_python_sparse | linotak/xml_writer.py | pdc/linotak | train | 0 |
ec2890a4d572bf8a26aade406687be280217d540 | [
"if frequency == icdtyp.Frequency.Minutely:\n df = cls._transform_minutely_df(df, trade_symbol_id)\nelif frequency == icdtyp.Frequency.Daily:\n df = cls._transform_daily_df(df, trade_symbol_id)\nelif frequency == icdtyp.Frequency.Tick:\n df = cls._transform_tick_df(df, trade_symbol_id)\nelse:\n dbg.dfat... | <|body_start_0|>
if frequency == icdtyp.Frequency.Minutely:
df = cls._transform_minutely_df(df, trade_symbol_id)
elif frequency == icdtyp.Frequency.Daily:
df = cls._transform_daily_df(df, trade_symbol_id)
elif frequency == icdtyp.Frequency.Tick:
df = cls._tran... | IbS3ToSqlTransformer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IbS3ToSqlTransformer:
def transform(cls, df: pd.DataFrame, trade_symbol_id: int, frequency: icdtyp.Frequency) -> pd.DataFrame:
"""Transform IB data loaded from S3 to load to SQL. :param df: dataframe with data from S3 :param trade_symbol_id: symbol id in SQL database :param frequency: da... | stack_v2_sparse_classes_36k_train_008310 | 3,028 | permissive | [
{
"docstring": "Transform IB data loaded from S3 to load to SQL. :param df: dataframe with data from S3 :param trade_symbol_id: symbol id in SQL database :param frequency: dataframe frequency :return: processed dataframe",
"name": "transform",
"signature": "def transform(cls, df: pd.DataFrame, trade_sym... | 4 | null | Implement the Python class `IbS3ToSqlTransformer` described below.
Class description:
Implement the IbS3ToSqlTransformer class.
Method signatures and docstrings:
- def transform(cls, df: pd.DataFrame, trade_symbol_id: int, frequency: icdtyp.Frequency) -> pd.DataFrame: Transform IB data loaded from S3 to load to SQL. ... | Implement the Python class `IbS3ToSqlTransformer` described below.
Class description:
Implement the IbS3ToSqlTransformer class.
Method signatures and docstrings:
- def transform(cls, df: pd.DataFrame, trade_symbol_id: int, frequency: icdtyp.Frequency) -> pd.DataFrame: Transform IB data loaded from S3 to load to SQL. ... | 363c59fa29df2ba2719cbad2f8a19ae12cc54a92 | <|skeleton|>
class IbS3ToSqlTransformer:
def transform(cls, df: pd.DataFrame, trade_symbol_id: int, frequency: icdtyp.Frequency) -> pd.DataFrame:
"""Transform IB data loaded from S3 to load to SQL. :param df: dataframe with data from S3 :param trade_symbol_id: symbol id in SQL database :param frequency: da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IbS3ToSqlTransformer:
def transform(cls, df: pd.DataFrame, trade_symbol_id: int, frequency: icdtyp.Frequency) -> pd.DataFrame:
"""Transform IB data loaded from S3 to load to SQL. :param df: dataframe with data from S3 :param trade_symbol_id: symbol id in SQL database :param frequency: dataframe freque... | the_stack_v2_python_sparse | im/ib/data/transform/ib_s3_to_sql_transformer.py | srlindemann/amp | train | 0 | |
0c80ba8767cc2ef9b8f37ae1ed5c296550bfd226 | [
"GenBank.__init__(self, email, api_key, **kwargs)\nself.accessions = accessions\nself.directory = directory\nself.outputfile = outputfile",
"for i in range(0, len(self.accessions), self.number_of_requests):\n if self.verbose:\n sys.stderr.write(f'{color.PINK}Chunk {i}-{i + self.number_of_requests}{color... | <|body_start_0|>
GenBank.__init__(self, email, api_key, **kwargs)
self.accessions = accessions
self.directory = directory
self.outputfile = outputfile
<|end_body_0|>
<|body_start_1|>
for i in range(0, len(self.accessions), self.number_of_requests):
if self.verbose:
... | A genbank download object. This has a directory to store the results and a list of accessions to retrieve. | GenBankDownload | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenBankDownload:
"""A genbank download object. This has a directory to store the results and a list of accessions to retrieve."""
def __init__(self, email, api_key, outputfile='sequences.gb', directory='.', accessions=[], **kwargs):
"""Initialize the object."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_008311 | 2,093 | permissive | [
{
"docstring": "Initialize the object.",
"name": "__init__",
"signature": "def __init__(self, email, api_key, outputfile='sequences.gb', directory='.', accessions=[], **kwargs)"
},
{
"docstring": "Split the list into the number of elements to request",
"name": "chunk_accessions",
"signat... | 3 | stack_v2_sparse_classes_30k_train_000269 | Implement the Python class `GenBankDownload` described below.
Class description:
A genbank download object. This has a directory to store the results and a list of accessions to retrieve.
Method signatures and docstrings:
- def __init__(self, email, api_key, outputfile='sequences.gb', directory='.', accessions=[], **... | Implement the Python class `GenBankDownload` described below.
Class description:
A genbank download object. This has a directory to store the results and a list of accessions to retrieve.
Method signatures and docstrings:
- def __init__(self, email, api_key, outputfile='sequences.gb', directory='.', accessions=[], **... | 42575fa93e8a1c53012bbfe292514d95b48fbd9d | <|skeleton|>
class GenBankDownload:
"""A genbank download object. This has a directory to store the results and a list of accessions to retrieve."""
def __init__(self, email, api_key, outputfile='sequences.gb', directory='.', accessions=[], **kwargs):
"""Initialize the object."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenBankDownload:
"""A genbank download object. This has a directory to store the results and a list of accessions to retrieve."""
def __init__(self, email, api_key, outputfile='sequences.gb', directory='.', accessions=[], **kwargs):
"""Initialize the object."""
GenBank.__init__(self, emai... | the_stack_v2_python_sparse | pppf_lib/genbank_download.py | linsalrob/PPPF | train | 2 |
86cdffad3925e3a9e31b6de81edd58eed1fadb92 | [
"self.lookup = collections.defaultdict(set)\nfor word in dictionary:\n if len(word) > 2:\n new_word = '{0}{1}{2}'.format(word[0], len(word) - 2, word[-1])\n else:\n new_word = word\n self.lookup[new_word].add(word)",
"if len(word) > 2:\n new_word = '{0}{1}{2}'.format(word[0], len(word) -... | <|body_start_0|>
self.lookup = collections.defaultdict(set)
for word in dictionary:
if len(word) > 2:
new_word = '{0}{1}{2}'.format(word[0], len(word) - 2, word[-1])
else:
new_word = word
self.lookup[new_word].add(word)
<|end_body_0|>
... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_008312 | 819 | no_license | [
{
"docstring": "initialize your data structure here. :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": "check if a word is unique. :type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
... | 2 | null | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | c33559dc5e0bf6879bb3462ab65a9446a66d19f6 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
self.lookup = collections.defaultdict(set)
for word in dictionary:
if len(word) > 2:
new_word = '{0}{1}{2}'.format(word[0], len(word) - 2, w... | the_stack_v2_python_sparse | 288.py | htl1126/leetcode | train | 7 | |
45d301b7c70130ef1f17df94957b9eb7a6298ac5 | [
"author_data = validated_data.pop('author', None)\nvalidated_data['author'] = get_author(author_data.get('uuid'), author_data.get('node'))\nreturn super(CommentSerializer, self).create(validated_data)",
"author_data = validated_data.pop('author', None)\npubDate = validated_data.get('pubDate', None)\nif pubDate an... | <|body_start_0|>
author_data = validated_data.pop('author', None)
validated_data['author'] = get_author(author_data.get('uuid'), author_data.get('node'))
return super(CommentSerializer, self).create(validated_data)
<|end_body_0|>
<|body_start_1|>
author_data = validated_data.pop('author... | A Serializer for the Comment Model | CommentSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentSerializer:
"""A Serializer for the Comment Model"""
def create(self, validated_data):
"""Creates and return a new `Comment` instance, given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Updates and returns an instance of... | stack_v2_sparse_classes_36k_train_008313 | 1,729 | permissive | [
{
"docstring": "Creates and return a new `Comment` instance, given the validated data.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Updates and returns an instance of the `Comment` Model with validated data",
"name": "update",
"signature": "def u... | 2 | stack_v2_sparse_classes_30k_train_008677 | Implement the Python class `CommentSerializer` described below.
Class description:
A Serializer for the Comment Model
Method signatures and docstrings:
- def create(self, validated_data): Creates and return a new `Comment` instance, given the validated data.
- def update(self, instance, validated_data): Updates and r... | Implement the Python class `CommentSerializer` described below.
Class description:
A Serializer for the Comment Model
Method signatures and docstrings:
- def create(self, validated_data): Creates and return a new `Comment` instance, given the validated data.
- def update(self, instance, validated_data): Updates and r... | a05a5161c415b546084bbe98b00e0671860c9bc6 | <|skeleton|>
class CommentSerializer:
"""A Serializer for the Comment Model"""
def create(self, validated_data):
"""Creates and return a new `Comment` instance, given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Updates and returns an instance of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentSerializer:
"""A Serializer for the Comment Model"""
def create(self, validated_data):
"""Creates and return a new `Comment` instance, given the validated data."""
author_data = validated_data.pop('author', None)
validated_data['author'] = get_author(author_data.get('uuid')... | the_stack_v2_python_sparse | DistributedSocialNetworking/api/serializers/comment_serializer.py | Roshack/cmput410-project | train | 0 |
9a2afa68e12538797ee347b0851e7fc7e6d09114 | [
"def partition(left: int, right: int, pivot_index: int) -> int:\n pivot = nums[pivot_index]\n nums[pivot_index], nums[right] = (nums[right], nums[pivot_index])\n store_index = left\n for i in range(left, right):\n if nums[i] < pivot:\n nums[store_index], nums[i] = (nums[i], nums[store_... | <|body_start_0|>
def partition(left: int, right: int, pivot_index: int) -> int:
pivot = nums[pivot_index]
nums[pivot_index], nums[right] = (nums[right], nums[pivot_index])
store_index = left
for i in range(left, right):
if nums[i] < pivot:
... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def kth_largest_element_(self, nums: List[int], k: int) -> int:
"""Approach: Partition Algortihm Time Complexity: O(N) Worst Case: O(N^2) Space Complexity: O(1) :param nums: :param k: :return:"""
<|body_0|>
def kth_largest_element(self, nums: List[int], k: int) -> int... | stack_v2_sparse_classes_36k_train_008314 | 2,568 | no_license | [
{
"docstring": "Approach: Partition Algortihm Time Complexity: O(N) Worst Case: O(N^2) Space Complexity: O(1) :param nums: :param k: :return:",
"name": "kth_largest_element_",
"signature": "def kth_largest_element_(self, nums: List[int], k: int) -> int"
},
{
"docstring": "Approach: Heap Time Com... | 2 | null | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def kth_largest_element_(self, nums: List[int], k: int) -> int: Approach: Partition Algortihm Time Complexity: O(N) Worst Case: O(N^2) Space Complexity: O(1) :param nums: :param k: :re... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def kth_largest_element_(self, nums: List[int], k: int) -> int: Approach: Partition Algortihm Time Complexity: O(N) Worst Case: O(N^2) Space Complexity: O(1) :param nums: :param k: :re... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def kth_largest_element_(self, nums: List[int], k: int) -> int:
"""Approach: Partition Algortihm Time Complexity: O(N) Worst Case: O(N^2) Space Complexity: O(1) :param nums: :param k: :return:"""
<|body_0|>
def kth_largest_element(self, nums: List[int], k: int) -> int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Array:
def kth_largest_element_(self, nums: List[int], k: int) -> int:
"""Approach: Partition Algortihm Time Complexity: O(N) Worst Case: O(N^2) Space Complexity: O(1) :param nums: :param k: :return:"""
def partition(left: int, right: int, pivot_index: int) -> int:
pivot = nums[piv... | the_stack_v2_python_sparse | amazon/heap/kth_largest_element.py | Shiv2157k/leet_code | train | 1 | |
22e4d9702a840cce0e1551289c50561225b4f268 | [
"if (image_folder is None) == (image_files is None):\n raise ValueError('One of image_folder and image_files should be provided')\ndataset, preproc_transform = _load_dataset(image_folder, image_files)\nsuper().__init__(dataset, batchsize_per_replica, shuffle, transform, num_samples)\nif preproc_transform is not ... | <|body_start_0|>
if (image_folder is None) == (image_files is None):
raise ValueError('One of image_folder and image_files should be provided')
dataset, preproc_transform = _load_dataset(image_folder, image_files)
super().__init__(dataset, batchsize_per_replica, shuffle, transform, n... | Dataset which reads images from a local filesystem. Implements ClassyDataset. | ImagePathDataset | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePathDataset:
"""Dataset which reads images from a local filesystem. Implements ClassyDataset."""
def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, num_samples: Optional[int]=None, image_folder: Optional[str]=None, i... | stack_v2_sparse_classes_36k_train_008315 | 4,706 | permissive | [
{
"docstring": "Constructor for ImagePathDataset. Only one of image_folder or image_files should be passed to specify the images. Args: batchsize_per_replica: Positive integer indicating batch size for each replica shuffle: Whether we should shuffle between epochs transform: Transform to be applied to each samp... | 2 | stack_v2_sparse_classes_30k_train_002258 | Implement the Python class `ImagePathDataset` described below.
Class description:
Dataset which reads images from a local filesystem. Implements ClassyDataset.
Method signatures and docstrings:
- def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, ... | Implement the Python class `ImagePathDataset` described below.
Class description:
Dataset which reads images from a local filesystem. Implements ClassyDataset.
Method signatures and docstrings:
- def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, ... | 08a82e88fcfa143933832994ace2424c03dd43b8 | <|skeleton|>
class ImagePathDataset:
"""Dataset which reads images from a local filesystem. Implements ClassyDataset."""
def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, num_samples: Optional[int]=None, image_folder: Optional[str]=None, i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImagePathDataset:
"""Dataset which reads images from a local filesystem. Implements ClassyDataset."""
def __init__(self, batchsize_per_replica: int, shuffle: bool, transform: Optional[Union[ClassyTransform, Callable]]=None, num_samples: Optional[int]=None, image_folder: Optional[str]=None, image_files: O... | the_stack_v2_python_sparse | classy_vision/dataset/image_path_dataset.py | facebookresearch/ClassyVision | train | 1,673 |
90f01c7dc72e7a2462fc064b137cf49c22de6ea1 | [
"row, col = (len(matrix), len(matrix[0]))\nif matrix[row_index][col_index] == '0':\n return 0\nlength = 1\nmax_size = min(row - row_index, col - col_index)\nfor size in range(1, max_size):\n for i in range(row_index, row_index + size + 1):\n new_col = col_index + size\n if matrix[i][new_col] == ... | <|body_start_0|>
row, col = (len(matrix), len(matrix[0]))
if matrix[row_index][col_index] == '0':
return 0
length = 1
max_size = min(row - row_index, col - col_index)
for size in range(1, max_size):
for i in range(row_index, row_index + size + 1):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int:
"""获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量"""
<|body_0|>
def maximal_square(self, matrix: List[List[chr]]) -> int:
"""获取最大正方形 Args: matrix: 输入二... | stack_v2_sparse_classes_36k_train_008316 | 3,418 | permissive | [
{
"docstring": "获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量",
"name": "get_max",
"signature": "def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int"
},
{
"docstring": "获取最大正方形 Args: matrix: 输入二维数组 Returns: 最大正方形数量",
"name": "maximal_squ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int: 获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量
- def maximal_square(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int: 获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量
- def maximal_square(sel... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int:
"""获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量"""
<|body_0|>
def maximal_square(self, matrix: List[List[chr]]) -> int:
"""获取最大正方形 Args: matrix: 输入二... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int:
"""获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量"""
row, col = (len(matrix), len(matrix[0]))
if matrix[row_index][col_index] == '0':
return 0
length... | the_stack_v2_python_sparse | src/leetcodepython/array/maximal_square_221.py | zhangyu345293721/leetcode | train | 101 | |
7557e2b426cb44ab37acc747abe296de70974d86 | [
"Thread.__init__(self)\nself.predict = predict\nself.name = name\nself.faceCascade = faceCascade\nself.is_running = False",
"self.is_running = True\nimage_processor = image_processing(frame, self.faceCascade)\nimage_processor.img_prep(face)\nself.name = self.predict.predict_face(image_processor.img)\nif self.name... | <|body_start_0|>
Thread.__init__(self)
self.predict = predict
self.name = name
self.faceCascade = faceCascade
self.is_running = False
<|end_body_0|>
<|body_start_1|>
self.is_running = True
image_processor = image_processing(frame, self.faceCascade)
image_... | A class used to parallelize calculations in order to use the model in realtime Attributes ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string people name faceCascade : cv2.CascadeClassifier cascade object use to localize faces on an image is_running : b... | Name | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Name:
"""A class used to parallelize calculations in order to use the model in realtime Attributes ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string people name faceCascade : cv2.CascadeClassifier cascade object use to localize ... | stack_v2_sparse_classes_36k_train_008317 | 2,084 | no_license | [
{
"docstring": "Parameters ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string identity name faceCascade : cv2.CascadeClassifier cascade object use to localize faces on an image is_running : bool boolean variable that indicates whether the calcu... | 2 | stack_v2_sparse_classes_30k_train_003802 | Implement the Python class `Name` described below.
Class description:
A class used to parallelize calculations in order to use the model in realtime Attributes ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string people name faceCascade : cv2.CascadeCla... | Implement the Python class `Name` described below.
Class description:
A class used to parallelize calculations in order to use the model in realtime Attributes ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string people name faceCascade : cv2.CascadeCla... | d1ba87ff5b0f2b58c98f02519073b335cdc55c58 | <|skeleton|>
class Name:
"""A class used to parallelize calculations in order to use the model in realtime Attributes ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string people name faceCascade : cv2.CascadeClassifier cascade object use to localize ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Name:
"""A class used to parallelize calculations in order to use the model in realtime Attributes ---------- predict : prediction.predict prediction object use to get the identity of a people on a frame name : string people name faceCascade : cv2.CascadeClassifier cascade object use to localize faces on an i... | the_stack_v2_python_sparse | AI/face_recognition/thread_pred.py | cemot/DaVinciBot-InMoov-2020-2021 | train | 0 |
29ee016a4f20be96d35e962054f723be2bffada2 | [
"self.internreferanse_field = internreferanse_field\nself.fodt_dato_field = APIHelper.RFC3339DateTime(fodt_dato_field) if fodt_dato_field else None\nself.fodt_dato_field_specified = fodt_dato_field_specified\nself.navn_field = navn_field\nself.adresse_field = adresse_field\nself.postnr_field = postnr_field\nself.po... | <|body_start_0|>
self.internreferanse_field = internreferanse_field
self.fodt_dato_field = APIHelper.RFC3339DateTime(fodt_dato_field) if fodt_dato_field else None
self.fodt_dato_field_specified = fodt_dato_field_specified
self.navn_field = navn_field
self.adresse_field = adresse_... | Implementation of the 'Rettighetshavere' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type description here. navn_field (string): TODO: type descriptio... | Rettighetshavere | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rettighetshavere:
"""Implementation of the 'Rettighetshavere' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type description here... | stack_v2_sparse_classes_36k_train_008318 | 4,475 | permissive | [
{
"docstring": "Constructor for the Rettighetshavere class",
"name": "__init__",
"signature": "def __init__(self, internreferanse_field=None, fodt_dato_field=None, fodt_dato_field_specified=None, navn_field=None, adresse_field=None, postnr_field=None, poststed_field=None, andel_field=None, indirekte_eie... | 2 | null | Implement the Python class `Rettighetshavere` described below.
Class description:
Implementation of the 'Rettighetshavere' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specif... | Implement the Python class `Rettighetshavere` described below.
Class description:
Implementation of the 'Rettighetshavere' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specif... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Rettighetshavere:
"""Implementation of the 'Rettighetshavere' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type description here... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rettighetshavere:
"""Implementation of the 'Rettighetshavere' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type description here. navn_field ... | the_stack_v2_python_sparse | idfy_rest_client/models/rettighetshavere.py | dealflowteam/Idfy | train | 0 |
eb4c5fc86dff7c664005e51d55409b6086e660bf | [
"is_in_time_interval.return_value = (False, datetime(2019, 1, 1, 8, 0, 0))\nsend_message(None)\nretry.assert_called_once_with(eta=datetime(2019, 1, 1, 8, 0, 0))",
"is_in_time_interval.return_value = (True, datetime(2019, 1, 1, 8, 0, 0))\nsend_message(None)\nretry.assert_not_called()"
] | <|body_start_0|>
is_in_time_interval.return_value = (False, datetime(2019, 1, 1, 8, 0, 0))
send_message(None)
retry.assert_called_once_with(eta=datetime(2019, 1, 1, 8, 0, 0))
<|end_body_0|>
<|body_start_1|>
is_in_time_interval.return_value = (True, datetime(2019, 1, 1, 8, 0, 0))
... | SendMessageTests | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendMessageTests:
def test_retry_outside_of_safe_time(self, is_in_time_interval, retry):
"""If we are outside of the safe sending time, then we should retry"""
<|body_0|>
def test_no_retry_inside_of_safe_time(self, is_in_time_interval, retry):
"""If we are inside the... | stack_v2_sparse_classes_36k_train_008319 | 1,224 | permissive | [
{
"docstring": "If we are outside of the safe sending time, then we should retry",
"name": "test_retry_outside_of_safe_time",
"signature": "def test_retry_outside_of_safe_time(self, is_in_time_interval, retry)"
},
{
"docstring": "If we are inside the safe sending time, then we should send the me... | 2 | stack_v2_sparse_classes_30k_test_000213 | Implement the Python class `SendMessageTests` described below.
Class description:
Implement the SendMessageTests class.
Method signatures and docstrings:
- def test_retry_outside_of_safe_time(self, is_in_time_interval, retry): If we are outside of the safe sending time, then we should retry
- def test_no_retry_inside... | Implement the Python class `SendMessageTests` described below.
Class description:
Implement the SendMessageTests class.
Method signatures and docstrings:
- def test_retry_outside_of_safe_time(self, is_in_time_interval, retry): If we are outside of the safe sending time, then we should retry
- def test_no_retry_inside... | d90ef4dc9fa248df97ca97f07569c6c70afcd1bd | <|skeleton|>
class SendMessageTests:
def test_retry_outside_of_safe_time(self, is_in_time_interval, retry):
"""If we are outside of the safe sending time, then we should retry"""
<|body_0|>
def test_no_retry_inside_of_safe_time(self, is_in_time_interval, retry):
"""If we are inside the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendMessageTests:
def test_retry_outside_of_safe_time(self, is_in_time_interval, retry):
"""If we are outside of the safe sending time, then we should retry"""
is_in_time_interval.return_value = (False, datetime(2019, 1, 1, 8, 0, 0))
send_message(None)
retry.assert_called_once_... | the_stack_v2_python_sparse | message_sender/test_tasks.py | praekeltfoundation/seed-message-sender | train | 0 | |
e2a24c4e7c8e369d2f4267652c1940486e416620 | [
"if len(nums) == 0:\n return None\nself.sums = [0 for _ in range(len(nums))]\nself.sums[0] = nums[0]\nfor i in range(1, len(nums)):\n self.sums[i] = self.sums[i - 1] + nums[i]",
"if i > 0 and j > 0:\n return self.sums[j] - self.sums[i - 1]\nelse:\n return self.sums[j]"
] | <|body_start_0|>
if len(nums) == 0:
return None
self.sums = [0 for _ in range(len(nums))]
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
<|end_body_0|>
<|body_start_1|>
if i > 0 and j > 0:
return... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
return None
self.sum... | stack_v2_sparse_classes_36k_train_008320 | 1,117 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020474 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if len(nums) == 0:
return None
self.sums = [0 for _ in range(len(nums))]
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
def sumRa... | the_stack_v2_python_sparse | sum/range_sum_query.py | gerrycfchang/leetcode-python | train | 2 | |
1302e58baa08a2603260d5c737a9804ae140fa9a | [
"current_node = self.head\nwhile current_node is not None:\n if current_node.value[0] == key:\n return current_node.value[1]\n current_node = current_node.next_value\nreturn None",
"if self.head is not None:\n current_node = self.head\n idx = 0\n while current_node is not None:\n if c... | <|body_start_0|>
current_node = self.head
while current_node is not None:
if current_node.value[0] == key:
return current_node.value[1]
current_node = current_node.next_value
return None
<|end_body_0|>
<|body_start_1|>
if self.head is not None:
... | This class describes nodes for Hash Table | HashNodeList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashNodeList:
"""This class describes nodes for Hash Table"""
def check_node_exist(self, key):
"""This method checks node exist in Hash Table"""
<|body_0|>
def delete_node(self, key):
"""This method removes node of Hash Table by key"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_008321 | 2,293 | no_license | [
{
"docstring": "This method checks node exist in Hash Table",
"name": "check_node_exist",
"signature": "def check_node_exist(self, key)"
},
{
"docstring": "This method removes node of Hash Table by key",
"name": "delete_node",
"signature": "def delete_node(self, key)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011256 | Implement the Python class `HashNodeList` described below.
Class description:
This class describes nodes for Hash Table
Method signatures and docstrings:
- def check_node_exist(self, key): This method checks node exist in Hash Table
- def delete_node(self, key): This method removes node of Hash Table by key | Implement the Python class `HashNodeList` described below.
Class description:
This class describes nodes for Hash Table
Method signatures and docstrings:
- def check_node_exist(self, key): This method checks node exist in Hash Table
- def delete_node(self, key): This method removes node of Hash Table by key
<|skelet... | 9e9fd6583ef4f586c3b4d8cae06c23bdff89c35a | <|skeleton|>
class HashNodeList:
"""This class describes nodes for Hash Table"""
def check_node_exist(self, key):
"""This method checks node exist in Hash Table"""
<|body_0|>
def delete_node(self, key):
"""This method removes node of Hash Table by key"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HashNodeList:
"""This class describes nodes for Hash Table"""
def check_node_exist(self, key):
"""This method checks node exist in Hash Table"""
current_node = self.head
while current_node is not None:
if current_node.value[0] == key:
return current_nod... | the_stack_v2_python_sparse | data_structures/basic_data_structure/hash_table.py | Mariia-Kosorotykova/python-education | train | 0 |
3e5f1255c2276781a1a4f553bef9fa53919a388e | [
"beta = parameters['beta'].value\ngamma = parameters['gamma'].value\nsigma = parameters['sigma'].value\neta = parameters['eta'].value\nT_quarantine = parameters['T'].value\nK = parameters['K'].value\nassert len(y) == 6 * K, f'Error: SEIRCM states not organized into {K} age groups!'\ndydt = [0] * len(y)\n\ndef epsil... | <|body_start_0|>
beta = parameters['beta'].value
gamma = parameters['gamma'].value
sigma = parameters['sigma'].value
eta = parameters['eta'].value
T_quarantine = parameters['T'].value
K = parameters['K'].value
assert len(y) == 6 * K, f'Error: SEIRCM states not org... | Age-structured SEIRCM Model from https://www.medrxiv.org/content/10.1101/2020.03.04.20031104v1.full.pdf | SEIRCMAgeStratified | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEIRCMAgeStratified:
"""Age-structured SEIRCM Model from https://www.medrxiv.org/content/10.1101/2020.03.04.20031104v1.full.pdf"""
def calibrate(cls, y: list, t: float, parameters: Parameters) -> list:
"""SEIR model derivatives at t. :param y: variables that we are solving for i.e. [... | stack_v2_sparse_classes_36k_train_008322 | 29,649 | permissive | [
{
"docstring": "SEIR model derivatives at t. :param y: variables that we are solving for i.e. [S]usceptible, [E]xposed, [I]nfected, [R]emoved, [C]ases, [M]ortality :param t: time parameter :param parameters: parameters of the model (not including initial conditions) i.e. beta, gamma, sigma, eta, epsilon :return... | 2 | null | Implement the Python class `SEIRCMAgeStratified` described below.
Class description:
Age-structured SEIRCM Model from https://www.medrxiv.org/content/10.1101/2020.03.04.20031104v1.full.pdf
Method signatures and docstrings:
- def calibrate(cls, y: list, t: float, parameters: Parameters) -> list: SEIR model derivatives... | Implement the Python class `SEIRCMAgeStratified` described below.
Class description:
Age-structured SEIRCM Model from https://www.medrxiv.org/content/10.1101/2020.03.04.20031104v1.full.pdf
Method signatures and docstrings:
- def calibrate(cls, y: list, t: float, parameters: Parameters) -> list: SEIR model derivatives... | 4cf8ec75c4d85b16ec08371c46cc1a9ede9d72a2 | <|skeleton|>
class SEIRCMAgeStratified:
"""Age-structured SEIRCM Model from https://www.medrxiv.org/content/10.1101/2020.03.04.20031104v1.full.pdf"""
def calibrate(cls, y: list, t: float, parameters: Parameters) -> list:
"""SEIR model derivatives at t. :param y: variables that we are solving for i.e. [... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEIRCMAgeStratified:
"""Age-structured SEIRCM Model from https://www.medrxiv.org/content/10.1101/2020.03.04.20031104v1.full.pdf"""
def calibrate(cls, y: list, t: float, parameters: Parameters) -> list:
"""SEIR model derivatives at t. :param y: variables that we are solving for i.e. [S]usceptible,... | the_stack_v2_python_sparse | gs_quant/models/epidemiology.py | goldmansachs/gs-quant | train | 2,088 |
933c17fa7a81e3805b9e3c86a4cc5973c6159718 | [
"try:\n return json_encode(packet.get_dict())\nexcept Exception as e:\n logger.debug('can not serialize packet to text: %s' % e)\n return None",
"if 'code' not in data or not data['code']:\n raise Exception('packet data must contain non-empty \"code\" field')\nif len(data['code'].split(':')) != 2:\n ... | <|body_start_0|>
try:
return json_encode(packet.get_dict())
except Exception as e:
logger.debug('can not serialize packet to text: %s' % e)
return None
<|end_body_0|>
<|body_start_1|>
if 'code' not in data or not data['code']:
raise Exception('pac... | Класс сериализации/десериализации сообщений. | Converter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
"""Класс сериализации/десериализации сообщений."""
def serialize(cls, packet):
"""Превращает пакет в текст. @param message: dmgame.packets.outcoming.OutcomingPacket @return: string"""
<|body_0|>
def _check_packet_data(cls, data):
"""Проверяет корректно... | stack_v2_sparse_classes_36k_train_008323 | 2,353 | no_license | [
{
"docstring": "Превращает пакет в текст. @param message: dmgame.packets.outcoming.OutcomingPacket @return: string",
"name": "serialize",
"signature": "def serialize(cls, packet)"
},
{
"docstring": "Проверяет корректность данных пакета. @param data: dict",
"name": "_check_packet_data",
"... | 4 | stack_v2_sparse_classes_30k_train_002945 | Implement the Python class `Converter` described below.
Class description:
Класс сериализации/десериализации сообщений.
Method signatures and docstrings:
- def serialize(cls, packet): Превращает пакет в текст. @param message: dmgame.packets.outcoming.OutcomingPacket @return: string
- def _check_packet_data(cls, data)... | Implement the Python class `Converter` described below.
Class description:
Класс сериализации/десериализации сообщений.
Method signatures and docstrings:
- def serialize(cls, packet): Превращает пакет в текст. @param message: dmgame.packets.outcoming.OutcomingPacket @return: string
- def _check_packet_data(cls, data)... | c1d6f129ce321b9bfa448442a33ac89eb0ccd3ee | <|skeleton|>
class Converter:
"""Класс сериализации/десериализации сообщений."""
def serialize(cls, packet):
"""Превращает пакет в текст. @param message: dmgame.packets.outcoming.OutcomingPacket @return: string"""
<|body_0|>
def _check_packet_data(cls, data):
"""Проверяет корректно... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Converter:
"""Класс сериализации/десериализации сообщений."""
def serialize(cls, packet):
"""Превращает пакет в текст. @param message: dmgame.packets.outcoming.OutcomingPacket @return: string"""
try:
return json_encode(packet.get_dict())
except Exception as e:
... | the_stack_v2_python_sparse | dmgame/servers/ws/converter.py | micdm/dmgame-server | train | 0 |
4ac5f763bfd8ded430ed0e586212cbe7aeb70ce0 | [
"decorator_name = ''.join(('@', Reduction.__name__.lower()))\nself.decorator_name = decorator_name\nself.args = args\nself.kwargs = kwargs\nself.scope = CONTEXT.in_pycompss()\nself.core_element = None\nself.core_element_configured = False\nif self.scope:\n check_arguments(MANDATORY_ARGUMENTS, DEPRECATED_ARGUMENT... | <|body_start_0|>
decorator_name = ''.join(('@', Reduction.__name__.lower()))
self.decorator_name = decorator_name
self.args = args
self.kwargs = kwargs
self.scope = CONTEXT.in_pycompss()
self.core_element = None
self.core_element_configured = False
if self... | Reduction decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on Reduction task creation. | Reduction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reduction:
"""Reduction decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on Reduction task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. s... | stack_v2_sparse_classes_36k_train_008324 | 7,263 | permissive | [
{
"docstring": "Store arguments passed to the decorator. self = itself. args = not used. kwargs = dictionary with the given Reduce parameters :param args: Arguments :param kwargs: Keyword arguments",
"name": "__init__",
"signature": "def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None"
... | 4 | null | Implement the Python class `Reduction` described below.
Class description:
Reduction decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on Reduction task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: typing... | Implement the Python class `Reduction` described below.
Class description:
Reduction decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on Reduction task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: typing... | 5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092 | <|skeleton|>
class Reduction:
"""Reduction decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on Reduction task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reduction:
"""Reduction decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on Reduction task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. self = itself.... | the_stack_v2_python_sparse | compss/programming_model/bindings/python/src/pycompss/api/reduction.py | bsc-wdc/compss | train | 39 |
7eb323ed5105d95a645bbb42cf8da571db09bbac | [
"super().__init__(list_of_modules_to_winnow, reshape, in_place, verbose)\ndebug_level = logger.getEffectiveLevel()\nlogger.debug('Current log level: %s', debug_level)\nself._conn_graph = ConnectedGraph(sess.graph, input_op_names, output_op_names)\nself._modules_by_name = None\nself._mask_propagator = MaskPropagator... | <|body_start_0|>
super().__init__(list_of_modules_to_winnow, reshape, in_place, verbose)
debug_level = logger.getEffectiveLevel()
logger.debug('Current log level: %s', debug_level)
self._conn_graph = ConnectedGraph(sess.graph, input_op_names, output_op_names)
self._modules_by_nam... | The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed. | MaskPropagationWinnower | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskPropagationWinnower:
"""The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed."""
def __init__(self, sess: tf.compat.v1.Session, input_op_names: List[str], output_op_names: List[str], list... | stack_v2_sparse_classes_36k_train_008325 | 9,289 | permissive | [
{
"docstring": "MaskPropagationWinnower object initialization. :param sess: The model to be winnowed. :param input_op_names: Input operations to the model. :param output_op_names: List of output op names of the model, used to help ConnectedGraph determine valid ops (to ignore training ops for example). :param l... | 5 | null | Implement the Python class `MaskPropagationWinnower` described below.
Class description:
The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.
Method signatures and docstrings:
- def __init__(self, sess: tf.compat.v1.... | Implement the Python class `MaskPropagationWinnower` described below.
Class description:
The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.
Method signatures and docstrings:
- def __init__(self, sess: tf.compat.v1.... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class MaskPropagationWinnower:
"""The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed."""
def __init__(self, sess: tf.compat.v1.Session, input_op_names: List[str], output_op_names: List[str], list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskPropagationWinnower:
"""The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed."""
def __init__(self, sess: tf.compat.v1.Session, input_op_names: List[str], output_op_names: List[str], list_of_modules_t... | the_stack_v2_python_sparse | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/winnow/mask_propagation_winnower.py | quic/aimet | train | 1,676 |
2535decd5c6f5ff9e24e08b2da00da8d1d2ddd97 | [
"self.__neighbours = NearestNeighbors(n_neighbors=1)\nself.__neighbours.fit(mapping.colours)\nself.minerals = list(mapping.minerals)\nself.fields = fields or {}",
"data = image.convert('RGB').tobytes()\narray = np.frombuffer(data, dtype=np.uint8).reshape(-1, 3)\ndistances, indices = self.__neighbours.kneighbors(a... | <|body_start_0|>
self.__neighbours = NearestNeighbors(n_neighbors=1)
self.__neighbours.fit(mapping.colours)
self.minerals = list(mapping.minerals)
self.fields = fields or {}
<|end_body_0|>
<|body_start_1|>
data = image.convert('RGB').tobytes()
array = np.frombuffer(data,... | The ImageDataExtractor class combines tools to extract data from images via transformations | ImageDataExtractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageDataExtractor:
"""The ImageDataExtractor class combines tools to extract data from images via transformations"""
def __init__(self, mapping: ColourMapping, fields: Optional[Dict[str, Field]]=None):
"""Construct the extractor using a colour mapping appropriate to the images to be... | stack_v2_sparse_classes_36k_train_008326 | 3,069 | permissive | [
{
"docstring": "Construct the extractor using a colour mapping appropriate to the images to be supplied. The mapping should assign a mineral name to each colour in the image. Parameters ---------- mapping : A mapping between minerals and colours",
"name": "__init__",
"signature": "def __init__(self, map... | 3 | stack_v2_sparse_classes_30k_train_008655 | Implement the Python class `ImageDataExtractor` described below.
Class description:
The ImageDataExtractor class combines tools to extract data from images via transformations
Method signatures and docstrings:
- def __init__(self, mapping: ColourMapping, fields: Optional[Dict[str, Field]]=None): Construct the extract... | Implement the Python class `ImageDataExtractor` described below.
Class description:
The ImageDataExtractor class combines tools to extract data from images via transformations
Method signatures and docstrings:
- def __init__(self, mapping: ColourMapping, fields: Optional[Dict[str, Field]]=None): Construct the extract... | 7343e352cecfabb0e19c0ce97d02cd7d9ddf0631 | <|skeleton|>
class ImageDataExtractor:
"""The ImageDataExtractor class combines tools to extract data from images via transformations"""
def __init__(self, mapping: ColourMapping, fields: Optional[Dict[str, Field]]=None):
"""Construct the extractor using a colour mapping appropriate to the images to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageDataExtractor:
"""The ImageDataExtractor class combines tools to extract data from images via transformations"""
def __init__(self, mapping: ColourMapping, fields: Optional[Dict[str, Field]]=None):
"""Construct the extractor using a colour mapping appropriate to the images to be supplied. Th... | the_stack_v2_python_sparse | steinbit/core/imagedataextractor.py | rocktype/steinbit | train | 0 |
73d5a2f05e89ae64a530c141d9d9ec3c4a6eefe0 | [
"self.filename = filename\nself.bias_polarisation = bias_polarisation\nwith open(self.filename, 'rb') as input:\n self.exec_path, self.tmax, self.nc, self.nRuns, self.initSim, self.sValues, self.seed, self.seeds, self.N, self.lp, self.phi, self._tau, self.dt, self.tSCGF, self.activeWork, self.activeWorkForce, se... | <|body_start_0|>
self.filename = filename
self.bias_polarisation = bias_polarisation
with open(self.filename, 'rb') as input:
self.exec_path, self.tmax, self.nc, self.nRuns, self.initSim, self.sValues, self.seed, self.seeds, self.N, self.lp, self.phi, self._tau, self.dt, self.tSCGF, ... | Read and analyse aggregated data from cloning simulations launched with active_work.cloning. | CloningOutput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloningOutput:
"""Read and analyse aggregated data from cloning simulations launched with active_work.cloning."""
def __init__(self, filename, bias_polarisation=False):
"""Get data. Parameters ---------- filename : string Path to data file. bias_polarisation : bool Cloning data corre... | stack_v2_sparse_classes_36k_train_008327 | 26,002 | permissive | [
{
"docstring": "Get data. Parameters ---------- filename : string Path to data file. bias_polarisation : bool Cloning data corresponds to simulation biased with respect to the polarisation. (default: False)",
"name": "__init__",
"signature": "def __init__(self, filename, bias_polarisation=False)"
},
... | 2 | stack_v2_sparse_classes_30k_train_006348 | Implement the Python class `CloningOutput` described below.
Class description:
Read and analyse aggregated data from cloning simulations launched with active_work.cloning.
Method signatures and docstrings:
- def __init__(self, filename, bias_polarisation=False): Get data. Parameters ---------- filename : string Path ... | Implement the Python class `CloningOutput` described below.
Class description:
Read and analyse aggregated data from cloning simulations launched with active_work.cloning.
Method signatures and docstrings:
- def __init__(self, filename, bias_polarisation=False): Get data. Parameters ---------- filename : string Path ... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class CloningOutput:
"""Read and analyse aggregated data from cloning simulations launched with active_work.cloning."""
def __init__(self, filename, bias_polarisation=False):
"""Get data. Parameters ---------- filename : string Path to data file. bias_polarisation : bool Cloning data corre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloningOutput:
"""Read and analyse aggregated data from cloning simulations launched with active_work.cloning."""
def __init__(self, filename, bias_polarisation=False):
"""Get data. Parameters ---------- filename : string Path to data file. bias_polarisation : bool Cloning data corresponds to sim... | the_stack_v2_python_sparse | cloning.py | yketa/active_work | train | 1 |
ab25c9316ecac532f9d7e71bf23c412ca504a29d | [
"self.__screen = screen\nself.__msg = TextboxReflowed(40, 'The system configuration is completed. Exit from the configuration tool and log into the system.')\nself.__buttonsBar = ButtonBar(self.__screen, [('Exit', 'exit')])\nself.__grid = GridForm(self.__screen, 'IBM zKVM', 1, 2)\nself.__grid.add(self.__msg, 0, 0)\... | <|body_start_0|>
self.__screen = screen
self.__msg = TextboxReflowed(40, 'The system configuration is completed. Exit from the configuration tool and log into the system.')
self.__buttonsBar = ButtonBar(self.__screen, [('Exit', 'exit')])
self.__grid = GridForm(self.__screen, 'IBM zKVM', ... | Last screen for the configuration application | ConfigCompleted | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigCompleted:
"""Last screen for the configuration application"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def run(self):
"""Draws the screen @rtype: integer @returns: sucess status"... | stack_v2_sparse_classes_36k_train_008328 | 996 | no_license | [
{
"docstring": "Constructor @type screen: SnackScreen @param screen: SnackScreen instance",
"name": "__init__",
"signature": "def __init__(self, screen)"
},
{
"docstring": "Draws the screen @rtype: integer @returns: sucess status",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019666 | Implement the Python class `ConfigCompleted` described below.
Class description:
Last screen for the configuration application
Method signatures and docstrings:
- def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def run(self): Draws the screen @rtype: integer @re... | Implement the Python class `ConfigCompleted` described below.
Class description:
Last screen for the configuration application
Method signatures and docstrings:
- def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def run(self): Draws the screen @rtype: integer @re... | 1c738fd5e6ee3f8fd4f47acf2207038f20868212 | <|skeleton|>
class ConfigCompleted:
"""Last screen for the configuration application"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def run(self):
"""Draws the screen @rtype: integer @returns: sucess status"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigCompleted:
"""Last screen for the configuration application"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
self.__screen = screen
self.__msg = TextboxReflowed(40, 'The system configuration is completed. Exit fro... | the_stack_v2_python_sparse | zfrobisher-installer/src/ui/systemconfig/configcompleted.py | fedosu85nce/work | train | 2 |
ca53850649ed3c3cbf06f49f91cc804519fdbf37 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"Label(self, text='Choose your favorite movie types').grid(row=0, column=0, sticky=W)\nLabel(self, text='Select all that apply').grid(row=1, column=0, sticky=W)\nself.favorite = StringVar()\nself.favorite.set(None)\nRadiobutton(self,... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
Label(self, text='Choose your favorite movie types').grid(row=0, column=0, sticky=W)
Label(self, text='Select all that apply').grid(row=1, column=0, stick... | GUI Application for favorite movie types. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI Application for favorite movie types."""
def __init__(self, master):
"""Initialiaze the frame."""
<|body_0|>
def create_widgets(self):
"""Create widgets for movie type choices"""
<|body_1|>
def update_text(self):
"""Update... | stack_v2_sparse_classes_36k_train_008329 | 2,164 | no_license | [
{
"docstring": "Initialiaze the frame.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create widgets for movie type choices",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "Update the text area and dispaly ... | 3 | stack_v2_sparse_classes_30k_train_019548 | Implement the Python class `Application` described below.
Class description:
GUI Application for favorite movie types.
Method signatures and docstrings:
- def __init__(self, master): Initialiaze the frame.
- def create_widgets(self): Create widgets for movie type choices
- def update_text(self): Update the text area ... | Implement the Python class `Application` described below.
Class description:
GUI Application for favorite movie types.
Method signatures and docstrings:
- def __init__(self, master): Initialiaze the frame.
- def create_widgets(self): Create widgets for movie type choices
- def update_text(self): Update the text area ... | 2e96474567d31988944a865aad35dc8ae63a990a | <|skeleton|>
class Application:
"""GUI Application for favorite movie types."""
def __init__(self, master):
"""Initialiaze the frame."""
<|body_0|>
def create_widgets(self):
"""Create widgets for movie type choices"""
<|body_1|>
def update_text(self):
"""Update... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""GUI Application for favorite movie types."""
def __init__(self, master):
"""Initialiaze the frame."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create widgets for movie type choices... | the_stack_v2_python_sparse | Chapter 10/movie_chooser2.py | dguzman96/Python-Practice | train | 0 |
af788f1b33b24a6c2c3e80cb974c69b73c94106a | [
"try:\n login_options = OrgService.get_login_options_for_org(org_id, allowed_roles=ALL_ALLOWED_ROLES)\n response, status = (jsonify({'loginOption': login_options.login_source if login_options else None}), http_status.HTTP_200_OK)\nexcept BusinessException as exception:\n response, status = ({'code': except... | <|body_start_0|>
try:
login_options = OrgService.get_login_options_for_org(org_id, allowed_roles=ALL_ALLOWED_ROLES)
response, status = (jsonify({'loginOption': login_options.login_source if login_options else None}), http_status.HTTP_200_OK)
except BusinessException as exception:... | Resource for managing org login options. | OrgLoginOptions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrgLoginOptions:
"""Resource for managing org login options."""
def get(org_id):
"""Retrieve the set of payment settings associated with the specified org."""
<|body_0|>
def post(org_id):
"""Create a new login type for the specified org."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_008330 | 30,185 | permissive | [
{
"docstring": "Retrieve the set of payment settings associated with the specified org.",
"name": "get",
"signature": "def get(org_id)"
},
{
"docstring": "Create a new login type for the specified org.",
"name": "post",
"signature": "def post(org_id)"
},
{
"docstring": "Update a ... | 3 | stack_v2_sparse_classes_30k_train_012711 | Implement the Python class `OrgLoginOptions` described below.
Class description:
Resource for managing org login options.
Method signatures and docstrings:
- def get(org_id): Retrieve the set of payment settings associated with the specified org.
- def post(org_id): Create a new login type for the specified org.
- de... | Implement the Python class `OrgLoginOptions` described below.
Class description:
Resource for managing org login options.
Method signatures and docstrings:
- def get(org_id): Retrieve the set of payment settings associated with the specified org.
- def post(org_id): Create a new login type for the specified org.
- de... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class OrgLoginOptions:
"""Resource for managing org login options."""
def get(org_id):
"""Retrieve the set of payment settings associated with the specified org."""
<|body_0|>
def post(org_id):
"""Create a new login type for the specified org."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrgLoginOptions:
"""Resource for managing org login options."""
def get(org_id):
"""Retrieve the set of payment settings associated with the specified org."""
try:
login_options = OrgService.get_login_options_for_org(org_id, allowed_roles=ALL_ALLOWED_ROLES)
respons... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org.py | bcgov/sbc-auth | train | 13 |
53fc07946786b13849ac4b77ff5a580876c24102 | [
"self.request = requests.Session()\nself.headers = dict()\nif user_agent is None:\n self.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'\nelse:\n self.headers['User-Agent'] = user_agent\nself.query_string_param... | <|body_start_0|>
self.request = requests.Session()
self.headers = dict()
if user_agent is None:
self.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
else:
self.head... | Stock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stock:
def __init__(self, user_agent: str=None):
"""请求参数初始化 :type user_agent: str :param:浏览器"""
<|body_0|>
def get_real_time_a_stock(self, page: int, block: int=2, number: int=50) -> list:
"""获取泸深A股实时数据 :rtype: iterable[dict] :param page: 第几页,范围为1-43 :param block: 请求... | stack_v2_sparse_classes_36k_train_008331 | 5,700 | no_license | [
{
"docstring": "请求参数初始化 :type user_agent: str :param:浏览器",
"name": "__init__",
"signature": "def __init__(self, user_agent: str=None)"
},
{
"docstring": "获取泸深A股实时数据 :rtype: iterable[dict] :param page: 第几页,范围为1-43 :param block: 请求类型,默认2,暂且支持2 :param number: 一次请求返回多少条数据,建议默认值50 :return:iterable[{\... | 3 | stack_v2_sparse_classes_30k_train_003995 | Implement the Python class `Stock` described below.
Class description:
Implement the Stock class.
Method signatures and docstrings:
- def __init__(self, user_agent: str=None): 请求参数初始化 :type user_agent: str :param:浏览器
- def get_real_time_a_stock(self, page: int, block: int=2, number: int=50) -> list: 获取泸深A股实时数据 :rtype... | Implement the Python class `Stock` described below.
Class description:
Implement the Stock class.
Method signatures and docstrings:
- def __init__(self, user_agent: str=None): 请求参数初始化 :type user_agent: str :param:浏览器
- def get_real_time_a_stock(self, page: int, block: int=2, number: int=50) -> list: 获取泸深A股实时数据 :rtype... | 5e34873cd13950dd3b5dc6341aad144522af0eae | <|skeleton|>
class Stock:
def __init__(self, user_agent: str=None):
"""请求参数初始化 :type user_agent: str :param:浏览器"""
<|body_0|>
def get_real_time_a_stock(self, page: int, block: int=2, number: int=50) -> list:
"""获取泸深A股实时数据 :rtype: iterable[dict] :param page: 第几页,范围为1-43 :param block: 请求... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stock:
def __init__(self, user_agent: str=None):
"""请求参数初始化 :type user_agent: str :param:浏览器"""
self.request = requests.Session()
self.headers = dict()
if user_agent is None:
self.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/5... | the_stack_v2_python_sparse | spyderpro/data_requests/financialmodel/stockmarket.py | LianZS/spyderpro | train | 8 | |
c6f53d340217b112e5658222d402cac5ca3b1a8d | [
"get_user = request.user\ndata = get_profile_data(get_user)\nresponse_data = success_response(data=data)\nreturn Response(response_data, status=response_data['code'])",
"serializer_data = self.serializer_class(request.user, data=request.data)\nif serializer_data.is_valid():\n user_obj = serializer_data.save()\... | <|body_start_0|>
get_user = request.user
data = get_profile_data(get_user)
response_data = success_response(data=data)
return Response(response_data, status=response_data['code'])
<|end_body_0|>
<|body_start_1|>
serializer_data = self.serializer_class(request.user, data=request.... | UserProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileView:
def get(self, request):
"""for Retrieve profile data"""
<|body_0|>
def post(self, request):
"""for Update profile data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
get_user = request.user
data = get_profile_data(get_user)... | stack_v2_sparse_classes_36k_train_008332 | 12,263 | no_license | [
{
"docstring": "for Retrieve profile data",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "for Update profile data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014306 | Implement the Python class `UserProfileView` described below.
Class description:
Implement the UserProfileView class.
Method signatures and docstrings:
- def get(self, request): for Retrieve profile data
- def post(self, request): for Update profile data | Implement the Python class `UserProfileView` described below.
Class description:
Implement the UserProfileView class.
Method signatures and docstrings:
- def get(self, request): for Retrieve profile data
- def post(self, request): for Update profile data
<|skeleton|>
class UserProfileView:
def get(self, request... | 41b019e11e2106f57875fc00f85ea6b49d535d86 | <|skeleton|>
class UserProfileView:
def get(self, request):
"""for Retrieve profile data"""
<|body_0|>
def post(self, request):
"""for Update profile data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileView:
def get(self, request):
"""for Retrieve profile data"""
get_user = request.user
data = get_profile_data(get_user)
response_data = success_response(data=data)
return Response(response_data, status=response_data['code'])
def post(self, request):
... | the_stack_v2_python_sparse | auth/views.py | SimranSingh11/new-fisher-python | train | 0 | |
f4729bcec08c3bf70a8b3093e70d4b0dc76e2b04 | [
"cumsum = [0]\nfor i in range(len(nums)):\n if i == 0:\n cumsum.append(nums[i])\n else:\n cumsum.append(nums[i] + cumsum[-1])\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n s = cumsum[j + 1] - cumsum[i]\n if k == 0:\n if s == 0:\n ret... | <|body_start_0|>
cumsum = [0]
for i in range(len(nums)):
if i == 0:
cumsum.append(nums[i])
else:
cumsum.append(nums[i] + cumsum[-1])
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
s = cumsum[j + 1] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""05/31/2020 17:30"""
<|body_0|>
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""05/31/2020 17:39"""
<|body_1|>
def checkSubarraySum(self, nums: List[int], k: int) ->... | stack_v2_sparse_classes_36k_train_008333 | 3,007 | no_license | [
{
"docstring": "05/31/2020 17:30",
"name": "checkSubarraySum",
"signature": "def checkSubarraySum(self, nums: List[int], k: int) -> bool"
},
{
"docstring": "05/31/2020 17:39",
"name": "checkSubarraySum",
"signature": "def checkSubarraySum(self, nums: List[int], k: int) -> bool"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkSubarraySum(self, nums: List[int], k: int) -> bool: 05/31/2020 17:30
- def checkSubarraySum(self, nums: List[int], k: int) -> bool: 05/31/2020 17:39
- def checkSubarrayS... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkSubarraySum(self, nums: List[int], k: int) -> bool: 05/31/2020 17:30
- def checkSubarraySum(self, nums: List[int], k: int) -> bool: 05/31/2020 17:39
- def checkSubarrayS... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""05/31/2020 17:30"""
<|body_0|>
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""05/31/2020 17:39"""
<|body_1|>
def checkSubarraySum(self, nums: List[int], k: int) ->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
"""05/31/2020 17:30"""
cumsum = [0]
for i in range(len(nums)):
if i == 0:
cumsum.append(nums[i])
else:
cumsum.append(nums[i] + cumsum[-1])
for i in ran... | the_stack_v2_python_sparse | leetcode/solved/523_Continuous_Subarray_Sum/solution.py | sungminoh/algorithms | train | 0 | |
bea7481e77508a599f97dd9d8adb87ef46071178 | [
"self.cap = capacity\nself.lookup = {}\nself.tail = None\nself.head = None\nself.counter = 0",
"if self.lookup.get(key):\n node = self.lookup[key]\n prev_node = node.prev\n next_node = node.next\n if prev_node:\n prev_node.next = next_node\n else:\n self.head = next_node\n self.tai... | <|body_start_0|>
self.cap = capacity
self.lookup = {}
self.tail = None
self.head = None
self.counter = 0
<|end_body_0|>
<|body_start_1|>
if self.lookup.get(key):
node = self.lookup[key]
prev_node = node.prev
next_node = node.next
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_008334 | 2,374 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 5fed58c0cbbaf7dfa6b27282e4914b691f9e0759 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.lookup = {}
self.tail = None
self.head = None
self.counter = 0
def get(self, key):
""":type key: int :rtype: int"""
if self.lookup.get(key):
... | the_stack_v2_python_sparse | design/146_lru.py | misa5555/py | train | 0 | |
9b5064a672d0fe14038bbd1040b23d0c2811e769 | [
"self.size = 10\nself.times = [0 for _ in range(self.size)]\nself.d = collections.defaultdict(set)",
"t = timestamp % self.size\nif timestamp != self.times[t]:\n self.d[t] = set()\n self.times[t] = timestamp\nfor i in range(self.size):\n if self.times[i] + 10 > timestamp and message in self.d[i]:\n ... | <|body_start_0|>
self.size = 10
self.times = [0 for _ in range(self.size)]
self.d = collections.defaultdict(set)
<|end_body_0|>
<|body_start_1|>
t = timestamp % self.size
if timestamp != self.times[t]:
self.d[t] = set()
self.times[t] = timestamp
f... | Logger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method retu... | stack_v2_sparse_classes_36k_train_008335 | 2,846 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timest... | 2 | null | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp: int, message: str) -> bool: Returns true if the message should be printed in the gi... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp: int, message: str) -> bool: Returns true if the message should be printed in the gi... | 4c1288c99f78823c7c3bac0ceedd532e64af1258 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logger:
def __init__(self):
"""Initialize your data structure here."""
self.size = 10
self.times = [0 for _ in range(self.size)]
self.d = collections.defaultdict(set)
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message... | the_stack_v2_python_sparse | Algorithms/0359 Logger Rate Limiter.py | cravo123/LeetCode | train | 6 | |
4170dd059797402dbda541b33d7d8be187e3ee41 | [
"self.data_struct = defaultdict()\nself.counter_struct = defaultdict(set)\nself.max_count = 0\nself.min_count = 0",
"old_count = 0\nif self.data_struct.get(key):\n old_count = self.data_struct[key]\n new_count = old_count + 1\n self.counter_struct[old_count] -= {key}\n self.data_struct[key] += 1\nelse... | <|body_start_0|>
self.data_struct = defaultdict()
self.counter_struct = defaultdict(set)
self.max_count = 0
self.min_count = 0
<|end_body_0|>
<|body_start_1|>
old_count = 0
if self.data_struct.get(key):
old_count = self.data_struct[key]
new_count ... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""De... | stack_v2_sparse_classes_36k_train_008336 | 3,617 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void",
"name": "inc",
"signature": "def inc(self, key)"
},
... | 5 | stack_v2_sparse_classes_30k_train_008868 | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void
-... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void
-... | 009484a2bb80fed61970558a72670d66d9b71b6b | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""De... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.data_struct = defaultdict()
self.counter_struct = defaultdict(set)
self.max_count = 0
self.min_count = 0
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments a... | the_stack_v2_python_sparse | design_O_1_.py | at3103/Leetcode | train | 0 | |
c5005fe514407501cdd06f3d98b7a81109e975e0 | [
"super(ScaledDotProductAttention, self).__init__()\nself.scaling = 1 / sqrt(size)\nself.dropout = nn.Dropout(p)",
"batch_size, query_len, _ = q.size()\nattention = t.bmm(q, k.transpose(1, 2)) * self.scaling\n'\\n In order to prevent contribution of padding symbols in attention lockup, \\n it is nece... | <|body_start_0|>
super(ScaledDotProductAttention, self).__init__()
self.scaling = 1 / sqrt(size)
self.dropout = nn.Dropout(p)
<|end_body_0|>
<|body_start_1|>
batch_size, query_len, _ = q.size()
attention = t.bmm(q, k.transpose(1, 2)) * self.scaling
'\n In order to... | ScaledDotProductAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaledDotProductAttention:
def __init__(self, size, p=0.1):
""":param size: float number that is necessary for estimation scaling factor :param m_size: int number of size of the window that performing local-m attention. None corresponds to global attention mechanism :param p: drop prob""... | stack_v2_sparse_classes_36k_train_008337 | 1,623 | permissive | [
{
"docstring": ":param size: float number that is necessary for estimation scaling factor :param m_size: int number of size of the window that performing local-m attention. None corresponds to global attention mechanism :param p: drop prob",
"name": "__init__",
"signature": "def __init__(self, size, p=0... | 2 | stack_v2_sparse_classes_30k_train_007271 | Implement the Python class `ScaledDotProductAttention` described below.
Class description:
Implement the ScaledDotProductAttention class.
Method signatures and docstrings:
- def __init__(self, size, p=0.1): :param size: float number that is necessary for estimation scaling factor :param m_size: int number of size of ... | Implement the Python class `ScaledDotProductAttention` described below.
Class description:
Implement the ScaledDotProductAttention class.
Method signatures and docstrings:
- def __init__(self, size, p=0.1): :param size: float number that is necessary for estimation scaling factor :param m_size: int number of size of ... | 6dcca5743ea8750a740c569181ec6998352ef784 | <|skeleton|>
class ScaledDotProductAttention:
def __init__(self, size, p=0.1):
""":param size: float number that is necessary for estimation scaling factor :param m_size: int number of size of the window that performing local-m attention. None corresponds to global attention mechanism :param p: drop prob""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScaledDotProductAttention:
def __init__(self, size, p=0.1):
""":param size: float number that is necessary for estimation scaling factor :param m_size: int number of size of the window that performing local-m attention. None corresponds to global attention mechanism :param p: drop prob"""
supe... | the_stack_v2_python_sparse | nn/attention/scaled_dot_product.py | kefirski/amt | train | 28 | |
268d2ebcc2d4b134ad720e109c366fe9adac7eea | [
"self.ControlDAO = UserDao(controldatabase_name, controldatabase_address)\nself.SISAControlCollectionName = 'Control'\nself.SISAControlLastDateString = 'lastDate'\nself.SISAInformationCollectionName = 'Info'\ndefault_initial_date = '2015-01-01 12:00:00'\nself.numberOfItemsToBatchProcess = 50\nself.SensingDAO = Sens... | <|body_start_0|>
self.ControlDAO = UserDao(controldatabase_name, controldatabase_address)
self.SISAControlCollectionName = 'Control'
self.SISAControlLastDateString = 'lastDate'
self.SISAInformationCollectionName = 'Info'
default_initial_date = '2015-01-01 12:00:00'
self.n... | DataBaseExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataBaseExtractor:
def __init__(self, queue, controldatabase_name, controldatabase_address, SensingDAO):
"""Queue used for working thread send data collected form DB to processing method This class fetches data from sensing database and put on a queue for analysis processing plugin This ... | stack_v2_sparse_classes_36k_train_008338 | 6,753 | permissive | [
{
"docstring": "Queue used for working thread send data collected form DB to processing method This class fetches data from sensing database and put on a queue for analysis processing plugin This class mantains a control database to identify the sensig data already processed/analysed This class starts a thread ... | 2 | stack_v2_sparse_classes_30k_train_020950 | Implement the Python class `DataBaseExtractor` described below.
Class description:
Implement the DataBaseExtractor class.
Method signatures and docstrings:
- def __init__(self, queue, controldatabase_name, controldatabase_address, SensingDAO): Queue used for working thread send data collected form DB to processing me... | Implement the Python class `DataBaseExtractor` described below.
Class description:
Implement the DataBaseExtractor class.
Method signatures and docstrings:
- def __init__(self, queue, controldatabase_name, controldatabase_address, SensingDAO): Queue used for working thread send data collected form DB to processing me... | a2d71916b0f1bd79d0f5b444865279530eb6b836 | <|skeleton|>
class DataBaseExtractor:
def __init__(self, queue, controldatabase_name, controldatabase_address, SensingDAO):
"""Queue used for working thread send data collected form DB to processing method This class fetches data from sensing database and put on a queue for analysis processing plugin This ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataBaseExtractor:
def __init__(self, queue, controldatabase_name, controldatabase_address, SensingDAO):
"""Queue used for working thread send data collected form DB to processing method This class fetches data from sensing database and put on a queue for analysis processing plugin This class mantains... | the_stack_v2_python_sparse | sisa/src/informationanalysis/databaseprocessing.py | dmazzer/CogRIoT | train | 1 | |
fee352831935669d24c68eafbc5df41218c493d3 | [
"self.file_path = file_path\nself.current_row = 0\nself.workbook = ''\nself.sheet = ''\nself.load_workbook()",
"if os.path.exists(self.file_path):\n temp_workbook = xlrd.open_workbook(self.file_path)\n self.workbook = copy(temp_workbook)\nelse:\n self.workbook = xlwt.Workbook(encoding='utf-8')",
"try:\... | <|body_start_0|>
self.file_path = file_path
self.current_row = 0
self.workbook = ''
self.sheet = ''
self.load_workbook()
<|end_body_0|>
<|body_start_1|>
if os.path.exists(self.file_path):
temp_workbook = xlrd.open_workbook(self.file_path)
self.wor... | It is for printer discovery tests | Excel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Excel:
"""It is for printer discovery tests"""
def __init__(self, file_path):
"""Initialize workbook instance with sheet instance :param file_path: path of Excel file"""
<|body_0|>
def load_workbook(self):
"""Load a workbook :return:"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_008339 | 4,409 | no_license | [
{
"docstring": "Initialize workbook instance with sheet instance :param file_path: path of Excel file",
"name": "__init__",
"signature": "def __init__(self, file_path)"
},
{
"docstring": "Load a workbook :return:",
"name": "load_workbook",
"signature": "def load_workbook(self)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_011846 | Implement the Python class `Excel` described below.
Class description:
It is for printer discovery tests
Method signatures and docstrings:
- def __init__(self, file_path): Initialize workbook instance with sheet instance :param file_path: path of Excel file
- def load_workbook(self): Load a workbook :return:
- def lo... | Implement the Python class `Excel` described below.
Class description:
It is for printer discovery tests
Method signatures and docstrings:
- def __init__(self, file_path): Initialize workbook instance with sheet instance :param file_path: path of Excel file
- def load_workbook(self): Load a workbook :return:
- def lo... | b5230c51d3bc7bb04b3448d1a1fe5a076d8898d5 | <|skeleton|>
class Excel:
"""It is for printer discovery tests"""
def __init__(self, file_path):
"""Initialize workbook instance with sheet instance :param file_path: path of Excel file"""
<|body_0|>
def load_workbook(self):
"""Load a workbook :return:"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Excel:
"""It is for printer discovery tests"""
def __init__(self, file_path):
"""Initialize workbook instance with sheet instance :param file_path: path of Excel file"""
self.file_path = file_path
self.current_row = 0
self.workbook = ''
self.sheet = ''
self... | the_stack_v2_python_sparse | MobileApps/libs/ma_misc/excel.py | Amal548/QAMA | train | 0 |
cf5ef9679cd1ec863b2ee1a29df0912ac42c1207 | [
"if new_server_name:\n srv_dyn.stop()\n srv_dyn = self.get_server(new_server_name)\n srv_dyn.start()\nclient = self.get_client('client')\nif isinstance(client, Wrk):\n client.duration = self.min_duration\nelse:\n client.options[0] += f' --duration {self.min_duration}'\nclient.start()\nself.wait_while... | <|body_start_0|>
if new_server_name:
srv_dyn.stop()
srv_dyn = self.get_server(new_server_name)
srv_dyn.start()
client = self.get_client('client')
if isinstance(client, Wrk):
client.duration = self.min_duration
else:
client.optio... | Check that server weight is re-calculated based on it's performance. | RatioDynamic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatioDynamic:
"""Check that server weight is re-calculated based on it's performance."""
def run_test(self, srv_const, srv_dyn, new_server_name=None):
"""Run wrk and get performance statistics from backends and Tempesta. If 'new_server_name' of 'srv_dyn' is set, first reload its conf... | stack_v2_sparse_classes_36k_train_008340 | 8,514 | no_license | [
{
"docstring": "Run wrk and get performance statistics from backends and Tempesta. If 'new_server_name' of 'srv_dyn' is set, first reload its configuration.",
"name": "run_test",
"signature": "def run_test(self, srv_const, srv_dyn, new_server_name=None)"
},
{
"docstring": "Calculate weights of s... | 3 | stack_v2_sparse_classes_30k_test_000817 | Implement the Python class `RatioDynamic` described below.
Class description:
Check that server weight is re-calculated based on it's performance.
Method signatures and docstrings:
- def run_test(self, srv_const, srv_dyn, new_server_name=None): Run wrk and get performance statistics from backends and Tempesta. If 'ne... | Implement the Python class `RatioDynamic` described below.
Class description:
Check that server weight is re-calculated based on it's performance.
Method signatures and docstrings:
- def run_test(self, srv_const, srv_dyn, new_server_name=None): Run wrk and get performance statistics from backends and Tempesta. If 'ne... | d56358ea653dbb367624937197ce5e489abf0b00 | <|skeleton|>
class RatioDynamic:
"""Check that server weight is re-calculated based on it's performance."""
def run_test(self, srv_const, srv_dyn, new_server_name=None):
"""Run wrk and get performance statistics from backends and Tempesta. If 'new_server_name' of 'srv_dyn' is set, first reload its conf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RatioDynamic:
"""Check that server weight is re-calculated based on it's performance."""
def run_test(self, srv_const, srv_dyn, new_server_name=None):
"""Run wrk and get performance statistics from backends and Tempesta. If 'new_server_name' of 'srv_dyn' is set, first reload its configuration."""... | the_stack_v2_python_sparse | t_sched/test_ratio_dynamic_recalc.py | tempesta-tech/tempesta-test | train | 13 |
0293f65a4aaa91f7b3cf7565b473eb955d2eec61 | [
"self.capacity = capacity\nself.cache = {}\nself.recent = 0",
"if key in self.cache:\n self.recent += 1\n self.cache[key][1] = self.recent\n return self.cache[key][0]\nelse:\n return -1",
"if key in self.cache:\n self.cache[key][0] = value\nelse:\n if len(self.cache) == self.capacity:\n ... | <|body_start_0|>
self.capacity = capacity
self.cache = {}
self.recent = 0
<|end_body_0|>
<|body_start_1|>
if key in self.cache:
self.recent += 1
self.cache[key][1] = self.recent
return self.cache[key][0]
else:
return -1
<|end_body_... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_008341 | 3,359 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | aac41ddd2ec5f6e5c0f46659696ed5b67769bde2 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.cache = {}
self.recent = 0
def get(self, key):
""":type key: int :rtype: int"""
if key in self.cache:
self.recent += 1
self.cache[key][1]... | the_stack_v2_python_sparse | lru_cache.py | aroraakshit/coding_prep | train | 8 | |
0f146d3e5232a742fadb963e253b3a9e1772d28b | [
"if root is None:\n return 0\nres = 0\nif root.val == sum:\n res += 1\nres += self.containNode(root.left, sum - root.val)\nres += self.containNode(root.right, sum - root.val)\nreturn res",
"if root is None:\n return 0\nres = self.containNode(root, sum)\nres += self.pathSum(root.left, sum)\nres += self.pa... | <|body_start_0|>
if root is None:
return 0
res = 0
if root.val == sum:
res += 1
res += self.containNode(root.left, sum - root.val)
res += self.containNode(root.right, sum - root.val)
return res
<|end_body_0|>
<|body_start_1|>
if root is No... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containNode(self, root, sum):
"""calcuate how many path is valid from root, that sums up to the given value"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_008342 | 1,068 | no_license | [
{
"docstring": "calcuate how many path is valid from root, that sums up to the given value",
"name": "containNode",
"signature": "def containNode(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: int",
"name": "pathSum",
"signature": "def pathSum(self, root... | 2 | stack_v2_sparse_classes_30k_train_017199 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containNode(self, root, sum): calcuate how many path is valid from root, that sums up to the given value
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containNode(self, root, sum): calcuate how many path is valid from root, that sums up to the given value
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :... | f8b35179b980e55f61bbcd2631fa3a9bf30c40ec | <|skeleton|>
class Solution:
def containNode(self, root, sum):
"""calcuate how many path is valid from root, that sums up to the given value"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containNode(self, root, sum):
"""calcuate how many path is valid from root, that sums up to the given value"""
if root is None:
return 0
res = 0
if root.val == sum:
res += 1
res += self.containNode(root.left, sum - root.val)
... | the_stack_v2_python_sparse | Python Solutions/437 Path Sum III.py | Sue9/Leetcode | train | 0 | |
700bd9de354e9003dd116be0ed618626b1a1e6ab | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.incomingCallOptions'.casefold():\n from ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | CallOptions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallOptions:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions:
"""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: Ca... | stack_v2_sparse_classes_36k_train_008343 | 3,943 | 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: CallOptions",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | null | Implement the Python class `CallOptions` described below.
Class description:
Implement the CallOptions class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `CallOptions` described below.
Class description:
Implement the CallOptions class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CallOptions:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions:
"""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: Ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallOptions:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallOptions:
"""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: CallOptions"""
... | the_stack_v2_python_sparse | msgraph/generated/models/call_options.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8b50a8804e58a0b95aac9e05e870fe0678a42afd | [
"if stanza_type is None:\n if element is None:\n raise ValueError('Missing iq type')\nelif stanza_type not in IQ_TYPES:\n raise ValueError('Bad iq type')\nif element is None and stanza_id is None and (stanza_type in ('get', 'set')):\n stanza_id = self.gen_id()\nif element is None:\n element = 'iq... | <|body_start_0|>
if stanza_type is None:
if element is None:
raise ValueError('Missing iq type')
elif stanza_type not in IQ_TYPES:
raise ValueError('Bad iq type')
if element is None and stanza_id is None and (stanza_type in ('get', 'set')):
sta... | <message /> stanza class. | Iq | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Iq:
"""<message /> stanza class."""
def __init__(self, element=None, from_jid=None, to_jid=None, stanza_type=None, stanza_id=None, error=None, error_cond=None, return_path=None, language=None):
"""Initialize an `Iq` object. :Parameters: - `element`: XML element of this stanza. - `fro... | stack_v2_sparse_classes_36k_train_008344 | 6,218 | permissive | [
{
"docstring": "Initialize an `Iq` object. :Parameters: - `element`: XML element of this stanza. - `from_jid`: sender JID. - `to_jid`: recipient JID. - `stanza_type`: staza type: one of: \"get\", \"set\", \"response\" or \"error\". - `stanza_id`: stanza id -- value of stanza's \"id\" attribute. If not given, th... | 5 | stack_v2_sparse_classes_30k_train_009053 | Implement the Python class `Iq` described below.
Class description:
<message /> stanza class.
Method signatures and docstrings:
- def __init__(self, element=None, from_jid=None, to_jid=None, stanza_type=None, stanza_id=None, error=None, error_cond=None, return_path=None, language=None): Initialize an `Iq` object. :Pa... | Implement the Python class `Iq` described below.
Class description:
<message /> stanza class.
Method signatures and docstrings:
- def __init__(self, element=None, from_jid=None, to_jid=None, stanza_type=None, stanza_id=None, error=None, error_cond=None, return_path=None, language=None): Initialize an `Iq` object. :Pa... | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | <|skeleton|>
class Iq:
"""<message /> stanza class."""
def __init__(self, element=None, from_jid=None, to_jid=None, stanza_type=None, stanza_id=None, error=None, error_cond=None, return_path=None, language=None):
"""Initialize an `Iq` object. :Parameters: - `element`: XML element of this stanza. - `fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Iq:
"""<message /> stanza class."""
def __init__(self, element=None, from_jid=None, to_jid=None, stanza_type=None, stanza_id=None, error=None, error_cond=None, return_path=None, language=None):
"""Initialize an `Iq` object. :Parameters: - `element`: XML element of this stanza. - `from_jid`: sende... | the_stack_v2_python_sparse | python3-alpha/python-libs/pyxmpp2/iq.py | kuri65536/python-for-android | train | 280 |
1d3585de4df8a057b0e453aa89670e3fa937d938 | [
"FeatureExtractor.__init__(self)\nself.width = 40\nself.height = 40\nself.channels = 3\nself.load_model(model_path)",
"with tf.variable_scope('placeholder'):\n Img = tf.placeholder('float', [None, self.width, self.height, self.channels])\n Dropout = tf.placeholder(tf.float32)\n Is_Training = tf.placehold... | <|body_start_0|>
FeatureExtractor.__init__(self)
self.width = 40
self.height = 40
self.channels = 3
self.load_model(model_path)
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope('placeholder'):
Img = tf.placeholder('float', [None, self.width, self.height... | MiniFacenet特征提取器 es 2018-11-06 | MiniFacenetFeatureExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MiniFacenetFeatureExtractor:
"""MiniFacenet特征提取器 es 2018-11-06"""
def __init__(self, model_path):
"""初始化"""
<|body_0|>
def load_model(self, model_path):
"""加载预先已训练的模型"""
<|body_1|>
def preprocess(self, imgs):
"""图像预处理"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_008345 | 3,122 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, model_path)"
},
{
"docstring": "加载预先已训练的模型",
"name": "load_model",
"signature": "def load_model(self, model_path)"
},
{
"docstring": "图像预处理",
"name": "preprocess",
"signature": "def preprocess(self... | 4 | stack_v2_sparse_classes_30k_train_009510 | Implement the Python class `MiniFacenetFeatureExtractor` described below.
Class description:
MiniFacenet特征提取器 es 2018-11-06
Method signatures and docstrings:
- def __init__(self, model_path): 初始化
- def load_model(self, model_path): 加载预先已训练的模型
- def preprocess(self, imgs): 图像预处理
- def extract_features(self, imgs, batc... | Implement the Python class `MiniFacenetFeatureExtractor` described below.
Class description:
MiniFacenet特征提取器 es 2018-11-06
Method signatures and docstrings:
- def __init__(self, model_path): 初始化
- def load_model(self, model_path): 加载预先已训练的模型
- def preprocess(self, imgs): 图像预处理
- def extract_features(self, imgs, batc... | 3c756d00c83cd0a8dd745fd32a074c9121977ab8 | <|skeleton|>
class MiniFacenetFeatureExtractor:
"""MiniFacenet特征提取器 es 2018-11-06"""
def __init__(self, model_path):
"""初始化"""
<|body_0|>
def load_model(self, model_path):
"""加载预先已训练的模型"""
<|body_1|>
def preprocess(self, imgs):
"""图像预处理"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MiniFacenetFeatureExtractor:
"""MiniFacenet特征提取器 es 2018-11-06"""
def __init__(self, model_path):
"""初始化"""
FeatureExtractor.__init__(self)
self.width = 40
self.height = 40
self.channels = 3
self.load_model(model_path)
def load_model(self, model_path):... | the_stack_v2_python_sparse | feature/mini_facenet_feature_extractor.py | esfamely/es_face_server | train | 0 |
e957317869ae26b95af468292c2668d038fe9347 | [
"N = len(nums)\nW = sum(nums) // 2\nif sum(nums) % 2 == 1:\n return False\nif N * W == 0:\n return False\ndp = [[False] * (W + 1) for _ in range(N + 1)]\nfor i in range(N + 1):\n dp[i][0] = True\nfor i in range(1, N + 1):\n for j in range(1, W + 1):\n if j >= nums[i - 1]:\n dp[i][j] = ... | <|body_start_0|>
N = len(nums)
W = sum(nums) // 2
if sum(nums) % 2 == 1:
return False
if N * W == 0:
return False
dp = [[False] * (W + 1) for _ in range(N + 1)]
for i in range(N + 1):
dp[i][0] = True
for i in range(1, N + 1):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""状态转移方程: 0-1背包:dp[i][j] = max(dp[i−1][j], dp[i−1][j−w[i]]+v[i]) // j >= w[i] 完全背包:dp[i][j] = max(dp[i−1][j], dp[i][j−w[i]]+v[i]) // j >= w[i] dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i]] dp[i][j] = x 表示,对于前i个物品,当前背包的容量为j时,... | stack_v2_sparse_classes_36k_train_008346 | 3,325 | permissive | [
{
"docstring": "状态转移方程: 0-1背包:dp[i][j] = max(dp[i−1][j], dp[i−1][j−w[i]]+v[i]) // j >= w[i] 完全背包:dp[i][j] = max(dp[i−1][j], dp[i][j−w[i]]+v[i]) // j >= w[i] dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i]] dp[i][j] = x 表示,对于前i个物品,当前背包的容量为j时,若x为true,则说明可以恰好将背包装满,若x为false,则说明不能恰好将背包装满。",
"name": "canPartitio... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums: List[int]) -> bool: 状态转移方程: 0-1背包:dp[i][j] = max(dp[i−1][j], dp[i−1][j−w[i]]+v[i]) // j >= w[i] 完全背包:dp[i][j] = max(dp[i−1][j], dp[i][j−w[i]]+v[i]) /... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums: List[int]) -> bool: 状态转移方程: 0-1背包:dp[i][j] = max(dp[i−1][j], dp[i−1][j−w[i]]+v[i]) // j >= w[i] 完全背包:dp[i][j] = max(dp[i−1][j], dp[i][j−w[i]]+v[i]) /... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""状态转移方程: 0-1背包:dp[i][j] = max(dp[i−1][j], dp[i−1][j−w[i]]+v[i]) // j >= w[i] 完全背包:dp[i][j] = max(dp[i−1][j], dp[i][j−w[i]]+v[i]) // j >= w[i] dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i]] dp[i][j] = x 表示,对于前i个物品,当前背包的容量为j时,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""状态转移方程: 0-1背包:dp[i][j] = max(dp[i−1][j], dp[i−1][j−w[i]]+v[i]) // j >= w[i] 完全背包:dp[i][j] = max(dp[i−1][j], dp[i][j−w[i]]+v[i]) // j >= w[i] dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i]] dp[i][j] = x 表示,对于前i个物品,当前背包的容量为j时,若x为true,则说明可以恰... | the_stack_v2_python_sparse | 416-partition-equal-subset-sum.py | yuenliou/leetcode | train | 0 | |
94ca94e2d08034f8675f0f9b6cafad0eda68ddb6 | [
"n = len(p) - 1\nm = [[0] * (n + 1) for _ in range(n + 1)]\ns = [[0] * (n + 1) for _ in range(n)]\nfor l in range(2, n + 1):\n for i in range(1, n - l + 2):\n j = i + l - 1\n m[i][j] = float('inf')\n for k in range(i, j):\n q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]\n ... | <|body_start_0|>
n = len(p) - 1
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n)]
for l in range(2, n + 1):
for i in range(1, n - l + 2):
j = i + l - 1
m[i][j] = float('inf')
for k in range(i, j):
... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def matrix_chain_order(p):
"""动态规划"""
<|body_0|>
def print_optimal_parens(self, s, i, j):
"""生成矩阵链最优括号化方案"""
<|body_1|>
def matrix_chain_multiply(self, A, s, i, j):
"""15.2-2:实现矩阵链最优代价乘法计算"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_008347 | 3,066 | no_license | [
{
"docstring": "动态规划",
"name": "matrix_chain_order",
"signature": "def matrix_chain_order(p)"
},
{
"docstring": "生成矩阵链最优括号化方案",
"name": "print_optimal_parens",
"signature": "def print_optimal_parens(self, s, i, j)"
},
{
"docstring": "15.2-2:实现矩阵链最优代价乘法计算",
"name": "matrix_cha... | 3 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def matrix_chain_order(p): 动态规划
- def print_optimal_parens(self, s, i, j): 生成矩阵链最优括号化方案
- def matrix_chain_multiply(self, A, s, i, j): 15.2-2:实现矩阵链最优代价乘法计算 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def matrix_chain_order(p): 动态规划
- def print_optimal_parens(self, s, i, j): 生成矩阵链最优括号化方案
- def matrix_chain_multiply(self, A, s, i, j): 15.2-2:实现矩阵链最优代价乘法计算
<|skeleton|>
class ... | 9fdc4b1a2b59b7aed22ddfe92aade487b4c19b71 | <|skeleton|>
class Solution1:
def matrix_chain_order(p):
"""动态规划"""
<|body_0|>
def print_optimal_parens(self, s, i, j):
"""生成矩阵链最优括号化方案"""
<|body_1|>
def matrix_chain_multiply(self, A, s, i, j):
"""15.2-2:实现矩阵链最优代价乘法计算"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def matrix_chain_order(p):
"""动态规划"""
n = len(p) - 1
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n)]
for l in range(2, n + 1):
for i in range(1, n - l + 2):
j = i + l - 1
m[i][j] = fl... | the_stack_v2_python_sparse | introduction_to_algorithms/15.2_matrix_chain_order.py | MemoryForSky/Data-Structures-and-Algorithms | train | 0 | |
c652428851eb81eab8ea3fa740d3fb1f52b51bfc | [
"super(topic_embedding, self).__init__()\nassert n_topics < embedding_dim\ntopic_vectors = ortho_group.rvs(embedding_dim)\ntopic_vectors = topic_vectors[0:n_topics]\ntopic_vectors = torch.FloatTensor(topic_vectors)\nself.topic_vectors = nn.Parameter(topic_vectors)\nself.n_topics = n_topics",
"doc_probs = F.softma... | <|body_start_0|>
super(topic_embedding, self).__init__()
assert n_topics < embedding_dim
topic_vectors = ortho_group.rvs(embedding_dim)
topic_vectors = topic_vectors[0:n_topics]
topic_vectors = torch.FloatTensor(topic_vectors)
self.topic_vectors = nn.Parameter(topic_vecto... | topic_embedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class topic_embedding:
def __init__(self, n_topics, embedding_dim):
"""Arguments: embedding_dim: An integer. n_topics: An integer."""
<|body_0|>
def forward(self, doc_weights):
"""Embed a batch of documents. Arguments: doc_weights: A float tensor of shape [batch_size, n_to... | stack_v2_sparse_classes_36k_train_008348 | 29,814 | no_license | [
{
"docstring": "Arguments: embedding_dim: An integer. n_topics: An integer.",
"name": "__init__",
"signature": "def __init__(self, n_topics, embedding_dim)"
},
{
"docstring": "Embed a batch of documents. Arguments: doc_weights: A float tensor of shape [batch_size, n_topics], document distributio... | 2 | stack_v2_sparse_classes_30k_train_007799 | Implement the Python class `topic_embedding` described below.
Class description:
Implement the topic_embedding class.
Method signatures and docstrings:
- def __init__(self, n_topics, embedding_dim): Arguments: embedding_dim: An integer. n_topics: An integer.
- def forward(self, doc_weights): Embed a batch of document... | Implement the Python class `topic_embedding` described below.
Class description:
Implement the topic_embedding class.
Method signatures and docstrings:
- def __init__(self, n_topics, embedding_dim): Arguments: embedding_dim: An integer. n_topics: An integer.
- def forward(self, doc_weights): Embed a batch of document... | 82d3e9808073f2145b039ccf464c526cb85274e3 | <|skeleton|>
class topic_embedding:
def __init__(self, n_topics, embedding_dim):
"""Arguments: embedding_dim: An integer. n_topics: An integer."""
<|body_0|>
def forward(self, doc_weights):
"""Embed a batch of documents. Arguments: doc_weights: A float tensor of shape [batch_size, n_to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class topic_embedding:
def __init__(self, n_topics, embedding_dim):
"""Arguments: embedding_dim: An integer. n_topics: An integer."""
super(topic_embedding, self).__init__()
assert n_topics < embedding_dim
topic_vectors = ortho_group.rvs(embedding_dim)
topic_vectors = topic_v... | the_stack_v2_python_sparse | business/p201908/3507_750/lda2vec_model.py | Alvin2580du/alvin_py | train | 12 | |
44c583f750ad5c040bdd9e1e413b57fc1571ef16 | [
"article_dict = list()\nfor key in ['课程名称', '任教老师', '人数限制', '课程描述']:\n a = input(f'请输入{key}')\n article_dict.append(a)\ncurriculum = Course(*article_dict)\ncurriculum.save()\ninput('课程增加成功,按任意键打印增加课程的信息')\nprint(curriculum)\ninput('按任意键返回')\nmin()",
"for i in Data.article_dict.values():\n print(i)\ninput... | <|body_start_0|>
article_dict = list()
for key in ['课程名称', '任教老师', '人数限制', '课程描述']:
a = input(f'请输入{key}')
article_dict.append(a)
curriculum = Course(*article_dict)
curriculum.save()
input('课程增加成功,按任意键打印增加课程的信息')
print(curriculum)
input('按任... | 管理员类 | Admin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Admin:
"""管理员类"""
def add_course(self):
"""添加课程"""
<|body_0|>
def check_course(cls, *args, **kwargs):
"""查看课程"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
article_dict = list()
for key in ['课程名称', '任教老师', '人数限制', '课程描述']:
... | stack_v2_sparse_classes_36k_train_008349 | 4,552 | no_license | [
{
"docstring": "添加课程",
"name": "add_course",
"signature": "def add_course(self)"
},
{
"docstring": "查看课程",
"name": "check_course",
"signature": "def check_course(cls, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009969 | Implement the Python class `Admin` described below.
Class description:
管理员类
Method signatures and docstrings:
- def add_course(self): 添加课程
- def check_course(cls, *args, **kwargs): 查看课程 | Implement the Python class `Admin` described below.
Class description:
管理员类
Method signatures and docstrings:
- def add_course(self): 添加课程
- def check_course(cls, *args, **kwargs): 查看课程
<|skeleton|>
class Admin:
"""管理员类"""
def add_course(self):
"""添加课程"""
<|body_0|>
def check_course(cls... | e11f5fcb10f37a0f0663e4c746ca862b076f9aee | <|skeleton|>
class Admin:
"""管理员类"""
def add_course(self):
"""添加课程"""
<|body_0|>
def check_course(cls, *args, **kwargs):
"""查看课程"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Admin:
"""管理员类"""
def add_course(self):
"""添加课程"""
article_dict = list()
for key in ['课程名称', '任教老师', '人数限制', '课程描述']:
a = input(f'请输入{key}')
article_dict.append(a)
curriculum = Course(*article_dict)
curriculum.save()
input('课程增加成功,按任... | the_stack_v2_python_sparse | 作业/5-11作业.py | liujiang9/python0421 | train | 1 |
bf09854c0c1f0c26af9941a158dfad534f5c984e | [
"if isinstance(exceptions, type):\n exceptions = [exceptions]\nself.exceptions = exceptions\nself.exceptions_dict = dict(((e.code, e) for e in self.exceptions))",
"code, message, data = err\ntry:\n exp = self.exceptions_dict[code]\n return exp(exp.code, message, data)\nexcept KeyError:\n return TRexEx... | <|body_start_0|>
if isinstance(exceptions, type):
exceptions = [exceptions]
self.exceptions = exceptions
self.exceptions_dict = dict(((e.code, e) for e in self.exceptions))
<|end_body_0|>
<|body_start_1|>
code, message, data = err
try:
exp = self.exceptio... | CExceptionHandler is responsible for generating TRex API related exceptions in client side. | CExceptionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CExceptionHandler:
"""CExceptionHandler is responsible for generating TRex API related exceptions in client side."""
def __init__(self, exceptions):
"""Instatiate a CExceptionHandler object :parameters: exceptions : list a list of all TRex acceptable exception objects. default list: ... | stack_v2_sparse_classes_36k_train_008350 | 5,237 | permissive | [
{
"docstring": "Instatiate a CExceptionHandler object :parameters: exceptions : list a list of all TRex acceptable exception objects. default list: - :exc:`trex_exceptions.TRexException` - :exc:`trex_exceptions.TRexError` - :exc:`trex_exceptions.TRexWarning` - :exc:`trex_exceptions.TRexInUseError` - :exc:`trex_... | 2 | null | Implement the Python class `CExceptionHandler` described below.
Class description:
CExceptionHandler is responsible for generating TRex API related exceptions in client side.
Method signatures and docstrings:
- def __init__(self, exceptions): Instatiate a CExceptionHandler object :parameters: exceptions : list a list... | Implement the Python class `CExceptionHandler` described below.
Class description:
CExceptionHandler is responsible for generating TRex API related exceptions in client side.
Method signatures and docstrings:
- def __init__(self, exceptions): Instatiate a CExceptionHandler object :parameters: exceptions : list a list... | e30f5af03aaaad518b5def6e1804c3741dd5d0c6 | <|skeleton|>
class CExceptionHandler:
"""CExceptionHandler is responsible for generating TRex API related exceptions in client side."""
def __init__(self, exceptions):
"""Instatiate a CExceptionHandler object :parameters: exceptions : list a list of all TRex acceptable exception objects. default list: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CExceptionHandler:
"""CExceptionHandler is responsible for generating TRex API related exceptions in client side."""
def __init__(self, exceptions):
"""Instatiate a CExceptionHandler object :parameters: exceptions : list a list of all TRex acceptable exception objects. default list: - :exc:`trex_... | the_stack_v2_python_sparse | trex_client/stf/trex_stf_lib/trex_exceptions.py | alwye/trex-http-proxy | train | 4 |
e315b8ddd4b1c9ae0575dc9f95e0702e500a2f05 | [
"detail = ''\nif detailed:\n detail = '/detail'\nif response_key:\n return self._get('/os-hypervisors%s' % detail, 'hypervisors', **kwargs)\nelse:\n return self._get('/os-hypervisors%s' % detail, **kwargs)",
"target = 'servers' if servers else 'search'\nurl = '/os-hypervisors/%s/%s' % (parse.quote(hyperv... | <|body_start_0|>
detail = ''
if detailed:
detail = '/detail'
if response_key:
return self._get('/os-hypervisors%s' % detail, 'hypervisors', **kwargs)
else:
return self._get('/os-hypervisors%s' % detail, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | HypervisorManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypervisorManager:
def list(self, detailed=True, response_key=True, **kwargs):
"""Get a list of hypervisors."""
<|body_0|>
def search(self, hypervisor_match, servers=False, response_key=True, **kwargs):
"""Get a list of matching hypervisors. :param servers: If True, ... | stack_v2_sparse_classes_36k_train_008351 | 2,287 | no_license | [
{
"docstring": "Get a list of hypervisors.",
"name": "list",
"signature": "def list(self, detailed=True, response_key=True, **kwargs)"
},
{
"docstring": "Get a list of matching hypervisors. :param servers: If True, server information is also retrieved.",
"name": "search",
"signature": "d... | 5 | null | Implement the Python class `HypervisorManager` described below.
Class description:
Implement the HypervisorManager class.
Method signatures and docstrings:
- def list(self, detailed=True, response_key=True, **kwargs): Get a list of hypervisors.
- def search(self, hypervisor_match, servers=False, response_key=True, **... | Implement the Python class `HypervisorManager` described below.
Class description:
Implement the HypervisorManager class.
Method signatures and docstrings:
- def list(self, detailed=True, response_key=True, **kwargs): Get a list of hypervisors.
- def search(self, hypervisor_match, servers=False, response_key=True, **... | 42f9197ba26ffb6b9dd336a524639ecbbf194365 | <|skeleton|>
class HypervisorManager:
def list(self, detailed=True, response_key=True, **kwargs):
"""Get a list of hypervisors."""
<|body_0|>
def search(self, hypervisor_match, servers=False, response_key=True, **kwargs):
"""Get a list of matching hypervisors. :param servers: If True, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HypervisorManager:
def list(self, detailed=True, response_key=True, **kwargs):
"""Get a list of hypervisors."""
detail = ''
if detailed:
detail = '/detail'
if response_key:
return self._get('/os-hypervisors%s' % detail, 'hypervisors', **kwargs)
e... | the_stack_v2_python_sparse | ops_client/project/nova/hypervisors.py | tokuzfunpi/ops_client | train | 0 | |
26f2162ea2709a5275a8780d7415161efc420589 | [
"super(GRRHuntOsqueryCollector, self).__init__(state, name=name, critical=critical)\nself.timeout_millis = self.DEFAULT_OSQUERY_TIMEOUT_MILLIS\nself.ignore_stderr_errors = True",
"self.GrrSetUp(reason, grr_server_url, grr_username, grr_password, approvers=approvers, verify=verify, message_callback=self.PublishMes... | <|body_start_0|>
super(GRRHuntOsqueryCollector, self).__init__(state, name=name, critical=critical)
self.timeout_millis = self.DEFAULT_OSQUERY_TIMEOUT_MILLIS
self.ignore_stderr_errors = True
<|end_body_0|>
<|body_start_1|>
self.GrrSetUp(reason, grr_server_url, grr_username, grr_password... | Osquery collector for a GRR Hunt. Attributes: timeout_millis (int): the number of milliseconds before osquery timeouts. ignore_stderr_errors (bool): ignore stderr errors from osquery. | GRRHuntOsqueryCollector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRRHuntOsqueryCollector:
"""Osquery collector for a GRR Hunt. Attributes: timeout_millis (int): the number of milliseconds before osquery timeouts. ignore_stderr_errors (bool): ignore stderr errors from osquery."""
def __init__(self, state: DFTimewolfState, name: Optional[str]=None, critical... | stack_v2_sparse_classes_36k_train_008352 | 27,645 | permissive | [
{
"docstring": "Initializes a GRR file collector hunt. Args: state (DFTimewolfState): recipe state. name (Optional[str]): The module's runtime name. critical (bool): True if the module is critical, which causes the entire recipe to fail if the module encounters an error.",
"name": "__init__",
"signature... | 3 | null | Implement the Python class `GRRHuntOsqueryCollector` described below.
Class description:
Osquery collector for a GRR Hunt. Attributes: timeout_millis (int): the number of milliseconds before osquery timeouts. ignore_stderr_errors (bool): ignore stderr errors from osquery.
Method signatures and docstrings:
- def __ini... | Implement the Python class `GRRHuntOsqueryCollector` described below.
Class description:
Osquery collector for a GRR Hunt. Attributes: timeout_millis (int): the number of milliseconds before osquery timeouts. ignore_stderr_errors (bool): ignore stderr errors from osquery.
Method signatures and docstrings:
- def __ini... | bcea85b1ce7a0feb2aa28b5be4fc6ae124e8ca3c | <|skeleton|>
class GRRHuntOsqueryCollector:
"""Osquery collector for a GRR Hunt. Attributes: timeout_millis (int): the number of milliseconds before osquery timeouts. ignore_stderr_errors (bool): ignore stderr errors from osquery."""
def __init__(self, state: DFTimewolfState, name: Optional[str]=None, critical... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRRHuntOsqueryCollector:
"""Osquery collector for a GRR Hunt. Attributes: timeout_millis (int): the number of milliseconds before osquery timeouts. ignore_stderr_errors (bool): ignore stderr errors from osquery."""
def __init__(self, state: DFTimewolfState, name: Optional[str]=None, critical: bool=False)... | the_stack_v2_python_sparse | dftimewolf/lib/collectors/grr_hunt.py | log2timeline/dftimewolf | train | 248 |
8f540844ba35df23b5dd0188d3d9d7fd9f0228b4 | [
"self.timeout = timeout\ntry:\n self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=self.timeout)\nexcept Exception as e:\n self.skipped('Cannot learn the feature', from_exception=e, goto=['next_tc'])\nfor stp in steps.details:\n if stp.result.name == 'skipped':\n ... | <|body_start_0|>
self.timeout = timeout
try:
self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=self.timeout)
except Exception as e:
self.skipped('Cannot learn the feature', from_exception=e, goto=['next_tc'])
for stp in ste... | Trigger class for Reload action | TriggerReload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerReload:
"""Trigger class for Reload action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`... | stack_v2_sparse_classes_36k_train_008353 | 20,969 | permissive | [
{
"docstring": "Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object timeout (`timeout obj`): Timeout Object Returns: None Raises: pyATS Res... | 4 | null | Implement the Python class `TriggerReload` described below.
Class description:
Trigger class for Reload action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next te... | Implement the Python class `TriggerReload` described below.
Class description:
Trigger class for Reload action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next te... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerReload:
"""Trigger class for Reload action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerReload:
"""Trigger class for Reload action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract o... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/ha/ha.py | CiscoTestAutomation/genielibs | train | 109 |
f38465223d99757ea736fb0d78f652b766861804 | [
"self.radius = np.abs(np.atleast_1d(radius))\nif len(self.radius) == 1:\n self.radius = np.abs(np.array([radius, radius, radius]))\nif len(self.radius) != 3 or (self.radius <= 0).any():\n self.error('non positive radius defined for ellipsoid object')\n self.empty = True\n return self\ntry:\n self.cen... | <|body_start_0|>
self.radius = np.abs(np.atleast_1d(radius))
if len(self.radius) == 1:
self.radius = np.abs(np.array([radius, radius, radius]))
if len(self.radius) != 3 or (self.radius <= 0).any():
self.error('non positive radius defined for ellipsoid object')
... | PyRatEllipsoid: A PyRat object P. Lewis 30/6/2012 For an ellipsoid or sphere | PyRatEllipsoid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyRatEllipsoid:
"""PyRatEllipsoid: A PyRat object P. Lewis 30/6/2012 For an ellipsoid or sphere"""
def __init__(self, base, radius, contents=None, material=None, info=None):
"""Load the object: base : vector that define the ellipsoid base (N.B. not centre) radius : vector (for ellips... | stack_v2_sparse_classes_36k_train_008354 | 4,469 | no_license | [
{
"docstring": "Load the object: base : vector that define the ellipsoid base (N.B. not centre) radius : vector (for ellipsoid) or scalar for sphere OPTIONAL: info['coords']: 3 x 2 vectors that define a coordinate for each vertex Options: contents : a list that may contain other objects or None material : a dic... | 4 | stack_v2_sparse_classes_30k_train_020275 | Implement the Python class `PyRatEllipsoid` described below.
Class description:
PyRatEllipsoid: A PyRat object P. Lewis 30/6/2012 For an ellipsoid or sphere
Method signatures and docstrings:
- def __init__(self, base, radius, contents=None, material=None, info=None): Load the object: base : vector that define the ell... | Implement the Python class `PyRatEllipsoid` described below.
Class description:
PyRatEllipsoid: A PyRat object P. Lewis 30/6/2012 For an ellipsoid or sphere
Method signatures and docstrings:
- def __init__(self, base, radius, contents=None, material=None, info=None): Load the object: base : vector that define the ell... | 031db80c597947cf089b72fbdc1a1e167b308bda | <|skeleton|>
class PyRatEllipsoid:
"""PyRatEllipsoid: A PyRat object P. Lewis 30/6/2012 For an ellipsoid or sphere"""
def __init__(self, base, radius, contents=None, material=None, info=None):
"""Load the object: base : vector that define the ellipsoid base (N.B. not centre) radius : vector (for ellips... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyRatEllipsoid:
"""PyRatEllipsoid: A PyRat object P. Lewis 30/6/2012 For an ellipsoid or sphere"""
def __init__(self, base, radius, contents=None, material=None, info=None):
"""Load the object: base : vector that define the ellipsoid base (N.B. not centre) radius : vector (for ellipsoid) or scala... | the_stack_v2_python_sparse | PyRat/PyRatEllipsoid.py | profLewis/PyRat | train | 2 |
e9eadedcbc1992bce435b1d3120e3e81bc3f46f3 | [
"for element in brain.getObject().objectValues():\n info = {'title': element.title or ''}\n if element.portal_type == 'PSCFileLink':\n info['url'] = element.externalURL\n else:\n info['url'] = element.absolute_url()\n yield info",
"sc = self.context\ncatalog = getToolByName(self.context,... | <|body_start_0|>
for element in brain.getObject().objectValues():
info = {'title': element.title or ''}
if element.portal_type == 'PSCFileLink':
info['url'] = element.externalURL
else:
info['url'] = element.absolute_url()
yield info... | view used for the main index page | PyPISimpleView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyPISimpleView:
"""view used for the main index page"""
def get_urls_and_titles(self, brain):
"""returns url and title"""
<|body_0|>
def get_files(self):
"""provides the simple view over the projects with links to the published files"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_008355 | 1,303 | no_license | [
{
"docstring": "returns url and title",
"name": "get_urls_and_titles",
"signature": "def get_urls_and_titles(self, brain)"
},
{
"docstring": "provides the simple view over the projects with links to the published files",
"name": "get_files",
"signature": "def get_files(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018166 | Implement the Python class `PyPISimpleView` described below.
Class description:
view used for the main index page
Method signatures and docstrings:
- def get_urls_and_titles(self, brain): returns url and title
- def get_files(self): provides the simple view over the projects with links to the published files | Implement the Python class `PyPISimpleView` described below.
Class description:
view used for the main index page
Method signatures and docstrings:
- def get_urls_and_titles(self, brain): returns url and title
- def get_files(self): provides the simple view over the projects with links to the published files
<|skele... | 8a7bdbdb98c3f9fc1073c6061cd2d3a0ec80caf5 | <|skeleton|>
class PyPISimpleView:
"""view used for the main index page"""
def get_urls_and_titles(self, brain):
"""returns url and title"""
<|body_0|>
def get_files(self):
"""provides the simple view over the projects with links to the published files"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyPISimpleView:
"""view used for the main index page"""
def get_urls_and_titles(self, brain):
"""returns url and title"""
for element in brain.getObject().objectValues():
info = {'title': element.title or ''}
if element.portal_type == 'PSCFileLink':
... | the_stack_v2_python_sparse | buildout-cache/eggs/Products.PloneSoftwareCenter-1.5-py2.7.egg/Products/PloneSoftwareCenter/browser/pypisimple.py | renansfs/Plone_SP | train | 0 |
edb58aedc46522ecb607c7cf4e6bac811ca0b5ea | [
"date_list = []\nstrstring = str(strstring)\nif strstring.find('-'):\n date_list = strstring.split('-')\nelif strstring.find(':'):\n date_list = strstring.split(':')\nelse:\n date_list[0], date_list[1], date_list[2] = (strstring[:4], strstring[4:6], strstring[6:])\nself.year, self.month, self.day = (date_l... | <|body_start_0|>
date_list = []
strstring = str(strstring)
if strstring.find('-'):
date_list = strstring.split('-')
elif strstring.find(':'):
date_list = strstring.split(':')
else:
date_list[0], date_list[1], date_list[2] = (strstring[:4], strs... | Datadis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Datadis:
def set_strdate(self, strstring):
"""读取字符串时间 :param strstring: 2020-1-9 or 2020:1:9 or 20200109 :return:"""
<|body_0|>
def get_int_md(self):
"""获取月天数 :return:"""
<|body_1|>
def get_interval_vacation(self, start_date, end_date):
"""获取时间段内... | stack_v2_sparse_classes_36k_train_008356 | 1,861 | no_license | [
{
"docstring": "读取字符串时间 :param strstring: 2020-1-9 or 2020:1:9 or 20200109 :return:",
"name": "set_strdate",
"signature": "def set_strdate(self, strstring)"
},
{
"docstring": "获取月天数 :return:",
"name": "get_int_md",
"signature": "def get_int_md(self)"
},
{
"docstring": "获取时间段内的双休日... | 3 | stack_v2_sparse_classes_30k_train_010627 | Implement the Python class `Datadis` described below.
Class description:
Implement the Datadis class.
Method signatures and docstrings:
- def set_strdate(self, strstring): 读取字符串时间 :param strstring: 2020-1-9 or 2020:1:9 or 20200109 :return:
- def get_int_md(self): 获取月天数 :return:
- def get_interval_vacation(self, start... | Implement the Python class `Datadis` described below.
Class description:
Implement the Datadis class.
Method signatures and docstrings:
- def set_strdate(self, strstring): 读取字符串时间 :param strstring: 2020-1-9 or 2020:1:9 or 20200109 :return:
- def get_int_md(self): 获取月天数 :return:
- def get_interval_vacation(self, start... | 88705807df697dc86a5ed8a648505b3fb895872b | <|skeleton|>
class Datadis:
def set_strdate(self, strstring):
"""读取字符串时间 :param strstring: 2020-1-9 or 2020:1:9 or 20200109 :return:"""
<|body_0|>
def get_int_md(self):
"""获取月天数 :return:"""
<|body_1|>
def get_interval_vacation(self, start_date, end_date):
"""获取时间段内... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Datadis:
def set_strdate(self, strstring):
"""读取字符串时间 :param strstring: 2020-1-9 or 2020:1:9 or 20200109 :return:"""
date_list = []
strstring = str(strstring)
if strstring.find('-'):
date_list = strstring.split('-')
elif strstring.find(':'):
date... | the_stack_v2_python_sparse | main/src/general/date_G.py | wangwuli/XLauto | train | 1 | |
d8f15ef7655b1a4ae4efdccf688635d326e085f0 | [
"self.name = name\nself.money = 20\ntry:\n soldiers, archers, cavalries = self._verifyInput(soldiers, archers, cavalries)\nexcept (ValueError, AssertionError):\n raise\ntry:\n self.money -= self.calculateMoney(soldiers, archers, cavalries)\nexcept AssertionError:\n raise\nself.createQueue(soldiers, arch... | <|body_start_0|>
self.name = name
self.money = 20
try:
soldiers, archers, cavalries = self._verifyInput(soldiers, archers, cavalries)
except (ValueError, AssertionError):
raise
try:
self.money -= self.calculateMoney(soldiers, archers, cavalries... | Army | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Army:
def __init__(self, name, soldiers, archers, cavalries):
"""creates an Army class that uses Linked Queue @ param name: string for the Army's name @ param soldiers: integer, positive @ param archers: integer, positive @ param cavalries: integer, positive @ post: Army class created @ ... | stack_v2_sparse_classes_36k_train_008357 | 8,892 | no_license | [
{
"docstring": "creates an Army class that uses Linked Queue @ param name: string for the Army's name @ param soldiers: integer, positive @ param archers: integer, positive @ param cavalries: integer, positive @ post: Army class created @ return: Army class @ complexity: O(1) -> because soldiers, archers, caval... | 4 | null | Implement the Python class `Army` described below.
Class description:
Implement the Army class.
Method signatures and docstrings:
- def __init__(self, name, soldiers, archers, cavalries): creates an Army class that uses Linked Queue @ param name: string for the Army's name @ param soldiers: integer, positive @ param ... | Implement the Python class `Army` described below.
Class description:
Implement the Army class.
Method signatures and docstrings:
- def __init__(self, name, soldiers, archers, cavalries): creates an Army class that uses Linked Queue @ param name: string for the Army's name @ param soldiers: integer, positive @ param ... | a6d7ce18d377aa975c29f2ec441e91d1480903e6 | <|skeleton|>
class Army:
def __init__(self, name, soldiers, archers, cavalries):
"""creates an Army class that uses Linked Queue @ param name: string for the Army's name @ param soldiers: integer, positive @ param archers: integer, positive @ param cavalries: integer, positive @ post: Army class created @ ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Army:
def __init__(self, name, soldiers, archers, cavalries):
"""creates an Army class that uses Linked Queue @ param name: string for the Army's name @ param soldiers: integer, positive @ param archers: integer, positive @ param cavalries: integer, positive @ post: Army class created @ return: Army c... | the_stack_v2_python_sparse | intro to comp science/python functions/fairer_army.py | gabimelo/AnDS-examples-python | train | 0 | |
c4eb1efc82cd72ca759782f138304b8f35ac80d5 | [
"self.nums = nums\nfor i in range(1, len(nums)):\n self.nums[i] += self.nums[i - 1]",
"if i > j:\n return None\nif j >= len(self.nums):\n return None\nsum = 0\nfor m in range(i, j + 1, 1):\n sum += self.nums[m]\nreturn self.nums[j] - (self.nums[i - 1] if i > 0 else 0)"
] | <|body_start_0|>
self.nums = nums
for i in range(1, len(nums)):
self.nums[i] += self.nums[i - 1]
<|end_body_0|>
<|body_start_1|>
if i > j:
return None
if j >= len(self.nums):
return None
sum = 0
for m in range(i, j + 1, 1):
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums = nums
for i in range(1, len(nums)):
... | stack_v2_sparse_classes_36k_train_008358 | 696 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | d87acd5481a2dbfad7288b73750e6e086650a17d | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
for i in range(1, len(nums)):
self.nums[i] += self.nums[i - 1]
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
if i > j:
return None
... | the_stack_v2_python_sparse | 303. Range Sum Query - Immutable/303. Range Sum Query - Immutable(AC).py | BohaoLiGithub/Leetcode | train | 0 | |
34bbd6cf700d5e47042556623c46e7ee002800d2 | [
"yield Request(url=response.url, callback=self.parse_details, dont_filter=True)\nnext_page = response.css('.next::attr(href)').extract_first('')\nif next_page:\n yield Request(url=parse.urljoin(response.url, next_page), callback=self.parse)",
"for i in range(len(response.css('.mod-bd .comment-item'))):\n it... | <|body_start_0|>
yield Request(url=response.url, callback=self.parse_details, dont_filter=True)
next_page = response.css('.next::attr(href)').extract_first('')
if next_page:
yield Request(url=parse.urljoin(response.url, next_page), callback=self.parse)
<|end_body_0|>
<|body_start_1|... | DoubanSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubanSpider:
def parse(self, response):
"""交给parse_details 进行处理"""
<|body_0|>
def parse_details(self, response):
"""解析爱情公寓具体短评论"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
yield Request(url=response.url, callback=self.parse_details, dont_filter... | stack_v2_sparse_classes_36k_train_008359 | 2,310 | no_license | [
{
"docstring": "交给parse_details 进行处理",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "解析爱情公寓具体短评论",
"name": "parse_details",
"signature": "def parse_details(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011111 | Implement the Python class `DoubanSpider` described below.
Class description:
Implement the DoubanSpider class.
Method signatures and docstrings:
- def parse(self, response): 交给parse_details 进行处理
- def parse_details(self, response): 解析爱情公寓具体短评论 | Implement the Python class `DoubanSpider` described below.
Class description:
Implement the DoubanSpider class.
Method signatures and docstrings:
- def parse(self, response): 交给parse_details 进行处理
- def parse_details(self, response): 解析爱情公寓具体短评论
<|skeleton|>
class DoubanSpider:
def parse(self, response):
... | 5e84bb83d46454b06ab65b819fd0f962b4d40421 | <|skeleton|>
class DoubanSpider:
def parse(self, response):
"""交给parse_details 进行处理"""
<|body_0|>
def parse_details(self, response):
"""解析爱情公寓具体短评论"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoubanSpider:
def parse(self, response):
"""交给parse_details 进行处理"""
yield Request(url=response.url, callback=self.parse_details, dont_filter=True)
next_page = response.css('.next::attr(href)').extract_first('')
if next_page:
yield Request(url=parse.urljoin(response.... | the_stack_v2_python_sparse | 爬虫 新scrape/爬虫 新scrape/scrapy_learn_bole-master/scrapy_learn_bole-master/ArticleSpider/spiders/douban.py | xzbuku/16219111133-qimo-work | train | 1 | |
624da4dcc8c6a8ae5c6a0d01e5663e0216d964ca | [
"super(LogmelFilterBank, self).__init__()\nself.is_log = is_log\nself.ref = ref\nself.amin = amin\nself.top_db = top_db\nself.melW = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax).T\nself.melW = nn.Parameter(torch.Tensor(self.melW))\nif freeze_parameters:\n for param in self.paramet... | <|body_start_0|>
super(LogmelFilterBank, self).__init__()
self.is_log = is_log
self.ref = ref
self.amin = amin
self.top_db = top_db
self.melW = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax).T
self.melW = nn.Parameter(torch.Tensor(sel... | LogmelFilterBank | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogmelFilterBank:
def __init__(self, sr=32000, n_fft=2048, n_mels=64, fmin=50, fmax=14000, is_log=True, ref=1.0, amin=1e-10, top_db=80.0, freeze_parameters=True):
"""Calculate logmel spectrogram using pytorch. The mel filter bank is the pytorch implementation of as librosa.filters.mel"""... | stack_v2_sparse_classes_36k_train_008360 | 25,139 | no_license | [
{
"docstring": "Calculate logmel spectrogram using pytorch. The mel filter bank is the pytorch implementation of as librosa.filters.mel",
"name": "__init__",
"signature": "def __init__(self, sr=32000, n_fft=2048, n_mels=64, fmin=50, fmax=14000, is_log=True, ref=1.0, amin=1e-10, top_db=80.0, freeze_param... | 3 | stack_v2_sparse_classes_30k_train_020536 | Implement the Python class `LogmelFilterBank` described below.
Class description:
Implement the LogmelFilterBank class.
Method signatures and docstrings:
- def __init__(self, sr=32000, n_fft=2048, n_mels=64, fmin=50, fmax=14000, is_log=True, ref=1.0, amin=1e-10, top_db=80.0, freeze_parameters=True): Calculate logmel ... | Implement the Python class `LogmelFilterBank` described below.
Class description:
Implement the LogmelFilterBank class.
Method signatures and docstrings:
- def __init__(self, sr=32000, n_fft=2048, n_mels=64, fmin=50, fmax=14000, is_log=True, ref=1.0, amin=1e-10, top_db=80.0, freeze_parameters=True): Calculate logmel ... | 7ab627aefa56525735684b6671918d7c7db1cc07 | <|skeleton|>
class LogmelFilterBank:
def __init__(self, sr=32000, n_fft=2048, n_mels=64, fmin=50, fmax=14000, is_log=True, ref=1.0, amin=1e-10, top_db=80.0, freeze_parameters=True):
"""Calculate logmel spectrogram using pytorch. The mel filter bank is the pytorch implementation of as librosa.filters.mel"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogmelFilterBank:
def __init__(self, sr=32000, n_fft=2048, n_mels=64, fmin=50, fmax=14000, is_log=True, ref=1.0, amin=1e-10, top_db=80.0, freeze_parameters=True):
"""Calculate logmel spectrogram using pytorch. The mel filter bank is the pytorch implementation of as librosa.filters.mel"""
super... | the_stack_v2_python_sparse | easy_gold/pann_utils.py | wdy06/kaggle-birdsong-recognition | train | 1 | |
3f07fc82aa1f55354352bdcba5273053e9e9129d | [
"if attributeData:\n attrData = array(attributeData)\n leafData = array(leafData, object_)\n self.root = Node(attrData, leafData, sepVal)\nelse:\n self.root = None",
"if not self.root:\n return []\nreturn _searchNode(self.root, target, window * window, [zero] * len(target), zero)",
"if not self.r... | <|body_start_0|>
if attributeData:
attrData = array(attributeData)
leafData = array(leafData, object_)
self.root = Node(attrData, leafData, sepVal)
else:
self.root = None
<|end_body_0|>
<|body_start_1|>
if not self.root:
return []
... | Define an 'adaptive k-d tree' as per "The Design and Analysis of Spatial Data Structures" pp. 70-71. Basically, given a set of k-dimensional points (each dimension referred to as an "attribute") with associated data, they are partitioned into leaf nodes. Each leaf nodes hold lists of associated data whose corresponding... | AdaptiveTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptiveTree:
"""Define an 'adaptive k-d tree' as per "The Design and Analysis of Spatial Data Structures" pp. 70-71. Basically, given a set of k-dimensional points (each dimension referred to as an "attribute") with associated data, they are partitioned into leaf nodes. Each leaf nodes hold list... | stack_v2_sparse_classes_36k_train_008361 | 7,623 | no_license | [
{
"docstring": "attributeData is a sequence of sequences. Each individual sequence is attribute data. For example, in a 3D space partitioning, the attribute data is x, y, and z values. leafData ia a sequence of the same length as attributeData. Each item is what is to put into leaf nodes after tree partitioning... | 3 | null | Implement the Python class `AdaptiveTree` described below.
Class description:
Define an 'adaptive k-d tree' as per "The Design and Analysis of Spatial Data Structures" pp. 70-71. Basically, given a set of k-dimensional points (each dimension referred to as an "attribute") with associated data, they are partitioned int... | Implement the Python class `AdaptiveTree` described below.
Class description:
Define an 'adaptive k-d tree' as per "The Design and Analysis of Spatial Data Structures" pp. 70-71. Basically, given a set of k-dimensional points (each dimension referred to as an "attribute") with associated data, they are partitioned int... | 024890dba56c3e82ea2cf8c773965117f8cda339 | <|skeleton|>
class AdaptiveTree:
"""Define an 'adaptive k-d tree' as per "The Design and Analysis of Spatial Data Structures" pp. 70-71. Basically, given a set of k-dimensional points (each dimension referred to as an "attribute") with associated data, they are partitioned into leaf nodes. Each leaf nodes hold list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdaptiveTree:
"""Define an 'adaptive k-d tree' as per "The Design and Analysis of Spatial Data Structures" pp. 70-71. Basically, given a set of k-dimensional points (each dimension referred to as an "attribute") with associated data, they are partitioned into leaf nodes. Each leaf nodes hold lists of associat... | the_stack_v2_python_sparse | tools/MolSurfGenService/MolSurfaceGen32/chimera/share/CGLutil/AdaptiveTree.py | project-renard-survey/semanticscience | train | 0 |
c70a497fa0a9db39e3f4546fd96775912458e71d | [
"i = 0\nwhile i < len(nums):\n if nums[i] == val:\n del nums[i]\n else:\n i += 1\nreturn len(nums)",
"tmp = list(filter(lambda x: x != val, nums))\nnums[:len(tmp)] = tmp\ndel nums[len(tmp):]\nreturn len(nums)"
] | <|body_start_0|>
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += 1
return len(nums)
<|end_body_0|>
<|body_start_1|>
tmp = list(filter(lambda x: x != val, nums))
nums[:len(tmp)] = tmp
del nums[le... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
"""direct solution"""
<|body_0|>
def removeElement2(self, nums, val):
"""use filter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
while i < len(nums):
if nums[i] == val:
... | stack_v2_sparse_classes_36k_train_008362 | 1,988 | permissive | [
{
"docstring": "direct solution",
"name": "removeElement",
"signature": "def removeElement(self, nums, val)"
},
{
"docstring": "use filter",
"name": "removeElement2",
"signature": "def removeElement2(self, nums, val)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): direct solution
- def removeElement2(self, nums, val): use filter | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): direct solution
- def removeElement2(self, nums, val): use filter
<|skeleton|>
class Solution:
def removeElement(self, nums, val):
... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
"""direct solution"""
<|body_0|>
def removeElement2(self, nums, val):
"""use filter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums, val):
"""direct solution"""
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += 1
return len(nums)
def removeElement2(self, nums, val):
"""use filter"""... | the_stack_v2_python_sparse | leetcode/0027_remove_element.py | chaosWsF/Python-Practice | train | 1 | |
6e63aabc3519f11574e7148e7766628800719288 | [
"self.seed = seed\nself.digits = digits\nself.base = len(self.digits)",
"result = ''\npower = len(self.seed)\nseedidx = 0\nwhile power > 0:\n digit = 0\n number = self.base ** (power - 1)\n while tbc >= number:\n digit += 1\n tbc -= number\n seedchar = self.seed[seedidx]\n pos = self.... | <|body_start_0|>
self.seed = seed
self.digits = digits
self.base = len(self.digits)
<|end_body_0|>
<|body_start_1|>
result = ''
power = len(self.seed)
seedidx = 0
while power > 0:
digit = 0
number = self.base ** (power - 1)
whi... | Class to Generate a new ID | IdGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdGenerator:
"""Class to Generate a new ID"""
def __init__(self, seed, digits):
"""initialse the seed for encoding the number"""
<|body_0|>
def dec2Encoded(self, tbc):
"""the function works by converting the sequence to a base 48 number represented by the digit s... | stack_v2_sparse_classes_36k_train_008363 | 3,805 | no_license | [
{
"docstring": "initialse the seed for encoding the number",
"name": "__init__",
"signature": "def __init__(self, seed, digits)"
},
{
"docstring": "the function works by converting the sequence to a base 48 number represented by the digit set above. It is then encoded by add the corresponding di... | 2 | null | Implement the Python class `IdGenerator` described below.
Class description:
Class to Generate a new ID
Method signatures and docstrings:
- def __init__(self, seed, digits): initialse the seed for encoding the number
- def dec2Encoded(self, tbc): the function works by converting the sequence to a base 48 number repre... | Implement the Python class `IdGenerator` described below.
Class description:
Class to Generate a new ID
Method signatures and docstrings:
- def __init__(self, seed, digits): initialse the seed for encoding the number
- def dec2Encoded(self, tbc): the function works by converting the sequence to a base 48 number repre... | e6c967c5e70bca099657655db62e3a33593a1a58 | <|skeleton|>
class IdGenerator:
"""Class to Generate a new ID"""
def __init__(self, seed, digits):
"""initialse the seed for encoding the number"""
<|body_0|>
def dec2Encoded(self, tbc):
"""the function works by converting the sequence to a base 48 number represented by the digit s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdGenerator:
"""Class to Generate a new ID"""
def __init__(self, seed, digits):
"""initialse the seed for encoding the number"""
self.seed = seed
self.digits = digits
self.base = len(self.digits)
def dec2Encoded(self, tbc):
"""the function works by converting ... | the_stack_v2_python_sparse | site/controllers/generator.py | mikejmets/polokelo-bookings | train | 0 |
69c790f2feb2571758d6d99f6b0221f6a61443a3 | [
"while obj:\n yield obj\n for opChild in IESMetaSaverHelper.HierarchyIterator(obj.GetDown()):\n yield opChild\n obj = obj.GetNext()",
"if not isinstance(op, c4d.BaseObject):\n raise TypeError('Expected a BaseObject or derived class got {0}'.format(op.__class__.__name__))\ntemp = op.GetDeformCac... | <|body_start_0|>
while obj:
yield obj
for opChild in IESMetaSaverHelper.HierarchyIterator(obj.GetDown()):
yield opChild
obj = obj.GetNext()
<|end_body_0|>
<|body_start_1|>
if not isinstance(op, c4d.BaseObject):
raise TypeError('Expected a ... | IESMetaSaverHelper | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IESMetaSaverHelper:
def HierarchyIterator(obj):
"""A Generator to iterate over the Hierarchy. Args: obj: The starting object of the generator (will be the first result) Returns: All objects under and next of the `obj`"""
<|body_0|>
def CacheIterator(op):
"""A Python ... | stack_v2_sparse_classes_36k_train_008364 | 8,297 | permissive | [
{
"docstring": "A Generator to iterate over the Hierarchy. Args: obj: The starting object of the generator (will be the first result) Returns: All objects under and next of the `obj`",
"name": "HierarchyIterator",
"signature": "def HierarchyIterator(obj)"
},
{
"docstring": "A Python Generator to... | 2 | stack_v2_sparse_classes_30k_train_008420 | Implement the Python class `IESMetaSaverHelper` described below.
Class description:
Implement the IESMetaSaverHelper class.
Method signatures and docstrings:
- def HierarchyIterator(obj): A Generator to iterate over the Hierarchy. Args: obj: The starting object of the generator (will be the first result) Returns: All... | Implement the Python class `IESMetaSaverHelper` described below.
Class description:
Implement the IESMetaSaverHelper class.
Method signatures and docstrings:
- def HierarchyIterator(obj): A Generator to iterate over the Hierarchy. Args: obj: The starting object of the generator (will be the first result) Returns: All... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class IESMetaSaverHelper:
def HierarchyIterator(obj):
"""A Generator to iterate over the Hierarchy. Args: obj: The starting object of the generator (will be the first result) Returns: All objects under and next of the `obj`"""
<|body_0|>
def CacheIterator(op):
"""A Python ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IESMetaSaverHelper:
def HierarchyIterator(obj):
"""A Generator to iterate over the Hierarchy. Args: obj: The starting object of the generator (will be the first result) Returns: All objects under and next of the `obj`"""
while obj:
yield obj
for opChild in IESMetaSaverH... | the_stack_v2_python_sparse | plugins/py-ies_meta_r12/py-ies_meta_r12.pyp | PluginCafe/cinema4d_py_sdk_extended | train | 112 | |
5093d43f88877843c5f6da9a33bb9ec148ef253d | [
"if k <= 1:\n return head\np = head\nlength = 0\nwhile p is not None:\n length += 1\n p = p.next\ncnt = 0\ncur_node = head\nwhile cur_node is not None:\n if cnt + k <= length:\n if cnt == 0:\n head = self.reverse_k(cur_node, k)\n cnt += k\n else:\n next_nod... | <|body_start_0|>
if k <= 1:
return head
p = head
length = 0
while p is not None:
length += 1
p = p.next
cnt = 0
cur_node = head
while cur_node is not None:
if cnt + k <= length:
if cnt == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_k_group(self, head, k):
"""leetcode 25. K 个一组翻转链表 :param head: ListNode 链表的表头 :param k: 每个翻转的个数 :return: 翻转后链表的表头"""
<|body_0|>
def reverse_k(self, head, k):
"""对以head为表头的链表进行翻转k个节点 返回翻转后表头 :param head: 链表表头 :param k: k个节点 :return: 翻转后的表头"""
... | stack_v2_sparse_classes_36k_train_008365 | 2,790 | no_license | [
{
"docstring": "leetcode 25. K 个一组翻转链表 :param head: ListNode 链表的表头 :param k: 每个翻转的个数 :return: 翻转后链表的表头",
"name": "reverse_k_group",
"signature": "def reverse_k_group(self, head, k)"
},
{
"docstring": "对以head为表头的链表进行翻转k个节点 返回翻转后表头 :param head: 链表表头 :param k: k个节点 :return: 翻转后的表头",
"name": "re... | 3 | stack_v2_sparse_classes_30k_train_016314 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_k_group(self, head, k): leetcode 25. K 个一组翻转链表 :param head: ListNode 链表的表头 :param k: 每个翻转的个数 :return: 翻转后链表的表头
- def reverse_k(self, head, k): 对以head为表头的链表进行翻转k个节点 返回... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_k_group(self, head, k): leetcode 25. K 个一组翻转链表 :param head: ListNode 链表的表头 :param k: 每个翻转的个数 :return: 翻转后链表的表头
- def reverse_k(self, head, k): 对以head为表头的链表进行翻转k个节点 返回... | 6479c0ad862a18d1021f35493e5e7d18d1ced5e4 | <|skeleton|>
class Solution:
def reverse_k_group(self, head, k):
"""leetcode 25. K 个一组翻转链表 :param head: ListNode 链表的表头 :param k: 每个翻转的个数 :return: 翻转后链表的表头"""
<|body_0|>
def reverse_k(self, head, k):
"""对以head为表头的链表进行翻转k个节点 返回翻转后表头 :param head: 链表表头 :param k: k个节点 :return: 翻转后的表头"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_k_group(self, head, k):
"""leetcode 25. K 个一组翻转链表 :param head: ListNode 链表的表头 :param k: 每个翻转的个数 :return: 翻转后链表的表头"""
if k <= 1:
return head
p = head
length = 0
while p is not None:
length += 1
p = p.next
... | the_stack_v2_python_sparse | linkedlist_relate/ReverseKGroup.py | Batman001/leetcode_in_python | train | 3 | |
146c8ecf92f9cb293b69a3285616d43a12c205a2 | [
"if degree < 0:\n raise ValueError('Polynomial degree must be non-negative')\nself.degree = degree\nself.params = None",
"rows, *remaining = data.shape\nif remaining:\n raise ValueError('Data must have dimensions N x 1')\nreturn np.vander(data, N=degree + 1, increasing=True)",
"X = PolynomialRegression._d... | <|body_start_0|>
if degree < 0:
raise ValueError('Polynomial degree must be non-negative')
self.degree = degree
self.params = None
<|end_body_0|>
<|body_start_1|>
rows, *remaining = data.shape
if remaining:
raise ValueError('Data must have dimensions N x ... | PolynomialRegression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolynomialRegression:
def __init__(self, degree: int) -> None:
"""@raises ValueError: if the polynomial degree is negative"""
<|body_0|>
def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray:
"""Constructs a polynomial regression design matrix for the given... | stack_v2_sparse_classes_36k_train_008366 | 7,827 | permissive | [
{
"docstring": "@raises ValueError: if the polynomial degree is negative",
"name": "__init__",
"signature": "def __init__(self, degree: int) -> None"
},
{
"docstring": "Constructs a polynomial regression design matrix for the given input data. For input data x = (x₁, x₂, ..., xₙ) and polynomial ... | 4 | null | Implement the Python class `PolynomialRegression` described below.
Class description:
Implement the PolynomialRegression class.
Method signatures and docstrings:
- def __init__(self, degree: int) -> None: @raises ValueError: if the polynomial degree is negative
- def _design_matrix(data: np.ndarray, degree: int) -> n... | Implement the Python class `PolynomialRegression` described below.
Class description:
Implement the PolynomialRegression class.
Method signatures and docstrings:
- def __init__(self, degree: int) -> None: @raises ValueError: if the polynomial degree is negative
- def _design_matrix(data: np.ndarray, degree: int) -> n... | 421ace81edb0d9af3a173f4ca7e66cc900078c1d | <|skeleton|>
class PolynomialRegression:
def __init__(self, degree: int) -> None:
"""@raises ValueError: if the polynomial degree is negative"""
<|body_0|>
def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray:
"""Constructs a polynomial regression design matrix for the given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolynomialRegression:
def __init__(self, degree: int) -> None:
"""@raises ValueError: if the polynomial degree is negative"""
if degree < 0:
raise ValueError('Polynomial degree must be non-negative')
self.degree = degree
self.params = None
def _design_matrix(da... | the_stack_v2_python_sparse | machine_learning/polynomial_regression.py | TheAlgorithms/Python | train | 184,217 | |
6085c3fc8b08f9cc24ecae36b7d32f8b26182e3c | [
"roman_symbols = ['M', 'D', 'C', 'L', 'X', 'V', 'I']\nnumbers = [1000, 500, 100, 50, 10, 5, 1]\nroman = []\nfor idx, n in enumerate(numbers):\n i, num = (num / n, num % n)\n if i > 3:\n last = roman.pop()\n if last == '':\n li = [roman_symbols[idx], roman_symbols[idx - 1]]\n el... | <|body_start_0|>
roman_symbols = ['M', 'D', 'C', 'L', 'X', 'V', 'I']
numbers = [1000, 500, 100, 50, 10, 5, 1]
roman = []
for idx, n in enumerate(numbers):
i, num = (num / n, num % n)
if i > 3:
last = roman.pop()
if last == '':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intToRoman(self, num):
"""http://en.wikipedia.org/wiki/Roman_numerals"""
<|body_0|>
def intToRoman2(self, num):
"""little bit improvement"""
<|body_1|>
def intToRoman3(self, num):
"""recursive version"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k_train_008367 | 2,501 | no_license | [
{
"docstring": "http://en.wikipedia.org/wiki/Roman_numerals",
"name": "intToRoman",
"signature": "def intToRoman(self, num)"
},
{
"docstring": "little bit improvement",
"name": "intToRoman2",
"signature": "def intToRoman2(self, num)"
},
{
"docstring": "recursive version",
"na... | 3 | stack_v2_sparse_classes_30k_train_013550 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intToRoman(self, num): http://en.wikipedia.org/wiki/Roman_numerals
- def intToRoman2(self, num): little bit improvement
- def intToRoman3(self, num): recursive version | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intToRoman(self, num): http://en.wikipedia.org/wiki/Roman_numerals
- def intToRoman2(self, num): little bit improvement
- def intToRoman3(self, num): recursive version
<|ske... | c10ed7710cfbb74fd068e5c5d05d45564ad22194 | <|skeleton|>
class Solution:
def intToRoman(self, num):
"""http://en.wikipedia.org/wiki/Roman_numerals"""
<|body_0|>
def intToRoman2(self, num):
"""little bit improvement"""
<|body_1|>
def intToRoman3(self, num):
"""recursive version"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intToRoman(self, num):
"""http://en.wikipedia.org/wiki/Roman_numerals"""
roman_symbols = ['M', 'D', 'C', 'L', 'X', 'V', 'I']
numbers = [1000, 500, 100, 50, 10, 5, 1]
roman = []
for idx, n in enumerate(numbers):
i, num = (num / n, num % n)
... | the_stack_v2_python_sparse | leetcode/python/integer-to-roman.py | deepgully/codes | train | 1 | |
35d0dd01e2df73117f2db3b9bc922efdd9da0aa6 | [
"logging.info('=============测试登录16312345678=============')\nl = LoginView(self.driver)\ndata = l.get_csv_data(self.csv_file, 2)\nl.login_action(data[0], data[1])\nself.assertTrue(l.check_loginStatus())",
"logging.info('=============测试登录16212345678=============')\nl = LoginView(self.driver)\ndata = l.get_csv_data(... | <|body_start_0|>
logging.info('=============测试登录16312345678=============')
l = LoginView(self.driver)
data = l.get_csv_data(self.csv_file, 2)
l.login_action(data[0], data[1])
self.assertTrue(l.check_loginStatus())
<|end_body_0|>
<|body_start_1|>
logging.info('===========... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login_1(self):
"""测试登录账号16312345678 :return:"""
<|body_0|>
def test_login_2(self):
"""测试登录账号16212345678 :return:"""
<|body_1|>
def test_login_3(self):
"""测试登录账号16512345678 :return:"""
<|body_2|>
def test_login_4(s... | stack_v2_sparse_classes_36k_train_008368 | 2,618 | no_license | [
{
"docstring": "测试登录账号16312345678 :return:",
"name": "test_login_1",
"signature": "def test_login_1(self)"
},
{
"docstring": "测试登录账号16212345678 :return:",
"name": "test_login_2",
"signature": "def test_login_2(self)"
},
{
"docstring": "测试登录账号16512345678 :return:",
"name": "te... | 5 | stack_v2_sparse_classes_30k_train_014925 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_1(self): 测试登录账号16312345678 :return:
- def test_login_2(self): 测试登录账号16212345678 :return:
- def test_login_3(self): 测试登录账号16512345678 :return:
- def test_login_4(... | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_1(self): 测试登录账号16312345678 :return:
- def test_login_2(self): 测试登录账号16212345678 :return:
- def test_login_3(self): 测试登录账号16512345678 :return:
- def test_login_4(... | d2b7819fd3687e0a011988fefab3e6fd70bb014a | <|skeleton|>
class TestLogin:
def test_login_1(self):
"""测试登录账号16312345678 :return:"""
<|body_0|>
def test_login_2(self):
"""测试登录账号16212345678 :return:"""
<|body_1|>
def test_login_3(self):
"""测试登录账号16512345678 :return:"""
<|body_2|>
def test_login_4(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
def test_login_1(self):
"""测试登录账号16312345678 :return:"""
logging.info('=============测试登录16312345678=============')
l = LoginView(self.driver)
data = l.get_csv_data(self.csv_file, 2)
l.login_action(data[0], data[1])
self.assertTrue(l.check_loginStatus(... | the_stack_v2_python_sparse | care_doctor/test_case/test_login.py | vothin/code | train | 0 | |
c5c07fdb87f04aaeb008e3d02771d17ac3c3e1c0 | [
"message = MIMEMultipart('alternative')\nmessage['Subject'] = self.message_subject\nmessage['From'] = self.mail_from_header\nmessage['To'] = self.mail_to_header\nmessage['Reply-To'] = self.message_reply_to\nif self.html_content:\n message.attach(MIMEText(self.html_content, 'html'))\nif self.text_content:\n me... | <|body_start_0|>
message = MIMEMultipart('alternative')
message['Subject'] = self.message_subject
message['From'] = self.mail_from_header
message['To'] = self.mail_to_header
message['Reply-To'] = self.message_reply_to
if self.html_content:
message.attach(MIMET... | Mail smtp driver. | MailSmtpDriver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailSmtpDriver:
"""Mail smtp driver."""
def message(self):
"""Creates a message object for the underlying driver. Returns: email.mime.multipart.MIMEMultipart"""
<|body_0|>
def send(self, message=None, message_contents=None):
"""Send the message through SMTP. Keyw... | stack_v2_sparse_classes_36k_train_008369 | 3,884 | permissive | [
{
"docstring": "Creates a message object for the underlying driver. Returns: email.mime.multipart.MIMEMultipart",
"name": "message",
"signature": "def message(self)"
},
{
"docstring": "Send the message through SMTP. Keyword Arguments: message {string} -- The HTML message to be sent to SMTP. (def... | 4 | stack_v2_sparse_classes_30k_train_004516 | Implement the Python class `MailSmtpDriver` described below.
Class description:
Mail smtp driver.
Method signatures and docstrings:
- def message(self): Creates a message object for the underlying driver. Returns: email.mime.multipart.MIMEMultipart
- def send(self, message=None, message_contents=None): Send the messa... | Implement the Python class `MailSmtpDriver` described below.
Class description:
Mail smtp driver.
Method signatures and docstrings:
- def message(self): Creates a message object for the underlying driver. Returns: email.mime.multipart.MIMEMultipart
- def send(self, message=None, message_contents=None): Send the messa... | 66a6b1480a5771bbd1056ba59cec4014beb63fa8 | <|skeleton|>
class MailSmtpDriver:
"""Mail smtp driver."""
def message(self):
"""Creates a message object for the underlying driver. Returns: email.mime.multipart.MIMEMultipart"""
<|body_0|>
def send(self, message=None, message_contents=None):
"""Send the message through SMTP. Keyw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailSmtpDriver:
"""Mail smtp driver."""
def message(self):
"""Creates a message object for the underlying driver. Returns: email.mime.multipart.MIMEMultipart"""
message = MIMEMultipart('alternative')
message['Subject'] = self.message_subject
message['From'] = self.mail_fro... | the_stack_v2_python_sparse | src/masonite/drivers/mail/MailSmtpDriver.py | angrycaptain19/masonite | train | 0 |
547b08ebe69e3d8856c45267560203d6c1a0deed | [
"if root is None:\n return True\nreturn self.isMirror(root.left, root.right)",
"if root1 is None and root2 is None:\n return True\nelif root1 is None and root2 is not None or (root1 is not None and root2 is None):\n return False\nreturn root1.val == root2.val and self.isMirror(root1.left, root2.right) an... | <|body_start_0|>
if root is None:
return True
return self.isMirror(root.left, root.right)
<|end_body_0|>
<|body_start_1|>
if root1 is None and root2 is None:
return True
elif root1 is None and root2 is not None or (root1 is not None and root2 is None):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isMirror(self, root1, root2):
"""Checks if root1 is mirror image of root2 (and vice versa.) i.e. flip(root1) == root2 and flip(root2) == root1"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_008370 | 3,665 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": "Checks if root1 is mirror image of root2 (and vice versa.) i.e. flip(root1) == root2 and flip(root2) == root1",
"name": "isMirror",
"signature": "def i... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isMirror(self, root1, root2): Checks if root1 is mirror image of root2 (and vice versa.) i.e. flip(root1) == ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isMirror(self, root1, root2): Checks if root1 is mirror image of root2 (and vice versa.) i.e. flip(root1) == ... | 69a960dd8f39e9c8435a3678852071e1085fcb72 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isMirror(self, root1, root2):
"""Checks if root1 is mirror image of root2 (and vice versa.) i.e. flip(root1) == root2 and flip(root2) == root1"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, root1, root2):
"""Checks if root1 is mirror image of root2 (and vice versa.) i.e. flip(roo... | the_stack_v2_python_sparse | python/tree/lc101.py | chao-ji/LeetCode | train | 1 | |
9aac65469721ac4a9b0e984797a283f08f320604 | [
"self.device = device\nself.conn_cmd = conn_cmd\nself.device.conn_cmd = conn_cmd",
"try:\n bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])\n self.device.expect(pexpect.TIMEOUT, timeout=5)\nexcept pexpect.EOF:\n raise boardfarm.exceptions.ConnectionRefused('... | <|body_start_0|>
self.device = device
self.conn_cmd = conn_cmd
self.device.conn_cmd = conn_cmd
<|end_body_0|>
<|body_start_1|>
try:
bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])
self.device.expect(pexpect.TIMEOUT,... | This class is meant to be used to connect to a device using a custom Linux command instead of telnet/SSH. Sets connection_type to local_cmd, ignores all output for now | LocalCmd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalCmd:
"""This class is meant to be used to connect to a device using a custom Linux command instead of telnet/SSH. Sets connection_type to local_cmd, ignores all output for now"""
def __init__(self, device=None, conn_cmd=None, **kwargs):
"""Initializes instance of LocalCmd class ... | stack_v2_sparse_classes_36k_train_008371 | 1,895 | permissive | [
{
"docstring": "Initializes instance of LocalCmd class :param device: the device on which the command is to be executed, defaults to None :type device: object :param conn_cmd: the command to be used to connect to the device, defaults to None :type conn_cmd: string :param **kwargs: extra args to be used if any :... | 3 | stack_v2_sparse_classes_30k_train_001576 | Implement the Python class `LocalCmd` described below.
Class description:
This class is meant to be used to connect to a device using a custom Linux command instead of telnet/SSH. Sets connection_type to local_cmd, ignores all output for now
Method signatures and docstrings:
- def __init__(self, device=None, conn_cmd... | Implement the Python class `LocalCmd` described below.
Class description:
This class is meant to be used to connect to a device using a custom Linux command instead of telnet/SSH. Sets connection_type to local_cmd, ignores all output for now
Method signatures and docstrings:
- def __init__(self, device=None, conn_cmd... | 100521fde1fb67536682cafecc2f91a6e2e8a6f8 | <|skeleton|>
class LocalCmd:
"""This class is meant to be used to connect to a device using a custom Linux command instead of telnet/SSH. Sets connection_type to local_cmd, ignores all output for now"""
def __init__(self, device=None, conn_cmd=None, **kwargs):
"""Initializes instance of LocalCmd class ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalCmd:
"""This class is meant to be used to connect to a device using a custom Linux command instead of telnet/SSH. Sets connection_type to local_cmd, ignores all output for now"""
def __init__(self, device=None, conn_cmd=None, **kwargs):
"""Initializes instance of LocalCmd class :param device... | the_stack_v2_python_sparse | boardfarm/devices/local_cmd.py | mattsm/boardfarm | train | 45 |
9e5d16824ad827209f0aeb0c66e0b869a9761eaf | [
"self.min = np.array([0.0, 0.0])\nself.value = 0.0\nself.domain = np.array([[-100.0, 100.0], [-100.0, 100.0]])\nself.n = 2\nself.smooth = False\nself.info = [True, False, False]\nself.latex_name = 'Schaffer No. 4 Function'\nself.latex_type = 'Many Local Minima'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = 0.5 + \\\... | <|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-100.0, 100.0], [-100.0, 100.0]])
self.n = 2
self.smooth = False
self.info = [True, False, False]
self.latex_name = 'Schaffer No. 4 Function'
self.latex_type = 'Many... | Schaffer No. 4 Function. | Schaffer4 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Schaffer4:
"""Schaffer No. 4 Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
sel... | stack_v2_sparse_classes_36k_train_008372 | 1,054 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001642 | Implement the Python class `Schaffer4` described below.
Class description:
Schaffer No. 4 Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `Schaffer4` described below.
Class description:
Schaffer No. 4 Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class Schaffer4:
"""Schaffer No. 4 Function."""
def __init__(self):
"""Constructor... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Schaffer4:
"""Schaffer No. 4 Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Schaffer4:
"""Schaffer No. 4 Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-100.0, 100.0], [-100.0, 100.0]])
self.n = 2
self.smooth = False
self.info = [True, False, Fal... | the_stack_v2_python_sparse | ctf/functions2d/schaffer_4.py | cntaylor/ctf | train | 1 |
40873b9e0ffaadb6451f553b15a061d4381f80da | [
"if not isinstance(filePath, str):\n raise Exceptions.IncorrectTypeException(filePath, 'path', (str,))\nsuper().__init__(currentVersion, hostNamespace=hostNamespace)\nself.FilePath = filePath",
"operationSuccess = True\npersistentDataContainerString = '{}'\nif os.path.exists(self.FilePath):\n try:\n ... | <|body_start_0|>
if not isinstance(filePath, str):
raise Exceptions.IncorrectTypeException(filePath, 'path', (str,))
super().__init__(currentVersion, hostNamespace=hostNamespace)
self.FilePath = filePath
<|end_body_0|>
<|body_start_1|>
operationSuccess = True
persist... | A class for handling persistent data. This version will read and write the data to a file through the load and save methods. | PersistentBranchedFile | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistentBranchedFile:
"""A class for handling persistent data. This version will read and write the data to a file through the load and save methods."""
def __init__(self, filePath: str, currentVersion: Version.Version, hostNamespace: str=This.Mod.Namespace):
""":param filePath: Th... | stack_v2_sparse_classes_36k_train_008373 | 34,547 | permissive | [
{
"docstring": ":param filePath: The file path this persistence object will be written to and read from. :type filePath: str :param currentVersion: The current version of what ever will be controlling this persistence object. This value can allow you to correct outdated persistent data. :type currentVersion: Ve... | 3 | stack_v2_sparse_classes_30k_train_017978 | Implement the Python class `PersistentBranchedFile` described below.
Class description:
A class for handling persistent data. This version will read and write the data to a file through the load and save methods.
Method signatures and docstrings:
- def __init__(self, filePath: str, currentVersion: Version.Version, ho... | Implement the Python class `PersistentBranchedFile` described below.
Class description:
A class for handling persistent data. This version will read and write the data to a file through the load and save methods.
Method signatures and docstrings:
- def __init__(self, filePath: str, currentVersion: Version.Version, ho... | 2d85e6d4428f01294d2d34f1807287b753f7490c | <|skeleton|>
class PersistentBranchedFile:
"""A class for handling persistent data. This version will read and write the data to a file through the load and save methods."""
def __init__(self, filePath: str, currentVersion: Version.Version, hostNamespace: str=This.Mod.Namespace):
""":param filePath: Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersistentBranchedFile:
"""A class for handling persistent data. This version will read and write the data to a file through the load and save methods."""
def __init__(self, filePath: str, currentVersion: Version.Version, hostNamespace: str=This.Mod.Namespace):
""":param filePath: The file path t... | the_stack_v2_python_sparse | Python/NeonOcean.S4.Main/NeonOcean/S4/Main/Data/PersistenceBranched.py | NeonOcean/S4.Main | train | 1 |
46e1b6040e5c41d9cd5760ec9902fce4a5acda80 | [
"self.client = aff4.FACTORY.Open(self.client_id, token=self.token)\nself.system = str(self.client.Get(self.client.Schema.SYSTEM))\nself.os_version = str(self.client.Get(self.client.Schema.OS_VERSION))\nself.os_major_version = self.os_version.split('.')[0]\nif self.use_tsk:\n self.path_type = rdfvalue.PathSpec.Pa... | <|body_start_0|>
self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.system = str(self.client.Get(self.client.Schema.SYSTEM))
self.os_version = str(self.client.Get(self.client.Schema.OS_VERSION))
self.os_major_version = self.os_version.split('.')[0]
if self.use... | Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules. | LinSystemActivityInvestigation | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinSystemActivityInvestigation:
"""Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for... | stack_v2_sparse_classes_36k_train_008374 | 10,734 | permissive | [
{
"docstring": "Start.",
"name": "Start",
"signature": "def Start(self)"
},
{
"docstring": "Complete anything we need to do for each flow finishing.",
"name": "FinishFlow",
"signature": "def FinishFlow(self, responses)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016694 | Implement the Python class `LinSystemActivityInvestigation` described below.
Class description:
Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules.
Method signatures and docstrings:
- def Start(self): Start.
- def FinishFlow(self, responses): Complete anyth... | Implement the Python class `LinSystemActivityInvestigation` described below.
Class description:
Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules.
Method signatures and docstrings:
- def Start(self): Start.
- def FinishFlow(self, responses): Complete anyth... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class LinSystemActivityInvestigation:
"""Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinSystemActivityInvestigation:
"""Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.system = str(self.client.Get(... | the_stack_v2_python_sparse | lib/flows/general/automation.py | defaultnamehere/grr | train | 3 |
a7e187abfd5943af19f545145d7b31c2ef09db95 | [
"if not value:\n return None\nreturn ''.join([f'{int(i):02x}' for i in value.split(':')])",
"if not value:\n return None\nvalue = value.lstrip('#')\nreturn ':'.join([str(int(value[i:i + 2], 16)) for i in range(0, len(value) - 1, 2)])"
] | <|body_start_0|>
if not value:
return None
return ''.join([f'{int(i):02x}' for i in value.split(':')])
<|end_body_0|>
<|body_start_1|>
if not value:
return None
value = value.lstrip('#')
return ':'.join([str(int(value[i:i + 2], 16)) for i in range(0, len(... | Utility field class for color values. | ColorField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorField:
"""Utility field class for color values."""
def _serialize(self, value: str, *_, **__):
"""Convert a hex native color value (``ff0000``) to the format exposed by the SwitchBot API (``255:0:0``)."""
<|body_0|>
def _deserialize(self, value: str, *_, **__):
... | stack_v2_sparse_classes_36k_train_008375 | 8,416 | permissive | [
{
"docstring": "Convert a hex native color value (``ff0000``) to the format exposed by the SwitchBot API (``255:0:0``).",
"name": "_serialize",
"signature": "def _serialize(self, value: str, *_, **__)"
},
{
"docstring": "Convert a SwitchBot API color value (``255:0:0``) to the hex native format ... | 2 | stack_v2_sparse_classes_30k_train_017645 | Implement the Python class `ColorField` described below.
Class description:
Utility field class for color values.
Method signatures and docstrings:
- def _serialize(self, value: str, *_, **__): Convert a hex native color value (``ff0000``) to the format exposed by the SwitchBot API (``255:0:0``).
- def _deserialize(s... | Implement the Python class `ColorField` described below.
Class description:
Utility field class for color values.
Method signatures and docstrings:
- def _serialize(self, value: str, *_, **__): Convert a hex native color value (``ff0000``) to the format exposed by the SwitchBot API (``255:0:0``).
- def _deserialize(s... | 446bc2f67493d3554c5422242ff91d5b5c76d78a | <|skeleton|>
class ColorField:
"""Utility field class for color values."""
def _serialize(self, value: str, *_, **__):
"""Convert a hex native color value (``ff0000``) to the format exposed by the SwitchBot API (``255:0:0``)."""
<|body_0|>
def _deserialize(self, value: str, *_, **__):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorField:
"""Utility field class for color values."""
def _serialize(self, value: str, *_, **__):
"""Convert a hex native color value (``ff0000``) to the format exposed by the SwitchBot API (``255:0:0``)."""
if not value:
return None
return ''.join([f'{int(i):02x}' f... | the_stack_v2_python_sparse | platypush/schemas/switchbot.py | BlackLight/platypush | train | 265 |
e7686e33272482ab49e219eb9c5dff7e8f89f422 | [
"val = {}\nfor column in self.__table__.columns:\n val[column.key] = getattr(self, column.key)\nreturn val",
"val = self.value\nif hasattr(self.__class__, '_expandedFields'):\n for field in self.__class__._expandedFields:\n val[field] = [item.expandedValue for item in getattr(self, field).all()]\nret... | <|body_start_0|>
val = {}
for column in self.__table__.columns:
val[column.key] = getattr(self, column.key)
return val
<|end_body_0|>
<|body_start_1|>
val = self.value
if hasattr(self.__class__, '_expandedFields'):
for field in self.__class__._expandedFie... | Define the base functionality for the tables, including a simple primary key and method to convert into a simple (or extended) dictionary class, suitalble for JSON conversion. | TableBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableBase:
"""Define the base functionality for the tables, including a simple primary key and method to convert into a simple (or extended) dictionary class, suitalble for JSON conversion."""
def value(self):
"""This extracts the values of the object into a simple dictionary, suitab... | stack_v2_sparse_classes_36k_train_008376 | 2,266 | no_license | [
{
"docstring": "This extracts the values of the object into a simple dictionary, suitable for passing to jsonify. Values are selected based on __table__ object, which is created & managed by SQLAlchemy",
"name": "value",
"signature": "def value(self)"
},
{
"docstring": "This injects additional i... | 2 | stack_v2_sparse_classes_30k_train_003271 | Implement the Python class `TableBase` described below.
Class description:
Define the base functionality for the tables, including a simple primary key and method to convert into a simple (or extended) dictionary class, suitalble for JSON conversion.
Method signatures and docstrings:
- def value(self): This extracts ... | Implement the Python class `TableBase` described below.
Class description:
Define the base functionality for the tables, including a simple primary key and method to convert into a simple (or extended) dictionary class, suitalble for JSON conversion.
Method signatures and docstrings:
- def value(self): This extracts ... | a9dfbf6dd68ebfe8de5f3a4df3c26a9c8ee9e9f0 | <|skeleton|>
class TableBase:
"""Define the base functionality for the tables, including a simple primary key and method to convert into a simple (or extended) dictionary class, suitalble for JSON conversion."""
def value(self):
"""This extracts the values of the object into a simple dictionary, suitab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TableBase:
"""Define the base functionality for the tables, including a simple primary key and method to convert into a simple (or extended) dictionary class, suitalble for JSON conversion."""
def value(self):
"""This extracts the values of the object into a simple dictionary, suitable for passin... | the_stack_v2_python_sparse | raw/table_base.py | divido/littlefinger | train | 0 |
750d24eab80c9c45669671e6f463bfee0b0caa0b | [
"for _ in range(self.n_retries):\n try:\n r = requests.get(url)\n pathlib.Path(data_folder).mkdir(parents=True, exist_ok=True)\n open(os.path.join(data_folder, filename), 'wb').write(r.content)\n break\n except urllib.error.URLError:\n print(f'Download of {url} failed; wait ... | <|body_start_0|>
for _ in range(self.n_retries):
try:
r = requests.get(url)
pathlib.Path(data_folder).mkdir(parents=True, exist_ok=True)
open(os.path.join(data_folder, filename), 'wb').write(r.content)
break
except urllib.er... | This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all classes/groups. | WorstCase | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorstCase:
"""This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all cl... | stack_v2_sparse_classes_36k_train_008377 | 7,265 | permissive | [
{
"docstring": "Method to download the data given its' url, and the desired folder to stor int",
"name": "download",
"signature": "def download(self, url, data_folder, filename, md5)"
},
{
"docstring": "Calls the download method to download the cleaned labels from [3], as well as superclasses us... | 4 | stack_v2_sparse_classes_30k_train_014397 | Implement the Python class `WorstCase` described below.
Class description:
This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifie... | Implement the Python class `WorstCase` described below.
Class description:
This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifie... | 74b3cda69a2b90bcefed3848faca41a92ad0c9bf | <|skeleton|>
class WorstCase:
"""This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorstCase:
"""This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all classes/groups.... | the_stack_v2_python_sparse | shifthappens/tasks/worst_case/worst_case.py | shift-happens-benchmark/icml-2022 | train | 39 |
fbfac0fbad35566d36233ffa5a0da74310e9f2f3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ChecklistItem()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'checkedDateTime': lambda n: setattr(self, 'checked_date_time', n.get_datetime_value()), 'createdDateTime': lambda n... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ChecklistItem()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'checkedDateTime': lambda n: set... | ChecklistItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChecklistItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChecklistItem:
"""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... | stack_v2_sparse_classes_36k_train_008378 | 2,843 | 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: ChecklistItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `ChecklistItem` described below.
Class description:
Implement the ChecklistItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChecklistItem: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `ChecklistItem` described below.
Class description:
Implement the ChecklistItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChecklistItem: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ChecklistItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChecklistItem:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChecklistItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChecklistItem:
"""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: ChecklistIte... | the_stack_v2_python_sparse | msgraph/generated/models/checklist_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
5a66b20110b2947aefb4afa75292115957e03ecd | [
"try:\n return Member.objects.get(pk=pk)\nexcept Member.DoesNotExist:\n raise Http404",
"if pk is not None:\n member = self.get_member(int(pk))\nelse:\n member = None\nself.check_object_permissions(request, member)\ntransactions = Savings.get_savings_transactions(member)\nserializer = SavingsTransacti... | <|body_start_0|>
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
if pk is not None:
member = self.get_member(int(pk))
else:
member = None
self.check_object_permissions... | SavingsTransactionsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SavingsTransactionsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Member's savings Deposits"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
return Member.objects.get(p... | stack_v2_sparse_classes_36k_train_008379 | 5,809 | no_license | [
{
"docstring": "Get a member.",
"name": "get_member",
"signature": "def get_member(self, pk)"
},
{
"docstring": "List Member's savings Deposits",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003643 | Implement the Python class `SavingsTransactionsView` described below.
Class description:
Implement the SavingsTransactionsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Member's savings Deposits | Implement the Python class `SavingsTransactionsView` described below.
Class description:
Implement the SavingsTransactionsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Member's savings Deposits
<|skeleton|>
class SavingsTransac... | c5ac11e40a628c93c3865363e97b4f255a104ca8 | <|skeleton|>
class SavingsTransactionsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Member's savings Deposits"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SavingsTransactionsView:
def get_member(self, pk):
"""Get a member."""
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
"""List Member's savings Deposits"""
if pk is not... | the_stack_v2_python_sparse | savings/views.py | lubegamark/gosacco | train | 2 | |
56c2838ab83515f2317a84ef97e45d0d3d338d13 | [
"self.answers = answers\nself.gens = gens\nself.test = zip(answers, gens)\nreturn",
"totalscore = 0\nfor answer, gen in self.test:\n score = sentence_bleu([answer], gen, smoothing_function=SmoothingFunction().method4, auto_reweigh=True)\n totalscore = totalscore + score\nreturn totalscore / len(self.gens)",... | <|body_start_0|>
self.answers = answers
self.gens = gens
self.test = zip(answers, gens)
return
<|end_body_0|>
<|body_start_1|>
totalscore = 0
for answer, gen in self.test:
score = sentence_bleu([answer], gen, smoothing_function=SmoothingFunction().method4, au... | TestUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUtils:
def __init__(self, answers, gens):
"""初始化,读入标准answers与生成的gens :param answers: 标准回答的list :param gens: 生成回答的list"""
<|body_0|>
def get_bleu_score(self):
"""根据answer与gen逐条对比计算bleu_score :return: bleu_score(float类型)"""
<|body_1|>
def get_diversity... | stack_v2_sparse_classes_36k_train_008380 | 1,704 | permissive | [
{
"docstring": "初始化,读入标准answers与生成的gens :param answers: 标准回答的list :param gens: 生成回答的list",
"name": "__init__",
"signature": "def __init__(self, answers, gens)"
},
{
"docstring": "根据answer与gen逐条对比计算bleu_score :return: bleu_score(float类型)",
"name": "get_bleu_score",
"signature": "def get_b... | 3 | stack_v2_sparse_classes_30k_train_004622 | Implement the Python class `TestUtils` described below.
Class description:
Implement the TestUtils class.
Method signatures and docstrings:
- def __init__(self, answers, gens): 初始化,读入标准answers与生成的gens :param answers: 标准回答的list :param gens: 生成回答的list
- def get_bleu_score(self): 根据answer与gen逐条对比计算bleu_score :return: bl... | Implement the Python class `TestUtils` described below.
Class description:
Implement the TestUtils class.
Method signatures and docstrings:
- def __init__(self, answers, gens): 初始化,读入标准answers与生成的gens :param answers: 标准回答的list :param gens: 生成回答的list
- def get_bleu_score(self): 根据answer与gen逐条对比计算bleu_score :return: bl... | f56796a86620accd487480e5c3bd992cf3dc7578 | <|skeleton|>
class TestUtils:
def __init__(self, answers, gens):
"""初始化,读入标准answers与生成的gens :param answers: 标准回答的list :param gens: 生成回答的list"""
<|body_0|>
def get_bleu_score(self):
"""根据answer与gen逐条对比计算bleu_score :return: bleu_score(float类型)"""
<|body_1|>
def get_diversity... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUtils:
def __init__(self, answers, gens):
"""初始化,读入标准answers与生成的gens :param answers: 标准回答的list :param gens: 生成回答的list"""
self.answers = answers
self.gens = gens
self.test = zip(answers, gens)
return
def get_bleu_score(self):
"""根据answer与gen逐条对比计算bleu_sc... | the_stack_v2_python_sparse | 1.Metrics/metrics.py | imageslr/NLP | train | 2 | |
d4c2c99057c2e31c5ac851adc1151edfbb307a53 | [
"self.indices = np.empty(shape[0], dtype='int')\nself.array = np.empty(shape)\nself.next = 0",
"self.indices[self.next] = key\nself.array[self.next] = value\nself.next += 1",
"if self.next != self.indices.shape[0]:\n raise Exception('SparseRows object has not been filled')\nother[self.indices] += self.array"... | <|body_start_0|>
self.indices = np.empty(shape[0], dtype='int')
self.array = np.empty(shape)
self.next = 0
<|end_body_0|>
<|body_start_1|>
self.indices[self.next] = key
self.array[self.next] = value
self.next += 1
<|end_body_1|>
<|body_start_2|>
if self.next != ... | Sparse rows | SparseRows | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseRows:
"""Sparse rows"""
def __init__(self, shape):
"""Initialise a sparse numpy array with a given shape :param shape: tuple of integers, where the first index is the number of *non-zero* rows"""
<|body_0|>
def __setitem__(self, key, value):
"""Set the valu... | stack_v2_sparse_classes_36k_train_008381 | 9,083 | permissive | [
{
"docstring": "Initialise a sparse numpy array with a given shape :param shape: tuple of integers, where the first index is the number of *non-zero* rows",
"name": "__init__",
"signature": "def __init__(self, shape)"
},
{
"docstring": "Set the value of the next non-zero row :param key: index of... | 3 | null | Implement the Python class `SparseRows` described below.
Class description:
Sparse rows
Method signatures and docstrings:
- def __init__(self, shape): Initialise a sparse numpy array with a given shape :param shape: tuple of integers, where the first index is the number of *non-zero* rows
- def __setitem__(self, key,... | Implement the Python class `SparseRows` described below.
Class description:
Sparse rows
Method signatures and docstrings:
- def __init__(self, shape): Initialise a sparse numpy array with a given shape :param shape: tuple of integers, where the first index is the number of *non-zero* rows
- def __setitem__(self, key,... | 6945d02bc204203a7fb43d70bbf8aa232646158a | <|skeleton|>
class SparseRows:
"""Sparse rows"""
def __init__(self, shape):
"""Initialise a sparse numpy array with a given shape :param shape: tuple of integers, where the first index is the number of *non-zero* rows"""
<|body_0|>
def __setitem__(self, key, value):
"""Set the valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseRows:
"""Sparse rows"""
def __init__(self, shape):
"""Initialise a sparse numpy array with a given shape :param shape: tuple of integers, where the first index is the number of *non-zero* rows"""
self.indices = np.empty(shape[0], dtype='int')
self.array = np.empty(shape)
... | the_stack_v2_python_sparse | src/core/utils.py | guyemerson/sem-func | train | 4 |
d14e88a42aa4d1d53c01c1403d6692a8a5b6ef88 | [
"if data is None and isinstance(lambtha, (float, int)):\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = float(lambtha)\nelif data is not None:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) < 2:\n r... | <|body_start_0|>
if data is None and isinstance(lambtha, (float, int)):
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
self.lambtha = float(lambtha)
elif data is not None:
if not isinstance(data, list):
raise Type... | define class | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""define class"""
def __init__(self, data=None, lambtha=1.0):
"""class constructor"""
<|body_0|>
def pmf(self, k):
"""function that calculates the probability mass function for k successes"""
<|body_1|>
def fact(self, k):
"""functio... | stack_v2_sparse_classes_36k_train_008382 | 1,678 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "function that calculates the probability mass function for k successes",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "function... | 4 | stack_v2_sparse_classes_30k_train_018531 | Implement the Python class `Poisson` described below.
Class description:
define class
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): class constructor
- def pmf(self, k): function that calculates the probability mass function for k successes
- def fact(self, k): function that returns ... | Implement the Python class `Poisson` described below.
Class description:
define class
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): class constructor
- def pmf(self, k): function that calculates the probability mass function for k successes
- def fact(self, k): function that returns ... | 7d3b348aec3b20da25b162b71f150c87c7c28d71 | <|skeleton|>
class Poisson:
"""define class"""
def __init__(self, data=None, lambtha=1.0):
"""class constructor"""
<|body_0|>
def pmf(self, k):
"""function that calculates the probability mass function for k successes"""
<|body_1|>
def fact(self, k):
"""functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poisson:
"""define class"""
def __init__(self, data=None, lambtha=1.0):
"""class constructor"""
if data is None and isinstance(lambtha, (float, int)):
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
self.lambtha = float(lambtha... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | dacastanogo/holbertonschool-machine_learning | train | 0 |
9da2e5b13d4d669d3402defae75d2399f16b14f1 | [
"e = 2.718281828459045\nctx.save_for_backward(x, l, u, g)\ny = l + (u - l) / (1 + e ** (-g * x))\nreturn y",
"e = 2.718281828459045\nx, l, u, g = ctx.saved_tensors\ndzdx = dzdy * (g * (u - l) * e ** (-g * x) / (1 + e ** (-g * x)) ** 2)\ndzdl = dzdy * (1 / (e ** (g * x) + 1))\ndzdu = dzdy * (1 / (e ** (-g * x) + 1... | <|body_start_0|>
e = 2.718281828459045
ctx.save_for_backward(x, l, u, g)
y = l + (u - l) / (1 + e ** (-g * x))
return y
<|end_body_0|>
<|body_start_1|>
e = 2.718281828459045
x, l, u, g = ctx.saved_tensors
dzdx = dzdy * (g * (u - l) * e ** (-g * x) / (1 + e ** (-g... | GeneralizedLogistic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralizedLogistic:
def forward(ctx, x, l, u, g):
"""Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Retu... | stack_v2_sparse_classes_36k_train_008383 | 1,489 | no_license | [
{
"docstring": "Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Returns ------- y: (Tensor) of size (T x n), the outputs of the ge... | 2 | stack_v2_sparse_classes_30k_train_018910 | Implement the Python class `GeneralizedLogistic` described below.
Class description:
Implement the GeneralizedLogistic class.
Method signatures and docstrings:
- def forward(ctx, x, l, u, g): Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the ... | Implement the Python class `GeneralizedLogistic` described below.
Class description:
Implement the GeneralizedLogistic class.
Method signatures and docstrings:
- def forward(ctx, x, l, u, g): Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the ... | b6824c340272f65b8c5fd44fcea2a363a7e69f05 | <|skeleton|>
class GeneralizedLogistic:
def forward(ctx, x, l, u, g):
"""Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralizedLogistic:
def forward(ctx, x, l, u, g):
"""Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Returns ------- y:... | the_stack_v2_python_sparse | homework/Kirsten_Ziman_HW1/generalized_logistic.py | KirstensGitHub/deep_learning | train | 0 | |
4e1ccd6f4a660ce2919ceeac94483ae8dd711e41 | [
"res = [0]\nm = len(matrix)\nif m:\n n = len(matrix[0])\nelse:\n return 0\ndp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\nfor i in range(m):\n for j in range(n):\n if matrix[i][j] == '1':\n if dp[i][j] and dp[i + 1][j] and dp[i][j + 1]:\n dp[i + 1][j + 1] = min(dp[... | <|body_start_0|>
res = [0]
m = len(matrix)
if m:
n = len(matrix[0])
else:
return 0
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare0(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = [0]
m ... | stack_v2_sparse_classes_36k_train_008384 | 1,273 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare0",
"signature": "def maximalSquare0(self, matrix)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare0(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare0(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class Solut... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare0(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
res = [0]
m = len(matrix)
if m:
n = len(matrix[0])
else:
return 0
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m):... | the_stack_v2_python_sparse | PythonCode/src/0221_Maximal_Square.py | oneyuan/CodeforFun | train | 0 | |
23e1ca11a721f01b503928769d2cc82035a8f010 | [
"self.nzbget = NZBGetAPI(config[CONF_HOST], config.get(CONF_USERNAME), config.get(CONF_PASSWORD), config[CONF_SSL], config[CONF_VERIFY_SSL], config[CONF_PORT])\nself._completed_downloads_init = False\nself._completed_downloads = set[tuple]()\nupdate_interval = timedelta(seconds=options[CONF_SCAN_INTERVAL])\nsuper()... | <|body_start_0|>
self.nzbget = NZBGetAPI(config[CONF_HOST], config.get(CONF_USERNAME), config.get(CONF_PASSWORD), config[CONF_SSL], config[CONF_VERIFY_SSL], config[CONF_PORT])
self._completed_downloads_init = False
self._completed_downloads = set[tuple]()
update_interval = timedelta(seco... | Class to manage fetching NZBGet data. | NZBGetDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NZBGetDataUpdateCoordinator:
"""Class to manage fetching NZBGet data."""
def __init__(self, hass: HomeAssistant, *, config: Mapping[str, Any], options: Mapping[str, Any]) -> None:
"""Initialize global NZBGet data updater."""
<|body_0|>
def _check_completed_downloads(self... | stack_v2_sparse_classes_36k_train_008385 | 3,030 | permissive | [
{
"docstring": "Initialize global NZBGet data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, config: Mapping[str, Any], options: Mapping[str, Any]) -> None"
},
{
"docstring": "Check history for newly completed downloads.",
"name": "_check_completed_do... | 3 | stack_v2_sparse_classes_30k_test_000119 | Implement the Python class `NZBGetDataUpdateCoordinator` described below.
Class description:
Class to manage fetching NZBGet data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, config: Mapping[str, Any], options: Mapping[str, Any]) -> None: Initialize global NZBGet data updater.
- def... | Implement the Python class `NZBGetDataUpdateCoordinator` described below.
Class description:
Class to manage fetching NZBGet data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, config: Mapping[str, Any], options: Mapping[str, Any]) -> None: Initialize global NZBGet data updater.
- def... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NZBGetDataUpdateCoordinator:
"""Class to manage fetching NZBGet data."""
def __init__(self, hass: HomeAssistant, *, config: Mapping[str, Any], options: Mapping[str, Any]) -> None:
"""Initialize global NZBGet data updater."""
<|body_0|>
def _check_completed_downloads(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NZBGetDataUpdateCoordinator:
"""Class to manage fetching NZBGet data."""
def __init__(self, hass: HomeAssistant, *, config: Mapping[str, Any], options: Mapping[str, Any]) -> None:
"""Initialize global NZBGet data updater."""
self.nzbget = NZBGetAPI(config[CONF_HOST], config.get(CONF_USERN... | the_stack_v2_python_sparse | homeassistant/components/nzbget/coordinator.py | home-assistant/core | train | 35,501 |
1886a0e1996e1e4538c02e00aed4aa6f5ef99889 | [
"super(Transformer, self).__init__()\nself.encoder = encoder\nself.decoder = decoder\nself.linear = tf.keras.layers.Dense(units=target_vocab, input_shape=([None], [None]))",
"print('============================')\nprint(inputs)\nprint(target)\nprint('============================')\ndec_output = self.decoder.decod... | <|body_start_0|>
super(Transformer, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.linear = tf.keras.layers.Dense(units=target_vocab, input_shape=([None], [None]))
<|end_body_0|>
<|body_start_1|>
print('============================')
print(inputs)
... | The Transformer model class | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""The Transformer model class"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1):
"""init of transformer"""
<|body_0|>
def call(self, inputs, target, training, encoder_mask, loo... | stack_v2_sparse_classes_36k_train_008386 | 1,488 | no_license | [
{
"docstring": "init of transformer",
"name": "__init__",
"signature": "def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1)"
},
{
"docstring": "Calls the transformer",
"name": "call",
"signature": "def call(self,... | 2 | null | Implement the Python class `Transformer` described below.
Class description:
The Transformer model class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): init of transformer
- def call(self, inputs, tar... | Implement the Python class `Transformer` described below.
Class description:
The Transformer model class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1): init of transformer
- def call(self, inputs, tar... | 4200798bdbbe828db94e5585b62a595e3a96c3e6 | <|skeleton|>
class Transformer:
"""The Transformer model class"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1):
"""init of transformer"""
<|body_0|>
def call(self, inputs, target, training, encoder_mask, loo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""The Transformer model class"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, encoder, decoder, drop_rate=0.1):
"""init of transformer"""
super(Transformer, self).__init__()
self.encoder = encoder
self.decoder... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | JohnCook17/holbertonschool-machine_learning | train | 3 |
420fabc4c13777bf3a4a7a4796063b42e8a8e741 | [
"self.num_elem = self.kwargs['num_elem']\nnum_pts = self.num_elem + 1\nind_pts = range(num_pts)\nself._declare_variable('Temp', size=num_pts, lower=0.001)\nself._declare_argument('h', indices=ind_pts)",
"pvec = self.vec['p']\nuvec = self.vec['u']\nalt = pvec('h') * 1000.0\ntemp = uvec('Temp')\ntemp[:] = (288.16 -... | <|body_start_0|>
self.num_elem = self.kwargs['num_elem']
num_pts = self.num_elem + 1
ind_pts = range(num_pts)
self._declare_variable('Temp', size=num_pts, lower=0.001)
self._declare_argument('h', indices=ind_pts)
<|end_body_0|>
<|body_start_1|>
pvec = self.vec['p']
... | linear temperature model using the standard atmosphere | SysTempOld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SysTempOld:
"""linear temperature model using the standard atmosphere"""
def _declare(self):
"""owned variable: Temp (temperature) dependencies: h (altitude)"""
<|body_0|>
def apply_G(self):
"""temperature model extracted from linear portion of the standard atmos... | stack_v2_sparse_classes_36k_train_008387 | 17,488 | no_license | [
{
"docstring": "owned variable: Temp (temperature) dependencies: h (altitude)",
"name": "_declare",
"signature": "def _declare(self)"
},
{
"docstring": "temperature model extracted from linear portion of the standard atmosphere",
"name": "apply_G",
"signature": "def apply_G(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_009852 | Implement the Python class `SysTempOld` described below.
Class description:
linear temperature model using the standard atmosphere
Method signatures and docstrings:
- def _declare(self): owned variable: Temp (temperature) dependencies: h (altitude)
- def apply_G(self): temperature model extracted from linear portion ... | Implement the Python class `SysTempOld` described below.
Class description:
linear temperature model using the standard atmosphere
Method signatures and docstrings:
- def _declare(self): owned variable: Temp (temperature) dependencies: h (altitude)
- def apply_G(self): temperature model extracted from linear portion ... | f5b1ce287c6692540b738a7e9ec85be645f4947a | <|skeleton|>
class SysTempOld:
"""linear temperature model using the standard atmosphere"""
def _declare(self):
"""owned variable: Temp (temperature) dependencies: h (altitude)"""
<|body_0|>
def apply_G(self):
"""temperature model extracted from linear portion of the standard atmos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SysTempOld:
"""linear temperature model using the standard atmosphere"""
def _declare(self):
"""owned variable: Temp (temperature) dependencies: h (altitude)"""
self.num_elem = self.kwargs['num_elem']
num_pts = self.num_elem + 1
ind_pts = range(num_pts)
self._decla... | the_stack_v2_python_sparse | cmf_original_code/atmospherics.py | naylor-b/pyMission | train | 0 |
5c53351570bfcd2c3247bc5f9fd70e3ce2d882b4 | [
"if model._meta.app_label == 'data_source':\n return 'moodle'\nif model._meta.app_label == 'export':\n return 'cassandra'\nreturn None",
"if model._meta.app_label == 'data_source':\n raise Exception('No writing to Moodle DB allowed.')\nif model._meta.app_label == 'export':\n return 'cassandra'\nreturn... | <|body_start_0|>
if model._meta.app_label == 'data_source':
return 'moodle'
if model._meta.app_label == 'export':
return 'cassandra'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'data_source':
raise Exception('No writing to ... | A router to control all database operations on models in the applications listed in route_app_labels. | Router | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Router:
"""A router to control all database operations on models in the applications listed in route_app_labels."""
def db_for_read(self, model, **hints):
"""db to use to read models listed in in apps route_app_labels."""
<|body_0|>
def db_for_write(self, model, **hints)... | stack_v2_sparse_classes_36k_train_008388 | 1,669 | permissive | [
{
"docstring": "db to use to read models listed in in apps route_app_labels.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "db to use to write models listed in in apps route_app_labels. Beware that save() and delete() are not supposed to happen",... | 4 | stack_v2_sparse_classes_30k_train_013654 | Implement the Python class `Router` described below.
Class description:
A router to control all database operations on models in the applications listed in route_app_labels.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): db to use to read models listed in in apps route_app_labels.
- def db... | Implement the Python class `Router` described below.
Class description:
A router to control all database operations on models in the applications listed in route_app_labels.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): db to use to read models listed in in apps route_app_labels.
- def db... | e2d3fa7eb65bc32345acbda28fc4c7fb775f65cb | <|skeleton|>
class Router:
"""A router to control all database operations on models in the applications listed in route_app_labels."""
def db_for_read(self, model, **hints):
"""db to use to read models listed in in apps route_app_labels."""
<|body_0|>
def db_for_write(self, model, **hints)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Router:
"""A router to control all database operations on models in the applications listed in route_app_labels."""
def db_for_read(self, model, **hints):
"""db to use to read models listed in in apps route_app_labels."""
if model._meta.app_label == 'data_source':
return 'mood... | the_stack_v2_python_sparse | assessment_ms/app/app/db.py | jakobschroeber/bachelor_thesis | train | 0 |
3e703feef06773e70218659a7d05eddd42bacc99 | [
"self.words = dict()\nfor i, w in enumerate(words):\n self.words[w] = self.words.get(w, []) + [i]",
"result = float('inf')\nw1 = self.words.get(word1)\nw2 = self.words.get(word2)\ni1 = 0\ni2 = 0\nwhile i1 < len(w1) and i2 < len(w2):\n if w1[i1] < w2[i2]:\n result = min(result, w2[i2] - w1[i1])\n ... | <|body_start_0|>
self.words = dict()
for i, w in enumerate(words):
self.words[w] = self.words.get(w, []) + [i]
<|end_body_0|>
<|body_start_1|>
result = float('inf')
w1 = self.words.get(word1)
w2 = self.words.get(word2)
i1 = 0
i2 = 0
while i1 <... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.words = dict()
for i, w ... | stack_v2_sparse_classes_36k_train_008389 | 1,033 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 36cb33af758b1d01da35982481a8bbfbee5c2810 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.words = dict()
for i, w in enumerate(words):
self.words[w] = self.words.get(w, []) + [i]
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
res... | the_stack_v2_python_sparse | LeetCode/shortestWordDistance2.py | dicao425/algorithmExercise | train | 0 | |
1dd8840793332f3881cebaa3f1442f2d61a55931 | [
"self.TIDAL_CLIENT_VERSION = '1.9.1'\nself.TIDAL_API_BASE = 'https://api.tidalhifi.com/v1/'\nself.username = username\nself.token = token\nself.unique_id = str(uuid.uuid4()).replace('-', '')[16:]\nself.auth(password)\npassword = None",
"postParams = {'username': self.username, 'password': password, 'token': self.... | <|body_start_0|>
self.TIDAL_CLIENT_VERSION = '1.9.1'
self.TIDAL_API_BASE = 'https://api.tidalhifi.com/v1/'
self.username = username
self.token = token
self.unique_id = str(uuid.uuid4()).replace('-', '')[16:]
self.auth(password)
password = None
<|end_body_0|>
<|bo... | Tidal session object which can be used to communicate with Tidal servers | TidalSession | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TidalSession:
"""Tidal session object which can be used to communicate with Tidal servers"""
def __init__(self, username, password, token='4zx46pyr9o8qZNRw'):
"""Initiate a new session"""
<|body_0|>
def auth(self, password):
"""Attempts to authorize and create a ... | stack_v2_sparse_classes_36k_train_008390 | 8,327 | permissive | [
{
"docstring": "Initiate a new session",
"name": "__init__",
"signature": "def __init__(self, username, password, token='4zx46pyr9o8qZNRw')"
},
{
"docstring": "Attempts to authorize and create a new valid session",
"name": "auth",
"signature": "def auth(self, password)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_011504 | Implement the Python class `TidalSession` described below.
Class description:
Tidal session object which can be used to communicate with Tidal servers
Method signatures and docstrings:
- def __init__(self, username, password, token='4zx46pyr9o8qZNRw'): Initiate a new session
- def auth(self, password): Attempts to au... | Implement the Python class `TidalSession` described below.
Class description:
Tidal session object which can be used to communicate with Tidal servers
Method signatures and docstrings:
- def __init__(self, username, password, token='4zx46pyr9o8qZNRw'): Initiate a new session
- def auth(self, password): Attempts to au... | 2a7e339b97f173efa319abc5e4ec8fc9172f1505 | <|skeleton|>
class TidalSession:
"""Tidal session object which can be used to communicate with Tidal servers"""
def __init__(self, username, password, token='4zx46pyr9o8qZNRw'):
"""Initiate a new session"""
<|body_0|>
def auth(self, password):
"""Attempts to authorize and create a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TidalSession:
"""Tidal session object which can be used to communicate with Tidal servers"""
def __init__(self, username, password, token='4zx46pyr9o8qZNRw'):
"""Initiate a new session"""
self.TIDAL_CLIENT_VERSION = '1.9.1'
self.TIDAL_API_BASE = 'https://api.tidalhifi.com/v1/'
... | the_stack_v2_python_sparse | bin/redsea/tidal_api.py | SultanSGillani/dotfiles | train | 7 |
cdc578138d2b4d7413dcd6cdffb9d7717708b746 | [
"r = [str(len(strs))]\nfor s in strs:\n r.append(str(len(s)))\n r.append(s)\nreturn ' '.join(r)",
"q = 0\np = s.find(' ')\np = p if p > 0 else len(s)\nlistlen = int(s[q:p])\nstrs = []\nfor _ in xrange(listlen):\n q = p + 1\n p = s.find(' ', q)\n strlen = int(s[q:p])\n q = p + 1\n p = q + strl... | <|body_start_0|>
r = [str(len(strs))]
for s in strs:
r.append(str(len(s)))
r.append(s)
return ' '.join(r)
<|end_body_0|>
<|body_start_1|>
q = 0
p = s.find(' ')
p = p if p > 0 else len(s)
listlen = int(s[q:p])
strs = []
for ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_008391 | 877 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_013635 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 20580185c6f72f3c09a725168af48893156161f5 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
r = [str(len(strs))]
for s in strs:
r.append(str(len(s)))
r.append(s)
return ' '.join(r)
def decode(self, s):
"""Decodes a s... | the_stack_v2_python_sparse | coding/00271-encode-decode-str/solution.py | misaka-10032/leetcode | train | 3 | |
973014ada78ac62a8b1c58f59d1ac5619de47fee | [
"import matplotlib.pyplot\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = matplotlib.pyplot.figure()\naxs = fig.add_subplot(1, 1, 1, projection='3d')\naxs.plot_trisurf(V[:, 0], V[:, 1], V[:, 2], triangles=F)\naxs.set_xlabel('x')\naxs.set_ylabel('y')\naxs.set_zlabel('z')\naxs.axis('equal')\nmatplotlib.pyplot.show()\... | <|body_start_0|>
import matplotlib.pyplot
from mpl_toolkits.mplot3d import Axes3D
fig = matplotlib.pyplot.figure()
axs = fig.add_subplot(1, 1, 1, projection='3d')
axs.plot_trisurf(V[:, 0], V[:, 1], V[:, 2], triangles=F)
axs.set_xlabel('x')
axs.set_ylabel('y')
... | Define all of my functions within a class to keep the global name space clean. | myfuncs | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myfuncs:
"""Define all of my functions within a class to keep the global name space clean."""
def qp(F, V):
"""Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy arr... | stack_v2_sparse_classes_36k_train_008392 | 2,695 | permissive | [
{
"docstring": "Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy array of faces (V1, V2, V3) V : Nx3 NumPy array of vertexes ( X, Y, Z)",
"name": "qp",
"signature": "def qp(F, V)"
}... | 2 | stack_v2_sparse_classes_30k_train_015381 | Implement the Python class `myfuncs` described below.
Class description:
Define all of my functions within a class to keep the global name space clean.
Method signatures and docstrings:
- def qp(F, V): Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is ... | Implement the Python class `myfuncs` described below.
Class description:
Define all of my functions within a class to keep the global name space clean.
Method signatures and docstrings:
- def qp(F, V): Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is ... | c4fbebe26b09dde93249293ce3db2e71936a894b | <|skeleton|>
class myfuncs:
"""Define all of my functions within a class to keep the global name space clean."""
def qp(F, V):
"""Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy arr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class myfuncs:
"""Define all of my functions within a class to keep the global name space clean."""
def qp(F, V):
"""Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy array of faces (... | the_stack_v2_python_sparse | ipython/profile_default/startup/50_myfuncs.py | kprussing/dotfiles | train | 1 |
6092746b461e8423478ff35b1dc045f10190790a | [
"num_dic = {}\nfor i, num in enumerate(numbers):\n if num_dic.get(target - num) is not None:\n return [num_dic.get(target - num) + 1, i + 1]\n else:\n num_dic[num] = i\nreturn [-1, -1]",
"left, right = (0, len(numbers) - 1)\nwhile left < right:\n sums = numbers[left] + numbers[right]\n i... | <|body_start_0|>
num_dic = {}
for i, num in enumerate(numbers):
if num_dic.get(target - num) is not None:
return [num_dic.get(target - num) + 1, i + 1]
else:
num_dic[num] = i
return [-1, -1]
<|end_body_0|>
<|body_start_1|>
left, ri... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
"""字典边存边查看是否满足"""
<|body_0|>
def twoSum_(self, numbers, target):
"""双指针法:有效利用有序数组这个条件"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num_dic = {}
for i, num in enumerate(numbers):
if ... | stack_v2_sparse_classes_36k_train_008393 | 1,765 | no_license | [
{
"docstring": "字典边存边查看是否满足",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": "双指针法:有效利用有序数组这个条件",
"name": "twoSum_",
"signature": "def twoSum_(self, numbers, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014817 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): 字典边存边查看是否满足
- def twoSum_(self, numbers, target): 双指针法:有效利用有序数组这个条件 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): 字典边存边查看是否满足
- def twoSum_(self, numbers, target): 双指针法:有效利用有序数组这个条件
<|skeleton|>
class Solution:
def twoSum(self, numbers, target):
... | 2e81b871bf1db7ea7432d1ebf889c72066e64753 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
"""字典边存边查看是否满足"""
<|body_0|>
def twoSum_(self, numbers, target):
"""双指针法:有效利用有序数组这个条件"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers, target):
"""字典边存边查看是否满足"""
num_dic = {}
for i, num in enumerate(numbers):
if num_dic.get(target - num) is not None:
return [num_dic.get(target - num) + 1, i + 1]
else:
num_dic[num] = i
r... | the_stack_v2_python_sparse | array/twoSum.py | NextNight/LeetCodeAndStructAndAlgorithm | train | 0 | |
852d747b43a63cccaedfd6a77a1248f772c33014 | [
"len_n, right_most = (len(nums), 0)\nfor i in range(len_n):\n if i <= right_most:\n right_most = max(nums[i] + i, right_most)\n if right_most >= len_n - 1:\n return True\nreturn False",
"len_n = len(nums)\ndp = [False] * len_n\ndp[0] = True\nfor i in range(len_n):\n if dp[i]:\n ... | <|body_start_0|>
len_n, right_most = (len(nums), 0)
for i in range(len_n):
if i <= right_most:
right_most = max(nums[i] + i, right_most)
if right_most >= len_n - 1:
return True
return False
<|end_body_0|>
<|body_start_1|>
l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户"""
<|body_0|>
def canJump1(self, nums: List[int]) -> bool:
"""超时"""
<|body_1|>
def jump1(self, nums: List[int... | stack_v2_sparse_classes_36k_train_008394 | 4,093 | no_license | [
{
"docstring": "执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户",
"name": "canJump",
"signature": "def canJump(self, nums: List[int]) -> bool"
},
{
"docstring": "超时",
"name": "canJump1",
"signature": "def canJump1(self, nums: List[int]) -> bool"
... | 4 | stack_v2_sparse_classes_30k_train_011064 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: List[int]) -> bool: 执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户
- def canJump1(self, nums: List[int]) -> bool:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: List[int]) -> bool: 执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户
- def canJump1(self, nums: List[int]) -> bool:... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户"""
<|body_0|>
def canJump1(self, nums: List[int]) -> bool:
"""超时"""
<|body_1|>
def jump1(self, nums: List[int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums: List[int]) -> bool:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户"""
len_n, right_most = (len(nums), 0)
for i in range(len_n):
if i <= right_most:
right_most = max(nums[i] + i, ri... | the_stack_v2_python_sparse | 跳跃游戏1&2.py | nomboy/leetcode | train | 0 | |
e4ff882ac432ed2ee43f9e7487b700100fccbea4 | [
"super(QuickShift, self).__init__(paramlist)\nself.params['algorithm'] = 'QuickShift'\nself.params['alpha1'] = 0.5\nself.params['beta1'] = 0.5\nself.params['beta2'] = 0.5\nself.paramindexes = ['alpha1', 'beta1', 'beta2']\nself.set_params(paramlist)",
"mindim = min(img.shape)\nratio = self.params['alpha1']\nkernel... | <|body_start_0|>
super(QuickShift, self).__init__(paramlist)
self.params['algorithm'] = 'QuickShift'
self.params['alpha1'] = 0.5
self.params['beta1'] = 0.5
self.params['beta2'] = 0.5
self.paramindexes = ['alpha1', 'beta1', 'beta2']
self.set_params(paramlist)
<|end... | Perform the Quick Shift segmentation algorithm. Segments images with quickshift clustering in Color (x,y) space. Returns ndarray segmentation mask of the labels. Parameters: image -- ndarray, input image ratio -- float, balances color-space proximity & image-space proximity. Higher vals give more weight to color-space ... | QuickShift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuickShift:
"""Perform the Quick Shift segmentation algorithm. Segments images with quickshift clustering in Color (x,y) space. Returns ndarray segmentation mask of the labels. Parameters: image -- ndarray, input image ratio -- float, balances color-space proximity & image-space proximity. Higher... | stack_v2_sparse_classes_36k_train_008395 | 29,598 | permissive | [
{
"docstring": "Get parameters from parameter list that are used in segmentation algorithm. Assign default values to these parameters.",
"name": "__init__",
"signature": "def __init__(self, paramlist=None)"
},
{
"docstring": "Evaluate segmentation algorithm on training image. Keyword arguments: ... | 2 | stack_v2_sparse_classes_30k_test_000327 | Implement the Python class `QuickShift` described below.
Class description:
Perform the Quick Shift segmentation algorithm. Segments images with quickshift clustering in Color (x,y) space. Returns ndarray segmentation mask of the labels. Parameters: image -- ndarray, input image ratio -- float, balances color-space pr... | Implement the Python class `QuickShift` described below.
Class description:
Perform the Quick Shift segmentation algorithm. Segments images with quickshift clustering in Color (x,y) space. Returns ndarray segmentation mask of the labels. Parameters: image -- ndarray, input image ratio -- float, balances color-space pr... | 9246b8b20510d4c89357a6764ed96b919eb92d5a | <|skeleton|>
class QuickShift:
"""Perform the Quick Shift segmentation algorithm. Segments images with quickshift clustering in Color (x,y) space. Returns ndarray segmentation mask of the labels. Parameters: image -- ndarray, input image ratio -- float, balances color-space proximity & image-space proximity. Higher... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuickShift:
"""Perform the Quick Shift segmentation algorithm. Segments images with quickshift clustering in Color (x,y) space. Returns ndarray segmentation mask of the labels. Parameters: image -- ndarray, input image ratio -- float, balances color-space proximity & image-space proximity. Higher vals give mo... | the_stack_v2_python_sparse | see/Segmentors.py | Deepak768/see-segment | train | 0 |
03a5f5f33e6f3e79a050006d374c6dfd10a08ffc | [
"self.rects = rects\nself.sizes = list(map(lambda x: (x[2] - x[0] + 1) * (x[3] - x[1] + 1), rects))\nself.weights = list(accumulate(self.sizes))",
"r = random.randrange(0, self.weights[-1])\nidx = bisect(self.weights, r)\noffset = self.sizes[idx] + r - self.weights[idx]\nwidth = self.rects[idx][2] - self.rects[id... | <|body_start_0|>
self.rects = rects
self.sizes = list(map(lambda x: (x[2] - x[0] + 1) * (x[3] - x[1] + 1), rects))
self.weights = list(accumulate(self.sizes))
<|end_body_0|>
<|body_start_1|>
r = random.randrange(0, self.weights[-1])
idx = bisect(self.weights, r)
offset =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
self.sizes = list(map(lambda x: (x[2] - x[0] + 1) * (x... | stack_v2_sparse_classes_36k_train_008396 | 820 | permissive | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | b07f7ba69f3d2a7e294f915934db302f43c0848f | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
self.sizes = list(map(lambda x: (x[2] - x[0] + 1) * (x[3] - x[1] + 1), rects))
self.weights = list(accumulate(self.sizes))
def pick(self):
""":rtype: List[int]"""
r =... | the_stack_v2_python_sparse | algorithms/python/497.py | viing937/leetcode | train | 3 | |
249603cafd61a4eee2a3a77fefbe57ad8b700bab | [
"user = cls._from_database('SELECT * FROM users WHERE google_id = %s', (google_id,))\nif user is not None:\n return user\nreturn User()",
"user = cls._from_database('SELECT * FROM users WHERE email = %s', (email,))\nif user is not None:\n return user\nreturn User()",
"if authorization_level in ['EDIT', 'O... | <|body_start_0|>
user = cls._from_database('SELECT * FROM users WHERE google_id = %s', (google_id,))
if user is not None:
return user
return User()
<|end_body_0|>
<|body_start_1|>
user = cls._from_database('SELECT * FROM users WHERE email = %s', (email,))
if user is ... | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def from_google_id(cls, google_id):
"""Initialize a User by fetching them by their google id."""
<|body_0|>
def from_email(cls, email):
"""Initialize a User by fetching them by their email."""
<|body_1|>
def google_id_has_at_least(self, google_id, ... | stack_v2_sparse_classes_36k_train_008397 | 1,275 | permissive | [
{
"docstring": "Initialize a User by fetching them by their google id.",
"name": "from_google_id",
"signature": "def from_google_id(cls, google_id)"
},
{
"docstring": "Initialize a User by fetching them by their email.",
"name": "from_email",
"signature": "def from_email(cls, email)"
}... | 3 | null | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def from_google_id(cls, google_id): Initialize a User by fetching them by their google id.
- def from_email(cls, email): Initialize a User by fetching them by their email.
- def google_i... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def from_google_id(cls, google_id): Initialize a User by fetching them by their google id.
- def from_email(cls, email): Initialize a User by fetching them by their email.
- def google_i... | 71aa937a9b7db7289d69ac85587387070d2af851 | <|skeleton|>
class User:
def from_google_id(cls, google_id):
"""Initialize a User by fetching them by their google id."""
<|body_0|>
def from_email(cls, email):
"""Initialize a User by fetching them by their email."""
<|body_1|>
def google_id_has_at_least(self, google_id, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
def from_google_id(cls, google_id):
"""Initialize a User by fetching them by their google id."""
user = cls._from_database('SELECT * FROM users WHERE google_id = %s', (google_id,))
if user is not None:
return user
return User()
def from_email(cls, email):... | the_stack_v2_python_sparse | opendc/models/user.py | atlarge-research/opendc-web-server | train | 2 | |
e1fb48ad6c99e4875eacb656070cdb520fe327f7 | [
"template_values = {}\ntemplate_values['page_title'] = handler.format_title('Local Chapters')\ncontent = safe_dom.NodeList()\ncontent.append(safe_dom.Element('a', id='add_local_chapter', className='gcb-button gcb-pull-right', role='button', href='%s?action=add_local_chapter' % handler.LINK_URL).add_text('Add Local ... | <|body_start_0|>
template_values = {}
template_values['page_title'] = handler.format_title('Local Chapters')
content = safe_dom.NodeList()
content.append(safe_dom.Element('a', id='add_local_chapter', className='gcb-button gcb-pull-right', role='button', href='%s?action=add_local_chapter'... | LocalChapterBaseAdminHandler | [
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalChapterBaseAdminHandler:
def get_local_chapters(self, handler):
"""Shows a list of all local chapters available on this site."""
<|body_0|>
def get_add_local_chapter(self, handler):
"""Handles 'get_add_local_chapter' action and renders new course entry editor.""... | stack_v2_sparse_classes_36k_train_008398 | 20,021 | permissive | [
{
"docstring": "Shows a list of all local chapters available on this site.",
"name": "get_local_chapters",
"signature": "def get_local_chapters(self, handler)"
},
{
"docstring": "Handles 'get_add_local_chapter' action and renders new course entry editor.",
"name": "get_add_local_chapter",
... | 4 | null | Implement the Python class `LocalChapterBaseAdminHandler` described below.
Class description:
Implement the LocalChapterBaseAdminHandler class.
Method signatures and docstrings:
- def get_local_chapters(self, handler): Shows a list of all local chapters available on this site.
- def get_add_local_chapter(self, handle... | Implement the Python class `LocalChapterBaseAdminHandler` described below.
Class description:
Implement the LocalChapterBaseAdminHandler class.
Method signatures and docstrings:
- def get_local_chapters(self, handler): Shows a list of all local chapters available on this site.
- def get_add_local_chapter(self, handle... | 2bca9d64499e160b2da9bed6e97fcda712feec72 | <|skeleton|>
class LocalChapterBaseAdminHandler:
def get_local_chapters(self, handler):
"""Shows a list of all local chapters available on this site."""
<|body_0|>
def get_add_local_chapter(self, handler):
"""Handles 'get_add_local_chapter' action and renders new course entry editor.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalChapterBaseAdminHandler:
def get_local_chapters(self, handler):
"""Shows a list of all local chapters available on this site."""
template_values = {}
template_values['page_title'] = handler.format_title('Local Chapters')
content = safe_dom.NodeList()
content.append... | the_stack_v2_python_sparse | coursebuilder/modules/local_chapter/local_chapter.py | RavinderSinghPB/seek | train | 0 | |
9c0c3b64e469c154e4385b71e27e8bd3a22eebf6 | [
"query = {'uuid': bundle_id}\nprojection = {'_id': False, 'files': False}\nlogging.debug(f'MONGO-START: db.Bundles.find_one(filter={query}, projection={projection})')\nret = await self.db.Bundles.find_one(filter=query, projection=projection)\nlogging.debug('MONGO-END: db.Bundles.find_one(filter, projection)')\nif... | <|body_start_0|>
query = {'uuid': bundle_id}
projection = {'_id': False, 'files': False}
logging.debug(f'MONGO-START: db.Bundles.find_one(filter={query}, projection={projection})')
ret = await self.db.Bundles.find_one(filter=query, projection=projection)
logging.debug('MONGO-END:... | BundlesSingleHandler handles object level routes for Bundles. | BundlesSingleHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BundlesSingleHandler:
"""BundlesSingleHandler handles object level routes for Bundles."""
async def get(self, bundle_id: str) -> None:
"""Handle GET /Bundles/{uuid}."""
<|body_0|>
async def patch(self, bundle_id: str) -> None:
"""Handle PATCH /Bundles/{uuid}."""
... | stack_v2_sparse_classes_36k_train_008399 | 42,572 | permissive | [
{
"docstring": "Handle GET /Bundles/{uuid}.",
"name": "get",
"signature": "async def get(self, bundle_id: str) -> None"
},
{
"docstring": "Handle PATCH /Bundles/{uuid}.",
"name": "patch",
"signature": "async def patch(self, bundle_id: str) -> None"
},
{
"docstring": "Handle DELET... | 3 | stack_v2_sparse_classes_30k_train_000909 | Implement the Python class `BundlesSingleHandler` described below.
Class description:
BundlesSingleHandler handles object level routes for Bundles.
Method signatures and docstrings:
- async def get(self, bundle_id: str) -> None: Handle GET /Bundles/{uuid}.
- async def patch(self, bundle_id: str) -> None: Handle PATCH... | Implement the Python class `BundlesSingleHandler` described below.
Class description:
BundlesSingleHandler handles object level routes for Bundles.
Method signatures and docstrings:
- async def get(self, bundle_id: str) -> None: Handle GET /Bundles/{uuid}.
- async def patch(self, bundle_id: str) -> None: Handle PATCH... | 12719efa84be2281debe98a18c69bbe7a6d0f399 | <|skeleton|>
class BundlesSingleHandler:
"""BundlesSingleHandler handles object level routes for Bundles."""
async def get(self, bundle_id: str) -> None:
"""Handle GET /Bundles/{uuid}."""
<|body_0|>
async def patch(self, bundle_id: str) -> None:
"""Handle PATCH /Bundles/{uuid}."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BundlesSingleHandler:
"""BundlesSingleHandler handles object level routes for Bundles."""
async def get(self, bundle_id: str) -> None:
"""Handle GET /Bundles/{uuid}."""
query = {'uuid': bundle_id}
projection = {'_id': False, 'files': False}
logging.debug(f'MONGO-START: db.... | the_stack_v2_python_sparse | lta/rest_server.py | blinkdog/lta | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.