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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a55f1bdd4819f89d5c11908d82ca01631cefb29e | [
"if conn_string and (not Meta.ready):\n url = urlparse(conn_string)\n Meta.conn_string = conn_string\n Meta.DBNAME = url.path[1:]\n Meta.DBUSER = url.username\n Meta.DBPWD = url.password\n Meta.DBPORT = url.port\n Meta.postgres = url.scheme.startswith('postgres')\n Meta.ready = Meta.postgres... | <|body_start_0|>
if conn_string and (not Meta.ready):
url = urlparse(conn_string)
Meta.conn_string = conn_string
Meta.DBNAME = url.path[1:]
Meta.DBUSER = url.username
Meta.DBPWD = url.password
Meta.DBPORT = url.port
Meta.postgre... | Singleton-like metadata class for all global variables. Adapted from the Unique Design Pattern: https://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python | Meta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meta:
"""Singleton-like metadata class for all global variables. Adapted from the Unique Design Pattern: https://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python"""
def init(cls, conn_string=None):
"""Return the unique Meta class... | stack_v2_sparse_classes_36k_train_018400 | 3,027 | permissive | [
{
"docstring": "Return the unique Meta class.",
"name": "init",
"signature": "def init(cls, conn_string=None)"
},
{
"docstring": "Initialize the storage schema. This call must be performed after all classes that extend Base are declared to ensure the storage schema is initialized.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_014201 | Implement the Python class `Meta` described below.
Class description:
Singleton-like metadata class for all global variables. Adapted from the Unique Design Pattern: https://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python
Method signatures and docstrings:
- def ... | Implement the Python class `Meta` described below.
Class description:
Singleton-like metadata class for all global variables. Adapted from the Unique Design Pattern: https://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python
Method signatures and docstrings:
- def ... | 362aa56afe60194498c8e0a67b37053abebf04a2 | <|skeleton|>
class Meta:
"""Singleton-like metadata class for all global variables. Adapted from the Unique Design Pattern: https://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python"""
def init(cls, conn_string=None):
"""Return the unique Meta class... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Meta:
"""Singleton-like metadata class for all global variables. Adapted from the Unique Design Pattern: https://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python"""
def init(cls, conn_string=None):
"""Return the unique Meta class."""
... | the_stack_v2_python_sparse | fonduer/meta.py | stevenMevans/fonduer | train | 1 |
bb3df1b6deee5fd72dd41509c19491e442ec820b | [
"max_y, max_x = scr.getmaxyx()\npw = max_x - 4\nph = (max_y - 7) // 2\ncx = max_x // 2\ny = 1\nself.found_list = StreamSelectComponent('found', 7, cx - pw // 2, y, pw, ph, 'Found', where(os.getcwd(), fpat, cpat, recurse, scr))\ny += ph\nself.preview = FileBrowseComponent('browse', 8, cx - pw // 2, y, pw, ph, 'Previ... | <|body_start_0|>
max_y, max_x = scr.getmaxyx()
pw = max_x - 4
ph = (max_y - 7) // 2
cx = max_x // 2
y = 1
self.found_list = StreamSelectComponent('found', 7, cx - pw // 2, y, pw, ph, 'Found', where(os.getcwd(), fpat, cpat, recurse, scr))
y += ph
self.previ... | dialog subclass that implements a file find dialog with a list of found files/lines preview window and fields for file pattern, contents pattern, recursive search, starting path, buttons for opening the current file in the editor, search again, and cancel | FileFindDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileFindDialog:
"""dialog subclass that implements a file find dialog with a list of found files/lines preview window and fields for file pattern, contents pattern, recursive search, starting path, buttons for opening the current file in the editor, search again, and cancel"""
def __init__(s... | stack_v2_sparse_classes_36k_train_018401 | 7,426 | permissive | [
{
"docstring": "takes the curses window to pop up over, title to display, will dynamically size to parent window",
"name": "__init__",
"signature": "def __init__(self, scr, title='File Find Dialog', fpat='.*', cpat='', recurse=False)"
},
{
"docstring": "handles found file selection, populating t... | 2 | stack_v2_sparse_classes_30k_train_012666 | Implement the Python class `FileFindDialog` described below.
Class description:
dialog subclass that implements a file find dialog with a list of found files/lines preview window and fields for file pattern, contents pattern, recursive search, starting path, buttons for opening the current file in the editor, search a... | Implement the Python class `FileFindDialog` described below.
Class description:
dialog subclass that implements a file find dialog with a list of found files/lines preview window and fields for file pattern, contents pattern, recursive search, starting path, buttons for opening the current file in the editor, search a... | f753ca27e4462c321ed28f00e1ef47fbde62990e | <|skeleton|>
class FileFindDialog:
"""dialog subclass that implements a file find dialog with a list of found files/lines preview window and fields for file pattern, contents pattern, recursive search, starting path, buttons for opening the current file in the editor, search again, and cancel"""
def __init__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileFindDialog:
"""dialog subclass that implements a file find dialog with a list of found files/lines preview window and fields for file pattern, contents pattern, recursive search, starting path, buttons for opening the current file in the editor, search again, and cancel"""
def __init__(self, scr, tit... | the_stack_v2_python_sparse | ped_dialog/file_find.py | jpfxgood/ped | train | 1 |
2b23c9094096eab790e874c2e645bdb5d6575f4c | [
"flags.GetRequiredRepoFlag().AddToParser(parser)\nparser.add_argument('--destination', metavar='DESTINATION', required=True, help='The path where you want to save the downloaded file.')\nparser.add_argument('--package', metavar='ARTIFACT', required=True, help='The artifact to download.')\nparser.add_argument('--ver... | <|body_start_0|>
flags.GetRequiredRepoFlag().AddToParser(parser)
parser.add_argument('--destination', metavar='DESTINATION', required=True, help='The path where you want to save the downloaded file.')
parser.add_argument('--package', metavar='ARTIFACT', required=True, help='The artifact to downl... | Download a generic artifact from a generic artifact repository. | Download | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Download:
"""Download a generic artifact from a generic artifact repository."""
def Args(parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
<|body_0|>
def Run(self, args):
"""Run the generic artifact download command."""
... | stack_v2_sparse_classes_36k_train_018402 | 3,333 | permissive | [
{
"docstring": "Set up arguments for this command. Args: parser: An argparse.ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run the generic artifact download command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015240 | Implement the Python class `Download` described below.
Class description:
Download a generic artifact from a generic artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguments for this command. Args: parser: An argparse.ArgumentParser.
- def Run(self, args): Run the generic artifact d... | Implement the Python class `Download` described below.
Class description:
Download a generic artifact from a generic artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguments for this command. Args: parser: An argparse.ArgumentParser.
- def Run(self, args): Run the generic artifact d... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Download:
"""Download a generic artifact from a generic artifact repository."""
def Args(parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
<|body_0|>
def Run(self, args):
"""Run the generic artifact download command."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Download:
"""Download a generic artifact from a generic artifact repository."""
def Args(parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
flags.GetRequiredRepoFlag().AddToParser(parser)
parser.add_argument('--destination', metavar='DESTIN... | the_stack_v2_python_sparse | lib/surface/artifacts/generic/download.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
475bdf8154608f3adc3bf942e29663cff6dd85dc | [
"if len(nums) < 2:\n return nums\nmid = len(nums) // 2\nleft_nums = self.sortArray(nums[:mid])\nright_nums = self.sortArray(nums[mid:])\nreturn self.merge(left_nums, right_nums)",
"resusts = []\nwhile 1:\n if left_nums and right_nums:\n if left_nums[0] < right_nums[0]:\n mim_num, left_nums... | <|body_start_0|>
if len(nums) < 2:
return nums
mid = len(nums) // 2
left_nums = self.sortArray(nums[:mid])
right_nums = self.sortArray(nums[mid:])
return self.merge(left_nums, right_nums)
<|end_body_0|>
<|body_start_1|>
resusts = []
while 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortArray(self, nums):
"""归并排序 :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def merge(self, left_nums, right_nums):
"""合并子问题 :param left_nums: :param right_nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(... | stack_v2_sparse_classes_36k_train_018403 | 1,433 | no_license | [
{
"docstring": "归并排序 :type nums: List[int] :rtype: List[int]",
"name": "sortArray",
"signature": "def sortArray(self, nums)"
},
{
"docstring": "合并子问题 :param left_nums: :param right_nums: :return:",
"name": "merge",
"signature": "def merge(self, left_nums, right_nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortArray(self, nums): 归并排序 :type nums: List[int] :rtype: List[int]
- def merge(self, left_nums, right_nums): 合并子问题 :param left_nums: :param right_nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortArray(self, nums): 归并排序 :type nums: List[int] :rtype: List[int]
- def merge(self, left_nums, right_nums): 合并子问题 :param left_nums: :param right_nums: :return:
<|skeleton|... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def sortArray(self, nums):
"""归并排序 :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def merge(self, left_nums, right_nums):
"""合并子问题 :param left_nums: :param right_nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortArray(self, nums):
"""归并排序 :type nums: List[int] :rtype: List[int]"""
if len(nums) < 2:
return nums
mid = len(nums) // 2
left_nums = self.sortArray(nums[:mid])
right_nums = self.sortArray(nums[mid:])
return self.merge(left_nums, rig... | the_stack_v2_python_sparse | leetcode/912.py | yanggelinux/algorithm-data-structure | train | 0 | |
c77ae108637322005dcea720dd3a917d8e394aad | [
"from sktime.distances._distance_alignment_paths import compute_min_return_path\nfrom sktime.distances._dtw_numba import _cost_matrix\nfrom sktime.distances._numba_utils import is_no_python_compiled_callable\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import nj... | <|body_start_0|>
from sktime.distances._distance_alignment_paths import compute_min_return_path
from sktime.distances._dtw_numba import _cost_matrix
from sktime.distances._numba_utils import is_no_python_compiled_callable
from sktime.distances.lower_bounding import resolve_bounding_matri... | Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance) | _DdtwDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DdtwDistance:
"""Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)"""
def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray,... | stack_v2_sparse_classes_36k_train_018404 | 9,184 | permissive | [
{
"docstring": "Create a no_python compiled ddtw distance alignment path callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Series can be different lengths. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array ... | 2 | null | Implement the Python class `_DdtwDistance` described below.
Class description:
Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)
Method signatures and docstrings:
- def ... | Implement the Python class `_DdtwDistance` described below.
Class description:
Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)
Method signatures and docstrings:
- def ... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _DdtwDistance:
"""Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)"""
def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _DdtwDistance:
"""Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)"""
def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_... | the_stack_v2_python_sparse | sktime/distances/_ddtw.py | sktime/sktime | train | 1,117 |
9c5c20446e41bbe90b3b51b0c6059018bfa498f2 | [
"Thread.__init__(self, name='Writer' + str(instance))\nself.accessCount = accessCount\nself.cell = cell\nself.sleepMax = sleepMax",
"print('%s starting up' % self.getName())\nfor count in range(self.accessCount):\n time.sleep(random.randint(1, self.sleepMax))\n value = self.cell.write(lambda counter: counte... | <|body_start_0|>
Thread.__init__(self, name='Writer' + str(instance))
self.accessCount = accessCount
self.cell = cell
self.sleepMax = sleepMax
<|end_body_0|>
<|body_start_1|>
print('%s starting up' % self.getName())
for count in range(self.accessCount):
time.... | Increments the value in the shared cell | Writer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Writer:
"""Increments the value in the shared cell"""
def __init__(self, cell, accessCount, sleepMax, instance):
"""Create a writer to the given shared cell, number of accesses, and maximum sleep interval."""
<|body_0|>
def run(self):
"""Announce start-up, sleep ... | stack_v2_sparse_classes_36k_train_018405 | 5,757 | no_license | [
{
"docstring": "Create a writer to the given shared cell, number of accesses, and maximum sleep interval.",
"name": "__init__",
"signature": "def __init__(self, cell, accessCount, sleepMax, instance)"
},
{
"docstring": "Announce start-up, sleep and write to shared cell the given number of times,... | 2 | stack_v2_sparse_classes_30k_train_012256 | Implement the Python class `Writer` described below.
Class description:
Increments the value in the shared cell
Method signatures and docstrings:
- def __init__(self, cell, accessCount, sleepMax, instance): Create a writer to the given shared cell, number of accesses, and maximum sleep interval.
- def run(self): Anno... | Implement the Python class `Writer` described below.
Class description:
Increments the value in the shared cell
Method signatures and docstrings:
- def __init__(self, cell, accessCount, sleepMax, instance): Create a writer to the given shared cell, number of accesses, and maximum sleep interval.
- def run(self): Anno... | 30375264cf0103e3455fdf92c35a2c5c15b5d7ef | <|skeleton|>
class Writer:
"""Increments the value in the shared cell"""
def __init__(self, cell, accessCount, sleepMax, instance):
"""Create a writer to the given shared cell, number of accesses, and maximum sleep interval."""
<|body_0|>
def run(self):
"""Announce start-up, sleep ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Writer:
"""Increments the value in the shared cell"""
def __init__(self, cell, accessCount, sleepMax, instance):
"""Create a writer to the given shared cell, number of accesses, and maximum sleep interval."""
Thread.__init__(self, name='Writer' + str(instance))
self.accessCount = ... | the_stack_v2_python_sparse | Ch10 exercises/reader-writer.py | davelpat/Fundamentals_of_Python | train | 1 |
1dbb3019a5edc4bc1339804b31f40d3c3cdef24e | [
"tr_list = response.xpath(\"//table[@class='tablelist']//tr\")[1:-1]\nfor tr in tr_list:\n item = {}\n item['tag'] = 'tencent1'\n item['title'] = tr.xpath('.//td[1]/a/text()').extract_first()\n item['category'] = tr.xpath('./td[2]/text()').extract_first()\n item['nums'] = tr.xpath('.//td[3]/text()').... | <|body_start_0|>
tr_list = response.xpath("//table[@class='tablelist']//tr")[1:-1]
for tr in tr_list:
item = {}
item['tag'] = 'tencent1'
item['title'] = tr.xpath('.//td[1]/a/text()').extract_first()
item['category'] = tr.xpath('./td[2]/text()').extract_fir... | Tencent1Spider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tencent1Spider:
def parse_item(self, response):
"""列表页信息爬取"""
<|body_0|>
def parse_detail(self, response):
"""详情页信息存储"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tr_list = response.xpath("//table[@class='tablelist']//tr")[1:-1]
for tr in... | stack_v2_sparse_classes_36k_train_018406 | 1,703 | no_license | [
{
"docstring": "列表页信息爬取",
"name": "parse_item",
"signature": "def parse_item(self, response)"
},
{
"docstring": "详情页信息存储",
"name": "parse_detail",
"signature": "def parse_detail(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000807 | Implement the Python class `Tencent1Spider` described below.
Class description:
Implement the Tencent1Spider class.
Method signatures and docstrings:
- def parse_item(self, response): 列表页信息爬取
- def parse_detail(self, response): 详情页信息存储 | Implement the Python class `Tencent1Spider` described below.
Class description:
Implement the Tencent1Spider class.
Method signatures and docstrings:
- def parse_item(self, response): 列表页信息爬取
- def parse_detail(self, response): 详情页信息存储
<|skeleton|>
class Tencent1Spider:
def parse_item(self, response):
"... | 8f5b5aaf5f237c5e6ae153949da5f8c678789d4c | <|skeleton|>
class Tencent1Spider:
def parse_item(self, response):
"""列表页信息爬取"""
<|body_0|>
def parse_detail(self, response):
"""详情页信息存储"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tencent1Spider:
def parse_item(self, response):
"""列表页信息爬取"""
tr_list = response.xpath("//table[@class='tablelist']//tr")[1:-1]
for tr in tr_list:
item = {}
item['tag'] = 'tencent1'
item['title'] = tr.xpath('.//td[1]/a/text()').extract_first()
... | the_stack_v2_python_sparse | scrapy/crawlspider/crawlspider/spiders/tencent1.py | yuyexiaohan/crawler | train | 0 | |
323186cdc3c6115d56a4296c6aa248023d06e0d1 | [
"self.__name = '{}_{}'.format(type(self).__name__, id(self))\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx\nself.__target = target\nself.__propNames = propNames\nself.__currentOverlay = None\nself.__cache = {}\nself.__overlayList.addListener('overlays', self.__name, self.__selectedOverlayChanged... | <|body_start_0|>
self.__name = '{}_{}'.format(type(self).__name__, id(self))
self.__overlayList = overlayList
self.__displayCtx = displayCtx
self.__target = target
self.__propNames = propNames
self.__currentOverlay = None
self.__cache = {}
self.__overlayLi... | Deprecated - use :class:`fsleyes_props.PropCache` instead. A little convenience class which can be used to track and cache property values, related to each overlay in the :class:`.OverlayList`, on some :class:`.HasProperties` object. Whenever the selected overlay changes, the property values of the previously selected ... | PropCache | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropCache:
"""Deprecated - use :class:`fsleyes_props.PropCache` instead. A little convenience class which can be used to track and cache property values, related to each overlay in the :class:`.OverlayList`, on some :class:`.HasProperties` object. Whenever the selected overlay changes, the proper... | stack_v2_sparse_classes_36k_train_018407 | 18,637 | permissive | [
{
"docstring": "Create a ``PropCache``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The :class:`.DisplayContext` instance. :arg target: The :class:`.HasProperties` instance containing the properties that are to be cached. :arg propNames: List containing the names of ``target`` properties to be... | 5 | null | Implement the Python class `PropCache` described below.
Class description:
Deprecated - use :class:`fsleyes_props.PropCache` instead. A little convenience class which can be used to track and cache property values, related to each overlay in the :class:`.OverlayList`, on some :class:`.HasProperties` object. Whenever t... | Implement the Python class `PropCache` described below.
Class description:
Deprecated - use :class:`fsleyes_props.PropCache` instead. A little convenience class which can be used to track and cache property values, related to each overlay in the :class:`.OverlayList`, on some :class:`.HasProperties` object. Whenever t... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class PropCache:
"""Deprecated - use :class:`fsleyes_props.PropCache` instead. A little convenience class which can be used to track and cache property values, related to each overlay in the :class:`.OverlayList`, on some :class:`.HasProperties` object. Whenever the selected overlay changes, the proper... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropCache:
"""Deprecated - use :class:`fsleyes_props.PropCache` instead. A little convenience class which can be used to track and cache property values, related to each overlay in the :class:`.OverlayList`, on some :class:`.HasProperties` object. Whenever the selected overlay changes, the property values of ... | the_stack_v2_python_sparse | fsleyes/overlay.py | sanjayankur31/fsleyes | train | 1 |
5e85f509df1cf3df89e54b79b58fa7c7cd5f7fa7 | [
"super(SerializedStreamIdentifier, self).__init__()\nself.entry_index = entry_index\nself.stream_number = stream_number",
"if self.stream_number is not None and self.entry_index is not None:\n return '{0:d}.{1:d}'.format(self.stream_number, self.entry_index)\nreturn None"
] | <|body_start_0|>
super(SerializedStreamIdentifier, self).__init__()
self.entry_index = entry_index
self.stream_number = stream_number
<|end_body_0|>
<|body_start_1|>
if self.stream_number is not None and self.entry_index is not None:
return '{0:d}.{1:d}'.format(self.stream_n... | Serialized stream attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a ZIP file. Attributes: stream_number (int): number of the serialized attribute container stream. entry_index (int): number ... | SerializedStreamIdentifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerializedStreamIdentifier:
"""Serialized stream attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a ZIP file. Attributes: stream_number (int): number of the serialized ... | stack_v2_sparse_classes_36k_train_018408 | 4,240 | permissive | [
{
"docstring": "Initializes a serialized stream attribute container identifier. Args: stream_number (int): number of the serialized attribute container stream. entry_index (int): number of the serialized event within the stream.",
"name": "__init__",
"signature": "def __init__(self, stream_number, entry... | 2 | null | Implement the Python class `SerializedStreamIdentifier` described below.
Class description:
Serialized stream attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a ZIP file. Attributes: stream_... | Implement the Python class `SerializedStreamIdentifier` described below.
Class description:
Serialized stream attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a ZIP file. Attributes: stream_... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class SerializedStreamIdentifier:
"""Serialized stream attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a ZIP file. Attributes: stream_number (int): number of the serialized ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SerializedStreamIdentifier:
"""Serialized stream attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a ZIP file. Attributes: stream_number (int): number of the serialized attribute con... | the_stack_v2_python_sparse | plaso/storage/identifiers.py | cyb3rfox/plaso | train | 3 |
61f609a406ed121adde53a4f8c4978bab60420bc | [
"userid = self.request.user\naccessInst = access.objects.filter(user=userid)\nreturn Response(accessSerializer(accessInst, many=True).data)",
"enrollid = request.data.get('enrollid', '-1')\nif enrollid == '-1':\n return Response('Error', status=status.HTTP_204_NO_CONTENT)\nelse:\n enrollInst = enrolledProgr... | <|body_start_0|>
userid = self.request.user
accessInst = access.objects.filter(user=userid)
return Response(accessSerializer(accessInst, many=True).data)
<|end_body_0|>
<|body_start_1|>
enrollid = request.data.get('enrollid', '-1')
if enrollid == '-1':
return Respons... | Club access operations | accessView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class accessView:
"""Club access operations"""
def get(self, request):
"""Retrive recorded access for user/specific user userid -- user id (Optional)"""
<|body_0|>
def post(self, request):
"""Record access for specific enroll"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_018409 | 2,247 | no_license | [
{
"docstring": "Retrive recorded access for user/specific user userid -- user id (Optional)",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Record access for specific enroll",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018981 | Implement the Python class `accessView` described below.
Class description:
Club access operations
Method signatures and docstrings:
- def get(self, request): Retrive recorded access for user/specific user userid -- user id (Optional)
- def post(self, request): Record access for specific enroll | Implement the Python class `accessView` described below.
Class description:
Club access operations
Method signatures and docstrings:
- def get(self, request): Retrive recorded access for user/specific user userid -- user id (Optional)
- def post(self, request): Record access for specific enroll
<|skeleton|>
class ac... | e9cb892c6bfe469f349b8e5b7cd9103078d52f5c | <|skeleton|>
class accessView:
"""Club access operations"""
def get(self, request):
"""Retrive recorded access for user/specific user userid -- user id (Optional)"""
<|body_0|>
def post(self, request):
"""Record access for specific enroll"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class accessView:
"""Club access operations"""
def get(self, request):
"""Retrive recorded access for user/specific user userid -- user id (Optional)"""
userid = self.request.user
accessInst = access.objects.filter(user=userid)
return Response(accessSerializer(accessInst, many=T... | the_stack_v2_python_sparse | access/views.py | amandegar/sportup.ir | train | 0 |
9c879ac91c2692085274e3567788772c03231a63 | [
"try:\n return Response(self.nyuki.running_workflows[iid].report(data=False))\nexcept KeyError:\n return Response(status=404)",
"try:\n wf = self.nyuki.running_workflows[iid]\nexcept KeyError:\n return Response(status=404)\nrequest = await request.json()\ntry:\n action = request['action']\nexcept K... | <|body_start_0|>
try:
return Response(self.nyuki.running_workflows[iid].report(data=False))
except KeyError:
return Response(status=404)
<|end_body_0|>
<|body_start_1|>
try:
wf = self.nyuki.running_workflows[iid]
except KeyError:
return Re... | ApiWorkflow | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"LicenseRef-scancode-warran... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiWorkflow:
async def get(self, request, iid):
"""Return a workflow instance"""
<|body_0|>
async def post(self, request, iid):
"""Suspend/resume a runnning workflow."""
<|body_1|>
async def delete(self, request, iid):
"""Cancel a workflow instan... | stack_v2_sparse_classes_36k_train_018410 | 15,185 | permissive | [
{
"docstring": "Return a workflow instance",
"name": "get",
"signature": "async def get(self, request, iid)"
},
{
"docstring": "Suspend/resume a runnning workflow.",
"name": "post",
"signature": "async def post(self, request, iid)"
},
{
"docstring": "Cancel a workflow instance.",... | 3 | null | Implement the Python class `ApiWorkflow` described below.
Class description:
Implement the ApiWorkflow class.
Method signatures and docstrings:
- async def get(self, request, iid): Return a workflow instance
- async def post(self, request, iid): Suspend/resume a runnning workflow.
- async def delete(self, request, ii... | Implement the Python class `ApiWorkflow` described below.
Class description:
Implement the ApiWorkflow class.
Method signatures and docstrings:
- async def get(self, request, iid): Return a workflow instance
- async def post(self, request, iid): Suspend/resume a runnning workflow.
- async def delete(self, request, ii... | f185fababee380660930243515652093855acfe7 | <|skeleton|>
class ApiWorkflow:
async def get(self, request, iid):
"""Return a workflow instance"""
<|body_0|>
async def post(self, request, iid):
"""Suspend/resume a runnning workflow."""
<|body_1|>
async def delete(self, request, iid):
"""Cancel a workflow instan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiWorkflow:
async def get(self, request, iid):
"""Return a workflow instance"""
try:
return Response(self.nyuki.running_workflows[iid].report(data=False))
except KeyError:
return Response(status=404)
async def post(self, request, iid):
"""Suspend/r... | the_stack_v2_python_sparse | nyuki/workflow/api/instances.py | d-nery/nyuki | train | 0 | |
11f03a3f3fec1f4738fed99cbc1eb462f6175ecd | [
"options = super()._default_experiment_options()\noptions.frequency_shift = None\nreturn options",
"options = super()._default_analysis_options()\noptions.result_parameters = [ParameterRepr('freq', 'rabi_rate_12')]\nreturn options",
"if self.experiment_options.frequency_shift is None:\n try:\n anharm,... | <|body_start_0|>
options = super()._default_experiment_options()
options.frequency_shift = None
return options
<|end_body_0|>
<|body_start_1|>
options = super()._default_analysis_options()
options.result_parameters = [ParameterRepr('freq', 'rabi_rate_12')]
return options... | An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X gate used to populate the first excited state. The Rabi pulse is then appli... | EFRabi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EFRabi:
"""An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X gate used to populate the first excited s... | stack_v2_sparse_classes_36k_train_018411 | 11,710 | permissive | [
{
"docstring": "Default values for the pulse if no schedule is given. Experiment Options: frequency_shift (float): The frequency by which the 1 to 2 transition is detuned from the 0 to 1 transition.",
"name": "_default_experiment_options",
"signature": "def _default_experiment_options(cls) -> Options"
... | 4 | stack_v2_sparse_classes_30k_train_013624 | Implement the Python class `EFRabi` described below.
Class description:
An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X ga... | Implement the Python class `EFRabi` described below.
Class description:
An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X ga... | 22b1598b290464e59a12853efa1eb99b1b36513a | <|skeleton|>
class EFRabi:
"""An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X gate used to populate the first excited s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EFRabi:
"""An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X gate used to populate the first excited state. The Rab... | the_stack_v2_python_sparse | qiskit_experiments/library/calibration/rabi.py | huggingworld/qiskit-experiments | train | 0 |
0266368854551fdc68557bf55d4fa2d70102dc8c | [
"if color_index >= cls.MAX_OVERRIDE_COLORS or color_index < 0:\n om.MGlobal.displayError('Color index out-of-range (must be between 0-31)')\n return False\nshapes = cls.shape_nodes()\nif not shapes:\n om.MGlobal.displayError('No shape nodes selected')\n return False\nfor shape in shapes:\n try:\n ... | <|body_start_0|>
if color_index >= cls.MAX_OVERRIDE_COLORS or color_index < 0:
om.MGlobal.displayError('Color index out-of-range (must be between 0-31)')
return False
shapes = cls.shape_nodes()
if not shapes:
om.MGlobal.displayError('No shape nodes selected')
... | Class for modifying the drawing overrides of selected objects. No UI code is contained in this class. | DisplayColorOverride | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisplayColorOverride:
"""Class for modifying the drawing overrides of selected objects. No UI code is contained in this class."""
def override_color(cls, color_index):
"""Enables drawing overrides on the selected nodes and sets the override color"""
<|body_0|>
def use_de... | stack_v2_sparse_classes_36k_train_018412 | 6,795 | no_license | [
{
"docstring": "Enables drawing overrides on the selected nodes and sets the override color",
"name": "override_color",
"signature": "def override_color(cls, color_index)"
},
{
"docstring": "Disables drawing overrides on the selected nodes",
"name": "use_defaults",
"signature": "def use_... | 3 | stack_v2_sparse_classes_30k_train_004273 | Implement the Python class `DisplayColorOverride` described below.
Class description:
Class for modifying the drawing overrides of selected objects. No UI code is contained in this class.
Method signatures and docstrings:
- def override_color(cls, color_index): Enables drawing overrides on the selected nodes and sets... | Implement the Python class `DisplayColorOverride` described below.
Class description:
Class for modifying the drawing overrides of selected objects. No UI code is contained in this class.
Method signatures and docstrings:
- def override_color(cls, color_index): Enables drawing overrides on the selected nodes and sets... | 1cae8281508b518651e3d37af8f1bc06a8548f53 | <|skeleton|>
class DisplayColorOverride:
"""Class for modifying the drawing overrides of selected objects. No UI code is contained in this class."""
def override_color(cls, color_index):
"""Enables drawing overrides on the selected nodes and sets the override color"""
<|body_0|>
def use_de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DisplayColorOverride:
"""Class for modifying the drawing overrides of selected objects. No UI code is contained in this class."""
def override_color(cls, color_index):
"""Enables drawing overrides on the selected nodes and sets the override color"""
if color_index >= cls.MAX_OVERRIDE_COLO... | the_stack_v2_python_sparse | CZ_Tutorials/001_Maya Python - Display Color Override/maya_python_display_color_override/display_color_override.py | syurskyi/Maya_Programming | train | 0 |
8398fe5179b60cb0b0cdb2a9d4db173f4d8b3a2d | [
"self.__logger = State().getLogger('Preprocessing_Component_Logger')\nself.__logger.info('Starting __init__()', 'BitwiseNotPreprocessor:__init__')\nself.__showImagesInWindow = showImagesInWindow\nself.__logger.info('Finished __init__()', 'BitwiseNotPreprocessor:__init__')",
"self.__logger.info('Starting preProces... | <|body_start_0|>
self.__logger = State().getLogger('Preprocessing_Component_Logger')
self.__logger.info('Starting __init__()', 'BitwiseNotPreprocessor:__init__')
self.__showImagesInWindow = showImagesInWindow
self.__logger.info('Finished __init__()', 'BitwiseNotPreprocessor:__init__')
<|... | BitwiseNotPreprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitwiseNotPreprocessor:
def __init__(self, showImagesInWindow=False):
"""To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!"""
<|body_0|>
def preProcess(self, mat):
"""Führt eine Inversierung (bit-weises not) auf eine Bildmatrix aus. Parameters ---------- mat : Mat ... | stack_v2_sparse_classes_36k_train_018413 | 1,919 | no_license | [
{
"docstring": "To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!",
"name": "__init__",
"signature": "def __init__(self, showImagesInWindow=False)"
},
{
"docstring": "Führt eine Inversierung (bit-weises not) auf eine Bildmatrix aus. Parameters ---------- mat : Mat Die Matrix auf welche die Ope... | 2 | stack_v2_sparse_classes_30k_train_015181 | Implement the Python class `BitwiseNotPreprocessor` described below.
Class description:
Implement the BitwiseNotPreprocessor class.
Method signatures and docstrings:
- def __init__(self, showImagesInWindow=False): To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!
- def preProcess(self, mat): Führt eine Inversierung... | Implement the Python class `BitwiseNotPreprocessor` described below.
Class description:
Implement the BitwiseNotPreprocessor class.
Method signatures and docstrings:
- def __init__(self, showImagesInWindow=False): To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!
- def preProcess(self, mat): Führt eine Inversierung... | 3daaa72b193ebfb55894b47b6a752cdc2192bb6b | <|skeleton|>
class BitwiseNotPreprocessor:
def __init__(self, showImagesInWindow=False):
"""To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!"""
<|body_0|>
def preProcess(self, mat):
"""Führt eine Inversierung (bit-weises not) auf eine Bildmatrix aus. Parameters ---------- mat : Mat ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BitwiseNotPreprocessor:
def __init__(self, showImagesInWindow=False):
"""To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!"""
self.__logger = State().getLogger('Preprocessing_Component_Logger')
self.__logger.info('Starting __init__()', 'BitwiseNotPreprocessor:__init__')
self.... | the_stack_v2_python_sparse | SheetMusicScanner/Preprocessing_Component/PreprocessingUnit/BitwiseNotPreprocessor.py | jadeskon/score-scan | train | 0 | |
24906ed6aa5b0f57be95b64f1c61cde5804d26b9 | [
"super().__init__(**kwargs)\nself.set(w_pad=mpl.rcParams['figure.constrained_layout.w_pad'], h_pad=mpl.rcParams['figure.constrained_layout.h_pad'], wspace=mpl.rcParams['figure.constrained_layout.wspace'], hspace=mpl.rcParams['figure.constrained_layout.hspace'], rect=(0, 0, 1, 1))\nself.set(w_pad=w_pad, h_pad=h_pad,... | <|body_start_0|>
super().__init__(**kwargs)
self.set(w_pad=mpl.rcParams['figure.constrained_layout.w_pad'], h_pad=mpl.rcParams['figure.constrained_layout.h_pad'], wspace=mpl.rcParams['figure.constrained_layout.wspace'], hspace=mpl.rcParams['figure.constrained_layout.hspace'], rect=(0, 0, 1, 1))
... | Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details. | ConstrainedLayoutEngine | [
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"Bitstream-Charter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-bakoma-fonts-1995",
"LicenseRef-scancode-unknown-license-reference",
"OFL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstrainedLayoutEngine:
"""Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details."""
def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False, **kwargs):
"""I... | stack_v2_sparse_classes_36k_train_018414 | 11,335 | permissive | [
{
"docstring": "Initialize ``constrained_layout`` settings. Parameters ---------- h_pad, w_pad : float Padding around the axes elements in figure-normalized units. Default to :rc:`figure.constrained_layout.h_pad` and :rc:`figure.constrained_layout.w_pad`. hspace, wspace : float Fraction of the figure to dedicat... | 3 | stack_v2_sparse_classes_30k_train_006707 | Implement the Python class `ConstrainedLayoutEngine` described below.
Class description:
Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details.
Method signatures and docstrings:
- def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wsp... | Implement the Python class `ConstrainedLayoutEngine` described below.
Class description:
Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details.
Method signatures and docstrings:
- def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wsp... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class ConstrainedLayoutEngine:
"""Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details."""
def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False, **kwargs):
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConstrainedLayoutEngine:
"""Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details."""
def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False, **kwargs):
"""Initialize ``c... | the_stack_v2_python_sparse | contrib/python/matplotlib/py3/matplotlib/layout_engine.py | catboost/catboost | train | 8,012 |
116ec06fd21aaaa595de1903ead6f7a9c47301f4 | [
"super(PyMongoEvent, self).__init__(start_time)\nself.resource['operation'] = getattr(wrapped, '__name__')\nself.event_id = 'mongo-{}'.format(str(uuid4()))\nself.resource['name'] = instance.name\naddress = list(getattr(instance.database.client, '_topology_settings').seeds)[0]\nself.resource['metadata'] = {'DB URL':... | <|body_start_0|>
super(PyMongoEvent, self).__init__(start_time)
self.resource['operation'] = getattr(wrapped, '__name__')
self.event_id = 'mongo-{}'.format(str(uuid4()))
self.resource['name'] = instance.name
address = list(getattr(instance.database.client, '_topology_settings').s... | Represents base pymongo event. | PyMongoEvent | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyMongoEvent:
"""Represents base pymongo event."""
def __init__(self, wrapped, instance, args, kwargs, start_time, response, exception):
"""Initialize. :param wrapped: wrapt's wrapped :param instance: wrapt's instance :param args: wrapt's args :param kwargs: wrapt's kwargs :param sta... | stack_v2_sparse_classes_36k_train_018415 | 5,231 | permissive | [
{
"docstring": "Initialize. :param wrapped: wrapt's wrapped :param instance: wrapt's instance :param args: wrapt's args :param kwargs: wrapt's kwargs :param start_time: Start timestamp (epoch) :param response: response data :param exception: Exception (if happened)",
"name": "__init__",
"signature": "de... | 5 | stack_v2_sparse_classes_30k_train_012175 | Implement the Python class `PyMongoEvent` described below.
Class description:
Represents base pymongo event.
Method signatures and docstrings:
- def __init__(self, wrapped, instance, args, kwargs, start_time, response, exception): Initialize. :param wrapped: wrapt's wrapped :param instance: wrapt's instance :param ar... | Implement the Python class `PyMongoEvent` described below.
Class description:
Represents base pymongo event.
Method signatures and docstrings:
- def __init__(self, wrapped, instance, args, kwargs, start_time, response, exception): Initialize. :param wrapped: wrapt's wrapped :param instance: wrapt's instance :param ar... | 91e28fe43bc4f42152fb156145088cb8c9f69b85 | <|skeleton|>
class PyMongoEvent:
"""Represents base pymongo event."""
def __init__(self, wrapped, instance, args, kwargs, start_time, response, exception):
"""Initialize. :param wrapped: wrapt's wrapped :param instance: wrapt's instance :param args: wrapt's args :param kwargs: wrapt's kwargs :param sta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyMongoEvent:
"""Represents base pymongo event."""
def __init__(self, wrapped, instance, args, kwargs, start_time, response, exception):
"""Initialize. :param wrapped: wrapt's wrapped :param instance: wrapt's instance :param args: wrapt's args :param kwargs: wrapt's kwargs :param start_time: Star... | the_stack_v2_python_sparse | epsagon/events/pymongo.py | epsagon/epsagon-python | train | 57 |
fd5afd07ad8325ff4df2f0d9a54f82b5bb11a342 | [
"if len(nums) == 0:\n return 0\nnums = [0] + nums\nf = [0 for _ in range(len(nums))]\nf[1] = nums[1]\nfor i in range(2, len(nums)):\n f[i] = max(nums[i] + f[i - 2], f[i - 1])\nreturn f[-1]",
"if len(nums) == 0:\n return 0\nif len(nums) == 1:\n return nums[0]\nreturn max(self.rob_origin(nums[1:]), self... | <|body_start_0|>
if len(nums) == 0:
return 0
nums = [0] + nums
f = [0 for _ in range(len(nums))]
f[1] = nums[1]
for i in range(2, len(nums)):
f[i] = max(nums[i] + f[i - 2], f[i - 1])
return f[-1]
<|end_body_0|>
<|body_start_1|>
if len(nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob_origin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
return 0
nums =... | stack_v2_sparse_classes_36k_train_018416 | 743 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_origin",
"signature": "def rob_origin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015243 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob_origin(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob_origin(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob_origin(self, num... | c2b01374942dcba7fbbe7865d13d7599bbc083f3 | <|skeleton|>
class Solution:
def rob_origin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob_origin(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
nums = [0] + nums
f = [0 for _ in range(len(nums))]
f[1] = nums[1]
for i in range(2, len(nums)):
f[i] = max(nums[i] + f[i - 2], f[i ... | the_stack_v2_python_sparse | P0213.py | chenjiahui1991/LeetCode | train | 0 | |
cca7079eaf2e80a3809e64a46e16152ad9ce6e36 | [
"steam_turbines = [producer for producer in self.producers.steam_turbine_chps if producer.name != self.EXCLUDE]\ntotal_e_capacity = chp_capacities.capacity('Steam Turbine CHP')\ntotal_e_produced = self.produced('electricity', steam_turbines)\nfor producer in steam_turbines:\n heat = self.process_producer(produce... | <|body_start_0|>
steam_turbines = [producer for producer in self.producers.steam_turbine_chps if producer.name != self.EXCLUDE]
total_e_capacity = chp_capacities.capacity('Steam Turbine CHP')
total_e_produced = self.produced('electricity', steam_turbines)
for producer in steam_turbines:
... | SteamTurbineCHPConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteamTurbineCHPConverter:
def conversion(self, chp_capacities, flh_calc=None, heat_network=None):
"""Parses all Steam Turbine CHP's. They are added to the EB, HeatNetwork and FullLoadHours calculation. Params: chp_capacities(CHPCapacities): The CHP capacities as retrieved from Eurostat f... | stack_v2_sparse_classes_36k_train_018417 | 2,747 | no_license | [
{
"docstring": "Parses all Steam Turbine CHP's. They are added to the EB, HeatNetwork and FullLoadHours calculation. Params: chp_capacities(CHPCapacities): The CHP capacities as retrieved from Eurostat flh_calc(FullLoadHoursCalculator): All parsed producers will be added to the full load hours calculation and o... | 2 | stack_v2_sparse_classes_30k_train_015281 | Implement the Python class `SteamTurbineCHPConverter` described below.
Class description:
Implement the SteamTurbineCHPConverter class.
Method signatures and docstrings:
- def conversion(self, chp_capacities, flh_calc=None, heat_network=None): Parses all Steam Turbine CHP's. They are added to the EB, HeatNetwork and ... | Implement the Python class `SteamTurbineCHPConverter` described below.
Class description:
Implement the SteamTurbineCHPConverter class.
Method signatures and docstrings:
- def conversion(self, chp_capacities, flh_calc=None, heat_network=None): Parses all Steam Turbine CHP's. They are added to the EB, HeatNetwork and ... | bef8f76c7e0ebc172646fef085c8705245998b2f | <|skeleton|>
class SteamTurbineCHPConverter:
def conversion(self, chp_capacities, flh_calc=None, heat_network=None):
"""Parses all Steam Turbine CHP's. They are added to the EB, HeatNetwork and FullLoadHours calculation. Params: chp_capacities(CHPCapacities): The CHP capacities as retrieved from Eurostat f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SteamTurbineCHPConverter:
def conversion(self, chp_capacities, flh_calc=None, heat_network=None):
"""Parses all Steam Turbine CHP's. They are added to the EB, HeatNetwork and FullLoadHours calculation. Params: chp_capacities(CHPCapacities): The CHP capacities as retrieved from Eurostat flh_calc(FullLo... | the_stack_v2_python_sparse | tools/energy_balance_generator/etm_tools/energy_balance_operations/converters/heaters_and_chps/steam_turbine_chps.py | quintel/etdataset-public | train | 4 | |
29e69098549f57df35296abbf38aa579d765eca8 | [
"def get_height(width):\n max_height = 0\n for i in xrange(len(heights)):\n if i + width < len(heights) + 1:\n max_height = max(max_height, min(heights[i:i + width]))\n return max_height\nif not heights:\n return 0\nmax_area = 0\nfor width in xrange(1, len(heights) + 1):\n max_area ... | <|body_start_0|>
def get_height(width):
max_height = 0
for i in xrange(len(heights)):
if i + width < len(heights) + 1:
max_height = max(max_height, min(heights[i:i + width]))
return max_height
if not heights:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def get_height... | stack_v2_sparse_classes_36k_train_018418 | 2,196 | no_license | [
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea2",
"signature": "def largestRectangleArea2(self, heights)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def largestRectangleArea2(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def largestRectangleArea2(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
class... | 18ed31a3edf20a3e5a0b7a0b56acca5b98939693 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
def get_height(width):
max_height = 0
for i in xrange(len(heights)):
if i + width < len(heights) + 1:
max_height = max(max_height, min(heigh... | the_stack_v2_python_sparse | exercises/array/largest_rectangle_in_histogram.py | nahgnaw/data-structure | train | 0 | |
0c85fc1591fd0b74d4525818d2e60ca42ae2147f | [
"edr = pygmx.open(edrfile)\nself.time, data = edr.read()\nself.types, self.units = zip(*edr.types)\nself.data = data.T",
"if type in self.types:\n return self.data[self.types.index(type)]\nelse:\n raise KeyError('Energy type {} not found in Energy File.'.format(type))"
] | <|body_start_0|>
edr = pygmx.open(edrfile)
self.time, data = edr.read()
self.types, self.units = zip(*edr.types)
self.data = data.T
<|end_body_0|>
<|body_start_1|>
if type in self.types:
return self.data[self.types.index(type)]
else:
raise KeyErro... | A reader for Gromacs energy files. | EnergyReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnergyReader:
"""A reader for Gromacs energy files."""
def __init__(self, edrfile):
"""Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known"""
<|body_0|>
def __getitem__(self,... | stack_v2_sparse_classes_36k_train_018419 | 12,347 | permissive | [
{
"docstring": "Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known",
"name": "__init__",
"signature": "def __init__(self, edrfile)"
},
{
"docstring": "Get time series of an energy type.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_015950 | Implement the Python class `EnergyReader` described below.
Class description:
A reader for Gromacs energy files.
Method signatures and docstrings:
- def __init__(self, edrfile): Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file ... | Implement the Python class `EnergyReader` described below.
Class description:
A reader for Gromacs energy files.
Method signatures and docstrings:
- def __init__(self, edrfile): Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file ... | 204d206df45e1a8d2dbdc36428eb6ce24672d384 | <|skeleton|>
class EnergyReader:
"""A reader for Gromacs energy files."""
def __init__(self, edrfile):
"""Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known"""
<|body_0|>
def __getitem__(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnergyReader:
"""A reader for Gromacs energy files."""
def __init__(self, edrfile):
"""Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known"""
edr = pygmx.open(edrfile)
self.time, data ... | the_stack_v2_python_sparse | mdevaluate/reader.py | thonmaker/mdevaluate | train | 1 |
b75256a5b8bda4de524201c3d138fefc31144834 | [
"self.language = language\nself.subject = subject\nself.text = text\nself.sender_name = sender_name\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nlanguage = dictionary.get('language')\nsubject = dictionary.get('subject')\ntext = dictionary.get('text')\nsender_name... | <|body_start_0|>
self.language = language
self.subject = subject
self.text = text
self.sender_name = sender_name
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
language = dictionar... | Implementation of the 'Email' model. TODO: type model description here. Attributes: language (Language185): Email language subject (string): Email subject text (string): Insert your email text, we support plain text and markdown sender_name (string): Name of sender | Email | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Email:
"""Implementation of the 'Email' model. TODO: type model description here. Attributes: language (Language185): Email language subject (string): Email subject text (string): Insert your email text, we support plain text and markdown sender_name (string): Name of sender"""
def __init__(... | stack_v2_sparse_classes_36k_train_018420 | 2,463 | permissive | [
{
"docstring": "Constructor for the Email class",
"name": "__init__",
"signature": "def __init__(self, language=None, subject=None, text=None, sender_name=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | null | Implement the Python class `Email` described below.
Class description:
Implementation of the 'Email' model. TODO: type model description here. Attributes: language (Language185): Email language subject (string): Email subject text (string): Insert your email text, we support plain text and markdown sender_name (string... | Implement the Python class `Email` described below.
Class description:
Implementation of the 'Email' model. TODO: type model description here. Attributes: language (Language185): Email language subject (string): Email subject text (string): Insert your email text, we support plain text and markdown sender_name (string... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Email:
"""Implementation of the 'Email' model. TODO: type model description here. Attributes: language (Language185): Email language subject (string): Email subject text (string): Insert your email text, we support plain text and markdown sender_name (string): Name of sender"""
def __init__(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Email:
"""Implementation of the 'Email' model. TODO: type model description here. Attributes: language (Language185): Email language subject (string): Email subject text (string): Insert your email text, we support plain text and markdown sender_name (string): Name of sender"""
def __init__(self, languag... | the_stack_v2_python_sparse | idfy_rest_client/models/email.py | dealflowteam/Idfy | train | 0 |
c2714b768d805d981226df643e0d1b89b92289e7 | [
"decoded_token = UserRecord.verify_id_token(id_token, check_revoked=True, auth=web_sdk.auth)\nuser_record = UserRecord.get_user(decoded_token['uid'], auth=web_sdk.auth)\nif user_record.disabled:\n raise HandlerException(401, 'Account disabled')\nclaims = user_record.custom_claims\nif claims and 'admin' in claims... | <|body_start_0|>
decoded_token = UserRecord.verify_id_token(id_token, check_revoked=True, auth=web_sdk.auth)
user_record = UserRecord.get_user(decoded_token['uid'], auth=web_sdk.auth)
if user_record.disabled:
raise HandlerException(401, 'Account disabled')
claims = user_recor... | Service Auth | AuthService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthService:
"""Service Auth"""
def authentication(self, id_token):
"""Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): User"""
<|body_0|>
def create(self, body):
"""Create user account Ar... | stack_v2_sparse_classes_36k_train_018421 | 7,348 | no_license | [
{
"docstring": "Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): User",
"name": "authentication",
"signature": "def authentication(self, id_token)"
},
{
"docstring": "Create user account Args: body (dict): email (str): Us... | 6 | stack_v2_sparse_classes_30k_train_014386 | Implement the Python class `AuthService` described below.
Class description:
Service Auth
Method signatures and docstrings:
- def authentication(self, id_token): Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): User
- def create(self, body): C... | Implement the Python class `AuthService` described below.
Class description:
Service Auth
Method signatures and docstrings:
- def authentication(self, id_token): Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): User
- def create(self, body): C... | 828cb0109415b293a38f5c8ea6c11ce4a469a8ea | <|skeleton|>
class AuthService:
"""Service Auth"""
def authentication(self, id_token):
"""Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): User"""
<|body_0|>
def create(self, body):
"""Create user account Ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthService:
"""Service Auth"""
def authentication(self, id_token):
"""Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): User"""
decoded_token = UserRecord.verify_id_token(id_token, check_revoked=True, auth=web_sdk.... | the_stack_v2_python_sparse | src/services/auth.py | andresbermeoq/server | train | 0 |
b524d88baff6bdcc47fa3486a383a688a967b9fa | [
"try:\n from bokeh.plotting import Figure\nexcept (ModuleNotFoundError, ImportError) as Error:\n raise Error(\"Using 'BokehArtifact' requires bokeh package. Use pip install mlrun[bokeh] to install it.\")\nif figure is not None and (not isinstance(figure, Figure)):\n raise ValueError(\"BokehArtifact require... | <|body_start_0|>
try:
from bokeh.plotting import Figure
except (ModuleNotFoundError, ImportError) as Error:
raise Error("Using 'BokehArtifact' requires bokeh package. Use pip install mlrun[bokeh] to install it.")
if figure is not None and (not isinstance(figure, Figure)):... | Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format. | BokehArtifact | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('boke... | stack_v2_sparse_classes_36k_train_018422 | 15,717 | permissive | [
{
"docstring": "Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('bokeh.plotting.Figure' object) to save as an artifact. :param key: Key for the artifact to be stored in the database. :param target_path: Path to save the artifact.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_007440 | Implement the Python class `BokehArtifact` described below.
Class description:
Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format.
Method signatures and docstrings:
- def __init__(self, figure=None, key: str=None, target_path: str=None): Initialize a Bokeh artifact ... | Implement the Python class `BokehArtifact` described below.
Class description:
Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format.
Method signatures and docstrings:
- def __init__(self, figure=None, key: str=None, target_path: str=None): Initialize a Bokeh artifact ... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class BokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('boke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('bokeh.plotting.Fi... | the_stack_v2_python_sparse | mlrun/artifacts/plots.py | mlrun/mlrun | train | 1,093 |
f3dc754be3466b3e77961141e65282d2e06de147 | [
"curnum = 0\ncurarray = []\nk = 0\nstart = 0\ncurlength = 0\nans = 999999\nwhile start < len(nums):\n if curnum < s:\n curnum += nums[start]\n curarray.append(nums[start])\n start += 1\n curlength += 1\n else:\n while curnum >= s:\n ans = min(ans, curlength)\n ... | <|body_start_0|>
curnum = 0
curarray = []
k = 0
start = 0
curlength = 0
ans = 999999
while start < len(nums):
if curnum < s:
curnum += nums[start]
curarray.append(nums[start])
start += 1
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen2(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
curnu... | stack_v2_sparse_classes_36k_train_018423 | 1,465 | no_license | [
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen1",
"signature": "def minSubArrayLen1(self, s, nums)"
},
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen2",
"signature": "def minSubArrayLen2(self, s, nums)"
... | 2 | stack_v2_sparse_classes_30k_train_000536 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen1(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen2(self, s, nums): :type s: int :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen1(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen2(self, s, nums): :type s: int :type nums: List[int] :rtype: int
<|skeleto... | d741fe6138876587204ed395dddf58ade7ddb413 | <|skeleton|>
class Solution:
def minSubArrayLen1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen2(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubArrayLen1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
curnum = 0
curarray = []
k = 0
start = 0
curlength = 0
ans = 999999
while start < len(nums):
if curnum < s:
curnum += n... | the_stack_v2_python_sparse | 209 长度最小的子数组.py | wyhhuster/leetcode | train | 0 | |
49e2c04f9eeecfc3d50298252ff1d63548e55fee | [
"self.my_logger = set_logger(self.__class__.__name__)\nself.x0 = centroid_coords[0]\nself.y0 = centroid_coords[1]\nself.amplitude = amplitude\nself.psf = copy.deepcopy(psf)\nself.psf.params.values[1] = self.x0\nself.psf.params.values[2] = self.y0\nself.psf.params.values[0] = amplitude\nself.fwhm = self.psf.params.v... | <|body_start_0|>
self.my_logger = set_logger(self.__class__.__name__)
self.x0 = centroid_coords[0]
self.y0 = centroid_coords[1]
self.amplitude = amplitude
self.psf = copy.deepcopy(psf)
self.psf.params.values[1] = self.x0
self.psf.params.values[2] = self.y0
... | Class to model a star in the image simulation process. Attributes ---------- x0: float X position of the star centroid in pixels. y0: float Y position of the star centroid in pixels. amplitude: amplitude The amplitude of the star in image units. | StarModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarModel:
"""Class to model a star in the image simulation process. Attributes ---------- x0: float X position of the star centroid in pixels. y0: float Y position of the star centroid in pixels. amplitude: amplitude The amplitude of the star in image units."""
def __init__(self, centroid_c... | stack_v2_sparse_classes_36k_train_018424 | 22,700 | permissive | [
{
"docstring": "Create a StarModel instance. The model is based on an Astropy Fittable2DModel. The centroid and amplitude parameters of the given model are updated by the dedicated arguments. Parameters ---------- centroid_coords: array_like Tuple of (x,y) coordinates of the desired star centroid in pixels. psf... | 2 | stack_v2_sparse_classes_30k_train_004663 | Implement the Python class `StarModel` described below.
Class description:
Class to model a star in the image simulation process. Attributes ---------- x0: float X position of the star centroid in pixels. y0: float Y position of the star centroid in pixels. amplitude: amplitude The amplitude of the star in image units... | Implement the Python class `StarModel` described below.
Class description:
Class to model a star in the image simulation process. Attributes ---------- x0: float X position of the star centroid in pixels. y0: float Y position of the star centroid in pixels. amplitude: amplitude The amplitude of the star in image units... | d227d0fe3c61cabbfdea42d520da5f44e01632aa | <|skeleton|>
class StarModel:
"""Class to model a star in the image simulation process. Attributes ---------- x0: float X position of the star centroid in pixels. y0: float Y position of the star centroid in pixels. amplitude: amplitude The amplitude of the star in image units."""
def __init__(self, centroid_c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarModel:
"""Class to model a star in the image simulation process. Attributes ---------- x0: float X position of the star centroid in pixels. y0: float Y position of the star centroid in pixels. amplitude: amplitude The amplitude of the star in image units."""
def __init__(self, centroid_coords, psf, a... | the_stack_v2_python_sparse | spectractor/simulation/image_simulation.py | LSSTDESC/Spectractor | train | 19 |
3f46114013476fc25dd8a6b679b901c0883ad616 | [
"super().__init__(*args, **kwargs)\nself.learning_rate = learning_rate or 0.001\nself.rho = rho or 0.9\nself.epsilon = epsilon or 1e-08\nself.decay = decay or 0.0\nself.optimizer = None",
"if backend.get_name() == 'keras':\n import keras.optimizers as O\n self.optimizer = self.optimizer or O.RMSprop(lr=self... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.learning_rate = learning_rate or 0.001
self.rho = rho or 0.9
self.epsilon = epsilon or 1e-08
self.decay = decay or 0.0
self.optimizer = None
<|end_body_0|>
<|body_start_1|>
if backend.get_name() == 'keras':
... | RMSProp optimizer | RMSProp | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMSProp:
"""RMSProp optimizer"""
def __init__(self, learning_rate=None, rho=None, epsilon=None, decay=None, *args, **kwargs):
"""Create a new RMSProp optimizer. # Arguments learning_rate: float. The learning rate to use."""
<|body_0|>
def get_optimizer(self, backend):
... | stack_v2_sparse_classes_36k_train_018425 | 1,915 | permissive | [
{
"docstring": "Create a new RMSProp optimizer. # Arguments learning_rate: float. The learning rate to use.",
"name": "__init__",
"signature": "def __init__(self, learning_rate=None, rho=None, epsilon=None, decay=None, *args, **kwargs)"
},
{
"docstring": "Returns a backend-specific instantiation... | 2 | stack_v2_sparse_classes_30k_train_008011 | Implement the Python class `RMSProp` described below.
Class description:
RMSProp optimizer
Method signatures and docstrings:
- def __init__(self, learning_rate=None, rho=None, epsilon=None, decay=None, *args, **kwargs): Create a new RMSProp optimizer. # Arguments learning_rate: float. The learning rate to use.
- def ... | Implement the Python class `RMSProp` described below.
Class description:
RMSProp optimizer
Method signatures and docstrings:
- def __init__(self, learning_rate=None, rho=None, epsilon=None, decay=None, *args, **kwargs): Create a new RMSProp optimizer. # Arguments learning_rate: float. The learning rate to use.
- def ... | fd0c120e50815c1e5be64e5dde964dcd47234556 | <|skeleton|>
class RMSProp:
"""RMSProp optimizer"""
def __init__(self, learning_rate=None, rho=None, epsilon=None, decay=None, *args, **kwargs):
"""Create a new RMSProp optimizer. # Arguments learning_rate: float. The learning rate to use."""
<|body_0|>
def get_optimizer(self, backend):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RMSProp:
"""RMSProp optimizer"""
def __init__(self, learning_rate=None, rho=None, epsilon=None, decay=None, *args, **kwargs):
"""Create a new RMSProp optimizer. # Arguments learning_rate: float. The learning rate to use."""
super().__init__(*args, **kwargs)
self.learning_rate = le... | the_stack_v2_python_sparse | kur/optimizer/rmsprop.py | deepgram/kur | train | 873 |
8e419dd4daffbd51e106252a8ad6b1d0425b18a9 | [
"response = self.client.get(reverse('polls:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'No polls are available.')\nself.assertQuerysetEqual(response.context['latest_question_list'], [])",
"create_question(question_text='Past question.', days=-30)\nresponse = self.client.ge... | <|body_start_0|>
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are available.')
self.assertQuerysetEqual(response.context['latest_question_list'], [])
<|end_body_0|>
<|body_start_1|>
create_... | QuestionViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionViewTests:
def test_index_view_with_no_questions(self):
"""If no questions exist, an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_a_past_question(self):
"""Questions with a pub_date in the past should be displayed on the ind... | stack_v2_sparse_classes_36k_train_018426 | 12,478 | no_license | [
{
"docstring": "If no questions exist, an appropriate message should be displayed.",
"name": "test_index_view_with_no_questions",
"signature": "def test_index_view_with_no_questions(self)"
},
{
"docstring": "Questions with a pub_date in the past should be displayed on the index page",
"name"... | 5 | stack_v2_sparse_classes_30k_train_019077 | Implement the Python class `QuestionViewTests` described below.
Class description:
Implement the QuestionViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_questions(self): If no questions exist, an appropriate message should be displayed.
- def test_index_view_with_a_past_question(self)... | Implement the Python class `QuestionViewTests` described below.
Class description:
Implement the QuestionViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_questions(self): If no questions exist, an appropriate message should be displayed.
- def test_index_view_with_a_past_question(self)... | 43bca49c77eb16de7580e55f7418cdab92a9a596 | <|skeleton|>
class QuestionViewTests:
def test_index_view_with_no_questions(self):
"""If no questions exist, an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_a_past_question(self):
"""Questions with a pub_date in the past should be displayed on the ind... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionViewTests:
def test_index_view_with_no_questions(self):
"""If no questions exist, an appropriate message should be displayed."""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are av... | the_stack_v2_python_sparse | sdd_project copy/labhelpers/tests.py | katrusso/LabHelpers | train | 0 | |
da63514a74b8c80e7f60c9130a650ff5bf28c0e9 | [
"self.padding_index = 0\nself.unk_index = 1\nself.bos_index = 2\nself.eos_index = 3\nself.pad_word = '<pad>'\nself.unk_word = '<unk>'\nself.bos_word = '<s>'\nself.eos_word = '<\\\\s>'\nself.isolator = isolator\nself.init_bpe(bpe_code_address)\nself.vocab_establist(vocab_address, vocab_pad)\nself.sacremoses_tokenize... | <|body_start_0|>
self.padding_index = 0
self.unk_index = 1
self.bos_index = 2
self.eos_index = 3
self.pad_word = '<pad>'
self.unk_word = '<unk>'
self.bos_word = '<s>'
self.eos_word = '<\\s>'
self.isolator = isolator
self.init_bpe(bpe_code_a... | Tokenizer class. | Tokenizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenizer:
"""Tokenizer class."""
def __init__(self, vocab_address=None, bpe_code_address=None, src_en='en', tgt_de='de', vocab_pad=8, isolator='@@'):
"""Constructor for the Tokenizer class. Args: vocab_address: vocabulary address. bpe_code_address: path to the file with bpe codes. v... | stack_v2_sparse_classes_36k_train_018427 | 4,330 | permissive | [
{
"docstring": "Constructor for the Tokenizer class. Args: vocab_address: vocabulary address. bpe_code_address: path to the file with bpe codes. vocab_pad: pads vocabulary to a multiple of 'vocab_pad' tokens. isolator: tokenization isolator.",
"name": "__init__",
"signature": "def __init__(self, vocab_a... | 5 | null | Implement the Python class `Tokenizer` described below.
Class description:
Tokenizer class.
Method signatures and docstrings:
- def __init__(self, vocab_address=None, bpe_code_address=None, src_en='en', tgt_de='de', vocab_pad=8, isolator='@@'): Constructor for the Tokenizer class. Args: vocab_address: vocabulary addr... | Implement the Python class `Tokenizer` described below.
Class description:
Tokenizer class.
Method signatures and docstrings:
- def __init__(self, vocab_address=None, bpe_code_address=None, src_en='en', tgt_de='de', vocab_pad=8, isolator='@@'): Constructor for the Tokenizer class. Args: vocab_address: vocabulary addr... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Tokenizer:
"""Tokenizer class."""
def __init__(self, vocab_address=None, bpe_code_address=None, src_en='en', tgt_de='de', vocab_pad=8, isolator='@@'):
"""Constructor for the Tokenizer class. Args: vocab_address: vocabulary address. bpe_code_address: path to the file with bpe codes. v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tokenizer:
"""Tokenizer class."""
def __init__(self, vocab_address=None, bpe_code_address=None, src_en='en', tgt_de='de', vocab_pad=8, isolator='@@'):
"""Constructor for the Tokenizer class. Args: vocab_address: vocabulary address. bpe_code_address: path to the file with bpe codes. vocab_pad: pad... | the_stack_v2_python_sparse | research/nlp/gnmt_v2/src/dataset/tokenizer.py | mindspore-ai/models | train | 301 |
a62ed88e5ee03d1f25eeae36cf13cc97aecb272f | [
"if SHA1_RE.search(activation_key):\n log.debug('Activation key matches regex')\n try:\n profile = self.get(activation_key=activation_key)\n except self.model.DoesNotExist:\n log.warn('Activation profile not found!')\n return False\n if not profile.activation_key_expired():\n ... | <|body_start_0|>
if SHA1_RE.search(activation_key):
log.debug('Activation key matches regex')
try:
profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
log.warn('Activation profile not found!')
retur... | Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. | RegistrationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
"""Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts."""
def activate_user(self, acti... | stack_v2_sparse_classes_36k_train_018428 | 5,532 | no_license | [
{
"docstring": "Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To preve... | 2 | null | Implement the Python class `RegistrationManager` described below.
Class description:
Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive account... | Implement the Python class `RegistrationManager` described below.
Class description:
Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive account... | 302324dccc135f55d92fb705c58314c55fed22aa | <|skeleton|>
class RegistrationManager:
"""Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts."""
def activate_user(self, acti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationManager:
"""Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts."""
def activate_user(self, activation_key):
... | the_stack_v2_python_sparse | django-gc-shared/registration/models.py | riyanhax/a-demo | train | 0 |
5152a51fb44b67044dc478c3162a0035ac9c6714 | [
"if extra_args.has_key('output_dir'):\n del extra_args['output_dir']\nself.orb_basis = ridft_in._keywords['ORB_BASIS']\nself.rijk_basis = ridft_in._keywords['RIJK_BASIS']\nself.work_dir = os.path.join(work_dir, 'bas-%s/jkbas-%s' % (self.orb_basis, self.rijk_basis))\nself.name = name\nself.coord = coord\nself.rid... | <|body_start_0|>
if extra_args.has_key('output_dir'):
del extra_args['output_dir']
self.orb_basis = ridft_in._keywords['ORB_BASIS']
self.rijk_basis = ridft_in._keywords['RIJK_BASIS']
self.work_dir = os.path.join(work_dir, 'bas-%s/jkbas-%s' % (self.orb_basis, self.rijk_basis))... | Build a two-step sequence: - first task is RIDFT with given coordinates and ``define.in`` file; - second task is a parallel collection of RICC2 that uses the output files from the first stage as input, plus a new ``define.in``. | BasisSweepPasses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasisSweepPasses:
"""Build a two-step sequence: - first task is RIDFT with given coordinates and ``define.in`` file; - second task is a parallel collection of RICC2 that uses the output files from the first stage as input, plus a new ``define.in``."""
def __init__(self, name, coord, ridft_in... | stack_v2_sparse_classes_36k_train_018429 | 24,041 | no_license | [
{
"docstring": "Construct a new `BasisSweepPasses` sequential collection. :param str name: A string uniquely identifying this computation, to be used as a title in the TURBOMOLE input file. :param str coord: Path to the input ``coord`` file. :param str ridft_in: Path to the ``define.in`` file for the RIDFT step... | 3 | null | Implement the Python class `BasisSweepPasses` described below.
Class description:
Build a two-step sequence: - first task is RIDFT with given coordinates and ``define.in`` file; - second task is a parallel collection of RICC2 that uses the output files from the first stage as input, plus a new ``define.in``.
Method s... | Implement the Python class `BasisSweepPasses` described below.
Class description:
Build a two-step sequence: - first task is RIDFT with given coordinates and ``define.in`` file; - second task is a parallel collection of RICC2 that uses the output files from the first stage as input, plus a new ``define.in``.
Method s... | 8d2bc69aa8f2b2dd8e4dc0b306cf484551a20caf | <|skeleton|>
class BasisSweepPasses:
"""Build a two-step sequence: - first task is RIDFT with given coordinates and ``define.in`` file; - second task is a parallel collection of RICC2 that uses the output files from the first stage as input, plus a new ``define.in``."""
def __init__(self, name, coord, ridft_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasisSweepPasses:
"""Build a two-step sequence: - first task is RIDFT with given coordinates and ``define.in`` file; - second task is a parallel collection of RICC2 that uses the output files from the first stage as input, plus a new ``define.in``."""
def __init__(self, name, coord, ridft_in, ricc2_ins, ... | the_stack_v2_python_sparse | gc3apps/turbomole/gricomp.py | TissueMAPS/gc3pie | train | 1 |
ceff95d499b8495db279a0e1c86d454df2a5436f | [
"domain_name = url.split('/')\nif 'http:' in domain_name or 'https:' in domain_name:\n domain_name = domain_name[2]\nelse:\n domain_name = domain_name[0]\nwww_domain_name = domain_name.split('.')\nfinal_domain = ''\nif www_domain_name[0] == 'www':\n final_domain = '.'.join(www_domain_name[1:])\n return ... | <|body_start_0|>
domain_name = url.split('/')
if 'http:' in domain_name or 'https:' in domain_name:
domain_name = domain_name[2]
else:
domain_name = domain_name[0]
www_domain_name = domain_name.split('.')
final_domain = ''
if www_domain_name[0] == ... | WordOps domain validation utilities | WODomain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WODomain:
"""WordOps domain validation utilities"""
def validate(self, url):
"""This function returns domain name removing http:// and https:// returns domain name only with or without www as user provided."""
<|body_0|>
def getlevel(self, domain):
"""Returns the... | stack_v2_sparse_classes_36k_train_018430 | 1,872 | permissive | [
{
"docstring": "This function returns domain name removing http:// and https:// returns domain name only with or without www as user provided.",
"name": "validate",
"signature": "def validate(self, url)"
},
{
"docstring": "Returns the domain type : domain, subdomain and the root domain",
"na... | 2 | stack_v2_sparse_classes_30k_train_004822 | Implement the Python class `WODomain` described below.
Class description:
WordOps domain validation utilities
Method signatures and docstrings:
- def validate(self, url): This function returns domain name removing http:// and https:// returns domain name only with or without www as user provided.
- def getlevel(self,... | Implement the Python class `WODomain` described below.
Class description:
WordOps domain validation utilities
Method signatures and docstrings:
- def validate(self, url): This function returns domain name removing http:// and https:// returns domain name only with or without www as user provided.
- def getlevel(self,... | 64ad38600f98e021e699ee4216d7186197f01b3f | <|skeleton|>
class WODomain:
"""WordOps domain validation utilities"""
def validate(self, url):
"""This function returns domain name removing http:// and https:// returns domain name only with or without www as user provided."""
<|body_0|>
def getlevel(self, domain):
"""Returns the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WODomain:
"""WordOps domain validation utilities"""
def validate(self, url):
"""This function returns domain name removing http:// and https:// returns domain name only with or without www as user provided."""
domain_name = url.split('/')
if 'http:' in domain_name or 'https:' in d... | the_stack_v2_python_sparse | wo/core/domainvalidate.py | WordOps/WordOps | train | 1,214 |
1b516fd1f764b25e83edf869f06c39e327824270 | [
"self.model = BernoulliNB\nself.active_model = None\nself.param_grid = {'alpha': [0, 0.25, 0.5, 0.75, 1], 'fit_prior': [True, False], 'binarize': [True, False]}",
"classifier = GridSearchCV(self.model(), self.param_grid)\nclassifier.fit(training_data, training_labels)\nself.active_model = self.model(**classifier.... | <|body_start_0|>
self.model = BernoulliNB
self.active_model = None
self.param_grid = {'alpha': [0, 0.25, 0.5, 0.75, 1], 'fit_prior': [True, False], 'binarize': [True, False]}
<|end_body_0|>
<|body_start_1|>
classifier = GridSearchCV(self.model(), self.param_grid)
classifier.fit(... | Basic implementation of a grid-search optimized Logistic Regression. | NativeBernoulliBayes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NativeBernoulliBayes:
"""Basic implementation of a grid-search optimized Logistic Regression."""
def __init__(self):
"""Initialize internal classifier."""
<|body_0|>
def train(self, training_data, training_labels):
"""Run grid search to optimize hyper-parameters,... | stack_v2_sparse_classes_36k_train_018431 | 3,287 | no_license | [
{
"docstring": "Initialize internal classifier.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Run grid search to optimize hyper-parameters, then trains the final model.",
"name": "train",
"signature": "def train(self, training_data, training_labels)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_014271 | Implement the Python class `NativeBernoulliBayes` described below.
Class description:
Basic implementation of a grid-search optimized Logistic Regression.
Method signatures and docstrings:
- def __init__(self): Initialize internal classifier.
- def train(self, training_data, training_labels): Run grid search to optim... | Implement the Python class `NativeBernoulliBayes` described below.
Class description:
Basic implementation of a grid-search optimized Logistic Regression.
Method signatures and docstrings:
- def __init__(self): Initialize internal classifier.
- def train(self, training_data, training_labels): Run grid search to optim... | edffa89740e5cef810344a7bbf8a157241f46d02 | <|skeleton|>
class NativeBernoulliBayes:
"""Basic implementation of a grid-search optimized Logistic Regression."""
def __init__(self):
"""Initialize internal classifier."""
<|body_0|>
def train(self, training_data, training_labels):
"""Run grid search to optimize hyper-parameters,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NativeBernoulliBayes:
"""Basic implementation of a grid-search optimized Logistic Regression."""
def __init__(self):
"""Initialize internal classifier."""
self.model = BernoulliNB
self.active_model = None
self.param_grid = {'alpha': [0, 0.25, 0.5, 0.75, 1], 'fit_prior': [T... | the_stack_v2_python_sparse | enso/experiment/NB.py | RichGit101/Enso | train | 0 |
106fc4b8182aaab656b717e0c6f0934f2578715c | [
"Frame.__init__(self, master)\nself.pack()\nself.createWidgets()",
"top_frame = Frame(self)\nself.text1_in = Entry(top_frame)\nself.text2_in = Entry(top_frame)\nself.label = Label(top_frame, text='Output label')\nself.text1_in.pack(side=LEFT)\nself.text2_in.pack(side=LEFT)\nself.label.pack()\ntop_frame.pack(side=... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
self.text1_in = Entry(top_frame)
self.text2_in = Entry(top_frame)
self.label = Label(top_frame, text='Output label')
sel... | Application main window class. | Application | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k_train_018432 | 1,511 | permissive | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createWidgets",
"signature": "def createWidgets(self)"
},
{
"docstring": "Handle ... | 3 | null | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handle a c... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handle a c... | 042e0ce964bc88b3f4132dcbd7e06c5f504eae34 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
"""Add all the widgets to the main fram... | the_stack_v2_python_sparse | Python2/IntroGUI_homework/src/addnumbers.py | ceeblet/OST_PythonCertificationTrack | train | 0 |
ab8b6ef9fd6e00180f28a32f8a9d401ecb4c9d68 | [
"super().__init__(*args, **kwargs)\nself.helper = FormHelper()\nself.helper.form_method = 'post'\nself.helper.layout = Layout('email', 'first_name', 'last_name', 'user_type', 'password1', 'password2', HTML(render_to_string('account/signup-declarations.html')), 'captcha', HTML(render_to_string('account/recaptcha-dec... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout('email', 'first_name', 'last_name', 'user_type', 'password1', 'password2', HTML(render_to_string('account/signup-declarations.html')), 'captcha', HTM... | Sign up for user registration. | SignupForm | [
"MIT",
"AGPL-3.0-only",
"ISC",
"LGPL-2.1-or-later",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupForm:
"""Sign up for user registration."""
def __init__(self, *args, **kwargs):
"""Add crispyform helper to form."""
<|body_0|>
def signup(self, request, user):
"""Extra logic when a user signs up. Required by django-allauth."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_018433 | 7,234 | permissive | [
{
"docstring": "Add crispyform helper to form.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Extra logic when a user signs up. Required by django-allauth.",
"name": "signup",
"signature": "def signup(self, request, user)"
}
] | 2 | null | Implement the Python class `SignupForm` described below.
Class description:
Sign up for user registration.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add crispyform helper to form.
- def signup(self, request, user): Extra logic when a user signs up. Required by django-allauth. | Implement the Python class `SignupForm` described below.
Class description:
Sign up for user registration.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add crispyform helper to form.
- def signup(self, request, user): Extra logic when a user signs up. Required by django-allauth.
<|skeleto... | 5b668eb66449e2ebaeb2177237b9a55a14d69efb | <|skeleton|>
class SignupForm:
"""Sign up for user registration."""
def __init__(self, *args, **kwargs):
"""Add crispyform helper to form."""
<|body_0|>
def signup(self, request, user):
"""Extra logic when a user signs up. Required by django-allauth."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignupForm:
"""Sign up for user registration."""
def __init__(self, *args, **kwargs):
"""Add crispyform helper to form."""
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout('email', 'first_name... | the_stack_v2_python_sparse | codewof/users/forms.py | uccser/codewof | train | 7 |
de7634f482ea3720b88610d28484805fb8693ea0 | [
"self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"def softmax(x):\n \"\"\"Function that perform the softmax function\"\"\"\n e_x = np.exp(x - np.max(x, axis=1, keepdims=True))\n softmax = e_x / e_x.sum(axis=1, ... | <|body_start_0|>
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
def softmax(x):
"""Function that perform the softmax function"""
e_x... | Class that represents a cell of a simple RNN | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""Class that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wh, Wy, bh... | stack_v2_sparse_classes_36k_train_018434 | 2,107 | no_license | [
{
"docstring": "class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wh, Wy, bh, by that represent the weights and biases of the cell Wh and bh are for the concatenated hidden state a... | 2 | null | Implement the Python class `RNNCell` described below.
Class description:
Class that represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the ... | Implement the Python class `RNNCell` described below.
Class description:
Class that represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the ... | e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58 | <|skeleton|>
class RNNCell:
"""Class that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wh, Wy, bh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""Class that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wh, Wy, bh, by that rep... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | AndrewMiranda/holbertonschool-machine_learning-1 | train | 0 |
1cc129d24d3f6412319536b59e21cf62ebc7eb14 | [
"super().__init__(strategy_config)\nself.overbought = strategy_config.get('overbought', '70')\nself.oversold = strategy_config.get('oversold', '30')\nself.time_period = strategy_config.get('time_period', '14')",
"output = abstract.RSI(historical_df, self.time_period)\nif cross_over(output, self.oversold):\n ac... | <|body_start_0|>
super().__init__(strategy_config)
self.overbought = strategy_config.get('overbought', '70')
self.oversold = strategy_config.get('oversold', '30')
self.time_period = strategy_config.get('time_period', '14')
<|end_body_0|>
<|body_start_1|>
output = abstract.RSI(hi... | RSIStrategy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSIStrategy:
def __init__(self, strategy_config: Dict[Text, Any]={}) -> None:
""":param strategy_config: time_period: Calculating rsi of the close prices, with a time period. over_buy: The value at which this might be good to buy over_sell: The value at which this might be good to sell""... | stack_v2_sparse_classes_36k_train_018435 | 1,556 | permissive | [
{
"docstring": ":param strategy_config: time_period: Calculating rsi of the close prices, with a time period. over_buy: The value at which this might be good to buy over_sell: The value at which this might be good to sell",
"name": "__init__",
"signature": "def __init__(self, strategy_config: Dict[Text,... | 2 | stack_v2_sparse_classes_30k_train_021183 | Implement the Python class `RSIStrategy` described below.
Class description:
Implement the RSIStrategy class.
Method signatures and docstrings:
- def __init__(self, strategy_config: Dict[Text, Any]={}) -> None: :param strategy_config: time_period: Calculating rsi of the close prices, with a time period. over_buy: The... | Implement the Python class `RSIStrategy` described below.
Class description:
Implement the RSIStrategy class.
Method signatures and docstrings:
- def __init__(self, strategy_config: Dict[Text, Any]={}) -> None: :param strategy_config: time_period: Calculating rsi of the close prices, with a time period. over_buy: The... | 7fd828fe51832addea65b928193ce625bd091f2c | <|skeleton|>
class RSIStrategy:
def __init__(self, strategy_config: Dict[Text, Any]={}) -> None:
""":param strategy_config: time_period: Calculating rsi of the close prices, with a time period. over_buy: The value at which this might be good to buy over_sell: The value at which this might be good to sell""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RSIStrategy:
def __init__(self, strategy_config: Dict[Text, Any]={}) -> None:
""":param strategy_config: time_period: Calculating rsi of the close prices, with a time period. over_buy: The value at which this might be good to buy over_sell: The value at which this might be good to sell"""
supe... | the_stack_v2_python_sparse | tradingsignal/strategies/rsi_strategy.py | TradingSignal/TradingSignal | train | 2 | |
eadc3751f8ffb06b380949b3641bfd0c39ce454f | [
"url = '/Nal/service/'\nbody = self.client.post(url, data=fields)\nreturn body['result']",
"url = '/Nal/service/'\nbody = self.client.put(url, data=fields)\nreturn body['result']",
"url = '/Nal/service/'\nbody = self.client.delete(url, data=fields)\nreturn body['result']",
"url = '/Nal/service/'\nif kwargs:\n... | <|body_start_0|>
url = '/Nal/service/'
body = self.client.post(url, data=fields)
return body['result']
<|end_body_0|>
<|body_start_1|>
url = '/Nal/service/'
body = self.client.put(url, data=fields)
return body['result']
<|end_body_1|>
<|body_start_2|>
url = '/Na... | Manager class for manipulating Nal. | ServiceManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceManager:
"""Manager class for manipulating Nal."""
def create(self, fields):
"""Create a Service. :param fields: Service data."""
<|body_0|>
def update(self, fields):
"""Update a Service. :param fields: Service data."""
<|body_1|>
def delete(s... | stack_v2_sparse_classes_36k_train_018436 | 1,747 | permissive | [
{
"docstring": "Create a Service. :param fields: Service data.",
"name": "create",
"signature": "def create(self, fields)"
},
{
"docstring": "Update a Service. :param fields: Service data.",
"name": "update",
"signature": "def update(self, fields)"
},
{
"docstring": "Delete a Ser... | 4 | null | Implement the Python class `ServiceManager` described below.
Class description:
Manager class for manipulating Nal.
Method signatures and docstrings:
- def create(self, fields): Create a Service. :param fields: Service data.
- def update(self, fields): Update a Service. :param fields: Service data.
- def delete(self,... | Implement the Python class `ServiceManager` described below.
Class description:
Manager class for manipulating Nal.
Method signatures and docstrings:
- def create(self, fields): Create a Service. :param fields: Service data.
- def update(self, fields): Update a Service. :param fields: Service data.
- def delete(self,... | 24df42ee3927415b552b5e5d7326eecd04ebca61 | <|skeleton|>
class ServiceManager:
"""Manager class for manipulating Nal."""
def create(self, fields):
"""Create a Service. :param fields: Service data."""
<|body_0|>
def update(self, fields):
"""Update a Service. :param fields: Service data."""
<|body_1|>
def delete(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceManager:
"""Manager class for manipulating Nal."""
def create(self, fields):
"""Create a Service. :param fields: Service data."""
url = '/Nal/service/'
body = self.client.post(url, data=fields)
return body['result']
def update(self, fields):
"""Update a... | the_stack_v2_python_sparse | WORKFLOWS/Tools/NEC/NAL/nalclient/nalclient/v1/service.py | openmsa/NO | train | 0 |
d7c841a1c0bc2e9f925ed9e277e34e965d845761 | [
"self.scenario = scenario\nself.actions = load_action_list(scenario)\nnvec = [len(self.action_types), len(self.scenario.subnets) - 1, max(self.scenario.subnets), self.scenario.num_os + 1, self.scenario.num_services, self.scenario.num_processes]\nsuper().__init__(nvec)",
"assert isinstance(action_vec, (list, tuple... | <|body_start_0|>
self.scenario = scenario
self.actions = load_action_list(scenario)
nvec = [len(self.action_types), len(self.scenario.subnets) - 1, max(self.scenario.subnets), self.scenario.num_os + 1, self.scenario.num_services, self.scenario.num_processes]
super().__init__(nvec)
<|end_... | A parameterised action space for NASim environment. Inherits and implements the gym.spaces.MultiDiscrete action space, where each dimension corresponds to a different action parameter. The action parameters (in order) are: 0. Action Type = [0, 5] Where: 0=Exploit, 1=PrivilegeEscalation, 2=ServiceScan, 3=OSScan, 4=Subne... | ParameterisedActionSpace | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterisedActionSpace:
"""A parameterised action space for NASim environment. Inherits and implements the gym.spaces.MultiDiscrete action space, where each dimension corresponds to a different action parameter. The action parameters (in order) are: 0. Action Type = [0, 5] Where: 0=Exploit, 1=P... | stack_v2_sparse_classes_36k_train_018437 | 25,856 | permissive | [
{
"docstring": "Parameters ---------- scenario : Scenario scenario description",
"name": "__init__",
"signature": "def __init__(self, scenario)"
},
{
"docstring": "Get Action object corresponding to action vector. Parameters ---------- action_vector : list of ints or tuple of ints or Numpy.Array... | 5 | stack_v2_sparse_classes_30k_train_000782 | Implement the Python class `ParameterisedActionSpace` described below.
Class description:
A parameterised action space for NASim environment. Inherits and implements the gym.spaces.MultiDiscrete action space, where each dimension corresponds to a different action parameter. The action parameters (in order) are: 0. Act... | Implement the Python class `ParameterisedActionSpace` described below.
Class description:
A parameterised action space for NASim environment. Inherits and implements the gym.spaces.MultiDiscrete action space, where each dimension corresponds to a different action parameter. The action parameters (in order) are: 0. Act... | 4f26de37cfdc3e4553ed8b7484c4db8e2924bdea | <|skeleton|>
class ParameterisedActionSpace:
"""A parameterised action space for NASim environment. Inherits and implements the gym.spaces.MultiDiscrete action space, where each dimension corresponds to a different action parameter. The action parameters (in order) are: 0. Action Type = [0, 5] Where: 0=Exploit, 1=P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterisedActionSpace:
"""A parameterised action space for NASim environment. Inherits and implements the gym.spaces.MultiDiscrete action space, where each dimension corresponds to a different action parameter. The action parameters (in order) are: 0. Action Type = [0, 5] Where: 0=Exploit, 1=PrivilegeEscal... | the_stack_v2_python_sparse | nasim/envs/action.py | Jjschwartz/NetworkAttackSimulator | train | 101 |
f5a0807a38144bec14f22a50da6853b95fcdf96b | [
"try:\n claims = get_jwt_claims()\n authorised_user = get_jwt_identity()\n if claims['is_admin']:\n logs = UserLogModel.fetch_all()\n if logs:\n return (user_logs_schema.dump(logs), 200)\n return ({'message': 'No user logs created yet.'}, 404)\n return ({'message': 'You a... | <|body_start_0|>
try:
claims = get_jwt_claims()
authorised_user = get_jwt_identity()
if claims['is_admin']:
logs = UserLogModel.fetch_all()
if logs:
return (user_logs_schema.dump(logs), 200)
return ({'message... | UserLogList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserLogList:
def get(self):
"""List All Logs"""
<|body_0|>
def post(self):
"""Post User Log"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
claims = get_jwt_claims()
authorised_user = get_jwt_identity()
if cl... | stack_v2_sparse_classes_36k_train_018438 | 7,405 | no_license | [
{
"docstring": "List All Logs",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Post User Log",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012242 | Implement the Python class `UserLogList` described below.
Class description:
Implement the UserLogList class.
Method signatures and docstrings:
- def get(self): List All Logs
- def post(self): Post User Log | Implement the Python class `UserLogList` described below.
Class description:
Implement the UserLogList class.
Method signatures and docstrings:
- def get(self): List All Logs
- def post(self): Post User Log
<|skeleton|>
class UserLogList:
def get(self):
"""List All Logs"""
<|body_0|>
def po... | aa03d0e6491024145d2a6cecf4c4757052c95e06 | <|skeleton|>
class UserLogList:
def get(self):
"""List All Logs"""
<|body_0|>
def post(self):
"""Post User Log"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserLogList:
def get(self):
"""List All Logs"""
try:
claims = get_jwt_claims()
authorised_user = get_jwt_identity()
if claims['is_admin']:
logs = UserLogModel.fetch_all()
if logs:
return (user_logs_schema.d... | the_stack_v2_python_sparse | app/resources/user_logs.py | Keith-Njagi/ecommerce_app_user_management | train | 0 | |
6f1f468e01b1a9c574df90681f64355fba8495ee | [
"super(FunctionComponent, self).__init__(opts)\nself.opts = opts\nself.options = opts.get('fn_utilities', {})",
"try:\n rest_method = self.get_select_param(kwargs.get('rest_method'))\n rest_url = kwargs.get('rest_url')\n rest_headers = self.get_textarea_param(kwargs.get('rest_headers'))\n rest_cookies... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get('fn_utilities', {})
<|end_body_0|>
<|body_start_1|>
try:
rest_method = self.get_select_param(kwargs.get('rest_method'))
rest_url = kwargs.get('rest_url')
... | Component that implements SOAR function 'call_rest_api | FunctionComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements SOAR function 'call_rest_api"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _call_rest_api_function(self, event, *args, **kwargs):
"""Function: Call a REST... | stack_v2_sparse_classes_36k_train_018439 | 5,081 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Function: Call a REST web service. The function parameters determine the type of call (GET, POST, etc), the URL, and optionally the headers an... | 2 | null | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements SOAR function 'call_rest_api
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _call_rest_api_function(self, event, *args, **kwargs): ... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements SOAR function 'call_rest_api
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _call_rest_api_function(self, event, *args, **kwargs): ... | 6878c78b94eeca407998a41ce8db2cc00f2b6758 | <|skeleton|>
class FunctionComponent:
"""Component that implements SOAR function 'call_rest_api"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _call_rest_api_function(self, event, *args, **kwargs):
"""Function: Call a REST... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionComponent:
"""Component that implements SOAR function 'call_rest_api"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get('fn_utilities', {... | the_stack_v2_python_sparse | fn_utilities/fn_utilities/components/utilities_call_rest_api.py | ibmresilient/resilient-community-apps | train | 81 |
968026e1a57b999ee74cf8ed4c9dc0a6672036f5 | [
"def preOrderHelper(node, orderarr):\n if not node:\n orderarr.append('#')\n return\n orderarr.append(str(node.val))\n preOrderHelper(node.left, orderarr)\n preOrderHelper(node.right, orderarr)\ndic = {}\nret = []\n\ndef preOrderjudge(root):\n if root:\n orderarr = []\n pr... | <|body_start_0|>
def preOrderHelper(node, orderarr):
if not node:
orderarr.append('#')
return
orderarr.append(str(node.val))
preOrderHelper(node.left, orderarr)
preOrderHelper(node.right, orderarr)
dic = {}
ret = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_0|>
def findDuplicateSubtrees2(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def ... | stack_v2_sparse_classes_36k_train_018440 | 2,356 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[TreeNode]",
"name": "findDuplicateSubtrees",
"signature": "def findDuplicateSubtrees(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[TreeNode]",
"name": "findDuplicateSubtrees2",
"signature": "def findDuplicateSubtrees2(... | 2 | stack_v2_sparse_classes_30k_train_012318 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode]
- def findDuplicateSubtrees2(self, root): :type root: TreeNode :rtype: List[TreeNode] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode]
- def findDuplicateSubtrees2(self, root): :type root: TreeNode :rtype: List[TreeNode]
<|skelet... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_0|>
def findDuplicateSubtrees2(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
def preOrderHelper(node, orderarr):
if not node:
orderarr.append('#')
return
orderarr.append(str(node.val))
preOrderHelper(node... | the_stack_v2_python_sparse | src/findDuplicateSubtrees.py | jsdiuf/leetcode | train | 1 | |
f53e8d47c874f62e63b8b4e7a2f1b6c2e94f4df6 | [
"try:\n exploration = exp_fetchers.get_exploration_from_model(exp_model)\n exploration.validate(strict=exp_is_published)\n with datastore_services.get_ndb_context():\n if exp_services.get_story_id_linked_to_exploration(exp_model.id) is not None:\n exp_services.validate_exploration_for_sto... | <|body_start_0|>
try:
exploration = exp_fetchers.get_exploration_from_model(exp_model)
exploration.validate(strict=exp_is_published)
with datastore_services.get_ndb_context():
if exp_services.get_story_id_linked_to_exploration(exp_model.id) is not None:
... | Transform that gets all Exploration models, performs migration and filters any error results. | MigrateExplorationModels | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MigrateExplorationModels:
"""Transform that gets all Exploration models, performs migration and filters any error results."""
def _migrate_exploration(exp_model: exp_models.ExplorationModel, exp_is_published: bool) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
... | stack_v2_sparse_classes_36k_train_018441 | 28,752 | permissive | [
{
"docstring": "Migrates exploration and transform exploration model into exploration object. Args: exp_model: ExplorationModel. The exploration model to migrate. exp_is_published: bool. Whether the exploration is published or not. Returns: Result((str, Exploration), (str, Exception)). Result containing tuple t... | 3 | stack_v2_sparse_classes_30k_train_020492 | Implement the Python class `MigrateExplorationModels` described below.
Class description:
Transform that gets all Exploration models, performs migration and filters any error results.
Method signatures and docstrings:
- def _migrate_exploration(exp_model: exp_models.ExplorationModel, exp_is_published: bool) -> result... | Implement the Python class `MigrateExplorationModels` described below.
Class description:
Transform that gets all Exploration models, performs migration and filters any error results.
Method signatures and docstrings:
- def _migrate_exploration(exp_model: exp_models.ExplorationModel, exp_is_published: bool) -> result... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class MigrateExplorationModels:
"""Transform that gets all Exploration models, performs migration and filters any error results."""
def _migrate_exploration(exp_model: exp_models.ExplorationModel, exp_is_published: bool) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MigrateExplorationModels:
"""Transform that gets all Exploration models, performs migration and filters any error results."""
def _migrate_exploration(exp_model: exp_models.ExplorationModel, exp_is_published: bool) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Mi... | the_stack_v2_python_sparse | core/jobs/batch_jobs/exp_migration_jobs.py | oppia/oppia | train | 6,172 |
2b7a968aa766785319eede0edbdff4743b43d032 | [
"self.name = name\nself.domain = domain\nself.filename = file_name\nself.description = description\nself.keywords = set(keywords)",
"if domain.size != self.domain.size:\n return (0, False)\npoints = 0.0\nsame_domain = True\nif len(domain.variables) == len(self.domain.variables):\n n = sum([v1.length if v1.l... | <|body_start_0|>
self.name = name
self.domain = domain
self.filename = file_name
self.description = description
self.keywords = set(keywords)
<|end_body_0|>
<|body_start_1|>
if domain.size != self.domain.size:
return (0, False)
points = 0.0
sa... | DatasetDescriptor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetDescriptor:
def __init__(self, name, file_name, domain, description, keywords):
""":param name: :type name: str :param file_name: :type file_name: str :param domain: :type domain: Domain :param description: :type description: str :param keywords: :type keywords: list[str]"""
... | stack_v2_sparse_classes_36k_train_018442 | 5,188 | no_license | [
{
"docstring": ":param name: :type name: str :param file_name: :type file_name: str :param domain: :type domain: Domain :param description: :type description: str :param keywords: :type keywords: list[str]",
"name": "__init__",
"signature": "def __init__(self, name, file_name, domain, description, keywo... | 2 | stack_v2_sparse_classes_30k_train_013513 | Implement the Python class `DatasetDescriptor` described below.
Class description:
Implement the DatasetDescriptor class.
Method signatures and docstrings:
- def __init__(self, name, file_name, domain, description, keywords): :param name: :type name: str :param file_name: :type file_name: str :param domain: :type dom... | Implement the Python class `DatasetDescriptor` described below.
Class description:
Implement the DatasetDescriptor class.
Method signatures and docstrings:
- def __init__(self, name, file_name, domain, description, keywords): :param name: :type name: str :param file_name: :type file_name: str :param domain: :type dom... | 9f57dabd08e233882483db8728b7b1c2d83f6be8 | <|skeleton|>
class DatasetDescriptor:
def __init__(self, name, file_name, domain, description, keywords):
""":param name: :type name: str :param file_name: :type file_name: str :param domain: :type domain: Domain :param description: :type description: str :param keywords: :type keywords: list[str]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetDescriptor:
def __init__(self, name, file_name, domain, description, keywords):
""":param name: :type name: str :param file_name: :type file_name: str :param domain: :type domain: Domain :param description: :type description: str :param keywords: :type keywords: list[str]"""
self.name =... | the_stack_v2_python_sparse | herl/datasets/library.py | SamuelePolimi/HeRL | train | 3 | |
7f2409baf000c200f843a229735688d5263997e5 | [
"import re\nres = ''\ntmp = re.findall('^[-+]?[\\\\d]+', str.strip())\nif tmp:\n ms = tmp[0]\n if ms[0] == '-' or ms[0] == '+':\n res = ms[1:]\n else:\n res = ms\n res = int(res)\n if ms[0] == '-':\n return max(-res, -2147483648)\n return min(res, 2147483647)\nelse:\n retur... | <|body_start_0|>
import re
res = ''
tmp = re.findall('^[-+]?[\\d]+', str.strip())
if tmp:
ms = tmp[0]
if ms[0] == '-' or ms[0] == '+':
res = ms[1:]
else:
res = ms
res = int(res)
if ms[0] == '-':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi2(self, str):
""":type str: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import re
res = ''
tmp = re.findall('^[-+]?[\\d]+', st... | stack_v2_sparse_classes_36k_train_018443 | 1,417 | no_license | [
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi",
"signature": "def myAtoi(self, str)"
},
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi2",
"signature": "def myAtoi2(self, str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003785 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, str): :type str: str :rtype: int
- def myAtoi2(self, str): :type str: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, str): :type str: str :rtype: int
- def myAtoi2(self, str): :type str: str :rtype: int
<|skeleton|>
class Solution:
def myAtoi(self, str):
""":type ... | 829f918a0d4d94da5fd3004768421974fbe056e7 | <|skeleton|>
class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi2(self, str):
""":type str: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
import re
res = ''
tmp = re.findall('^[-+]?[\\d]+', str.strip())
if tmp:
ms = tmp[0]
if ms[0] == '-' or ms[0] == '+':
res = ms[1:]
else:
... | the_stack_v2_python_sparse | leetcode/medium/8_字符串转换成整数.py | Weikoi/OJ_Python | train | 0 | |
c2a4af0a2511deffd1afc708170ab0c0d396a864 | [
"if 'username' in request.COOKIES:\n username = request.COOKIES.get('username')\n checked = 'checked'\nelse:\n username = ''\n checked = ''\nreturn render(request, 'login.html', {'username': username, 'checked': checked})",
"username = request.POST.get('username')\npassword = request.POST.get('pwd')\n... | <|body_start_0|>
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked = 'checked'
else:
username = ''
checked = ''
return render(request, 'login.html', {'username': username, 'checked': checked})
<|end_body_0|>
<|bo... | 登录 | LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request):
"""登录校验"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
... | stack_v2_sparse_classes_36k_train_018444 | 10,797 | no_license | [
{
"docstring": "显示登录页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "登录校验",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001035 | Implement the Python class `LoginView` described below.
Class description:
登录
Method signatures and docstrings:
- def get(self, request): 显示登录页面
- def post(self, request): 登录校验 | Implement the Python class `LoginView` described below.
Class description:
登录
Method signatures and docstrings:
- def get(self, request): 显示登录页面
- def post(self, request): 登录校验
<|skeleton|>
class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request)... | 02eeb9bb293d6c3cf3d9882855f558de40238e10 | <|skeleton|>
class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request):
"""登录校验"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked = 'checked'
else:
username = ''
checked = ''
return render(request, 'login.html', {... | the_stack_v2_python_sparse | dailyfresh/user/views.py | pythonfeiji/djangoproject_1803 | train | 0 |
54e621a6bbf47bc2d25f0e9514ca32b062f0f68d | [
"clen = len(prerequisites)\nif clen == 0:\n return True\nvisited = [0 for _ in range(numCourses)]\ninverse_adj = [set() for _ in range(numCourses)]\nfor second, first in prerequisites:\n inverse_adj[second].add(first)\nfor i in range(numCourses):\n if self.__dfs(i, inverse_adj, visited):\n return Fa... | <|body_start_0|>
clen = len(prerequisites)
if clen == 0:
return True
visited = [0 for _ in range(numCourses)]
inverse_adj = [set() for _ in range(numCourses)]
for second, first in prerequisites:
inverse_adj[second].add(first)
for i in range(numCour... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
<|body_0|>
def __dfs(self, vertex, inverse_adj, visited):
"""注意:这个递归方法的返回值是返回是否有环 :pa... | stack_v2_sparse_classes_36k_train_018445 | 2,803 | permissive | [
{
"docstring": ":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool",
"name": "canFinish",
"signature": "def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool"
},
{
"docstring": "注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inverse_a... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool
- def __dfs(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool
- def __dfs(... | baabdb1990fd49ab82a712e121f49c4f68b29459 | <|skeleton|>
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
<|body_0|>
def __dfs(self, vertex, inverse_adj, visited):
"""注意:这个递归方法的返回值是返回是否有环 :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
clen = len(prerequisites)
if clen == 0:
return True
visited = [0 for _ in range(numC... | the_stack_v2_python_sparse | topological-sort/Python/0207-course-schedule(使用 DFS、逆邻接表、要设置三个状态).py | lemonnader/LeetCode-Solution-Well-Formed | train | 1 | |
a944df114a75c3f72cc6e646e0974c11eab1157a | [
"self.spider = Base_Spider(LgCfg)\nself.first_url = 'https://www.lagou.com/jobs/list_Python?px=new&gx=%E5%85%A8%E8%81%8C&city=%E5%8C%97%E4%BA%AC#order'\n'\\n r = self.spider.get_content(self.first_url)\\n cookies = dict(r.cookies) if not isinstance(r.cookies,dict) else r.cookies\\n cookies = co... | <|body_start_0|>
self.spider = Base_Spider(LgCfg)
self.first_url = 'https://www.lagou.com/jobs/list_Python?px=new&gx=%E5%85%A8%E8%81%8C&city=%E5%8C%97%E4%BA%AC#order'
'\n r = self.spider.get_content(self.first_url)\n cookies = dict(r.cookies) if not isinstance(r.cookies,dict) else ... | LG_Spider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LG_Spider:
def start_requests(self):
"""the method aims at getting the page number. :return:"""
<|body_0|>
def parse(self, response):
"""crawl related urls.the related url means the title must contains keyword python or web. otherwise,need to exclude these urls. :par... | stack_v2_sparse_classes_36k_train_018446 | 4,818 | permissive | [
{
"docstring": "the method aims at getting the page number. :return:",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "crawl related urls.the related url means the title must contains keyword python or web. otherwise,need to exclude these urls. :param respons... | 3 | stack_v2_sparse_classes_30k_train_002405 | Implement the Python class `LG_Spider` described below.
Class description:
Implement the LG_Spider class.
Method signatures and docstrings:
- def start_requests(self): the method aims at getting the page number. :return:
- def parse(self, response): crawl related urls.the related url means the title must contains key... | Implement the Python class `LG_Spider` described below.
Class description:
Implement the LG_Spider class.
Method signatures and docstrings:
- def start_requests(self): the method aims at getting the page number. :return:
- def parse(self, response): crawl related urls.the related url means the title must contains key... | ffae64974e3dda6828edea88167c6591224b998d | <|skeleton|>
class LG_Spider:
def start_requests(self):
"""the method aims at getting the page number. :return:"""
<|body_0|>
def parse(self, response):
"""crawl related urls.the related url means the title must contains keyword python or web. otherwise,need to exclude these urls. :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LG_Spider:
def start_requests(self):
"""the method aims at getting the page number. :return:"""
self.spider = Base_Spider(LgCfg)
self.first_url = 'https://www.lagou.com/jobs/list_Python?px=new&gx=%E5%85%A8%E8%81%8C&city=%E5%8C%97%E4%BA%AC#order'
'\n r = self.spider.get_c... | the_stack_v2_python_sparse | spider/jobspider/spiders/lagou.py | haipersist/webspider | train | 0 | |
8b1df7f45610beabb4ce1592ec51d60f3e9595f6 | [
"self.PntRefNum = None\nif FirstTraverse:\n self.CheckSurveyOrigin(LandXML_Obj)\n if self.PntRefNum is None:\n self.BdyConnectionStart(LandXML_Obj)",
"ConnectionChecker = BDY_Connections.CheckBdyConnection(self.PntRefNum, LandXML_Obj)\nfor point in LandXML_Obj.Coordinates.getchildren():\n if point... | <|body_start_0|>
self.PntRefNum = None
if FirstTraverse:
self.CheckSurveyOrigin(LandXML_Obj)
if self.PntRefNum is None:
self.BdyConnectionStart(LandXML_Obj)
<|end_body_0|>
<|body_start_1|>
ConnectionChecker = BDY_Connections.CheckBdyConnection(self.PntRef... | TraverseStart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraverseStart:
def __init__(self, LandXML_Obj, FirstTraverse):
"""Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:"""
<|body_0|>
def CheckSurveyOrigin(self, LandXML_Obj):
"""Checks surve... | stack_v2_sparse_classes_36k_train_018447 | 3,127 | no_license | [
{
"docstring": "Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:",
"name": "__init__",
"signature": "def __init__(self, LandXML_Obj, FirstTraverse)"
},
{
"docstring": "Checks survey origin if it is connected to a BD... | 3 | stack_v2_sparse_classes_30k_train_006779 | Implement the Python class `TraverseStart` described below.
Class description:
Implement the TraverseStart class.
Method signatures and docstrings:
- def __init__(self, LandXML_Obj, FirstTraverse): Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param Lan... | Implement the Python class `TraverseStart` described below.
Class description:
Implement the TraverseStart class.
Method signatures and docstrings:
- def __init__(self, LandXML_Obj, FirstTraverse): Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param Lan... | ccdc172ae5b5ef44de342d2d813b8ee21e9ba63e | <|skeleton|>
class TraverseStart:
def __init__(self, LandXML_Obj, FirstTraverse):
"""Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:"""
<|body_0|>
def CheckSurveyOrigin(self, LandXML_Obj):
"""Checks surve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TraverseStart:
def __init__(self, LandXML_Obj, FirstTraverse):
"""Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:"""
self.PntRefNum = None
if FirstTraverse:
self.CheckSurveyOrigin(LandXML_Obj)... | the_stack_v2_python_sparse | src/LandXML/RefMarks/TraverseStart.py | sparkes-intrax/SurveyingCalcsUI | train | 0 | |
8e00a064e4c1962219e02a7dc9195d87a2d5da7c | [
"if not isinstance(xs, list):\n return SyntaxError\nif not all([isinstance(x, list) for x in xs]):\n result = ' '.join([str(x) for x in xs])\nelse:\n n = range(len(xs))\n ps = [len(str(x)) for x in xs[-1]]\n str_table_list = ['|'.join(line) for line in [['%*d' % v for v in zip(ps, xs[n])] for n in ra... | <|body_start_0|>
if not isinstance(xs, list):
return SyntaxError
if not all([isinstance(x, list) for x in xs]):
result = ' '.join([str(x) for x in xs])
else:
n = range(len(xs))
ps = [len(str(x)) for x in xs[-1]]
str_table_list = ['|'.jo... | TableShow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableShow:
def __init__(self, *xs, index=None, column=None, mode=0):
"""リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)"""
<|body_0|>
def show(s... | stack_v2_sparse_classes_36k_train_018448 | 1,358 | no_license | [
{
"docstring": "リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)",
"name": "__init__",
"signature": "def __init__(self, *xs, index=None, column=None, mode=0)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_001193 | Implement the Python class `TableShow` described below.
Class description:
Implement the TableShow class.
Method signatures and docstrings:
- def __init__(self, *xs, index=None, column=None, mode=0): リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mo... | Implement the Python class `TableShow` described below.
Class description:
Implement the TableShow class.
Method signatures and docstrings:
- def __init__(self, *xs, index=None, column=None, mode=0): リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mo... | 2bf21081dd4803c7f4702b6cfccbaca3d2aa6f7b | <|skeleton|>
class TableShow:
def __init__(self, *xs, index=None, column=None, mode=0):
"""リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)"""
<|body_0|>
def show(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TableShow:
def __init__(self, *xs, index=None, column=None, mode=0):
"""リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)"""
if not isinstance(xs, list):
... | the_stack_v2_python_sparse | Python/201910/191010/TableShow00.py | 96no3/PythonStudy | train | 0 | |
fac277006581361c28119f9a8fc65ee8719ddfc4 | [
"self.op = op\nself.sa = sa\nbind = op.get_bind()\nself.insp = sa.inspect(bind)\nself.Session = sa.orm.sessionmaker(bind=bind)\nself.bind = bind\nfor name in kwargs:\n setattr(self, name, kwargs[name])",
"op = self.op\nsa = self.sa\nbind = self.bind\nmeta = sa.MetaData()\nsession = self.Session()\nsource_col_n... | <|body_start_0|>
self.op = op
self.sa = sa
bind = op.get_bind()
self.insp = sa.inspect(bind)
self.Session = sa.orm.sessionmaker(bind=bind)
self.bind = bind
for name in kwargs:
setattr(self, name, kwargs[name])
<|end_body_0|>
<|body_start_1|>
o... | AlembicHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlembicHelper:
def __init__(self, op, sa, **kwargs):
"""Pull in the current alembic context."""
<|body_0|>
def move_foreign_key_column(self, source_table_name, dest_table_name, source_col_name=None, dest_col_name=None):
"""Move foreign key from one side of a relation... | stack_v2_sparse_classes_36k_train_018449 | 3,748 | no_license | [
{
"docstring": "Pull in the current alembic context.",
"name": "__init__",
"signature": "def __init__(self, op, sa, **kwargs)"
},
{
"docstring": "Move foreign key from one side of a relationship to another. Great if you built your database wrong and need to fix it.",
"name": "move_foreign_ke... | 4 | stack_v2_sparse_classes_30k_train_020659 | Implement the Python class `AlembicHelper` described below.
Class description:
Implement the AlembicHelper class.
Method signatures and docstrings:
- def __init__(self, op, sa, **kwargs): Pull in the current alembic context.
- def move_foreign_key_column(self, source_table_name, dest_table_name, source_col_name=None,... | Implement the Python class `AlembicHelper` described below.
Class description:
Implement the AlembicHelper class.
Method signatures and docstrings:
- def __init__(self, op, sa, **kwargs): Pull in the current alembic context.
- def move_foreign_key_column(self, source_table_name, dest_table_name, source_col_name=None,... | 6168d7938c72a5a0bb36ca40b96a2a7232021cb5 | <|skeleton|>
class AlembicHelper:
def __init__(self, op, sa, **kwargs):
"""Pull in the current alembic context."""
<|body_0|>
def move_foreign_key_column(self, source_table_name, dest_table_name, source_col_name=None, dest_col_name=None):
"""Move foreign key from one side of a relation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlembicHelper:
def __init__(self, op, sa, **kwargs):
"""Pull in the current alembic context."""
self.op = op
self.sa = sa
bind = op.get_bind()
self.insp = sa.inspect(bind)
self.Session = sa.orm.sessionmaker(bind=bind)
self.bind = bind
for name in... | the_stack_v2_python_sparse | alembic/alembic_helpers.py | elthran/RPG-Game | train | 0 | |
4424c2d54552930d92305b87413c1b0a7b82975d | [
"if to_idx:\n self.l = [i for i in xrange(from_idx, to_idx)]\n if not self.l:\n raise ValueError\nelse:\n self.l = from_idx\nself.pos = len(self.l)",
"self.pos += 1\nif self.pos >= len(self.l):\n random.shuffle(self.l)\n self.pos = 0\nreturn self.l[self.pos]"
] | <|body_start_0|>
if to_idx:
self.l = [i for i in xrange(from_idx, to_idx)]
if not self.l:
raise ValueError
else:
self.l = from_idx
self.pos = len(self.l)
<|end_body_0|>
<|body_start_1|>
self.pos += 1
if self.pos >= len(self.l):... | This class can be used for reshuffling. Given a range of integers, it shuffles them and yields the shuffled numbers one by one. After having shown all numbers once, shuffle again and iterate through the new list. This assures complete coverage of the data. | Reshuffler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reshuffler:
"""This class can be used for reshuffling. Given a range of integers, it shuffles them and yields the shuffled numbers one by one. After having shown all numbers once, shuffle again and iterate through the new list. This assures complete coverage of the data."""
def __init__(self... | stack_v2_sparse_classes_36k_train_018450 | 34,005 | permissive | [
{
"docstring": "Create a new instance. Range boundaries are similar to ``xrange``. If the first and single argument is a list, it provides the allowed indices directly Args: from_idx (int or list): Lower bound of integer range (inclusive). If this is a list and the second argument is not provided, this lists al... | 2 | stack_v2_sparse_classes_30k_train_016375 | Implement the Python class `Reshuffler` described below.
Class description:
This class can be used for reshuffling. Given a range of integers, it shuffles them and yields the shuffled numbers one by one. After having shown all numbers once, shuffle again and iterate through the new list. This assures complete coverage... | Implement the Python class `Reshuffler` described below.
Class description:
This class can be used for reshuffling. Given a range of integers, it shuffles them and yields the shuffled numbers one by one. After having shown all numbers once, shuffle again and iterate through the new list. This assures complete coverage... | 533b0e5627d8dcef3adccf76e776d3dea5c24a3c | <|skeleton|>
class Reshuffler:
"""This class can be used for reshuffling. Given a range of integers, it shuffles them and yields the shuffled numbers one by one. After having shown all numbers once, shuffle again and iterate through the new list. This assures complete coverage of the data."""
def __init__(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reshuffler:
"""This class can be used for reshuffling. Given a range of integers, it shuffles them and yields the shuffled numbers one by one. After having shown all numbers once, shuffle again and iterate through the new list. This assures complete coverage of the data."""
def __init__(self, from_idx, t... | the_stack_v2_python_sparse | cam/sgnmt/blocks/stream.py | srgangireddy/sgnmt | train | 0 |
fd4bc45bdf24914b5d695661b8c8d42b6767da5c | [
"session_option = onnxruntime.SessionOptions()\nsession_option.log_severity_level = 3\nsession_option.intra_op_num_threads = psutil.cpu_count(logical=True) - 1\nself.onnx_session = onnxruntime.InferenceSession(model_path, sess_options=session_option, providers=providers)\nself.providers = self.onnx_session.get_prov... | <|body_start_0|>
session_option = onnxruntime.SessionOptions()
session_option.log_severity_level = 3
session_option.intra_op_num_threads = psutil.cpu_count(logical=True) - 1
self.onnx_session = onnxruntime.InferenceSession(model_path, sess_options=session_option, providers=providers)
... | UAEDONNX | [
"AGPL-3.0-only",
"LicenseRef-scancode-proprietary-license",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UAEDONNX:
def __init__(self, model_path: Optional[str]='uaed_1x3x480x640.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvider', 'CPUExecutionProvider']):
"""UAEDON... | stack_v2_sparse_classes_36k_train_018451 | 7,317 | permissive | [
{
"docstring": "UAEDONNX Parameters ---------- model_path: Optional[str] ONNX file path providers: Optional[List] Name of onnx execution providers",
"name": "__init__",
"signature": "def __init__(self, model_path: Optional[str]='uaed_1x3x480x640.onnx', providers: Optional[List]=[('TensorrtExecutionProvi... | 3 | null | Implement the Python class `UAEDONNX` described below.
Class description:
Implement the UAEDONNX class.
Method signatures and docstrings:
- def __init__(self, model_path: Optional[str]='uaed_1x3x480x640.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache... | Implement the Python class `UAEDONNX` described below.
Class description:
Implement the UAEDONNX class.
Method signatures and docstrings:
- def __init__(self, model_path: Optional[str]='uaed_1x3x480x640.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache... | ff08e6e8ab095d98e96fc4a136ad5cbccc75fcf9 | <|skeleton|>
class UAEDONNX:
def __init__(self, model_path: Optional[str]='uaed_1x3x480x640.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvider', 'CPUExecutionProvider']):
"""UAEDON... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UAEDONNX:
def __init__(self, model_path: Optional[str]='uaed_1x3x480x640.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvider', 'CPUExecutionProvider']):
"""UAEDONNX Parameters ... | the_stack_v2_python_sparse | 408_UAED/demo/demo_uaed_onnx.py | PINTO0309/PINTO_model_zoo | train | 2,849 | |
709fbd4599794c5cfda6e1ef3f1ff9ea620d3f49 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TimeBasedAttributeTrigger()",
"from .workflow_execution_trigger import WorkflowExecutionTrigger\nfrom .workflow_trigger_time_based_attribute import WorkflowTriggerTimeBasedAttribute\nfrom .workflow_execution_trigger import WorkflowExec... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TimeBasedAttributeTrigger()
<|end_body_0|>
<|body_start_1|>
from .workflow_execution_trigger import WorkflowExecutionTrigger
from .workflow_trigger_time_based_attribute import WorkflowTr... | TimeBasedAttributeTrigger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeBasedAttributeTrigger:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeBasedAttributeTrigger:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | stack_v2_sparse_classes_36k_train_018452 | 3,115 | 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: TimeBasedAttributeTrigger",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `TimeBasedAttributeTrigger` described below.
Class description:
Implement the TimeBasedAttributeTrigger class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeBasedAttributeTrigger: Creates a new instance of the appropriat... | Implement the Python class `TimeBasedAttributeTrigger` described below.
Class description:
Implement the TimeBasedAttributeTrigger class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeBasedAttributeTrigger: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TimeBasedAttributeTrigger:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeBasedAttributeTrigger:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeBasedAttributeTrigger:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeBasedAttributeTrigger:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | the_stack_v2_python_sparse | msgraph/generated/models/identity_governance/time_based_attribute_trigger.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4665cf2754a3fd98b5f8cae38d0a5b903d2885f6 | [
"self.image = image.astype(float, copy=False)\nself.margin = margin\nself.search_radius = search_radius\nself.radius = peak_radius\nself.peak_count = np.zeros(image.shape, dtype=int)\nself.pre_filter = pre_filter\nself.bg_estimator = bg_estimator",
"image = image.astype(float, copy=False)\nbg = self.bg_estimator(... | <|body_start_0|>
self.image = image.astype(float, copy=False)
self.margin = margin
self.search_radius = search_radius
self.radius = peak_radius
self.peak_count = np.zeros(image.shape, dtype=int)
self.pre_filter = pre_filter
self.bg_estimator = bg_estimator
<|end_b... | Routines for finding local maxima in an image Attributes ---------- max_peak_count : int Maximum number of times one peak (at the same spot) will be picked up. Defaults to 2. | Finder | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Finder:
"""Routines for finding local maxima in an image Attributes ---------- max_peak_count : int Maximum number of times one peak (at the same spot) will be picked up. Defaults to 2."""
def __init__(self, image, peak_radius, search_radius=5, margin=10, pre_filter=snr_filters.Identity(), b... | stack_v2_sparse_classes_36k_train_018453 | 6,456 | permissive | [
{
"docstring": "Parameters ---------- peak_radius : float Initial guess of peaks' radii search_radius : int, optional Search for local maxima within this radius. That is, if two local maxima are within search_radius of each other, only the greater one will be taken. Defaults to 5 margin : int, optional How much... | 3 | null | Implement the Python class `Finder` described below.
Class description:
Routines for finding local maxima in an image Attributes ---------- max_peak_count : int Maximum number of times one peak (at the same spot) will be picked up. Defaults to 2.
Method signatures and docstrings:
- def __init__(self, image, peak_radi... | Implement the Python class `Finder` described below.
Class description:
Routines for finding local maxima in an image Attributes ---------- max_peak_count : int Maximum number of times one peak (at the same spot) will be picked up. Defaults to 2.
Method signatures and docstrings:
- def __init__(self, image, peak_radi... | 2f953e553f32118c3ad1f244481e5a0ac6c533f0 | <|skeleton|>
class Finder:
"""Routines for finding local maxima in an image Attributes ---------- max_peak_count : int Maximum number of times one peak (at the same spot) will be picked up. Defaults to 2."""
def __init__(self, image, peak_radius, search_radius=5, margin=10, pre_filter=snr_filters.Identity(), b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Finder:
"""Routines for finding local maxima in an image Attributes ---------- max_peak_count : int Maximum number of times one peak (at the same spot) will be picked up. Defaults to 2."""
def __init__(self, image, peak_radius, search_radius=5, margin=10, pre_filter=snr_filters.Identity(), bg_estimator=_... | the_stack_v2_python_sparse | sdt/loc/daostorm_3d/find.py | schuetzgroup/sdt-python | train | 31 |
298efcb9bca28839396b1980075a94d298edb1a0 | [
"frame_load = 10 * [['H'], ['T']]\nexpected = math.log(2)\nframe = self.context.frame.create(frame_load, schema=[('data', str)])\ncomputed_entropy = frame.entropy('data')\nself.assertAlmostEqual(computed_entropy, expected, delta=0.001)",
"frame_load = [[0, 1], [1, 2], [2, 4], [4, 8]]\nexpected = 1.640223928941852... | <|body_start_0|>
frame_load = 10 * [['H'], ['T']]
expected = math.log(2)
frame = self.context.frame.create(frame_load, schema=[('data', str)])
computed_entropy = frame.entropy('data')
self.assertAlmostEqual(computed_entropy, expected, delta=0.001)
<|end_body_0|>
<|body_start_1|>... | EntropyTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntropyTest:
def test_entropy_coin_flip(self):
"""Get entropy on balanced coin flip."""
<|body_0|>
def test_entropy_exponential(self):
"""Get entropy on exponential distribution."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
frame_load = 10 * [['H... | stack_v2_sparse_classes_36k_train_018454 | 2,228 | permissive | [
{
"docstring": "Get entropy on balanced coin flip.",
"name": "test_entropy_coin_flip",
"signature": "def test_entropy_coin_flip(self)"
},
{
"docstring": "Get entropy on exponential distribution.",
"name": "test_entropy_exponential",
"signature": "def test_entropy_exponential(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017153 | Implement the Python class `EntropyTest` described below.
Class description:
Implement the EntropyTest class.
Method signatures and docstrings:
- def test_entropy_coin_flip(self): Get entropy on balanced coin flip.
- def test_entropy_exponential(self): Get entropy on exponential distribution. | Implement the Python class `EntropyTest` described below.
Class description:
Implement the EntropyTest class.
Method signatures and docstrings:
- def test_entropy_coin_flip(self): Get entropy on balanced coin flip.
- def test_entropy_exponential(self): Get entropy on exponential distribution.
<|skeleton|>
class Entr... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class EntropyTest:
def test_entropy_coin_flip(self):
"""Get entropy on balanced coin flip."""
<|body_0|>
def test_entropy_exponential(self):
"""Get entropy on exponential distribution."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntropyTest:
def test_entropy_coin_flip(self):
"""Get entropy on balanced coin flip."""
frame_load = 10 * [['H'], ['T']]
expected = math.log(2)
frame = self.context.frame.create(frame_load, schema=[('data', str)])
computed_entropy = frame.entropy('data')
self.as... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/frames/entropy_test.py | trustedanalytics/spark-tk | train | 35 | |
aa3b77ffcd4eaad46e09589f2179853c828083c5 | [
"deque = collections.deque([root])\nresult = ['#']\nwhile deque:\n node = deque.popleft()\n if node:\n deque.append(node.left)\n deque.append(node.right)\n result.append(str(node.val))\n else:\n result.append('#')\nreturn ' '.join(result)",
"if data == '# #':\n return None\... | <|body_start_0|>
deque = collections.deque([root])
result = ['#']
while deque:
node = deque.popleft()
if node:
deque.append(node.left)
deque.append(node.right)
result.append(str(node.val))
else:
r... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_018455 | 1,817 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 1a773bb02871d418def9629f608c68c4b0e8fe4e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
deque = collections.deque([root])
result = ['#']
while deque:
node = deque.popleft()
if node:
deque.append(node.left)
... | the_stack_v2_python_sparse | archive-len/leetcode/ch14-tree/p47-serialize-and-deserialize-binary-tree.py | LenKIM/implements | train | 3 | |
3517b4163199387526767f7f9c9fc5ee07ae98cd | [
"report = self.report\nobjs = AssessmentVersion.objects.filter(report=report).order_by('slo__number', 'number')\nreturn objs",
"context = super(AssessmentSummary, self).get_context_data()\ncontext['toDo'] = todoGetter(2, self.report)\ncontext['reqTodo'] = len(context['toDo']['r'])\ncontext['sugTodo'] = len(contex... | <|body_start_0|>
report = self.report
objs = AssessmentVersion.objects.filter(report=report).order_by('slo__number', 'number')
return objs
<|end_body_0|>
<|body_start_1|>
context = super(AssessmentSummary, self).get_context_data()
context['toDo'] = todoGetter(2, self.report)
... | View to summarize state of assessment section of form | AssessmentSummary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssessmentSummary:
"""View to summarize state of assessment section of form"""
def get_queryset(self):
"""Returns assessments in report ordered by SLO Returns: QuerySet : :class:`~makeReports.models.assessment_models.AssessmentVersion` objects in report"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_018456 | 27,436 | no_license | [
{
"docstring": "Returns assessments in report ordered by SLO Returns: QuerySet : :class:`~makeReports.models.assessment_models.AssessmentVersion` objects in report",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Gets context for template Notes: calls section2Co... | 2 | stack_v2_sparse_classes_30k_train_013277 | Implement the Python class `AssessmentSummary` described below.
Class description:
View to summarize state of assessment section of form
Method signatures and docstrings:
- def get_queryset(self): Returns assessments in report ordered by SLO Returns: QuerySet : :class:`~makeReports.models.assessment_models.Assessment... | Implement the Python class `AssessmentSummary` described below.
Class description:
View to summarize state of assessment section of form
Method signatures and docstrings:
- def get_queryset(self): Returns assessments in report ordered by SLO Returns: QuerySet : :class:`~makeReports.models.assessment_models.Assessment... | 472a6fd487811002a60a7812ae2eef941e7182cc | <|skeleton|>
class AssessmentSummary:
"""View to summarize state of assessment section of form"""
def get_queryset(self):
"""Returns assessments in report ordered by SLO Returns: QuerySet : :class:`~makeReports.models.assessment_models.AssessmentVersion` objects in report"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssessmentSummary:
"""View to summarize state of assessment section of form"""
def get_queryset(self):
"""Returns assessments in report ordered by SLO Returns: QuerySet : :class:`~makeReports.models.assessment_models.AssessmentVersion` objects in report"""
report = self.report
obj... | the_stack_v2_python_sparse | AACForm/makeReports/views/assessment_views.py | jdboyd-github/AAC-Capstone | train | 0 |
b40649f78e62e1a7f1cf93fe86becbb53f51a325 | [
"if not s:\n return ''\nn = len(s)\ndp = [[False] * n for _ in range(n)]\nmax_len = 1\nres = s[0]\nfor i in range(n):\n dp[i][i] = True\nfor j in range(1, n):\n for i in range(j):\n if s[i] == s[j]:\n if j - 1 - (i + 1) + 1 >= 2:\n dp[i][j] = dp[i + 1][j - 1]\n e... | <|body_start_0|>
if not s:
return ''
n = len(s)
dp = [[False] * n for _ in range(n)]
max_len = 1
res = s[0]
for i in range(n):
dp[i][i] = True
for j in range(1, n):
for i in range(j):
if s[i] == s[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""首先想到暴力:两重循环, 第一重,从头到尾遍历字符串,i 第二重,从头到尾取j属于[0, i], 看[i, j]是否为回文 时间复杂度:n**3 所以我们继续考虑,引入动态规划,空间换时间,这是从中间往外扩散过程 状态转移方程dp[i][j] = dp[i+1][j-1] if s[i] == s[j] and (j-1)-(i+1) + 1>= 2 True if s[i] == s[j] and j-1 - (i+1) + 1< 2 表明字符串长度不足2,为1 False if... | stack_v2_sparse_classes_36k_train_018457 | 4,417 | no_license | [
{
"docstring": "首先想到暴力:两重循环, 第一重,从头到尾遍历字符串,i 第二重,从头到尾取j属于[0, i], 看[i, j]是否为回文 时间复杂度:n**3 所以我们继续考虑,引入动态规划,空间换时间,这是从中间往外扩散过程 状态转移方程dp[i][j] = dp[i+1][j-1] if s[i] == s[j] and (j-1)-(i+1) + 1>= 2 True if s[i] == s[j] and j-1 - (i+1) + 1< 2 表明字符串长度不足2,为1 False if s[i] != s[j] 表明就不是字符串 考虑初始状态:自下而上,初始状态为字符串长度==1,dp[i... | 2 | stack_v2_sparse_classes_30k_train_020635 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): 首先想到暴力:两重循环, 第一重,从头到尾遍历字符串,i 第二重,从头到尾取j属于[0, i], 看[i, j]是否为回文 时间复杂度:n**3 所以我们继续考虑,引入动态规划,空间换时间,这是从中间往外扩散过程 状态转移方程dp[i][j] = dp[i+1][j-1] if s[i] =... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): 首先想到暴力:两重循环, 第一重,从头到尾遍历字符串,i 第二重,从头到尾取j属于[0, i], 看[i, j]是否为回文 时间复杂度:n**3 所以我们继续考虑,引入动态规划,空间换时间,这是从中间往外扩散过程 状态转移方程dp[i][j] = dp[i+1][j-1] if s[i] =... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""首先想到暴力:两重循环, 第一重,从头到尾遍历字符串,i 第二重,从头到尾取j属于[0, i], 看[i, j]是否为回文 时间复杂度:n**3 所以我们继续考虑,引入动态规划,空间换时间,这是从中间往外扩散过程 状态转移方程dp[i][j] = dp[i+1][j-1] if s[i] == s[j] and (j-1)-(i+1) + 1>= 2 True if s[i] == s[j] and j-1 - (i+1) + 1< 2 表明字符串长度不足2,为1 False if... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
"""首先想到暴力:两重循环, 第一重,从头到尾遍历字符串,i 第二重,从头到尾取j属于[0, i], 看[i, j]是否为回文 时间复杂度:n**3 所以我们继续考虑,引入动态规划,空间换时间,这是从中间往外扩散过程 状态转移方程dp[i][j] = dp[i+1][j-1] if s[i] == s[j] and (j-1)-(i+1) + 1>= 2 True if s[i] == s[j] and j-1 - (i+1) + 1< 2 表明字符串长度不足2,为1 False if s[i] != s[j] ... | the_stack_v2_python_sparse | leetcode/动态规划/5. 最长回文子串/longestPalindrome.py | guohaoyuan/algorithms-for-work | train | 2 | |
28c6ffc88b9377fe30b3cf8b595f231cb21fe5b2 | [
"url = host + '/api/address/create'\ndata = {'name': '王小二', 'phone': '13812151334', 'city': '江苏', 'address': '三人行', 'isdefault': 0}\nr = requests.post(url=url, headers=header, data=data).json()\nout_format('创建收货地址:', r)\nreturn r",
"url = host + '/api/address/update'\ndata = {'id': address_id, 'name': '张晓', 'phon... | <|body_start_0|>
url = host + '/api/address/create'
data = {'name': '王小二', 'phone': '13812151334', 'city': '江苏', 'address': '三人行', 'isdefault': 0}
r = requests.post(url=url, headers=header, data=data).json()
out_format('创建收货地址:', r)
return r
<|end_body_0|>
<|body_start_1|>
... | 定义一个地址管理所有接口的测试类 | address | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class address:
"""定义一个地址管理所有接口的测试类"""
def creat_address(self):
"""创建收货地址 :param:token:用户授权的token :param:name:收货人姓名 :param:phone:手机号码 :param:city:省市区 :param:address:地址 :param:isdefault:是否默认地址,默认值: 0 :return: 以上参数均为必填"""
<|body_0|>
def address_update(self):
"""地址更新 :para... | stack_v2_sparse_classes_36k_train_018458 | 2,595 | no_license | [
{
"docstring": "创建收货地址 :param:token:用户授权的token :param:name:收货人姓名 :param:phone:手机号码 :param:city:省市区 :param:address:地址 :param:isdefault:是否默认地址,默认值: 0 :return: 以上参数均为必填",
"name": "creat_address",
"signature": "def creat_address(self)"
},
{
"docstring": "地址更新 :param:token:用户授权的token :param:id:地址id :... | 4 | null | Implement the Python class `address` described below.
Class description:
定义一个地址管理所有接口的测试类
Method signatures and docstrings:
- def creat_address(self): 创建收货地址 :param:token:用户授权的token :param:name:收货人姓名 :param:phone:手机号码 :param:city:省市区 :param:address:地址 :param:isdefault:是否默认地址,默认值: 0 :return: 以上参数均为必填
- def address_upd... | Implement the Python class `address` described below.
Class description:
定义一个地址管理所有接口的测试类
Method signatures and docstrings:
- def creat_address(self): 创建收货地址 :param:token:用户授权的token :param:name:收货人姓名 :param:phone:手机号码 :param:city:省市区 :param:address:地址 :param:isdefault:是否默认地址,默认值: 0 :return: 以上参数均为必填
- def address_upd... | 0ebaae335de2f1633e31c4fc3f60e556220a8bfb | <|skeleton|>
class address:
"""定义一个地址管理所有接口的测试类"""
def creat_address(self):
"""创建收货地址 :param:token:用户授权的token :param:name:收货人姓名 :param:phone:手机号码 :param:city:省市区 :param:address:地址 :param:isdefault:是否默认地址,默认值: 0 :return: 以上参数均为必填"""
<|body_0|>
def address_update(self):
"""地址更新 :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class address:
"""定义一个地址管理所有接口的测试类"""
def creat_address(self):
"""创建收货地址 :param:token:用户授权的token :param:name:收货人姓名 :param:phone:手机号码 :param:city:省市区 :param:address:地址 :param:isdefault:是否默认地址,默认值: 0 :return: 以上参数均为必填"""
url = host + '/api/address/create'
data = {'name': '王小二', 'phone': '... | the_stack_v2_python_sparse | Atle/interface/framework/base/aAddress.py | shiqi0128/My_scripts | train | 0 |
f0189dba76963edfcdf1f5cb63f36423adc2ab9e | [
"super(DropStripes, self).__init__()\nassert dim in [2, 3]\nself.dim = dim\nself.drop_width = drop_width\nself.stripes_num = stripes_num",
"assert input.ndimension() == 4\nif self.training is False and (not test):\n return input\nelse:\n batch_size = input.shape[0]\n total_width = input.shape[self.dim]\n... | <|body_start_0|>
super(DropStripes, self).__init__()
assert dim in [2, 3]
self.dim = dim
self.drop_width = drop_width
self.stripes_num = stripes_num
<|end_body_0|>
<|body_start_1|>
assert input.ndimension() == 4
if self.training is False and (not test):
... | DropStripes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input, test=False):
... | stack_v2_sparse_classes_36k_train_018459 | 9,371 | no_license | [
{
"docstring": "Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop",
"name": "__init__",
"signature": "def __init__(self, dim, drop_width, stripes_num)"
},
{
"docstring": "input: (batch_size, ch... | 3 | stack_v2_sparse_classes_30k_train_015290 | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | 369321993ef2a5358170a2593d9f1f2631886036 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input, test=False):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
super(DropStripes, self).__init__()
assert dim in [2, 3]
... | the_stack_v2_python_sparse | utils/generic_utils.py | Edresson/SPIRA-ComParE2021 | train | 1 | |
304dd669e063b1fca2fd3b28029664000de7bb83 | [
"self._backend = backend\nself._printing = printing\nself._doctest = doctest\nself._test_method = test_method\nself._base_ring = base_ring",
"_a = getattr(self._backend, attr)\nif callable(_a):\n import types\n _mm = types.MethodType(_make_wrapper(self._backend, attr), self)\n setattr(self, attr, _mm)\n ... | <|body_start_0|>
self._backend = backend
self._printing = printing
self._doctest = doctest
self._test_method = test_method
self._base_ring = base_ring
<|end_body_0|>
<|body_start_1|>
_a = getattr(self._backend, attr)
if callable(_a):
import types
... | See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backend import get_solver sage: b = get_solver(solver = "GLPK") sage: lb = LoggingBack... | LoggingBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingBackend:
"""See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backend import get_solver sage: b = get_solv... | stack_v2_sparse_classes_36k_train_018460 | 15,517 | no_license | [
{
"docstring": "See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backend import get_solver sage: b = get_solver(solver = \"GLPK... | 3 | null | Implement the Python class `LoggingBackend` described below.
Class description:
See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backe... | Implement the Python class `LoggingBackend` described below.
Class description:
See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backe... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class LoggingBackend:
"""See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backend import get_solver sage: b = get_solv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoggingBackend:
"""See :class:`LoggingBackendFactory` for documentation. EXAMPLES:: sage: import sage.numerical.backends.logging_backend sage: from sage.numerical.backends.logging_backend import LoggingBackend sage: from sage.numerical.backends.generic_backend import get_solver sage: b = get_solver(solver = "... | the_stack_v2_python_sparse | sage/src/sage/numerical/backends/logging_backend.py | bopopescu/geosci | train | 0 |
225587b44eba4dc043d75c04ebfb48172f90986e | [
"s = ''\nif root:\n s = str(root.val)\n left = right = ''\n if root.left:\n left = str(self.tree2str(root.left))\n if root.right:\n right = str(self.tree2str(root.right))\n if right != '':\n s += '(' + left + ')'\n s += '(' + right + ')'\n return s\n if left != '... | <|body_start_0|>
s = ''
if root:
s = str(root.val)
left = right = ''
if root.left:
left = str(self.tree2str(root.left))
if root.right:
right = str(self.tree2str(root.right))
if right != '':
s += '... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
"""My Solution: O(n) Solution IDEA: Use recursive preorder traversal. There are a couple of cases to consider: 1. For any node, if there exists a right node, then we need empty () for the left node regardless if left has a va... | stack_v2_sparse_classes_36k_train_018461 | 2,691 | no_license | [
{
"docstring": "My Solution: O(n) Solution IDEA: Use recursive preorder traversal. There are a couple of cases to consider: 1. For any node, if there exists a right node, then we need empty () for the left node regardless if left has a value 2. If there exists only a left node, then we do not need the empty () ... | 2 | stack_v2_sparse_classes_30k_train_013234 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tree2str(self, root: Optional[TreeNode]) -> str: My Solution: O(n) Solution IDEA: Use recursive preorder traversal. There are a couple of cases to consider: 1. For any node, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tree2str(self, root: Optional[TreeNode]) -> str: My Solution: O(n) Solution IDEA: Use recursive preorder traversal. There are a couple of cases to consider: 1. For any node, ... | 8b11ceb675089a12a4a44f9b044dac7c3e666819 | <|skeleton|>
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
"""My Solution: O(n) Solution IDEA: Use recursive preorder traversal. There are a couple of cases to consider: 1. For any node, if there exists a right node, then we need empty () for the left node regardless if left has a va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
"""My Solution: O(n) Solution IDEA: Use recursive preorder traversal. There are a couple of cases to consider: 1. For any node, if there exists a right node, then we need empty () for the left node regardless if left has a value 2. If ther... | the_stack_v2_python_sparse | Python_Solutions/606_Construct_String_from_Binary_Tree.py | lw75251/leetcode | train | 0 | |
85c36fd25b4b991d9e7f274499cb7e05fdd74594 | [
"self.key = key\nself.children = []\nself.end = None",
"cur = self\nlen_word = len(word)\nj = 0\nwhile j < len_word:\n len_child = len(cur.children)\n i = 0\n while i < len_child:\n if word[j] == cur.children[i].key:\n cur = cur.children[i]\n break\n i += 1\n if i =... | <|body_start_0|>
self.key = key
self.children = []
self.end = None
<|end_body_0|>
<|body_start_1|>
cur = self
len_word = len(word)
j = 0
while j < len_word:
len_child = len(cur.children)
i = 0
while i < len_child:
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self, key=None):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word is in the... | stack_v2_sparse_classes_36k_train_018462 | 2,365 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self, key=None)"
},
{
"docstring": "Inserts a word into the trie. :type word: str :rtype: void",
"name": "insert",
"signature": "def insert(self, word)"
},
{
"docstring": "Return... | 4 | null | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self, key=None): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: void
- def search(self, word): Returns ... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self, key=None): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: void
- def search(self, word): Returns ... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class Trie:
def __init__(self, key=None):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word is in the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self, key=None):
"""Initialize your data structure here."""
self.key = key
self.children = []
self.end = None
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: void"""
cur = self
len_word = len(word)... | the_stack_v2_python_sparse | CLRS/Trie/Trie_struct.py | SuperMartinYang/learning_algorithm | train | 0 | |
19489dc7818e7cd86c07d1bd1bd7eca7d6df53f0 | [
"apps = {site_name: [] for site_name in LocalSite.objects.filter(users=self.user).values_list('name', flat=True)}\napps[''] = []\napp_qs = Application.objects.select_related('local_site').filter(user=self.user)\nfor app in app_qs:\n app = self.serialize_app(app)\n apps[app['localSiteName'] or ''].append(app)\... | <|body_start_0|>
apps = {site_name: [] for site_name in LocalSite.objects.filter(users=self.user).values_list('name', flat=True)}
apps[''] = []
app_qs = Application.objects.select_related('local_site').filter(user=self.user)
for app in app_qs:
app = self.serialize_app(app)
... | The OAuth Application form. This provides a list of all current OAuth2 applications the user has access to. | OAuthApplicationsForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuthApplicationsForm:
"""The OAuth Application form. This provides a list of all current OAuth2 applications the user has access to."""
def get_js_view_data(self):
"""Return the data for the associated Javascript view. Returns: dict: Data to be passed to the Javascript view."""
... | stack_v2_sparse_classes_36k_train_018463 | 23,770 | permissive | [
{
"docstring": "Return the data for the associated Javascript view. Returns: dict: Data to be passed to the Javascript view.",
"name": "get_js_view_data",
"signature": "def get_js_view_data(self)"
},
{
"docstring": "Serialize an application for the JavaScript view. Args: app (reviewboard.oauth.m... | 2 | null | Implement the Python class `OAuthApplicationsForm` described below.
Class description:
The OAuth Application form. This provides a list of all current OAuth2 applications the user has access to.
Method signatures and docstrings:
- def get_js_view_data(self): Return the data for the associated Javascript view. Returns... | Implement the Python class `OAuthApplicationsForm` described below.
Class description:
The OAuth Application form. This provides a list of all current OAuth2 applications the user has access to.
Method signatures and docstrings:
- def get_js_view_data(self): Return the data for the associated Javascript view. Returns... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class OAuthApplicationsForm:
"""The OAuth Application form. This provides a list of all current OAuth2 applications the user has access to."""
def get_js_view_data(self):
"""Return the data for the associated Javascript view. Returns: dict: Data to be passed to the Javascript view."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OAuthApplicationsForm:
"""The OAuth Application form. This provides a list of all current OAuth2 applications the user has access to."""
def get_js_view_data(self):
"""Return the data for the associated Javascript view. Returns: dict: Data to be passed to the Javascript view."""
apps = {s... | the_stack_v2_python_sparse | reviewboard/accounts/forms/pages.py | reviewboard/reviewboard | train | 1,141 |
6ab1fce6403e5eb9523a8d4a61f75c94e87aafee | [
"self.notifications = []\nself.append = self.notifications.append\nself.indexOf = self.notifications.index",
"latestNotifications = list(self.notifications)\nlatestNotifications.reverse()\nreturn latestNotifications[:self.MAX_NOTIFICATIONS]"
] | <|body_start_0|>
self.notifications = []
self.append = self.notifications.append
self.indexOf = self.notifications.index
<|end_body_0|>
<|body_start_1|>
latestNotifications = list(self.notifications)
latestNotifications.reverse()
return latestNotifications[:self.MAX_NOTI... | Represents the colletion of notifications the game has generated | NotificationTracker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationTracker:
"""Represents the colletion of notifications the game has generated"""
def __init__(self):
"""Initialize the Notification Tracker"""
<|body_0|>
def latestNotifications(self):
"""Return the notifications from most recent to least recent"""
... | stack_v2_sparse_classes_36k_train_018464 | 641 | no_license | [
{
"docstring": "Initialize the Notification Tracker",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return the notifications from most recent to least recent",
"name": "latestNotifications",
"signature": "def latestNotifications(self)"
}
] | 2 | null | Implement the Python class `NotificationTracker` described below.
Class description:
Represents the colletion of notifications the game has generated
Method signatures and docstrings:
- def __init__(self): Initialize the Notification Tracker
- def latestNotifications(self): Return the notifications from most recent t... | Implement the Python class `NotificationTracker` described below.
Class description:
Represents the colletion of notifications the game has generated
Method signatures and docstrings:
- def __init__(self): Initialize the Notification Tracker
- def latestNotifications(self): Return the notifications from most recent t... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class NotificationTracker:
"""Represents the colletion of notifications the game has generated"""
def __init__(self):
"""Initialize the Notification Tracker"""
<|body_0|>
def latestNotifications(self):
"""Return the notifications from most recent to least recent"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationTracker:
"""Represents the colletion of notifications the game has generated"""
def __init__(self):
"""Initialize the Notification Tracker"""
self.notifications = []
self.append = self.notifications.append
self.indexOf = self.notifications.index
def latest... | the_stack_v2_python_sparse | src/Game/Notifications/notification_tracker.py | dfwarden/DeckBuilding | train | 0 |
20b15068e8816399b24575a7fa9a0bf5d93bbbc9 | [
"self.result = []\nl1 = len(v1)\nl2 = len(v2)\nif l1 == 0 and l2 > 0:\n self.result.extend(v2)\nelif l2 == 0 and l1 > 0:\n self.result.extend(v1)\nelif l1 == 0 and l2 == 0:\n self.result = []\nelse:\n for num in v1:\n self.result.append(num)\n self.result.append(None)\n i = 1\n for n... | <|body_start_0|>
self.result = []
l1 = len(v1)
l2 = len(v2)
if l1 == 0 and l2 > 0:
self.result.extend(v2)
elif l2 == 0 and l1 > 0:
self.result.extend(v1)
elif l1 == 0 and l2 == 0:
self.result = []
else:
for num in v1... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k_train_018465 | 2,741 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | null | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | fcf6c3d5d60d13706950247d8a2327adc5faf17e | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.result = []
l1 = len(v1)
l2 = len(v2)
if l1 == 0 and l2 > 0:
self.result.extend(v2)
elif l2 == 0 and l1 > 0:
... | the_stack_v2_python_sparse | Medium/ZigzagIterator.py | mangalagb/Leetcode | train | 0 | |
630912a7aa09d063ac17e7baa36843011c793fcf | [
"for i in range(len(numbers)):\n current_value = numbers[i]\n for j in range(i + 1, len(numbers)):\n if current_value + numbers[j] == target:\n return [i + 1, j + 1]\n if current_value + numbers[j] > target:\n break",
"numbers_set = set(numbers)\nfor i in range(len(number... | <|body_start_0|>
for i in range(len(numbers)):
current_value = numbers[i]
for j in range(i + 1, len(numbers)):
if current_value + numbers[j] == target:
return [i + 1, j + 1]
if current_value + numbers[j] > target:
br... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_018466 | 1,092 | no_license | [
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, ta... | 2 | stack_v2_sparse_classes_30k_train_017330 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :r... | 6de551327f96ec4d4b63d0045281b65bbb4f5d0f | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
for i in range(len(numbers)):
current_value = numbers[i]
for j in range(i + 1, len(numbers)):
if current_value + numbers[j] == target:
... | the_stack_v2_python_sparse | twoSum.py | JingweiTu/leetcode | train | 0 | |
50d98101dde7ef8c3e746f6611041c3134fcc7d8 | [
"if isinstance(tag, six.integer_types):\n try:\n tag = Tag.objects.get(pk=tag, owner=self.owner)\n except Tag.DoesNotExist:\n return\nif isinstance(tag, six.string_types):\n tname = tag\n try:\n tag = Tag(owner=self.owner, name=tag)\n tag.save()\n except IntegrityError:\n ... | <|body_start_0|>
if isinstance(tag, six.integer_types):
try:
tag = Tag.objects.get(pk=tag, owner=self.owner)
except Tag.DoesNotExist:
return
if isinstance(tag, six.string_types):
tname = tag
try:
tag = Tag(ow... | Base class for taggable models; anything taggable must extend this | Taggable | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Taggable:
"""Base class for taggable models; anything taggable must extend this"""
def tag(self, tag):
"""Tags this object with a tag specified by a tag name, primary key or Tag model instance"""
<|body_0|>
def untag(self, tag):
"""Untags this object from a tag s... | stack_v2_sparse_classes_36k_train_018467 | 10,108 | permissive | [
{
"docstring": "Tags this object with a tag specified by a tag name, primary key or Tag model instance",
"name": "tag",
"signature": "def tag(self, tag)"
},
{
"docstring": "Untags this object from a tag specified by a tag name, primary key or Tag model instance",
"name": "untag",
"signat... | 3 | stack_v2_sparse_classes_30k_train_019650 | Implement the Python class `Taggable` described below.
Class description:
Base class for taggable models; anything taggable must extend this
Method signatures and docstrings:
- def tag(self, tag): Tags this object with a tag specified by a tag name, primary key or Tag model instance
- def untag(self, tag): Untags thi... | Implement the Python class `Taggable` described below.
Class description:
Base class for taggable models; anything taggable must extend this
Method signatures and docstrings:
- def tag(self, tag): Tags this object with a tag specified by a tag name, primary key or Tag model instance
- def untag(self, tag): Untags thi... | 5e102935cc6166f4d8ea13051769787c47303153 | <|skeleton|>
class Taggable:
"""Base class for taggable models; anything taggable must extend this"""
def tag(self, tag):
"""Tags this object with a tag specified by a tag name, primary key or Tag model instance"""
<|body_0|>
def untag(self, tag):
"""Untags this object from a tag s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Taggable:
"""Base class for taggable models; anything taggable must extend this"""
def tag(self, tag):
"""Tags this object with a tag specified by a tag name, primary key or Tag model instance"""
if isinstance(tag, six.integer_types):
try:
tag = Tag.objects.get... | the_stack_v2_python_sparse | tags/models.py | RossBrunton/BMAT | train | 0 |
cb5800570c14ff3897a8a6e66f3b9a5e44c616cb | [
"N = len(nums)\ns, l, ans = (sum(nums), 1, float('inf'))\nnums.insert(0, 0)\nfor r in range(N + 1):\n s -= nums[r]\n while l < r and s < x:\n s += nums[l]\n l += 1\n if s == x:\n ans = min(ans, l - 1 + N - r)\nreturn ans if ans != float('inf') else -1",
"N = len(nums)\nd = {0: -1}\ns... | <|body_start_0|>
N = len(nums)
s, l, ans = (sum(nums), 1, float('inf'))
nums.insert(0, 0)
for r in range(N + 1):
s -= nums[r]
while l < r and s < x:
s += nums[l]
l += 1
if s == x:
ans = min(ans, l - 1 + N... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
"""Sliding Window O(N) / O(1)"""
<|body_0|>
def minOperations1(self, nums: List[int], x: int) -> int:
"""Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 시작해서 최소의 길이를 구함. O(N) / O(N)"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_018468 | 1,322 | no_license | [
{
"docstring": "Sliding Window O(N) / O(1)",
"name": "minOperations",
"signature": "def minOperations(self, nums: List[int], x: int) -> int"
},
{
"docstring": "Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 시작해서 최소의 길이를 구함. O(N) / O(N)",
"name": "minOperations1",
"signature": "def minOperations1(self... | 2 | stack_v2_sparse_classes_30k_train_009411 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minOperations(self, nums: List[int], x: int) -> int: Sliding Window O(N) / O(1)
- def minOperations1(self, nums: List[int], x: int) -> int: Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minOperations(self, nums: List[int], x: int) -> int: Sliding Window O(N) / O(1)
- def minOperations1(self, nums: List[int], x: int) -> int: Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 ... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
"""Sliding Window O(N) / O(1)"""
<|body_0|>
def minOperations1(self, nums: List[int], x: int) -> int:
"""Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 시작해서 최소의 길이를 구함. O(N) / O(N)"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
"""Sliding Window O(N) / O(1)"""
N = len(nums)
s, l, ans = (sum(nums), 1, float('inf'))
nums.insert(0, 0)
for r in range(N + 1):
s -= nums[r]
while l < r and s < x:
... | the_stack_v2_python_sparse | Leetcode/1658.py | hanwgyu/algorithm_problem_solving | train | 5 | |
8a460a6a38a79c47894789ed40bc94285590e9bd | [
"p = dict()\nn = len(input)\nfor i in input:\n if i not in p.keys():\n p[i] = float(input.count(i)) / n\nentropy = 0\nfor i in p.keys():\n entropy += -1 * p[i] * math.log(p[i], 2)\nreturn entropy",
"species_a = []\nspecies_b = []\nfor i in range(len(lengths)):\n if lengths[i] <= l:\n specie... | <|body_start_0|>
p = dict()
n = len(input)
for i in input:
if i not in p.keys():
p[i] = float(input.count(i)) / n
entropy = 0
for i in p.keys():
entropy += -1 * p[i] * math.log(p[i], 2)
return entropy
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateEntropy(self, input):
""":type input: List[int] :rtype: float"""
<|body_0|>
def split(self, lengths, species, l):
"""rtype: species_a and species_b"""
<|body_1|>
def calculateMaxInfoGain(self, petal_length, species):
""":ty... | stack_v2_sparse_classes_36k_train_018469 | 2,472 | no_license | [
{
"docstring": ":type input: List[int] :rtype: float",
"name": "calculateEntropy",
"signature": "def calculateEntropy(self, input)"
},
{
"docstring": "rtype: species_a and species_b",
"name": "split",
"signature": "def split(self, lengths, species, l)"
},
{
"docstring": ":type pe... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateEntropy(self, input): :type input: List[int] :rtype: float
- def split(self, lengths, species, l): rtype: species_a and species_b
- def calculateMaxInfoGain(self, pe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateEntropy(self, input): :type input: List[int] :rtype: float
- def split(self, lengths, species, l): rtype: species_a and species_b
- def calculateMaxInfoGain(self, pe... | 4d7e675c795c841f99ca95b8b60c4995bcb632fb | <|skeleton|>
class Solution:
def calculateEntropy(self, input):
""":type input: List[int] :rtype: float"""
<|body_0|>
def split(self, lengths, species, l):
"""rtype: species_a and species_b"""
<|body_1|>
def calculateMaxInfoGain(self, petal_length, species):
""":ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculateEntropy(self, input):
""":type input: List[int] :rtype: float"""
p = dict()
n = len(input)
for i in input:
if i not in p.keys():
p[i] = float(input.count(i)) / n
entropy = 0
for i in p.keys():
entrop... | the_stack_v2_python_sparse | calculateMaxInfoGain.py | stephenchenxj/myLeetCode | train | 0 | |
1d01fdaa51139514339e6b59e8f1b2b9ebcaee4e | [
"original = [b'small record']\nfn = self._WriteRecordsToFile(original, 'small_record')\nwith open(fn, 'rb') as h:\n buff = h.read()\ncompressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)\noutput = b''\nfor c in buff:\n if isinstance(c, int):\n c = six.int2byte(c)\n output += compressor.com... | <|body_start_0|>
original = [b'small record']
fn = self._WriteRecordsToFile(original, 'small_record')
with open(fn, 'rb') as h:
buff = h.read()
compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)
output = b''
for c in buff:
if isinstanc... | TFRecordWriter Zlib test | TFRecordWriterZlibTest | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFRecordWriterZlibTest:
"""TFRecordWriter Zlib test"""
def testZLibFlushRecord(self):
"""test ZLib Flush Record"""
<|body_0|>
def testZlibReadWrite(self):
"""Verify that files produced are zlib compatible."""
<|body_1|>
def testZlibReadWriteLarge(sel... | stack_v2_sparse_classes_36k_train_018470 | 24,442 | permissive | [
{
"docstring": "test ZLib Flush Record",
"name": "testZLibFlushRecord",
"signature": "def testZLibFlushRecord(self)"
},
{
"docstring": "Verify that files produced are zlib compatible.",
"name": "testZlibReadWrite",
"signature": "def testZlibReadWrite(self)"
},
{
"docstring": "Ver... | 4 | null | Implement the Python class `TFRecordWriterZlibTest` described below.
Class description:
TFRecordWriter Zlib test
Method signatures and docstrings:
- def testZLibFlushRecord(self): test ZLib Flush Record
- def testZlibReadWrite(self): Verify that files produced are zlib compatible.
- def testZlibReadWriteLarge(self): ... | Implement the Python class `TFRecordWriterZlibTest` described below.
Class description:
TFRecordWriter Zlib test
Method signatures and docstrings:
- def testZLibFlushRecord(self): test ZLib Flush Record
- def testZlibReadWrite(self): Verify that files produced are zlib compatible.
- def testZlibReadWriteLarge(self): ... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class TFRecordWriterZlibTest:
"""TFRecordWriter Zlib test"""
def testZLibFlushRecord(self):
"""test ZLib Flush Record"""
<|body_0|>
def testZlibReadWrite(self):
"""Verify that files produced are zlib compatible."""
<|body_1|>
def testZlibReadWriteLarge(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFRecordWriterZlibTest:
"""TFRecordWriter Zlib test"""
def testZLibFlushRecord(self):
"""test ZLib Flush Record"""
original = [b'small record']
fn = self._WriteRecordsToFile(original, 'small_record')
with open(fn, 'rb') as h:
buff = h.read()
compressor ... | the_stack_v2_python_sparse | tensorflow/python/lib/io/tf_record_test.py | tensorflow/tensorflow | train | 208,740 |
61f667fa3b1cc396f5ff6c82b26a229a28e7281f | [
"dq = collections.deque()\ndq.append(root)\nres = []\nwhile len(dq):\n size = len(dq)\n temp = []\n for _ in range(size):\n node = dq.popleft()\n if node:\n dq.append(node.left)\n dq.append(node.right)\n temp.append(node.val if node else None)\n res += temp\nre... | <|body_start_0|>
dq = collections.deque()
dq.append(root)
res = []
while len(dq):
size = len(dq)
temp = []
for _ in range(size):
node = dq.popleft()
if node:
dq.append(node.left)
d... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_018471 | 1,818 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_019155 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | df3a589ea858218f689fe315d134adc957c3debd | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
dq = collections.deque()
dq.append(root)
res = []
while len(dq):
size = len(dq)
temp = []
for _ in range(size):
... | the_stack_v2_python_sparse | 297.py | supperllx/LeetCode | train | 0 | |
2dc0f74851d24e31290e96be60ce04183a3df2b8 | [
"heap = []\nheapq.heappush(heap, 1)\nfor _ in range(n):\n ugly = heapq.heappop(heap)\n if ugly % 2 == 0:\n heapq.heappush(heap, ugly * 2)\n elif ugly % 3 == 0:\n heapq.heappush(heap, ugly * 2)\n heapq.heappush(heap, ugly * 3)\n else:\n heapq.heappush(heap, ugly * 2)\n ... | <|body_start_0|>
heap = []
heapq.heappush(heap, 1)
for _ in range(n):
ugly = heapq.heappop(heap)
if ugly % 2 == 0:
heapq.heappush(heap, ugly * 2)
elif ugly % 3 == 0:
heapq.heappush(heap, ugly * 2)
heapq.heappush(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nthUglyNumber_TLE(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
heap = []
heapq.heappush(heap, 1)
for _ in ra... | stack_v2_sparse_classes_36k_train_018472 | 2,226 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumber",
"signature": "def nthUglyNumber(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumber_TLE",
"signature": "def nthUglyNumber_TLE(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000520 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthUglyNumber_TLE(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthUglyNumber_TLE(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def nthUglyNumber(self, n):
... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nthUglyNumber_TLE(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
heap = []
heapq.heappush(heap, 1)
for _ in range(n):
ugly = heapq.heappop(heap)
if ugly % 2 == 0:
heapq.heappush(heap, ugly * 2)
elif ugly % 3 == 0:
... | the_stack_v2_python_sparse | src/lt_264.py | oxhead/CodingYourWay | train | 0 | |
8430aaf35ce23419d5b04b8884194718923c69cc | [
"try:\n self.sqlhandler = None\n self.practiceId = self.get_body_argument('PracticeId')\n self.fullScore = self.get_body_argument('FullScore')\n self.examDetail = self.get_body_argument('ExamDetail')\n print(self.practiceId)\n if self.pushPractice():\n self.write('success')\n self.fi... | <|body_start_0|>
try:
self.sqlhandler = None
self.practiceId = self.get_body_argument('PracticeId')
self.fullScore = self.get_body_argument('FullScore')
self.examDetail = self.get_body_argument('ExamDetail')
print(self.practiceId)
if self.p... | TeaPushPracticeRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeaPushPracticeRequestHandler:
def post(self):
"""将老师上传的题目存到数据库"""
<|body_0|>
def pushPractice(self):
"""从数据库读取学生信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.sqlhandler = None
self.practiceId = self.get_body_a... | stack_v2_sparse_classes_36k_train_018473 | 1,912 | no_license | [
{
"docstring": "将老师上传的题目存到数据库",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "从数据库读取学生信息",
"name": "pushPractice",
"signature": "def pushPractice(self)"
}
] | 2 | null | Implement the Python class `TeaPushPracticeRequestHandler` described below.
Class description:
Implement the TeaPushPracticeRequestHandler class.
Method signatures and docstrings:
- def post(self): 将老师上传的题目存到数据库
- def pushPractice(self): 从数据库读取学生信息 | Implement the Python class `TeaPushPracticeRequestHandler` described below.
Class description:
Implement the TeaPushPracticeRequestHandler class.
Method signatures and docstrings:
- def post(self): 将老师上传的题目存到数据库
- def pushPractice(self): 从数据库读取学生信息
<|skeleton|>
class TeaPushPracticeRequestHandler:
def post(self... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class TeaPushPracticeRequestHandler:
def post(self):
"""将老师上传的题目存到数据库"""
<|body_0|>
def pushPractice(self):
"""从数据库读取学生信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeaPushPracticeRequestHandler:
def post(self):
"""将老师上传的题目存到数据库"""
try:
self.sqlhandler = None
self.practiceId = self.get_body_argument('PracticeId')
self.fullScore = self.get_body_argument('FullScore')
self.examDetail = self.get_body_argument('E... | the_stack_v2_python_sparse | app/src/main/pythonWork/TeaPushPracticeRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
60f48bb88b1b6772339b4020c90f26d9296be2b9 | [
"TaskManager.__init__(self)\nif task_assignment_timeout is None or task_assignment_timeout <= 0:\n task_assignment_timeout = 0\ntask.props[_KEY_ORDER] = send_order\ntask.props[_KEY_TASK_ASSIGN_TIMEOUT] = task_assignment_timeout",
"task = client_task.task\nif len(task.client_tasks) > 0:\n if client_task.task... | <|body_start_0|>
TaskManager.__init__(self)
if task_assignment_timeout is None or task_assignment_timeout <= 0:
task_assignment_timeout = 0
task.props[_KEY_ORDER] = send_order
task.props[_KEY_TASK_ASSIGN_TIMEOUT] = task_assignment_timeout
<|end_body_0|>
<|body_start_1|>
... | SendTaskManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendTaskManager:
def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout):
"""Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a clie... | stack_v2_sparse_classes_36k_train_018474 | 4,727 | permissive | [
{
"docstring": "Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a client requesting its task",
"name": "__init__",
"signature": "def __init__(self, task: Task, send_order... | 3 | null | Implement the Python class `SendTaskManager` described below.
Class description:
Implement the SendTaskManager class.
Method signatures and docstrings:
- def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout): Task manager for send controller. Args: task (Task): an instance of Task send_order ... | Implement the Python class `SendTaskManager` described below.
Class description:
Implement the SendTaskManager class.
Method signatures and docstrings:
- def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout): Task manager for send controller. Args: task (Task): an instance of Task send_order ... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class SendTaskManager:
def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout):
"""Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a clie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendTaskManager:
def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout):
"""Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a client requesting ... | the_stack_v2_python_sparse | nvflare/apis/impl/send_manager.py | NVIDIA/NVFlare | train | 442 | |
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae | [
"q = quantity.Acceleration(1.0, 'm/s^2')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'm/s^2')",
"q = quantity.Acceleration(1.0, 'cm/s^2')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 0.01, delta=1e-08)\ns... | <|body_start_0|>
q = quantity.Acceleration(1.0, 'm/s^2')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)
self.assertEqual(q.units, 'm/s^2')
<|end_body_0|>
<|body_start_1|>
q = quantity.Acceleration(1.0, 'cm/s^2')
self.assertAl... | Contains unit tests of the Acceleration unit type object. | TestAcceleration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAcceleration:
"""Contains unit tests of the Acceleration unit type object."""
def test_mpers2(self):
"""Test the creation of an acceleration quantity with units of m/s^2."""
<|body_0|>
def test_cmpers2(self):
"""Test the creation of an acceleration quantity w... | stack_v2_sparse_classes_36k_train_018475 | 33,010 | permissive | [
{
"docstring": "Test the creation of an acceleration quantity with units of m/s^2.",
"name": "test_mpers2",
"signature": "def test_mpers2(self)"
},
{
"docstring": "Test the creation of an acceleration quantity with units of cm/s^2.",
"name": "test_cmpers2",
"signature": "def test_cmpers2... | 2 | stack_v2_sparse_classes_30k_val_000465 | Implement the Python class `TestAcceleration` described below.
Class description:
Contains unit tests of the Acceleration unit type object.
Method signatures and docstrings:
- def test_mpers2(self): Test the creation of an acceleration quantity with units of m/s^2.
- def test_cmpers2(self): Test the creation of an ac... | Implement the Python class `TestAcceleration` described below.
Class description:
Contains unit tests of the Acceleration unit type object.
Method signatures and docstrings:
- def test_mpers2(self): Test the creation of an acceleration quantity with units of m/s^2.
- def test_cmpers2(self): Test the creation of an ac... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class TestAcceleration:
"""Contains unit tests of the Acceleration unit type object."""
def test_mpers2(self):
"""Test the creation of an acceleration quantity with units of m/s^2."""
<|body_0|>
def test_cmpers2(self):
"""Test the creation of an acceleration quantity w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAcceleration:
"""Contains unit tests of the Acceleration unit type object."""
def test_mpers2(self):
"""Test the creation of an acceleration quantity with units of m/s^2."""
q = quantity.Acceleration(1.0, 'm/s^2')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmo... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | vrlambert/RMG-Py | train | 1 |
68cc61b7bfec9ce2288297615dcae55bf1894c84 | [
"sympify(self.factor)\nif self.target.scale != self.scheme.target_scale:\n raise ValueError('Target operator not at same scale as scheme specifies.')\nif self.source.scale != self.scheme.source_scale:\n raise ValueError('Source operator not at same scale as scheme specifies.')",
"out = 1\nfor expansion in s... | <|body_start_0|>
sympify(self.factor)
if self.target.scale != self.scheme.target_scale:
raise ValueError('Target operator not at same scale as scheme specifies.')
if self.source.scale != self.scheme.source_scale:
raise ValueError('Source operator not at same scale as sche... | Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.) | OperatorRelation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperatorRelation:
"""Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.)"""
def check_cons... | stack_v2_sparse_classes_36k_train_018476 | 6,555 | permissive | [
{
"docstring": "Runs consistency checks on operator relation. Checks: * factor can be converted to sympy expression * target scale equals scheme target scale * source scale equals scheme source scale * all expansion parameters defined by scheme are present",
"name": "check_consistency",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_003600 | Implement the Python class `OperatorRelation` described below.
Class description:
Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present... | Implement the Python class `OperatorRelation` described below.
Class description:
Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present... | 2131354fd6822b3aa7b7d9c3c0db79723b06b8ca | <|skeleton|>
class OperatorRelation:
"""Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.)"""
def check_cons... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OperatorRelation:
"""Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.)"""
def check_consistency(self)... | the_stack_v2_python_sparse | strops/schemes/models.py | ckoerber/strops | train | 1 |
3a1f56afcd0d07dadf12d4e2d697bdb3cbc25898 | [
"supported_content_types = supported_content_types or self.default_accept_types\nparts = self.path.rsplit('.', 1)\nif len(parts) > 1:\n ctype = 'application/{0}'.format(parts[1])\n if ctype in supported_content_types:\n return ctype\nif specific_content_types and action in specific_content_types:\n ... | <|body_start_0|>
supported_content_types = supported_content_types or self.default_accept_types
parts = self.path.rsplit('.', 1)
if len(parts) > 1:
ctype = 'application/{0}'.format(parts[1])
if ctype in supported_content_types:
return ctype
if spec... | Add some OpenStack API-specific logic to the base webob.Request. | Request | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
"""Add some OpenStack API-specific logic to the base webob.Request."""
def best_match_content_type(self, action, supported_content_types=None, specific_content_types=None):
"""Determine the requested response content-type. Based on the query extension then the Accept header.... | stack_v2_sparse_classes_36k_train_018477 | 40,862 | permissive | [
{
"docstring": "Determine the requested response content-type. Based on the query extension then the Accept header. Raise NotAcceptableContentType exception if we don't find a preference",
"name": "best_match_content_type",
"signature": "def best_match_content_type(self, action, supported_content_types=... | 2 | null | Implement the Python class `Request` described below.
Class description:
Add some OpenStack API-specific logic to the base webob.Request.
Method signatures and docstrings:
- def best_match_content_type(self, action, supported_content_types=None, specific_content_types=None): Determine the requested response content-t... | Implement the Python class `Request` described below.
Class description:
Add some OpenStack API-specific logic to the base webob.Request.
Method signatures and docstrings:
- def best_match_content_type(self, action, supported_content_types=None, specific_content_types=None): Determine the requested response content-t... | c898a310afbc27f12190446ef75d8b0bd12115eb | <|skeleton|>
class Request:
"""Add some OpenStack API-specific logic to the base webob.Request."""
def best_match_content_type(self, action, supported_content_types=None, specific_content_types=None):
"""Determine the requested response content-type. Based on the query extension then the Accept header.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Request:
"""Add some OpenStack API-specific logic to the base webob.Request."""
def best_match_content_type(self, action, supported_content_types=None, specific_content_types=None):
"""Determine the requested response content-type. Based on the query extension then the Accept header. Raise NotAcc... | the_stack_v2_python_sparse | murano/common/wsgi.py | openstack/murano | train | 94 |
546a0bbe47034f3443306888432d8e84a792c4e7 | [
"low, high = (0, len(nums) - 1)\nwhile low <= high:\n mid = low + (high - low) // 2\n if nums[mid] == target:\n return mid\n if nums[mid] < target:\n low = mid + 1\n else:\n high = mid - 1\nif high >= 0 and nums[high] > target:\n return high\nreturn low",
"start = 0\nend = len(... | <|body_start_0|>
low, high = (0, len(nums) - 1)
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
low = mid + 1
else:
high = mid - 1
if high >=... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsert2(self, nums: List[int], target: int) -> int:
"""20210824 do it again Runtime: 63 ms, faster than 22.19% Memory Usage: 15 MB, less than 56.94% :param nums: :param target: :return:"""
<|body_0|>
def searchInsert(self, nums, target):
""":type ... | stack_v2_sparse_classes_36k_train_018478 | 2,922 | permissive | [
{
"docstring": "20210824 do it again Runtime: 63 ms, faster than 22.19% Memory Usage: 15 MB, less than 56.94% :param nums: :param target: :return:",
"name": "searchInsert2",
"signature": "def searchInsert2(self, nums: List[int], target: int) -> int"
},
{
"docstring": ":type nums: List[int] :type... | 2 | stack_v2_sparse_classes_30k_train_014907 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert2(self, nums: List[int], target: int) -> int: 20210824 do it again Runtime: 63 ms, faster than 22.19% Memory Usage: 15 MB, less than 56.94% :param nums: :param ta... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert2(self, nums: List[int], target: int) -> int: 20210824 do it again Runtime: 63 ms, faster than 22.19% Memory Usage: 15 MB, less than 56.94% :param nums: :param ta... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def searchInsert2(self, nums: List[int], target: int) -> int:
"""20210824 do it again Runtime: 63 ms, faster than 22.19% Memory Usage: 15 MB, less than 56.94% :param nums: :param target: :return:"""
<|body_0|>
def searchInsert(self, nums, target):
""":type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchInsert2(self, nums: List[int], target: int) -> int:
"""20210824 do it again Runtime: 63 ms, faster than 22.19% Memory Usage: 15 MB, less than 56.94% :param nums: :param target: :return:"""
low, high = (0, len(nums) - 1)
while low <= high:
mid = low + (hi... | the_stack_v2_python_sparse | src/35-SearchInsertPosition.py | Jiezhi/myleetcode | train | 1 | |
5841a7d19df584cd34445c179ae5405c77b636af | [
"self.root_depth = p['root_depth']\nself.fine_radius = p['fine_radius']\nself.root_cond = p['root_cond']\nself.RAI = p['RAI_LAI_multiplier'] * LAImax\nself.rad = self.RAI * RootDistribution(p['beta'], dz_soil, p['root_depth'])\nself.ix = np.where(np.isfinite(self.rad))\nself.dz = dz_soil[self.ix]\nself.h_root = 0.0... | <|body_start_0|>
self.root_depth = p['root_depth']
self.fine_radius = p['fine_radius']
self.root_cond = p['root_cond']
self.RAI = p['RAI_LAI_multiplier'] * LAImax
self.rad = self.RAI * RootDistribution(p['beta'], dz_soil, p['root_depth'])
self.ix = np.where(np.isfinite(se... | Describes roots of planttype. | RootUptake | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootUptake:
"""Describes roots of planttype."""
def __init__(self, p, dz_soil, LAImax):
"""Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root a... | stack_v2_sparse_classes_36k_train_018479 | 3,776 | no_license | [
{
"docstring": "Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root area index (RAI = 2*LAImax) 'fine_radius': fine root radius [m] 'radial_K': maximum bulk root membrane c... | 2 | stack_v2_sparse_classes_30k_train_008054 | Implement the Python class `RootUptake` described below.
Class description:
Describes roots of planttype.
Method signatures and docstrings:
- def __init__(self, p, dz_soil, LAImax): Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution mod... | Implement the Python class `RootUptake` described below.
Class description:
Describes roots of planttype.
Method signatures and docstrings:
- def __init__(self, p, dz_soil, LAImax): Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution mod... | c662ad355af798b5036c3b080dafcb39728b969c | <|skeleton|>
class RootUptake:
"""Describes roots of planttype."""
def __init__(self, p, dz_soil, LAImax):
"""Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RootUptake:
"""Describes roots of planttype."""
def __init__(self, p, dz_soil, LAImax):
"""Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root area index (RA... | the_stack_v2_python_sparse | canopy/planttype/rootzone.py | zmoon/pyAPES_skeleton | train | 0 |
6e72c696afff34f756072cf334852123b2aa7a23 | [
"existing = Customer.objects.filter(email__iexact=self.cleaned_data['email'])\nif existing.exists():\n raise forms.ValidationError('A user with that email already exists.')\nelse:\n return self.cleaned_data['email']",
"if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:\n if self.cl... | <|body_start_0|>
existing = Customer.objects.filter(email__iexact=self.cleaned_data['email'])
if existing.exists():
raise forms.ValidationError('A user with that email already exists.')
else:
return self.cleaned_data['email']
<|end_body_0|>
<|body_start_1|>
if 'p... | Form for registering a new user account. | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account."""
def clean_email(self):
"""Validate that the username is alphanumeric and is not already in use."""
<|body_0|>
def clean(self):
"""Verifiy that the values entered into the two password fields match."... | stack_v2_sparse_classes_36k_train_018480 | 3,800 | no_license | [
{
"docstring": "Validate that the username is alphanumeric and is not already in use.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Verifiy that the values entered into the two password fields match.",
"name": "clean",
"signature": "def clean(self)"
}... | 2 | null | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account.
Method signatures and docstrings:
- def clean_email(self): Validate that the username is alphanumeric and is not already in use.
- def clean(self): Verifiy that the values entered into the two pa... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account.
Method signatures and docstrings:
- def clean_email(self): Validate that the username is alphanumeric and is not already in use.
- def clean(self): Verifiy that the values entered into the two pa... | f1a8cd8268d032ea8321e1588e226da09925b7aa | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account."""
def clean_email(self):
"""Validate that the username is alphanumeric and is not already in use."""
<|body_0|>
def clean(self):
"""Verifiy that the values entered into the two password fields match."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Form for registering a new user account."""
def clean_email(self):
"""Validate that the username is alphanumeric and is not already in use."""
existing = Customer.objects.filter(email__iexact=self.cleaned_data['email'])
if existing.exists():
raise ... | the_stack_v2_python_sparse | website/apps/accounts/forms.py | protoprojects/worksample | train | 0 |
b02ce935b41b7e3d610eccbf5ecef28139d0c7fa | [
"n = len(height)\ndp = [[-1, -1] for i in range(n)]\nfor i in range(n):\n if i == 0:\n dp[i][0] = height[i]\n dp[n - 1 - i][1] = height[n - 1 - i]\n else:\n dp[i][0] = max(dp[i - 1][0], height[i])\n dp[n - 1 - i][1] = max(dp[n - i][1], height[n - i - 1])\nres = 0\nfor i in range(n)... | <|body_start_0|>
n = len(height)
dp = [[-1, -1] for i in range(n)]
for i in range(n):
if i == 0:
dp[i][0] = height[i]
dp[n - 1 - i][1] = height[n - 1 - i]
else:
dp[i][0] = max(dp[i - 1][0], height[i])
dp[n - ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap1(self, height: List[int]) -> int:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 44.42% 的用户 内存消耗: 15.8 MB , 在所有 Python3 提交中击败了 5.07% 的用户"""
<|body_0|>
def trap(self, height: List[int]) -> int:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 45.70% 的用户 内存消耗: 15 MB , 在所有 P... | stack_v2_sparse_classes_36k_train_018481 | 2,860 | no_license | [
{
"docstring": "执行用时: 52 ms , 在所有 Python3 提交中击败了 44.42% 的用户 内存消耗: 15.8 MB , 在所有 Python3 提交中击败了 5.07% 的用户",
"name": "trap1",
"signature": "def trap1(self, height: List[int]) -> int"
},
{
"docstring": "执行用时: 52 ms , 在所有 Python3 提交中击败了 45.70% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 68.59% 的用户",
"n... | 2 | stack_v2_sparse_classes_30k_train_009151 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap1(self, height: List[int]) -> int: 执行用时: 52 ms , 在所有 Python3 提交中击败了 44.42% 的用户 内存消耗: 15.8 MB , 在所有 Python3 提交中击败了 5.07% 的用户
- def trap(self, height: List[int]) -> int: 执行... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap1(self, height: List[int]) -> int: 执行用时: 52 ms , 在所有 Python3 提交中击败了 44.42% 的用户 内存消耗: 15.8 MB , 在所有 Python3 提交中击败了 5.07% 的用户
- def trap(self, height: List[int]) -> int: 执行... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def trap1(self, height: List[int]) -> int:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 44.42% 的用户 内存消耗: 15.8 MB , 在所有 Python3 提交中击败了 5.07% 的用户"""
<|body_0|>
def trap(self, height: List[int]) -> int:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 45.70% 的用户 内存消耗: 15 MB , 在所有 P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap1(self, height: List[int]) -> int:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 44.42% 的用户 内存消耗: 15.8 MB , 在所有 Python3 提交中击败了 5.07% 的用户"""
n = len(height)
dp = [[-1, -1] for i in range(n)]
for i in range(n):
if i == 0:
dp[i][0] = height[i]
... | the_stack_v2_python_sparse | 接雨水.py | nomboy/leetcode | train | 0 | |
6f9200e6eac1ba1940a7c116e45a2559e0964547 | [
"account = db().query(RedHatAccount).first()\nif not account:\n raise web.notfound()\nreturn self.render(account)",
"data = self.checked_data()\nlicense_type = data.get('license_type')\nif license_type == 'rhsm':\n data['satellite'] = ''\n data['activation_key'] = ''\nrelease_id = data.pop('release_id')\... | <|body_start_0|>
account = db().query(RedHatAccount).first()
if not account:
raise web.notfound()
return self.render(account)
<|end_body_0|>
<|body_start_1|>
data = self.checked_data()
license_type = data.get('license_type')
if license_type == 'rhsm':
... | Red Hat account handler | RedHatAccountHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedHatAccountHandler:
"""Red Hat account handler"""
def GET(self):
""":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 404 (account not found in db)"""
<|body_0|>
def POST(self):
""":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 400 (inv... | stack_v2_sparse_classes_36k_train_018482 | 4,410 | no_license | [
{
"docstring": ":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 404 (account not found in db)",
"name": "GET",
"signature": "def GET(self)"
},
{
"docstring": ":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 400 (invalid account data specified) * 404 (account not found i... | 2 | stack_v2_sparse_classes_30k_train_012032 | Implement the Python class `RedHatAccountHandler` described below.
Class description:
Red Hat account handler
Method signatures and docstrings:
- def GET(self): :returns: JSONized RedHatAccount object. :http: * 200 (OK) * 404 (account not found in db)
- def POST(self): :returns: JSONized RedHatAccount object. :http: ... | Implement the Python class `RedHatAccountHandler` described below.
Class description:
Red Hat account handler
Method signatures and docstrings:
- def GET(self): :returns: JSONized RedHatAccount object. :http: * 200 (OK) * 404 (account not found in db)
- def POST(self): :returns: JSONized RedHatAccount object. :http: ... | 64d5e511c5ceb0e2d18107012d73042ad1daa345 | <|skeleton|>
class RedHatAccountHandler:
"""Red Hat account handler"""
def GET(self):
""":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 404 (account not found in db)"""
<|body_0|>
def POST(self):
""":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 400 (inv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedHatAccountHandler:
"""Red Hat account handler"""
def GET(self):
""":returns: JSONized RedHatAccount object. :http: * 200 (OK) * 404 (account not found in db)"""
account = db().query(RedHatAccount).first()
if not account:
raise web.notfound()
return self.rend... | the_stack_v2_python_sparse | nailgun/nailgun/api/handlers/redhat.py | loles/fuel-web | train | 1 |
31d745ad243bfbcac8dff280c93f139ee28f0cfa | [
"self.memory = {1: 1, 2: 2}\nfor i in range(3, n + 1):\n self.memory[i] = self.memory[i - 1] + self.memory[i - 2]\nreturn self.memory[n]",
"one_step = 1\ntwo_step = 2\nfor _ in range(3, n + 1):\n all_way = one_step + two_step\n one_step, two_step = (two_step, all_way)\nreturn all_way",
"if 0 < n < 3:\n... | <|body_start_0|>
self.memory = {1: 1, 2: 2}
for i in range(3, n + 1):
self.memory[i] = self.memory[i - 1] + self.memory[i - 2]
return self.memory[n]
<|end_body_0|>
<|body_start_1|>
one_step = 1
two_step = 2
for _ in range(3, n + 1):
all_way = one_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs1(self, n: int) -> int:
"""动态规划"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""动态规划优化"""
<|body_1|>
def climbStairs2(self, n: int) -> int:
"""递归法 时间复杂度 O(2 ^ n)"""
<|body_2|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_018483 | 1,424 | no_license | [
{
"docstring": "动态规划",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n: int) -> int"
},
{
"docstring": "动态规划优化",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
},
{
"docstring": "递归法 时间复杂度 O(2 ^ n)",
"name": "climbStairs2",
"sign... | 3 | stack_v2_sparse_classes_30k_train_007927 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n: int) -> int: 动态规划
- def climbStairs(self, n: int) -> int: 动态规划优化
- def climbStairs2(self, n: int) -> int: 递归法 时间复杂度 O(2 ^ n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n: int) -> int: 动态规划
- def climbStairs(self, n: int) -> int: 动态规划优化
- def climbStairs2(self, n: int) -> int: 递归法 时间复杂度 O(2 ^ n)
<|skeleton|>
class Solutio... | 2acf8468c2e3454b9685b214e25617c98d55b3bc | <|skeleton|>
class Solution:
def climbStairs1(self, n: int) -> int:
"""动态规划"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""动态规划优化"""
<|body_1|>
def climbStairs2(self, n: int) -> int:
"""递归法 时间复杂度 O(2 ^ n)"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs1(self, n: int) -> int:
"""动态规划"""
self.memory = {1: 1, 2: 2}
for i in range(3, n + 1):
self.memory[i] = self.memory[i - 1] + self.memory[i - 2]
return self.memory[n]
def climbStairs(self, n: int) -> int:
"""动态规划优化"""
on... | the_stack_v2_python_sparse | 70_climbing-stairs.py | linxuedong/leetcode | train | 0 | |
6fee75ca78b5971ace56e6ccb12022d550203d34 | [
"logger.info('initializing hooks')\nif not isinstance(hook, ESHook):\n raise Exception('hook(%s) is not instance of %s' % (hook, ESHook))\nself.__hook = hook\nlogger.info('initialized hooks')",
"logger.debug('gettting payload')\npayload = self.__hook.get_payload()\nlogger.debug('got payload: %s' % payload)\nlo... | <|body_start_0|>
logger.info('initializing hooks')
if not isinstance(hook, ESHook):
raise Exception('hook(%s) is not instance of %s' % (hook, ESHook))
self.__hook = hook
logger.info('initialized hooks')
<|end_body_0|>
<|body_start_1|>
logger.debug('gettting payload')... | ESManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESManager:
def __init__(self, hook):
"""Initialization: setup ES hooks. :param hook: an instance of ESHook."""
<|body_0|>
def run(self):
"""Initialize and run ESProcess."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger.info('initializing hooks... | stack_v2_sparse_classes_36k_train_018484 | 1,479 | permissive | [
{
"docstring": "Initialization: setup ES hooks. :param hook: an instance of ESHook.",
"name": "__init__",
"signature": "def __init__(self, hook)"
},
{
"docstring": "Initialize and run ESProcess.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004334 | Implement the Python class `ESManager` described below.
Class description:
Implement the ESManager class.
Method signatures and docstrings:
- def __init__(self, hook): Initialization: setup ES hooks. :param hook: an instance of ESHook.
- def run(self): Initialize and run ESProcess. | Implement the Python class `ESManager` described below.
Class description:
Implement the ESManager class.
Method signatures and docstrings:
- def __init__(self, hook): Initialization: setup ES hooks. :param hook: an instance of ESHook.
- def run(self): Initialize and run ESProcess.
<|skeleton|>
class ESManager:
... | 029e013dec888eecadb34c485f8d7498fccd000f | <|skeleton|>
class ESManager:
def __init__(self, hook):
"""Initialization: setup ES hooks. :param hook: an instance of ESHook."""
<|body_0|>
def run(self):
"""Initialize and run ESProcess."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESManager:
def __init__(self, hook):
"""Initialization: setup ES hooks. :param hook: an instance of ESHook."""
logger.info('initializing hooks')
if not isinstance(hook, ESHook):
raise Exception('hook(%s) is not instance of %s' % (hook, ESHook))
self.__hook = hook
... | the_stack_v2_python_sparse | pilot/eventservice/esprocess/esmanager.py | mlassnig/pilot2 | train | 0 | |
bc11f74212d15953ee52c8f1d5d14992876240f7 | [
"parser.add_argument('sso_email_user_id', help='The SSO email user ID of the adviser to add an access token for.')\nparser.add_argument('--hours', type=int, default=10, help='Number of hours in which the access token will expire.')\nparser.add_argument('--token', type=str, help='If specified, a token will not be ra... | <|body_start_0|>
parser.add_argument('sso_email_user_id', help='The SSO email user ID of the adviser to add an access token for.')
parser.add_argument('--hours', type=int, default=10, help='Number of hours in which the access token will expire.')
parser.add_argument('--token', type=str, help='If... | Temporarily adds an access token for local development purposes. | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Temporarily adds an access token for local development purposes."""
def add_arguments(self, parser):
"""Define extra arguments."""
<|body_0|>
def handle(self, *args, **options):
"""Main logic for the actual command."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_018485 | 1,776 | permissive | [
{
"docstring": "Define extra arguments.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Main logic for the actual command.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
}
] | 2 | null | Implement the Python class `Command` described below.
Class description:
Temporarily adds an access token for local development purposes.
Method signatures and docstrings:
- def add_arguments(self, parser): Define extra arguments.
- def handle(self, *args, **options): Main logic for the actual command. | Implement the Python class `Command` described below.
Class description:
Temporarily adds an access token for local development purposes.
Method signatures and docstrings:
- def add_arguments(self, parser): Define extra arguments.
- def handle(self, *args, **options): Main logic for the actual command.
<|skeleton|>
... | a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e | <|skeleton|>
class Command:
"""Temporarily adds an access token for local development purposes."""
def add_arguments(self, parser):
"""Define extra arguments."""
<|body_0|>
def handle(self, *args, **options):
"""Main logic for the actual command."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Temporarily adds an access token for local development purposes."""
def add_arguments(self, parser):
"""Define extra arguments."""
parser.add_argument('sso_email_user_id', help='The SSO email user ID of the adviser to add an access token for.')
parser.add_argument('--h... | the_stack_v2_python_sparse | datahub/oauth/management/commands/add_access_token.py | cgsunkel/data-hub-api | train | 0 |
55e5dbb89135356f8f136f7fffed38a6338d58e3 | [
"self.enabled = enabled\nself.retention_period_days = retention_period_days\nself.verbose_audit = verbose_audit",
"if dictionary is None:\n return None\nenabled = dictionary.get('enabled')\nretention_period_days = dictionary.get('retentionPeriodDays')\nverbose_audit = dictionary.get('verboseAudit')\nreturn cls... | <|body_start_0|>
self.enabled = enabled
self.retention_period_days = retention_period_days
self.verbose_audit = verbose_audit
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
enabled = dictionary.get('enabled')
retention_period_days = dictio... | Implementation of the 'ClusterAuditLogConfiguration' model. Specifies the settings of the Cluster audit log configuration. Attributes: enabled (bool, required): Specifies if the Cluster audit logging is enabled on the Cohesity Cluster. If 'true', Cluster audit logging is enabled. Otherwise, it is disabled. retention_pe... | ClusterAuditLogConfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterAuditLogConfiguration:
"""Implementation of the 'ClusterAuditLogConfiguration' model. Specifies the settings of the Cluster audit log configuration. Attributes: enabled (bool, required): Specifies if the Cluster audit logging is enabled on the Cohesity Cluster. If 'true', Cluster audit log... | stack_v2_sparse_classes_36k_train_018486 | 2,374 | permissive | [
{
"docstring": "Constructor for the ClusterAuditLogConfiguration class",
"name": "__init__",
"signature": "def __init__(self, enabled=None, retention_period_days=None, verbose_audit=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dic... | 2 | null | Implement the Python class `ClusterAuditLogConfiguration` described below.
Class description:
Implementation of the 'ClusterAuditLogConfiguration' model. Specifies the settings of the Cluster audit log configuration. Attributes: enabled (bool, required): Specifies if the Cluster audit logging is enabled on the Cohesit... | Implement the Python class `ClusterAuditLogConfiguration` described below.
Class description:
Implementation of the 'ClusterAuditLogConfiguration' model. Specifies the settings of the Cluster audit log configuration. Attributes: enabled (bool, required): Specifies if the Cluster audit logging is enabled on the Cohesit... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterAuditLogConfiguration:
"""Implementation of the 'ClusterAuditLogConfiguration' model. Specifies the settings of the Cluster audit log configuration. Attributes: enabled (bool, required): Specifies if the Cluster audit logging is enabled on the Cohesity Cluster. If 'true', Cluster audit log... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterAuditLogConfiguration:
"""Implementation of the 'ClusterAuditLogConfiguration' model. Specifies the settings of the Cluster audit log configuration. Attributes: enabled (bool, required): Specifies if the Cluster audit logging is enabled on the Cohesity Cluster. If 'true', Cluster audit logging is enabl... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_audit_log_configuration.py | cohesity/management-sdk-python | train | 24 |
a041f80fe7653b0ec01a1c1f951b5bbfac826323 | [
"self.sequence = []\nif entirety == True:\n self.SequenceID = ['02', '04', '05', '09', '10', '11', '13']\nelse:\n self.SequenceID = ['09']\nself.vis_save_path = 'MOT17/visualize'\nprint('\\n-------------------------- initialization --------------------------')\nfor id in self.SequenceID:\n print('initializ... | <|body_start_0|>
self.sequence = []
if entirety == True:
self.SequenceID = ['02', '04', '05', '09', '10', '11', '13']
else:
self.SequenceID = ['09']
self.vis_save_path = 'MOT17/visualize'
print('\n-------------------------- initialization -----------------... | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
def __init__(self, entirety=False):
""":param entirety:"""
<|body_0|>
def visualize(self, seq_ID, frame, save_path=None):
""":param seq_ID: :param frame: :param save_path:"""
<|body_1|>
def __call__(self):
""":return:"""
<|body... | stack_v2_sparse_classes_36k_train_018487 | 7,355 | no_license | [
{
"docstring": ":param entirety:",
"name": "__init__",
"signature": "def __init__(self, entirety=False)"
},
{
"docstring": ":param seq_ID: :param frame: :param save_path:",
"name": "visualize",
"signature": "def visualize(self, seq_ID, frame, save_path=None)"
},
{
"docstring": ":... | 3 | stack_v2_sparse_classes_30k_train_001584 | Implement the Python class `Generator` described below.
Class description:
Implement the Generator class.
Method signatures and docstrings:
- def __init__(self, entirety=False): :param entirety:
- def visualize(self, seq_ID, frame, save_path=None): :param seq_ID: :param frame: :param save_path:
- def __call__(self): ... | Implement the Python class `Generator` described below.
Class description:
Implement the Generator class.
Method signatures and docstrings:
- def __init__(self, entirety=False): :param entirety:
- def visualize(self, seq_ID, frame, save_path=None): :param seq_ID: :param frame: :param save_path:
- def __call__(self): ... | ad377c6e5aebda059302a54fe5c830c0ac46fb8d | <|skeleton|>
class Generator:
def __init__(self, entirety=False):
""":param entirety:"""
<|body_0|>
def visualize(self, seq_ID, frame, save_path=None):
""":param seq_ID: :param frame: :param save_path:"""
<|body_1|>
def __call__(self):
""":return:"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
def __init__(self, entirety=False):
""":param entirety:"""
self.sequence = []
if entirety == True:
self.SequenceID = ['02', '04', '05', '09', '10', '11', '13']
else:
self.SequenceID = ['09']
self.vis_save_path = 'MOT17/visualize'
... | the_stack_v2_python_sparse | Generator.py | SundaramMuthu/EDA_GNN | train | 0 | |
587fcc5493081aa26787413f58e6f8e5d8782256 | [
"adm = ProjektAdministration()\nprojektart = adm.get_alle_projektarten()\nreturn projektart",
"id = request.args.get('id')\nadm = ProjektAdministration()\nadm.delete_projektart(id)",
"adm = ProjektAdministration()\nprojektart = Projektart.from_dict(api.payload)\nif projektart is not None:\n ' Wir verwenden p... | <|body_start_0|>
adm = ProjektAdministration()
projektart = adm.get_alle_projektarten()
return projektart
<|end_body_0|>
<|body_start_1|>
id = request.args.get('id')
adm = ProjektAdministration()
adm.delete_projektart(id)
<|end_body_1|>
<|body_start_2|>
adm = Pr... | ProjektartOperationen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjektartOperationen:
def get(self):
"""Auslesen aller Projektart-Objekten."""
<|body_0|>
def delete(self):
"""Löschen eines bestimmten Projektart-Objekts nach id."""
<|body_1|>
def put(self):
"""Update eines bestimmten Projektart-Objekts."""
... | stack_v2_sparse_classes_36k_train_018488 | 29,521 | no_license | [
{
"docstring": "Auslesen aller Projektart-Objekten.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Löschen eines bestimmten Projektart-Objekts nach id.",
"name": "delete",
"signature": "def delete(self)"
},
{
"docstring": "Update eines bestimmten Projektart-Obje... | 4 | stack_v2_sparse_classes_30k_train_005472 | Implement the Python class `ProjektartOperationen` described below.
Class description:
Implement the ProjektartOperationen class.
Method signatures and docstrings:
- def get(self): Auslesen aller Projektart-Objekten.
- def delete(self): Löschen eines bestimmten Projektart-Objekts nach id.
- def put(self): Update eine... | Implement the Python class `ProjektartOperationen` described below.
Class description:
Implement the ProjektartOperationen class.
Method signatures and docstrings:
- def get(self): Auslesen aller Projektart-Objekten.
- def delete(self): Löschen eines bestimmten Projektart-Objekts nach id.
- def put(self): Update eine... | 9014f16fed08956bd28216e1373b60139e5caea1 | <|skeleton|>
class ProjektartOperationen:
def get(self):
"""Auslesen aller Projektart-Objekten."""
<|body_0|>
def delete(self):
"""Löschen eines bestimmten Projektart-Objekts nach id."""
<|body_1|>
def put(self):
"""Update eines bestimmten Projektart-Objekts."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjektartOperationen:
def get(self):
"""Auslesen aller Projektart-Objekten."""
adm = ProjektAdministration()
projektart = adm.get_alle_projektarten()
return projektart
def delete(self):
"""Löschen eines bestimmten Projektart-Objekts nach id."""
id = reques... | the_stack_v2_python_sparse | src/main.py | leanderpeter/university_project_selector | train | 3 | |
ed06247e5cca786cc6982417be2c150576bd87b5 | [
"S = m - 1 + n - 1\nX = min(m, n) - 1\nnom = 1\nden = 1\nfor i in range(1, X + 1):\n nom *= S + 1 - i\n den *= i\nreturn nom // den",
"grid = {(0, 0): 1}\nfor i in range(m):\n for j in range(n):\n if (i, j) in grid:\n continue\n grid[i, j] = grid.get((i, j - 1), 0) + grid.get((i ... | <|body_start_0|>
S = m - 1 + n - 1
X = min(m, n) - 1
nom = 1
den = 1
for i in range(1, X + 1):
nom *= S + 1 - i
den *= i
return nom // den
<|end_body_0|>
<|body_start_1|>
grid = {(0, 0): 1}
for i in range(m):
for j in r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""Using binomial"""
<|body_0|>
def uniquePaths2(self, m: int, n: int) -> int:
"""Using cache"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
S = m - 1 + n - 1
X = min(m, n) - 1
... | stack_v2_sparse_classes_36k_train_018489 | 665 | permissive | [
{
"docstring": "Using binomial",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m: int, n: int) -> int"
},
{
"docstring": "Using cache",
"name": "uniquePaths2",
"signature": "def uniquePaths2(self, m: int, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_004422 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m: int, n: int) -> int: Using binomial
- def uniquePaths2(self, m: int, n: int) -> int: Using cache | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m: int, n: int) -> int: Using binomial
- def uniquePaths2(self, m: int, n: int) -> int: Using cache
<|skeleton|>
class Solution:
def uniquePaths(self,... | 1f6d597ebdfa0a39dc5ba91ba246840f972d881d | <|skeleton|>
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""Using binomial"""
<|body_0|>
def uniquePaths2(self, m: int, n: int) -> int:
"""Using cache"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""Using binomial"""
S = m - 1 + n - 1
X = min(m, n) - 1
nom = 1
den = 1
for i in range(1, X + 1):
nom *= S + 1 - i
den *= i
return nom // den
def uniquePaths2(self, m: ... | the_stack_v2_python_sparse | leetcode/62_Unique_Paths.py | Valiev/contests | train | 0 | |
0502dec3ca366127bbf437470e1ee00a72dedbad | [
"x = start + 1\ny = end + 1\nz = 2 * x\nwhile z <= y:\n if z <= end and nums[z - 1] < nums[z]:\n z += 1\n if nums[x - 1] < nums[z - 1]:\n nums[x - 1], nums[z - 1] = (nums[z - 1], nums[x - 1])\n x = z\n z = x * 2\n else:\n break",
"n = len(nums)\nsub_roots = n // 2\nfor ... | <|body_start_0|>
x = start + 1
y = end + 1
z = 2 * x
while z <= y:
if z <= end and nums[z - 1] < nums[z]:
z += 1
if nums[x - 1] < nums[z - 1]:
nums[x - 1], nums[z - 1] = (nums[z - 1], nums[x - 1])
x = z
... | Solution4 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution4:
def sift_down(self, nums, start, end):
"""max heap"""
<|body_0|>
def findKthLargest(self, nums: List[int], k: int) -> int:
"""priority queue, heap sort solution; similar to https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zh... | stack_v2_sparse_classes_36k_train_018490 | 11,869 | no_license | [
{
"docstring": "max heap",
"name": "sift_down",
"signature": "def sift_down(self, nums, start, end)"
},
{
"docstring": "priority queue, heap sort solution; similar to https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode-/ 912... | 2 | stack_v2_sparse_classes_30k_train_012904 | Implement the Python class `Solution4` described below.
Class description:
Implement the Solution4 class.
Method signatures and docstrings:
- def sift_down(self, nums, start, end): max heap
- def findKthLargest(self, nums: List[int], k: int) -> int: priority queue, heap sort solution; similar to https://leetcode-cn.c... | Implement the Python class `Solution4` described below.
Class description:
Implement the Solution4 class.
Method signatures and docstrings:
- def sift_down(self, nums, start, end): max heap
- def findKthLargest(self, nums: List[int], k: int) -> int: priority queue, heap sort solution; similar to https://leetcode-cn.c... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution4:
def sift_down(self, nums, start, end):
"""max heap"""
<|body_0|>
def findKthLargest(self, nums: List[int], k: int) -> int:
"""priority queue, heap sort solution; similar to https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution4:
def sift_down(self, nums, start, end):
"""max heap"""
x = start + 1
y = end + 1
z = 2 * x
while z <= y:
if z <= end and nums[z - 1] < nums[z]:
z += 1
if nums[x - 1] < nums[z - 1]:
nums[x - 1], nums[z - 1... | the_stack_v2_python_sparse | Kth_Largest_Element_in_an_Array_215.py | jay6413682/Leetcode | train | 0 | |
0cf4d6fac4082cf456afc78b9cb480aa948d7f9b | [
"args = self.args\nif len(args.rsplit()) != 3:\n self.skillset = None\n self.skillname = None\n self.skillvalue = None\n return\nskillset = args.rsplit()[0].title()\nskillname = args.rsplit()[1].title()\nskillvalue = args.rsplit()[2]\nself.skillset = skillset\nself.skillname = skillname\nself.skillvalue... | <|body_start_0|>
args = self.args
if len(args.rsplit()) != 3:
self.skillset = None
self.skillname = None
self.skillvalue = None
return
skillset = args.rsplit()[0].title()
skillname = args.rsplit()[1].title()
skillvalue = args.rsplit... | set a stat of a character Usage: +setskill (skillset) (skillname) (skillvalue) This sets the power of the current character. This can only be used during character generation. | CmdSetSkill | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdSetSkill:
"""set a stat of a character Usage: +setskill (skillset) (skillname) (skillvalue) This sets the power of the current character. This can only be used during character generation."""
def parse(self):
"""This parses the arguments"""
<|body_0|>
def func(self):
... | stack_v2_sparse_classes_36k_train_018491 | 19,545 | no_license | [
{
"docstring": "This parses the arguments",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "This performs the actual command",
"name": "func",
"signature": "def func(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001862 | Implement the Python class `CmdSetSkill` described below.
Class description:
set a stat of a character Usage: +setskill (skillset) (skillname) (skillvalue) This sets the power of the current character. This can only be used during character generation.
Method signatures and docstrings:
- def parse(self): This parses ... | Implement the Python class `CmdSetSkill` described below.
Class description:
set a stat of a character Usage: +setskill (skillset) (skillname) (skillvalue) This sets the power of the current character. This can only be used during character generation.
Method signatures and docstrings:
- def parse(self): This parses ... | 66e9c2ab1570bc8f439cf6ccde872534eecb0d62 | <|skeleton|>
class CmdSetSkill:
"""set a stat of a character Usage: +setskill (skillset) (skillname) (skillvalue) This sets the power of the current character. This can only be used during character generation."""
def parse(self):
"""This parses the arguments"""
<|body_0|>
def func(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CmdSetSkill:
"""set a stat of a character Usage: +setskill (skillset) (skillname) (skillvalue) This sets the power of the current character. This can only be used during character generation."""
def parse(self):
"""This parses the arguments"""
args = self.args
if len(args.rsplit()... | the_stack_v2_python_sparse | commands/command.py | Cidusii/Kyatsu | train | 0 |
d864c45db07e3044e790a4eb1e2ea0c3c708e02c | [
"self.condition = condition\nself.effects = effects\nself.otherwiseEffect = otherwiseEffect",
"coroutine = None\nif self.condition.evaluate(context):\n coroutine = self.performEffects(context)\nelif self.otherwiseEffect is not None:\n coroutine = self.performOtherwiseEffect(context)\nelse:\n context.fail... | <|body_start_0|>
self.condition = condition
self.effects = effects
self.otherwiseEffect = otherwiseEffect
<|end_body_0|>
<|body_start_1|>
coroutine = None
if self.condition.evaluate(context):
coroutine = self.performEffects(context)
elif self.otherwiseEffect ... | Represents an effect that conditionally applies | ConditionalEffect | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalEffect:
"""Represents an effect that conditionally applies"""
def __init__(self, condition, effects, otherwiseEffect=None):
"""Initialize the Effect with the condition to evaluate and effect to perform"""
<|body_0|>
def perform(self, context):
"""Perfo... | stack_v2_sparse_classes_36k_train_018492 | 1,567 | no_license | [
{
"docstring": "Initialize the Effect with the condition to evaluate and effect to perform",
"name": "__init__",
"signature": "def __init__(self, condition, effects, otherwiseEffect=None)"
},
{
"docstring": "Perform the Game Effect",
"name": "perform",
"signature": "def perform(self, con... | 4 | null | Implement the Python class `ConditionalEffect` described below.
Class description:
Represents an effect that conditionally applies
Method signatures and docstrings:
- def __init__(self, condition, effects, otherwiseEffect=None): Initialize the Effect with the condition to evaluate and effect to perform
- def perform(... | Implement the Python class `ConditionalEffect` described below.
Class description:
Represents an effect that conditionally applies
Method signatures and docstrings:
- def __init__(self, condition, effects, otherwiseEffect=None): Initialize the Effect with the condition to evaluate and effect to perform
- def perform(... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class ConditionalEffect:
"""Represents an effect that conditionally applies"""
def __init__(self, condition, effects, otherwiseEffect=None):
"""Initialize the Effect with the condition to evaluate and effect to perform"""
<|body_0|>
def perform(self, context):
"""Perfo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalEffect:
"""Represents an effect that conditionally applies"""
def __init__(self, condition, effects, otherwiseEffect=None):
"""Initialize the Effect with the condition to evaluate and effect to perform"""
self.condition = condition
self.effects = effects
self.ot... | the_stack_v2_python_sparse | src/Game/Effects/conditional_effect.py | dfwarden/DeckBuilding | train | 0 |
58d8c2271fb423f8309143ccf3d44b10f145e02b | [
"try:\n user = User.objects.get(pk=data)\nexcept User.DoesNotExist:\n raise serializers.ValidationError('Invalid Passanger')\ncircle = self.context['circle']\ntry:\n membership = MemberShip.objects.get(user=user, circle=circle, is_active=True)\nexcept MemberShip.DoesNotExist:\n raise serializers.Validat... | <|body_start_0|>
try:
user = User.objects.get(pk=data)
except User.DoesNotExist:
raise serializers.ValidationError('Invalid Passanger')
circle = self.context['circle']
try:
membership = MemberShip.objects.get(user=user, circle=circle, is_active=True)
... | Join Ride serializer | JoinRideSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinRideSerializer:
"""Join Ride serializer"""
def validate_passanger(self, data):
"""Verify passenger exist and is a circle member"""
<|body_0|>
def validate(self, data):
"""verify ride allow new passangers"""
<|body_1|>
def update(self, instance, d... | stack_v2_sparse_classes_36k_train_018493 | 7,953 | no_license | [
{
"docstring": "Verify passenger exist and is a circle member",
"name": "validate_passanger",
"signature": "def validate_passanger(self, data)"
},
{
"docstring": "verify ride allow new passangers",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Add... | 3 | stack_v2_sparse_classes_30k_train_016413 | Implement the Python class `JoinRideSerializer` described below.
Class description:
Join Ride serializer
Method signatures and docstrings:
- def validate_passanger(self, data): Verify passenger exist and is a circle member
- def validate(self, data): verify ride allow new passangers
- def update(self, instance, data)... | Implement the Python class `JoinRideSerializer` described below.
Class description:
Join Ride serializer
Method signatures and docstrings:
- def validate_passanger(self, data): Verify passenger exist and is a circle member
- def validate(self, data): verify ride allow new passangers
- def update(self, instance, data)... | 0cede53169041667bd40bbce3c4774af84ffc2fa | <|skeleton|>
class JoinRideSerializer:
"""Join Ride serializer"""
def validate_passanger(self, data):
"""Verify passenger exist and is a circle member"""
<|body_0|>
def validate(self, data):
"""verify ride allow new passangers"""
<|body_1|>
def update(self, instance, d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JoinRideSerializer:
"""Join Ride serializer"""
def validate_passanger(self, data):
"""Verify passenger exist and is a circle member"""
try:
user = User.objects.get(pk=data)
except User.DoesNotExist:
raise serializers.ValidationError('Invalid Passanger')
... | the_stack_v2_python_sparse | rides/serializers/rides.py | KrystellCR/DjangoRF | train | 0 |
e944924f06776adce205340fdb95884385004029 | [
"t1 = PartParameterTemplate.objects.get(pk=1)\nself.assertEqual(str(t1), 'Length (mm)')\np1 = PartParameter.objects.get(pk=1)\nself.assertEqual(str(p1), 'M2x4 LPHS : Length = 4 (mm)')\nc1 = PartCategoryParameterTemplate.objects.get(pk=1)\nself.assertEqual(str(c1), 'Mechanical | Length | 2.8')",
"n = PartParameter... | <|body_start_0|>
t1 = PartParameterTemplate.objects.get(pk=1)
self.assertEqual(str(t1), 'Length (mm)')
p1 = PartParameter.objects.get(pk=1)
self.assertEqual(str(p1), 'M2x4 LPHS : Length = 4 (mm)')
c1 = PartCategoryParameterTemplate.objects.get(pk=1)
self.assertEqual(str(c... | Unit test class for testing the PartParameter model | TestParams | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestParams:
"""Unit test class for testing the PartParameter model"""
def test_str(self):
"""Test the str representation of the PartParameterTemplate model"""
<|body_0|>
def test_validate(self):
"""Test validation for part templates"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_018494 | 12,864 | permissive | [
{
"docstring": "Test the str representation of the PartParameterTemplate model",
"name": "test_str",
"signature": "def test_str(self)"
},
{
"docstring": "Test validation for part templates",
"name": "test_validate",
"signature": "def test_validate(self)"
},
{
"docstring": "Unit t... | 4 | stack_v2_sparse_classes_30k_train_018606 | Implement the Python class `TestParams` described below.
Class description:
Unit test class for testing the PartParameter model
Method signatures and docstrings:
- def test_str(self): Test the str representation of the PartParameterTemplate model
- def test_validate(self): Test validation for part templates
- def tes... | Implement the Python class `TestParams` described below.
Class description:
Unit test class for testing the PartParameter model
Method signatures and docstrings:
- def test_str(self): Test the str representation of the PartParameterTemplate model
- def test_validate(self): Test validation for part templates
- def tes... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestParams:
"""Unit test class for testing the PartParameter model"""
def test_str(self):
"""Test the str representation of the PartParameterTemplate model"""
<|body_0|>
def test_validate(self):
"""Test validation for part templates"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestParams:
"""Unit test class for testing the PartParameter model"""
def test_str(self):
"""Test the str representation of the PartParameterTemplate model"""
t1 = PartParameterTemplate.objects.get(pk=1)
self.assertEqual(str(t1), 'Length (mm)')
p1 = PartParameter.objects.g... | the_stack_v2_python_sparse | InvenTree/part/test_param.py | inventree/InvenTree | train | 3,077 |
86606bc769437f84b37de8eb1be2a52e0111826a | [
"for key in inconfigs:\n if not key.startswith('text search configuration '):\n raise KeyError('Unrecognized object type: %s' % key)\n tsc = key[26:]\n self[schema.name, tsc] = config = TSConfiguration(schema=schema.name, name=tsc)\n inconfig = inconfigs[key]\n if inconfig:\n for attr, ... | <|body_start_0|>
for key in inconfigs:
if not key.startswith('text search configuration '):
raise KeyError('Unrecognized object type: %s' % key)
tsc = key[26:]
self[schema.name, tsc] = config = TSConfiguration(schema=schema.name, name=tsc)
inconfig... | The collection of text search configurations in a database | TSConfigurationDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSConfigurationDict:
"""The collection of text search configurations in a database"""
def from_map(self, schema, inconfigs):
"""Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining th... | stack_v2_sparse_classes_36k_train_018495 | 15,925 | permissive | [
{
"docstring": "Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining the configurations",
"name": "from_map",
"signature": "def from_map(self, schema, inconfigs)"
},
{
"docstring": "Generate SQL ... | 2 | stack_v2_sparse_classes_30k_val_000220 | Implement the Python class `TSConfigurationDict` described below.
Class description:
The collection of text search configurations in a database
Method signatures and docstrings:
- def from_map(self, schema, inconfigs): Initialize the dictionary of configs by examining the input map :param schema: schema owning the co... | Implement the Python class `TSConfigurationDict` described below.
Class description:
The collection of text search configurations in a database
Method signatures and docstrings:
- def from_map(self, schema, inconfigs): Initialize the dictionary of configs by examining the input map :param schema: schema owning the co... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class TSConfigurationDict:
"""The collection of text search configurations in a database"""
def from_map(self, schema, inconfigs):
"""Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TSConfigurationDict:
"""The collection of text search configurations in a database"""
def from_map(self, schema, inconfigs):
"""Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining the configurati... | the_stack_v2_python_sparse | pyrseas/dbobject/textsearch.py | vayerx/Pyrseas | train | 1 |
a671e163df21aee3d74330660ba4caea68251629 | [
"enc1, enc2 = ([], [])\ncount1, count2 = (0, 0)\ndict1, dict2 = (dict(), dict())\nfor i in range(len(s1)):\n char1, char2 = (s1[i], s2[i])\n if char1 in dict1:\n enc1.append(dict1[char1])\n else:\n count1 += 1\n dict1[char1] = count1\n enc1.append(dict1[char1])\n if char2 in ... | <|body_start_0|>
enc1, enc2 = ([], [])
count1, count2 = (0, 0)
dict1, dict2 = (dict(), dict())
for i in range(len(s1)):
char1, char2 = (s1[i], s2[i])
if char1 in dict1:
enc1.append(dict1[char1])
else:
count1 += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_isomorphic(self, s1, s2):
"""Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take ind... | stack_v2_sparse_classes_36k_train_018496 | 2,448 | no_license | [
{
"docstring": "Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take index from a dictionary, otherwise we assign a new index.... | 2 | stack_v2_sparse_classes_30k_train_008923 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_isomorphic(self, s1, s2): Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, star... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_isomorphic(self, s1, s2): Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, star... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def is_isomorphic(self, s1, s2):
"""Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take ind... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def is_isomorphic(self, s1, s2):
"""Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take index from a dict... | the_stack_v2_python_sparse | Strings/isomorphic_strings.py | vladn90/Algorithms | train | 0 | |
1b3f5d2fd1e63b1ee0a68539b0137502279c1dba | [
"self.source_detection: SourceDetection = source_detection()\nself.reference_centroids = None\nself.max_sources = 42\nself.search_boxsize = 9",
"self.reference_centroids = []\nfor img in images:\n image = self.source_detection(img)\n sources = image.catalog\n sources.sort('peak')\n sources.reverse()\n... | <|body_start_0|>
self.source_detection: SourceDetection = source_detection()
self.reference_centroids = None
self.max_sources = 42
self.search_boxsize = 9
<|end_body_0|>
<|body_start_1|>
self.reference_centroids = []
for img in images:
image = self.source_det... | Guide offset based on source detection. | GuideCalcSimple | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuideCalcSimple:
"""Guide offset based on source detection."""
def __init__(self, source_detection: SourceDetection, **kwargs: Any):
"""Initialize"""
<|body_0|>
async def reference_target(self, images: List[Image]) -> None:
"""Analyse given images."""
<|b... | stack_v2_sparse_classes_36k_train_018497 | 2,531 | permissive | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, source_detection: SourceDetection, **kwargs: Any)"
},
{
"docstring": "Analyse given images.",
"name": "reference_target",
"signature": "async def reference_target(self, images: List[Image]) -> None"
},
... | 3 | stack_v2_sparse_classes_30k_train_005629 | Implement the Python class `GuideCalcSimple` described below.
Class description:
Guide offset based on source detection.
Method signatures and docstrings:
- def __init__(self, source_detection: SourceDetection, **kwargs: Any): Initialize
- async def reference_target(self, images: List[Image]) -> None: Analyse given i... | Implement the Python class `GuideCalcSimple` described below.
Class description:
Guide offset based on source detection.
Method signatures and docstrings:
- def __init__(self, source_detection: SourceDetection, **kwargs: Any): Initialize
- async def reference_target(self, images: List[Image]) -> None: Analyse given i... | f04723f708dc6767a57a397e7ed8359eace281ba | <|skeleton|>
class GuideCalcSimple:
"""Guide offset based on source detection."""
def __init__(self, source_detection: SourceDetection, **kwargs: Any):
"""Initialize"""
<|body_0|>
async def reference_target(self, images: List[Image]) -> None:
"""Analyse given images."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GuideCalcSimple:
"""Guide offset based on source detection."""
def __init__(self, source_detection: SourceDetection, **kwargs: Any):
"""Initialize"""
self.source_detection: SourceDetection = source_detection()
self.reference_centroids = None
self.max_sources = 42
s... | the_stack_v2_python_sparse | python/lvmagp/guide/calc/simple.py | sdss/lvmagp | train | 1 |
577ae3925eac1b8ae72ec67fe6e5544791ca7674 | [
"if not graph:\n return False\nnode_sets = [set(), set()]\nvisited = [False] * len(graph)\nfor k in range(len(graph)):\n if visited[k]:\n continue\n queue = [[k, 0]]\n for i, set_idx in queue:\n alt_set_idx = (set_idx + 1) % 2\n this_set = node_sets[set_idx]\n alt_set = node_... | <|body_start_0|>
if not graph:
return False
node_sets = [set(), set()]
visited = [False] * len(graph)
for k in range(len(graph)):
if visited[k]:
continue
queue = [[k, 0]]
for i, set_idx in queue:
alt_set_idx ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBipartite_v1(self, graph: List[List[int]]) -> bool:
"""Use two sets to track two groups."""
<|body_0|>
def isBipartite_v2(self, graph: List[List[int]]) -> bool:
"""Use one color array to track two colors (0, 1)."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_018498 | 3,413 | no_license | [
{
"docstring": "Use two sets to track two groups.",
"name": "isBipartite_v1",
"signature": "def isBipartite_v1(self, graph: List[List[int]]) -> bool"
},
{
"docstring": "Use one color array to track two colors (0, 1).",
"name": "isBipartite_v2",
"signature": "def isBipartite_v2(self, grap... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBipartite_v1(self, graph: List[List[int]]) -> bool: Use two sets to track two groups.
- def isBipartite_v2(self, graph: List[List[int]]) -> bool: Use one color array to tra... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBipartite_v1(self, graph: List[List[int]]) -> bool: Use two sets to track two groups.
- def isBipartite_v2(self, graph: List[List[int]]) -> bool: Use one color array to tra... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def isBipartite_v1(self, graph: List[List[int]]) -> bool:
"""Use two sets to track two groups."""
<|body_0|>
def isBipartite_v2(self, graph: List[List[int]]) -> bool:
"""Use one color array to track two colors (0, 1)."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isBipartite_v1(self, graph: List[List[int]]) -> bool:
"""Use two sets to track two groups."""
if not graph:
return False
node_sets = [set(), set()]
visited = [False] * len(graph)
for k in range(len(graph)):
if visited[k]:
... | the_stack_v2_python_sparse | python3/trees_and_graphs/bipartite_graph.py | victorchu/algorithms | train | 0 | |
8f10efb74ccb55bb09d73165c19634e1c7d016bc | [
"self._init_attrs()\nsuper().__init__(host)\nself.onvif_port = onvif_port\nself._build_interfaces()",
"interfaces_data = []\nfor interface_name, interface in self._interfaces.items():\n interfaces_data.append(f\"{(interface_name + ':').ljust(10)} {repr(interface)}\")\nstr_interfaces = '\\n\\t'.join(interfaces_... | <|body_start_0|>
self._init_attrs()
super().__init__(host)
self.onvif_port = onvif_port
self._build_interfaces()
<|end_body_0|>
<|body_start_1|>
interfaces_data = []
for interface_name, interface in self._interfaces.items():
interfaces_data.append(f"{(interfa... | The most base yatwin camera, which condones hacking | BaseHackedYatwin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHackedYatwin:
"""The most base yatwin camera, which condones hacking"""
def __init__(self, host, onvif_port=onvif.constants.DEFAULT_PORT):
"""Initialises self Default onvif_port: onvif.constants.DEFAULT_PORT"""
<|body_0|>
def __repr__(self):
"""Returns a stri... | stack_v2_sparse_classes_36k_train_018499 | 2,265 | no_license | [
{
"docstring": "Initialises self Default onvif_port: onvif.constants.DEFAULT_PORT",
"name": "__init__",
"signature": "def __init__(self, host, onvif_port=onvif.constants.DEFAULT_PORT)"
},
{
"docstring": "Returns a string representation of the object ... in the form: <class_name ( interface_name:... | 4 | stack_v2_sparse_classes_30k_train_000286 | Implement the Python class `BaseHackedYatwin` described below.
Class description:
The most base yatwin camera, which condones hacking
Method signatures and docstrings:
- def __init__(self, host, onvif_port=onvif.constants.DEFAULT_PORT): Initialises self Default onvif_port: onvif.constants.DEFAULT_PORT
- def __repr__(... | Implement the Python class `BaseHackedYatwin` described below.
Class description:
The most base yatwin camera, which condones hacking
Method signatures and docstrings:
- def __init__(self, host, onvif_port=onvif.constants.DEFAULT_PORT): Initialises self Default onvif_port: onvif.constants.DEFAULT_PORT
- def __repr__(... | 7d370342f34e26e6e66718ae397eb1d81253cd8a | <|skeleton|>
class BaseHackedYatwin:
"""The most base yatwin camera, which condones hacking"""
def __init__(self, host, onvif_port=onvif.constants.DEFAULT_PORT):
"""Initialises self Default onvif_port: onvif.constants.DEFAULT_PORT"""
<|body_0|>
def __repr__(self):
"""Returns a stri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseHackedYatwin:
"""The most base yatwin camera, which condones hacking"""
def __init__(self, host, onvif_port=onvif.constants.DEFAULT_PORT):
"""Initialises self Default onvif_port: onvif.constants.DEFAULT_PORT"""
self._init_attrs()
super().__init__(host)
self.onvif_port ... | the_stack_v2_python_sparse | yatwin/cameras/BaseHackedYatwin.py | andre95d/python-yatwin | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.