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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fbbda4b432ced595779ba135742c37b92a9b729b | [
"try:\n params = Schema({Optional('page'): schema_int, Optional('count'): schema_int, Optional('only'): schema_unicode_multi}).validate(self.get_query_args())\nexcept SchemaError:\n self.resp_args_error()\n return\nparams.update({'creator__id': self.shop_info['id'], 'status__status__in': [ExprState.STATUS_... | <|body_start_0|>
try:
params = Schema({Optional('page'): schema_int, Optional('count'): schema_int, Optional('only'): schema_unicode_multi}).validate(self.get_query_args())
except SchemaError:
self.resp_args_error()
return
params.update({'creator__id': self.sh... | ExpressListWithCash | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpressListWithCash:
def get(self, fh_or_h5_or_song):
"""运单列表: 待配送员定价收件"""
<|body_0|>
def patch(self, fh_or_h5):
"""商户支付单个/多个运单"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
params = Schema({Optional('page'): schema_int, Optional(... | stack_v2_sparse_classes_36k_train_001400 | 18,990 | permissive | [
{
"docstring": "运单列表: 待配送员定价收件",
"name": "get",
"signature": "def get(self, fh_or_h5_or_song)"
},
{
"docstring": "商户支付单个/多个运单",
"name": "patch",
"signature": "def patch(self, fh_or_h5)"
}
] | 2 | null | Implement the Python class `ExpressListWithCash` described below.
Class description:
Implement the ExpressListWithCash class.
Method signatures and docstrings:
- def get(self, fh_or_h5_or_song): 运单列表: 待配送员定价收件
- def patch(self, fh_or_h5): 商户支付单个/多个运单 | Implement the Python class `ExpressListWithCash` described below.
Class description:
Implement the ExpressListWithCash class.
Method signatures and docstrings:
- def get(self, fh_or_h5_or_song): 运单列表: 待配送员定价收件
- def patch(self, fh_or_h5): 商户支付单个/多个运单
<|skeleton|>
class ExpressListWithCash:
def get(self, fh_or_h... | a7c9567975b5372b2edabddb0fec8d73bc01c3dc | <|skeleton|>
class ExpressListWithCash:
def get(self, fh_or_h5_or_song):
"""运单列表: 待配送员定价收件"""
<|body_0|>
def patch(self, fh_or_h5):
"""商户支付单个/多个运单"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpressListWithCash:
def get(self, fh_or_h5_or_song):
"""运单列表: 待配送员定价收件"""
try:
params = Schema({Optional('page'): schema_int, Optional('count'): schema_int, Optional('only'): schema_unicode_multi}).validate(self.get_query_args())
except SchemaError:
self.resp_a... | the_stack_v2_python_sparse | Dispatcher/api_gateway/express/handlers/fh.py | cash2one/Logistics | train | 0 | |
1596544c530ce4105be954aaabcc69f454614493 | [
"self.d = {}\nfor i, w in enumerate(words):\n self.d[w] = self.d.get(w, []) + [i]",
"a, b = (self.d[word1], self.d[word2])\nm, n, i, j, res = (len(a), len(b), 0, 0, sys.maxsize)\nwhile i < m and j < n:\n res = min(res, abs(a[i] - b[j]))\n if a[i] < b[j]:\n i += 1\n else:\n j += 1\nreturn... | <|body_start_0|>
self.d = {}
for i, w in enumerate(words):
self.d[w] = self.d.get(w, []) + [i]
<|end_body_0|>
<|body_start_1|>
a, b = (self.d[word1], self.d[word2])
m, n, i, j, res = (len(a), len(b), 0, 0, sys.maxsize)
while i < m and j < n:
res = min(res... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str] beats 24.33%"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = {}
for ... | stack_v2_sparse_classes_36k_train_001401 | 802 | no_license | [
{
"docstring": ":type words: List[str] beats 24.33%",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str] beats 24.33%
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str] beats 24.33%
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordD... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str] beats 24.33%"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str] beats 24.33%"""
self.d = {}
for i, w in enumerate(words):
self.d[w] = self.d.get(w, []) + [i]
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
a, b =... | the_stack_v2_python_sparse | LeetCode/244_shortest_word_distance_ii.py | yao23/Machine_Learning_Playground | train | 12 | |
d2d24f980e2cb83970763d43d62afb750cbadbbb | [
"if cartan_type is None:\n cartan_type = parent.domain().cartan_type()\nif isinstance(on_gens, dict):\n gens = on_gens.keys()\nI = cartan_type.index_set()\nif gens is None:\n if cartan_type == parent.domain().cartan_type():\n gens = parent.domain().highest_weight_vectors()\n else:\n gens =... | <|body_start_0|>
if cartan_type is None:
cartan_type = parent.domain().cartan_type()
if isinstance(on_gens, dict):
gens = on_gens.keys()
I = cartan_type.index_set()
if gens is None:
if cartan_type == parent.domain().cartan_type():
gens ... | A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the domain under ``self`` - ``cartan_type`` -- (optional) a ... | HighestWeightCrystalMorphism | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighestWeightCrystalMorphism:
"""A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the ... | stack_v2_sparse_classes_36k_train_001402 | 27,195 | no_license | [
{
"docstring": "Construct a crystal morphism. TESTS:: sage: B = crystals.infinity.Tableaux(['B',2]) sage: C = crystals.infinity.NakajimaMonomials(['B',2]) sage: psi = B.crystal_morphism(C.module_generators) sage: B = crystals.Tableaux(['B',3], shape=[1]) sage: C = crystals.Tableaux(['D',4], shape=[2]) sage: H =... | 2 | stack_v2_sparse_classes_30k_train_018847 | Implement the Python class `HighestWeightCrystalMorphism` described below.
Class description:
A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order o... | Implement the Python class `HighestWeightCrystalMorphism` described below.
Class description:
A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order o... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class HighestWeightCrystalMorphism:
"""A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HighestWeightCrystalMorphism:
"""A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the domain under ... | the_stack_v2_python_sparse | sage/src/sage/categories/highest_weight_crystals.py | bopopescu/geosci | train | 0 |
383125120f094cbdd3c29378d7d827eb3c4bbfc8 | [
"response = requests.get('https://favqs.com/api/quotes/', params={'filter': random.choice(CATEGORY)}, headers={'Authorization': 'Token token=' + ACCESS_KEY_QUOTES})\nquote_list_json = response.json()\nreturn [quote_list_json['quotes'][0]['body'], quote_list_json['quotes'][0]['author']]",
"response = requests.get(... | <|body_start_0|>
response = requests.get('https://favqs.com/api/quotes/', params={'filter': random.choice(CATEGORY)}, headers={'Authorization': 'Token token=' + ACCESS_KEY_QUOTES})
quote_list_json = response.json()
return [quote_list_json['quotes'][0]['body'], quote_list_json['quotes'][0]['autho... | Quotes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quotes:
def quotes_fav(self):
"""Fetches quotes from FavQuotes API from the category list returns a list of quote and author"""
<|body_0|>
def random_quote_fav(self):
"""Fetches quote of the Day returns a list of quote and author"""
<|body_1|>
def quotab... | stack_v2_sparse_classes_36k_train_001403 | 1,960 | permissive | [
{
"docstring": "Fetches quotes from FavQuotes API from the category list returns a list of quote and author",
"name": "quotes_fav",
"signature": "def quotes_fav(self)"
},
{
"docstring": "Fetches quote of the Day returns a list of quote and author",
"name": "random_quote_fav",
"signature"... | 4 | stack_v2_sparse_classes_30k_train_012148 | Implement the Python class `Quotes` described below.
Class description:
Implement the Quotes class.
Method signatures and docstrings:
- def quotes_fav(self): Fetches quotes from FavQuotes API from the category list returns a list of quote and author
- def random_quote_fav(self): Fetches quote of the Day returns a lis... | Implement the Python class `Quotes` described below.
Class description:
Implement the Quotes class.
Method signatures and docstrings:
- def quotes_fav(self): Fetches quotes from FavQuotes API from the category list returns a list of quote and author
- def random_quote_fav(self): Fetches quote of the Day returns a lis... | d87c6294043889d89a10b44811c7b240d4c1905d | <|skeleton|>
class Quotes:
def quotes_fav(self):
"""Fetches quotes from FavQuotes API from the category list returns a list of quote and author"""
<|body_0|>
def random_quote_fav(self):
"""Fetches quote of the Day returns a list of quote and author"""
<|body_1|>
def quotab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Quotes:
def quotes_fav(self):
"""Fetches quotes from FavQuotes API from the category list returns a list of quote and author"""
response = requests.get('https://favqs.com/api/quotes/', params={'filter': random.choice(CATEGORY)}, headers={'Authorization': 'Token token=' + ACCESS_KEY_QUOTES})
... | the_stack_v2_python_sparse | Resources/quotes_fetch.py | JayP09/Inspiquote | train | 0 | |
8ee40d41645cb11370ccb9c6013f05fbeb22ca30 | [
"super().__init__()\nself.roiSize = 50\nself.fpsFullFrame = 24\nself.fpsRoiFrame = 40",
"self.check('roiSize', config['roi'], 'size')\nself.check('fpsRoiFrame', config['roi'], 'fps')\ntry:\n self.check('fpsFullFrame', config['full'], 'fps')\nexcept KeyError:\n pass",
"config = {'roi': {}, 'full': {}}\ncon... | <|body_start_0|>
super().__init__()
self.roiSize = 50
self.fpsFullFrame = 24
self.fpsRoiFrame = 40
<|end_body_0|>
<|body_start_1|>
self.check('roiSize', config['roi'], 'size')
self.check('fpsRoiFrame', config['roi'], 'fps')
try:
self.check('fpsFullFra... | Class that handles the general configuration of cameras. Attributes ---------- fpsFullFrame : int The acquisition frame rate for full frames. fpsRoiFrame : int The acquisition frame rate for ROI frames. roiSize : int The size (pixels) of the ROI on the camera. | CameraConfig | [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraConfig:
"""Class that handles the general configuration of cameras. Attributes ---------- fpsFullFrame : int The acquisition frame rate for full frames. fpsRoiFrame : int The acquisition frame rate for ROI frames. roiSize : int The size (pixels) of the ROI on the camera."""
def __init_... | stack_v2_sparse_classes_36k_train_001404 | 1,884 | permissive | [
{
"docstring": "Initialize the class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Translate config to class attributes. Parameters ---------- config : dict The configuration to translate.",
"name": "fromDict",
"signature": "def fromDict(self, config)"
},
... | 3 | null | Implement the Python class `CameraConfig` described below.
Class description:
Class that handles the general configuration of cameras. Attributes ---------- fpsFullFrame : int The acquisition frame rate for full frames. fpsRoiFrame : int The acquisition frame rate for ROI frames. roiSize : int The size (pixels) of the... | Implement the Python class `CameraConfig` described below.
Class description:
Class that handles the general configuration of cameras. Attributes ---------- fpsFullFrame : int The acquisition frame rate for full frames. fpsRoiFrame : int The acquisition frame rate for ROI frames. roiSize : int The size (pixels) of the... | 3d0242276198126240667ba13e95b7bdf901d053 | <|skeleton|>
class CameraConfig:
"""Class that handles the general configuration of cameras. Attributes ---------- fpsFullFrame : int The acquisition frame rate for full frames. fpsRoiFrame : int The acquisition frame rate for ROI frames. roiSize : int The size (pixels) of the ROI on the camera."""
def __init_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CameraConfig:
"""Class that handles the general configuration of cameras. Attributes ---------- fpsFullFrame : int The acquisition frame rate for full frames. fpsRoiFrame : int The acquisition frame rate for ROI frames. roiSize : int The size (pixels) of the ROI on the camera."""
def __init__(self):
... | the_stack_v2_python_sparse | spot_motion_monitor/config/camera_config.py | lsst-sitcom/spot_motion_monitor | train | 0 |
653b9fef6f37593d0b951f3a5e75ce78824c6414 | [
"group = self.add_option_group(*args, **kwargs)\nself.option_groups.pop()\nself.option_groups.insert(idx, group)\nreturn group",
"res = self.option_list[:]\nfor i in self.option_groups:\n res.extend(i.option_list)\nreturn res"
] | <|body_start_0|>
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group
<|end_body_0|>
<|body_start_1|>
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
... | CustomOptionParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomOptionParser:
def insert_option_group(self, idx, *args, **kwargs):
"""Insert an OptionGroup at a given position."""
<|body_0|>
def option_list_all(self):
"""Get a list of all options, including those in option groups."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_001405 | 9,378 | permissive | [
{
"docstring": "Insert an OptionGroup at a given position.",
"name": "insert_option_group",
"signature": "def insert_option_group(self, idx, *args, **kwargs)"
},
{
"docstring": "Get a list of all options, including those in option groups.",
"name": "option_list_all",
"signature": "def op... | 2 | null | Implement the Python class `CustomOptionParser` described below.
Class description:
Implement the CustomOptionParser class.
Method signatures and docstrings:
- def insert_option_group(self, idx, *args, **kwargs): Insert an OptionGroup at a given position.
- def option_list_all(self): Get a list of all options, includ... | Implement the Python class `CustomOptionParser` described below.
Class description:
Implement the CustomOptionParser class.
Method signatures and docstrings:
- def insert_option_group(self, idx, *args, **kwargs): Insert an OptionGroup at a given position.
- def option_list_all(self): Get a list of all options, includ... | 40861791ec4ed3bbd14b07875af25cc740f76920 | <|skeleton|>
class CustomOptionParser:
def insert_option_group(self, idx, *args, **kwargs):
"""Insert an OptionGroup at a given position."""
<|body_0|>
def option_list_all(self):
"""Get a list of all options, including those in option groups."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomOptionParser:
def insert_option_group(self, idx, *args, **kwargs):
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group
def option_list_all(... | the_stack_v2_python_sparse | stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/cli/parser.py | wistbean/learn_python3_spider | train | 14,403 | |
9c0df8295537d34a94458b0776ea1a7d974959a7 | [
"super(LabelSmoothingLoss, self).__init__()\nself.reduction = reduction\nself.smoothing = smoothing\nself.ignore_index = ignore_index",
"num_classes = inputs.shape[1]\nsmoothed = inputs.new_full(inputs.shape, self.smoothing / num_classes)\nsmoothed.scatter_(1, targets.unsqueeze(1), 1 - self.smoothing)\nif self.ig... | <|body_start_0|>
super(LabelSmoothingLoss, self).__init__()
self.reduction = reduction
self.smoothing = smoothing
self.ignore_index = ignore_index
<|end_body_0|>
<|body_start_1|>
num_classes = inputs.shape[1]
smoothed = inputs.new_full(inputs.shape, self.smoothing / num_... | Implements the label smoothing loss as defined in https://arxiv.org/abs/1512.00567 The API for this loss is modeled after nn..CrossEntropyLoss: 1) The inputs and targets are expected to be (B x C x ...), where B is the batch dimension, and C is the number of classes 2) You can pass in an index to ignore | LabelSmoothingLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Implements the label smoothing loss as defined in https://arxiv.org/abs/1512.00567 The API for this loss is modeled after nn..CrossEntropyLoss: 1) The inputs and targets are expected to be (B x C x ...), where B is the batch dimension, and C is the number of classes 2) You ... | stack_v2_sparse_classes_36k_train_001406 | 8,378 | no_license | [
{
"docstring": "Initialize the label smoothing loss",
"name": "__init__",
"signature": "def __init__(self, smoothing=0.0, ignore_index=-1, reduction='sum')"
},
{
"docstring": "The implements the actual label smoothing loss",
"name": "forward",
"signature": "def forward(self, inputs, targ... | 2 | stack_v2_sparse_classes_30k_train_007073 | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Implements the label smoothing loss as defined in https://arxiv.org/abs/1512.00567 The API for this loss is modeled after nn..CrossEntropyLoss: 1) The inputs and targets are expected to be (B x C x ...), where B is the batch dimension,... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Implements the label smoothing loss as defined in https://arxiv.org/abs/1512.00567 The API for this loss is modeled after nn..CrossEntropyLoss: 1) The inputs and targets are expected to be (B x C x ...), where B is the batch dimension,... | 0fd556190c95f48e6730e49454e5449bf959671f | <|skeleton|>
class LabelSmoothingLoss:
"""Implements the label smoothing loss as defined in https://arxiv.org/abs/1512.00567 The API for this loss is modeled after nn..CrossEntropyLoss: 1) The inputs and targets are expected to be (B x C x ...), where B is the batch dimension, and C is the number of classes 2) You ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelSmoothingLoss:
"""Implements the label smoothing loss as defined in https://arxiv.org/abs/1512.00567 The API for this loss is modeled after nn..CrossEntropyLoss: 1) The inputs and targets are expected to be (B x C x ...), where B is the batch dimension, and C is the number of classes 2) You can pass in a... | the_stack_v2_python_sparse | model/utils.py | fallcat/rnn_nmt_syntax | train | 0 |
654d59495363afc4673604086c401f17665cdf11 | [
"om.out.debug('Executing: ' + command)\nresponse = apply(self._execMethod, (command,))\nom.out.debug('\"' + command + '\" returned: ' + response)\nreturn response",
"hour = int(hour)\nminute = int(minute)\nif minute == 60:\n minute = 0\n hour = hour + 1\n return self._fixTime(hour, minute, amPm)\nif hour... | <|body_start_0|>
om.out.debug('Executing: ' + command)
response = apply(self._execMethod, (command,))
om.out.debug('"' + command + '" returned: ' + response)
return response
<|end_body_0|>
<|body_start_1|>
hour = int(hour)
minute = int(minute)
if minute == 60:
... | This class is a base class for crontabHandler and atHandler. | delayedExecution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class delayedExecution:
"""This class is a base class for crontabHandler and atHandler."""
def _exec(self, command):
"""A wrapper for executing commands"""
<|body_0|>
def _fixTime(self, hour, minute, amPm=''):
"""Fix the time, this is done to fix if minute == 60, or am... | stack_v2_sparse_classes_36k_train_001407 | 1,827 | no_license | [
{
"docstring": "A wrapper for executing commands",
"name": "_exec",
"signature": "def _exec(self, command)"
},
{
"docstring": "Fix the time, this is done to fix if minute == 60, or ampm changes from am to pm, etc...",
"name": "_fixTime",
"signature": "def _fixTime(self, hour, minute, amP... | 2 | stack_v2_sparse_classes_30k_train_016037 | Implement the Python class `delayedExecution` described below.
Class description:
This class is a base class for crontabHandler and atHandler.
Method signatures and docstrings:
- def _exec(self, command): A wrapper for executing commands
- def _fixTime(self, hour, minute, amPm=''): Fix the time, this is done to fix i... | Implement the Python class `delayedExecution` described below.
Class description:
This class is a base class for crontabHandler and atHandler.
Method signatures and docstrings:
- def _exec(self, command): A wrapper for executing commands
- def _fixTime(self, hour, minute, amPm=''): Fix the time, this is done to fix i... | 651cc08eb50199ce1044c684dbf714ea26df6432 | <|skeleton|>
class delayedExecution:
"""This class is a base class for crontabHandler and atHandler."""
def _exec(self, command):
"""A wrapper for executing commands"""
<|body_0|>
def _fixTime(self, hour, minute, amPm=''):
"""Fix the time, this is done to fix if minute == 60, or am... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class delayedExecution:
"""This class is a base class for crontabHandler and atHandler."""
def _exec(self, command):
"""A wrapper for executing commands"""
om.out.debug('Executing: ' + command)
response = apply(self._execMethod, (command,))
om.out.debug('"' + command + '" return... | the_stack_v2_python_sparse | windows/w3af/w3af/core/controllers/intrusionTools/.svn/text-base/delayedExecution.py.svn-base | sui84/tools | train | 0 |
06f7ccc7f03ecee0c20bda4605795cd2b14c6219 | [
"left, right = (0, len(nums) - 1)\nwhile left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n return mid\n elif nums[left] <= nums[mid]:\n if nums[left] <= target <= nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n elif nums[mid]... | <|body_start_0|>
left, right = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[left] <= nums[mid]:
if nums[left] <= target <= nums[mid]:
right = m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_v2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def search_naive(self, nums, target):
... | stack_v2_sparse_classes_36k_train_001408 | 3,502 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search_v2",
"signature": "def search_v2(self, nums, target)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_v2(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_v2(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_v2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def search_naive(self, nums, target):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
left, right = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[le... | the_stack_v2_python_sparse | src/lt_33.py | oxhead/CodingYourWay | train | 0 | |
a0077cf72e6d5a749cc96501d89d5b388bf594cf | [
"assert batch_size == env.nenvs, 'batch_size should equal number of envs in vec_env'\nself.scheme = scheme\nself.env = env\nself.mac = mac\nself.logger = logger\nself.batch_size = batch_size\nself.max_episode_len = max_episode_len\nself.device = device\nself.t_env = t_env\nself.is_training = is_training\nself.share... | <|body_start_0|>
assert batch_size == env.nenvs, 'batch_size should equal number of envs in vec_env'
self.scheme = scheme
self.env = env
self.mac = mac
self.logger = logger
self.batch_size = batch_size
self.max_episode_len = max_episode_len
self.device = d... | wrap upon vectorized env to collect episdoes (vec env collect steps) | CTDEStepRunner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CTDEStepRunner:
"""wrap upon vectorized env to collect episdoes (vec env collect steps)"""
def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[], ma_step_keys=[], **kwargs):
"""Arguments: - scheme: sampl... | stack_v2_sparse_classes_36k_train_001409 | 17,139 | permissive | [
{
"docstring": "Arguments: - scheme: sample batch specs - env: vectorized (parallelized) env - mac: multiagent controller (e.g. maddpgs) - t_env: total env step so far using runner, used when restoring training",
"name": "__init__",
"signature": "def __init__(self, scheme, env, mac, logger, batch_size, ... | 5 | stack_v2_sparse_classes_30k_test_000825 | Implement the Python class `CTDEStepRunner` described below.
Class description:
wrap upon vectorized env to collect episdoes (vec env collect steps)
Method signatures and docstrings:
- def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[... | Implement the Python class `CTDEStepRunner` described below.
Class description:
wrap upon vectorized env to collect episdoes (vec env collect steps)
Method signatures and docstrings:
- def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[... | eb013bb3bab269bda8a8075e64fe3bcd2964d8ae | <|skeleton|>
class CTDEStepRunner:
"""wrap upon vectorized env to collect episdoes (vec env collect steps)"""
def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[], ma_step_keys=[], **kwargs):
"""Arguments: - scheme: sampl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CTDEStepRunner:
"""wrap upon vectorized env to collect episdoes (vec env collect steps)"""
def __init__(self, scheme, env, mac, logger, batch_size, max_episode_len, device='cpu', t_env=0, is_training=True, shared_step_keys=[], ma_step_keys=[], **kwargs):
"""Arguments: - scheme: sample batch specs... | the_stack_v2_python_sparse | marl/runners/ctde_runner.py | zhangtjtongxue/learn-to-interact | train | 0 |
c5043a4054952153f7f05659bb54bf4cf7821e0e | [
"self.nonpad_ids = None\nself.dim_origin = None\nwith tf.name_scope('pad_reduce/get_ids'):\n pad_mask = tf.reshape(pad_mask, [-1])\n self.nonpad_ids = tf.to_int32(tf.where(pad_mask < 1e-09))\n self.dim_origin = tf.shape(pad_mask)[:1]",
"with tf.name_scope('pad_reduce/remove'):\n x_shape = x.get_shape(... | <|body_start_0|>
self.nonpad_ids = None
self.dim_origin = None
with tf.name_scope('pad_reduce/get_ids'):
pad_mask = tf.reshape(pad_mask, [-1])
self.nonpad_ids = tf.to_int32(tf.where(pad_mask < 1e-09))
self.dim_origin = tf.shape(pad_mask)[:1]
<|end_body_0|>
<|... | Helper to remove padding from a tensor before sending to the experts. The padding is computed for one reference tensor containing the padding mask and then can be applied to any other tensor of shape [dim_origin,...]. Copied from Google's tensor2tensor Ex: input = [ [tok1, tok2], [tok3, tok4], [0, 0], [0, 0], [tok5, to... | PadRemover | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PadRemover:
"""Helper to remove padding from a tensor before sending to the experts. The padding is computed for one reference tensor containing the padding mask and then can be applied to any other tensor of shape [dim_origin,...]. Copied from Google's tensor2tensor Ex: input = [ [tok1, tok2], [... | stack_v2_sparse_classes_36k_train_001410 | 8,227 | permissive | [
{
"docstring": "Compute and store the location of the padding. Args: pad_mask (tf.Tensor): Reference padding tensor of shape [batch_size,length] or [dim_origin] (dim_origin=batch_size*length) containing non-zeros positive values to indicate padding location.",
"name": "__init__",
"signature": "def __ini... | 3 | stack_v2_sparse_classes_30k_train_014000 | Implement the Python class `PadRemover` described below.
Class description:
Helper to remove padding from a tensor before sending to the experts. The padding is computed for one reference tensor containing the padding mask and then can be applied to any other tensor of shape [dim_origin,...]. Copied from Google's tens... | Implement the Python class `PadRemover` described below.
Class description:
Helper to remove padding from a tensor before sending to the experts. The padding is computed for one reference tensor containing the padding mask and then can be applied to any other tensor of shape [dim_origin,...]. Copied from Google's tens... | 01155c740705f1641ebf3134829cea0e212f2d28 | <|skeleton|>
class PadRemover:
"""Helper to remove padding from a tensor before sending to the experts. The padding is computed for one reference tensor containing the padding mask and then can be applied to any other tensor of shape [dim_origin,...]. Copied from Google's tensor2tensor Ex: input = [ [tok1, tok2], [... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PadRemover:
"""Helper to remove padding from a tensor before sending to the experts. The padding is computed for one reference tensor containing the padding mask and then can be applied to any other tensor of shape [dim_origin,...]. Copied from Google's tensor2tensor Ex: input = [ [tok1, tok2], [tok3, tok4], ... | the_stack_v2_python_sparse | njunmt/utils/expert_utils.py | zhaocq-nlp/NJUNMT-tf | train | 114 |
02806d9a36d615e55b815e29d8768da88150e01a | [
"super(BertClassifier, self).__init__()\nD_in, H, D_out = (768, 50, 2)\nself.bert = BertModel.from_pretrained('D:\\\\model_dump\\\\bert-base-uncased')\nself.classifier = nn.Sequential(nn.Linear(D_in, H), nn.ReLU(), nn.Linear(H, D_out))\nif freeze_bert:\n for param in self.bert.parameters():\n param.requir... | <|body_start_0|>
super(BertClassifier, self).__init__()
D_in, H, D_out = (768, 50, 2)
self.bert = BertModel.from_pretrained('D:\\model_dump\\bert-base-uncased')
self.classifier = nn.Sequential(nn.Linear(D_in, H), nn.ReLU(), nn.Linear(H, D_out))
if freeze_bert:
for par... | Bert Model for Classification Tasks. | BertClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertClassifier:
"""Bert Model for Classification Tasks."""
def __init__(self, freeze_bert=False):
"""@param bert: a BertModel object @param classifier: a torch.nn.Module classifier @param freeze_bert (bool): Set `False` to fine-tune the BERT model"""
<|body_0|>
def forwa... | stack_v2_sparse_classes_36k_train_001411 | 22,591 | no_license | [
{
"docstring": "@param bert: a BertModel object @param classifier: a torch.nn.Module classifier @param freeze_bert (bool): Set `False` to fine-tune the BERT model",
"name": "__init__",
"signature": "def __init__(self, freeze_bert=False)"
},
{
"docstring": "Feed input to BERT and the classifier t... | 2 | null | Implement the Python class `BertClassifier` described below.
Class description:
Bert Model for Classification Tasks.
Method signatures and docstrings:
- def __init__(self, freeze_bert=False): @param bert: a BertModel object @param classifier: a torch.nn.Module classifier @param freeze_bert (bool): Set `False` to fine... | Implement the Python class `BertClassifier` described below.
Class description:
Bert Model for Classification Tasks.
Method signatures and docstrings:
- def __init__(self, freeze_bert=False): @param bert: a BertModel object @param classifier: a torch.nn.Module classifier @param freeze_bert (bool): Set `False` to fine... | 8d0700211a2881279df60ab2bea7095ef95ea8dc | <|skeleton|>
class BertClassifier:
"""Bert Model for Classification Tasks."""
def __init__(self, freeze_bert=False):
"""@param bert: a BertModel object @param classifier: a torch.nn.Module classifier @param freeze_bert (bool): Set `False` to fine-tune the BERT model"""
<|body_0|>
def forwa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertClassifier:
"""Bert Model for Classification Tasks."""
def __init__(self, freeze_bert=False):
"""@param bert: a BertModel object @param classifier: a torch.nn.Module classifier @param freeze_bert (bool): Set `False` to fine-tune the BERT model"""
super(BertClassifier, self).__init__()... | the_stack_v2_python_sparse | kaggle/fine_tune_bert_classification_text.py | tarunbhavnani/ml_diaries | train | 0 |
9f38a193da9b57ce8a248613f02fca3f1fa266d1 | [
"result = head\nchange_len = n - m + 1\nnew_head = None\npre_head = None\nfor i in range(1, m):\n pre_head = head\n head = head.next\nmodify_list_tail = head\nwhile change_len > 0 and head != None:\n tmp = head.next\n head.next = new_head\n new_head = head\n head = tmp\n change_len -= 1\nmodify... | <|body_start_0|>
result = head
change_len = n - m + 1
new_head = None
pre_head = None
for i in range(1, m):
pre_head = head
head = head.next
modify_list_tail = head
while change_len > 0 and head != None:
tmp = head.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def next_larger_nodes(self, head):
"""参考链接:https://blog.csdn.net/fuxuemingzhu/article/details/89048785 链表中的下一个更大节点(请注意是下一个更大节点 而不是全部节点中最大... | stack_v2_sparse_classes_36k_train_001412 | 3,746 | no_license | [
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverse_between",
"signature": "def reverse_between(self, head, m, n)"
},
{
"docstring": "参考链接:https://blog.csdn.net/fuxuemingzhu/article/details/89048785 链表中的下一个更大节点(请注意是下一个更大节点 而不是全部节点中最大) 示例1: 输入:[2,1,5... | 2 | stack_v2_sparse_classes_30k_val_000926 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_between(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def next_larger_nodes(self, head): 参考链接:https://blog.csdn.net/fuxuemingzh... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_between(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def next_larger_nodes(self, head): 参考链接:https://blog.csdn.net/fuxuemingzh... | 6479c0ad862a18d1021f35493e5e7d18d1ced5e4 | <|skeleton|>
class Solution:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def next_larger_nodes(self, head):
"""参考链接:https://blog.csdn.net/fuxuemingzhu/article/details/89048785 链表中的下一个更大节点(请注意是下一个更大节点 而不是全部节点中最大... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
result = head
change_len = n - m + 1
new_head = None
pre_head = None
for i in range(1, m):
pre_head = head
head = head.... | the_stack_v2_python_sparse | linkedlist_relate/ReverstListNode.py | Batman001/leetcode_in_python | train | 3 | |
c5a7613b0bb497ee9afaf672fd1ded36f1afebfb | [
"q_cls = type(q)\ncls_path = '%s.%s' % (q_cls.__module__, q_cls.__name__)\nif cls_path.startswith('django.db.models.query_utils'):\n cls_path = cls_path.replace('django.db.models.query_utils', 'django.db.models')\nargs = [serialize_to_signature(_child) for _child in q.children]\nkwargs = {}\nif q.connector != q.... | <|body_start_0|>
q_cls = type(q)
cls_path = '%s.%s' % (q_cls.__module__, q_cls.__name__)
if cls_path.startswith('django.db.models.query_utils'):
cls_path = cls_path.replace('django.db.models.query_utils', 'django.db.models')
args = [serialize_to_signature(_child) for _child i... | Base class for serialization for Q objects. This ensures a consistent representation of :py:class:`django.db.models.Q` objects across all supported versions of Django. Django 1.7 through 3.1 encode the data in a different form than 3.2+. This ensures serialized data in a form closer to 3.2+'s version, while providing c... | QSerialization | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QSerialization:
"""Base class for serialization for Q objects. This ensures a consistent representation of :py:class:`django.db.models.Q` objects across all supported versions of Django. Django 1.7 through 3.1 encode the data in a different form than 3.2+. This ensures serialized data in a form c... | stack_v2_sparse_classes_36k_train_001413 | 30,104 | permissive | [
{
"docstring": "Serialize a Q object to JSON-compatible signature data. Args: value (object or type): The value to serialize. Returns: object: The resulting signature data.",
"name": "serialize_to_signature",
"signature": "def serialize_to_signature(cls, q)"
},
{
"docstring": "Serialize a Q obje... | 3 | stack_v2_sparse_classes_30k_train_002278 | Implement the Python class `QSerialization` described below.
Class description:
Base class for serialization for Q objects. This ensures a consistent representation of :py:class:`django.db.models.Q` objects across all supported versions of Django. Django 1.7 through 3.1 encode the data in a different form than 3.2+. T... | Implement the Python class `QSerialization` described below.
Class description:
Base class for serialization for Q objects. This ensures a consistent representation of :py:class:`django.db.models.Q` objects across all supported versions of Django. Django 1.7 through 3.1 encode the data in a different form than 3.2+. T... | 756eedeacc41f77111a557fc13dee559cb94f433 | <|skeleton|>
class QSerialization:
"""Base class for serialization for Q objects. This ensures a consistent representation of :py:class:`django.db.models.Q` objects across all supported versions of Django. Django 1.7 through 3.1 encode the data in a different form than 3.2+. This ensures serialized data in a form c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QSerialization:
"""Base class for serialization for Q objects. This ensures a consistent representation of :py:class:`django.db.models.Q` objects across all supported versions of Django. Django 1.7 through 3.1 encode the data in a different form than 3.2+. This ensures serialized data in a form closer to 3.2+... | the_stack_v2_python_sparse | django_evolution/serialization.py | beanbaginc/django-evolution | train | 22 |
4f1d065fc3b81cc0925dd017b838eccf86b423f1 | [
"assert whook is not None\nwith open(GitlabIssueCommentWebhook._config_path, 'r') as f:\n configs = json.load(f)\nif os.environ['GITLAB_PRIVATE_TOKEN']:\n configs['PRIVATE-TOKEN'] = os.environ['GITLAB_PRIVATE_TOKEN']\nif os.environ['GITLAB_BASE_URL']:\n configs['base_url'] = os.environ['GITLAB_BASE_URL']\n... | <|body_start_0|>
assert whook is not None
with open(GitlabIssueCommentWebhook._config_path, 'r') as f:
configs = json.load(f)
if os.environ['GITLAB_PRIVATE_TOKEN']:
configs['PRIVATE-TOKEN'] = os.environ['GITLAB_PRIVATE_TOKEN']
if os.environ['GITLAB_BASE_URL']:
... | `GitLabIssueCommentWebhook` implementa `Webhook`. Parse degli eventi di commento di una Issue di Gitlab. | GitlabIssueCommentWebhook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitlabIssueCommentWebhook:
"""`GitLabIssueCommentWebhook` implementa `Webhook`. Parse degli eventi di commento di una Issue di Gitlab."""
def parse(self, whook: dict=None):
"""Parsing del file JSON. Restituisce un riferimento al dizionario ottenuto."""
<|body_0|>
def pro... | stack_v2_sparse_classes_36k_train_001414 | 2,931 | no_license | [
{
"docstring": "Parsing del file JSON. Restituisce un riferimento al dizionario ottenuto.",
"name": "parse",
"signature": "def parse(self, whook: dict=None)"
},
{
"docstring": "Restituisce i nomi delle labels relative al progetto `project_id`.",
"name": "project_labels",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_015589 | Implement the Python class `GitlabIssueCommentWebhook` described below.
Class description:
`GitLabIssueCommentWebhook` implementa `Webhook`. Parse degli eventi di commento di una Issue di Gitlab.
Method signatures and docstrings:
- def parse(self, whook: dict=None): Parsing del file JSON. Restituisce un riferimento a... | Implement the Python class `GitlabIssueCommentWebhook` described below.
Class description:
`GitLabIssueCommentWebhook` implementa `Webhook`. Parse degli eventi di commento di una Issue di Gitlab.
Method signatures and docstrings:
- def parse(self, whook: dict=None): Parsing del file JSON. Restituisce un riferimento a... | 1a23278f386e2b914fb2dbca17f795d0edea78d8 | <|skeleton|>
class GitlabIssueCommentWebhook:
"""`GitLabIssueCommentWebhook` implementa `Webhook`. Parse degli eventi di commento di una Issue di Gitlab."""
def parse(self, whook: dict=None):
"""Parsing del file JSON. Restituisce un riferimento al dizionario ottenuto."""
<|body_0|>
def pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitlabIssueCommentWebhook:
"""`GitLabIssueCommentWebhook` implementa `Webhook`. Parse degli eventi di commento di una Issue di Gitlab."""
def parse(self, whook: dict=None):
"""Parsing del file JSON. Restituisce un riferimento al dizionario ottenuto."""
assert whook is not None
wit... | the_stack_v2_python_sparse | Butterfly/webhook/gitlab/issue_comment_webhook.py | alphasixteam/Butterfly | train | 4 |
d441b85e15392c2057bfe64dde8c30c8d627129b | [
"title = self.data['title']\nslug_es = slugify(title.es)\nslug_en = slugify(title.en)\nquery = Q(slug_es=slug_es) | Q(slug_en=slug_en)\nquery = Category.objects.filter(query)\nif self.instance.id:\n query = query.exclude(id=self.instance.id)\nif query.exists():\n raise forms.ValidationError(INVALID_CATEGORY_N... | <|body_start_0|>
title = self.data['title']
slug_es = slugify(title.es)
slug_en = slugify(title.en)
query = Q(slug_es=slug_es) | Q(slug_en=slug_en)
query = Category.objects.filter(query)
if self.instance.id:
query = query.exclude(id=self.instance.id)
i... | Form to create a category from admin | AdminCreateCategoryForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminCreateCategoryForm:
"""Form to create a category from admin"""
def clean_title(self):
"""Validate title_es"""
<|body_0|>
def clean(self):
"""validate form"""
<|body_1|>
def save(self, commit=True):
"""Save form"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_001415 | 8,911 | no_license | [
{
"docstring": "Validate title_es",
"name": "clean_title",
"signature": "def clean_title(self)"
},
{
"docstring": "validate form",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Save form",
"name": "save",
"signature": "def save(self, commit=True)"
}... | 3 | stack_v2_sparse_classes_30k_val_000952 | Implement the Python class `AdminCreateCategoryForm` described below.
Class description:
Form to create a category from admin
Method signatures and docstrings:
- def clean_title(self): Validate title_es
- def clean(self): validate form
- def save(self, commit=True): Save form | Implement the Python class `AdminCreateCategoryForm` described below.
Class description:
Form to create a category from admin
Method signatures and docstrings:
- def clean_title(self): Validate title_es
- def clean(self): validate form
- def save(self, commit=True): Save form
<|skeleton|>
class AdminCreateCategoryFo... | 4dc6362ef624eb6591aad9d5c7de95eee40a01c9 | <|skeleton|>
class AdminCreateCategoryForm:
"""Form to create a category from admin"""
def clean_title(self):
"""Validate title_es"""
<|body_0|>
def clean(self):
"""validate form"""
<|body_1|>
def save(self, commit=True):
"""Save form"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminCreateCategoryForm:
"""Form to create a category from admin"""
def clean_title(self):
"""Validate title_es"""
title = self.data['title']
slug_es = slugify(title.es)
slug_en = slugify(title.en)
query = Q(slug_es=slug_es) | Q(slug_en=slug_en)
query = Cat... | the_stack_v2_python_sparse | app/offers/forms.py | arielMilan1899/orbita-api | train | 0 |
d6cc04cfd1a720cded40aa0fb43324f109df4860 | [
"date_time_sent = datetime.datetime.utcnow()\nresponse = self.request('GET', method='v2/sports', session=session)\nreturn self.process_response(response.json().get('sports', []), resources.SportsDetails, date_time_sent, datetime.datetime.utcnow())",
"date_time_sent = datetime.datetime.utcnow()\nresponse = self.re... | <|body_start_0|>
date_time_sent = datetime.datetime.utcnow()
response = self.request('GET', method='v2/sports', session=session)
return self.process_response(response.json().get('sports', []), resources.SportsDetails, date_time_sent, datetime.datetime.utcnow())
<|end_body_0|>
<|body_start_1|>
... | ReferenceData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReferenceData:
def get_sports(self, session=None):
"""Get all sports. :param session: requests session to be used. :return: list of sports."""
<|body_0|>
def get_currencies(self, session=None):
"""Get currencies accepted. :param session: requests session to be used. ... | stack_v2_sparse_classes_36k_train_001416 | 2,441 | permissive | [
{
"docstring": "Get all sports. :param session: requests session to be used. :return: list of sports.",
"name": "get_sports",
"signature": "def get_sports(self, session=None)"
},
{
"docstring": "Get currencies accepted. :param session: requests session to be used. :return: supported currencies."... | 4 | stack_v2_sparse_classes_30k_train_015747 | Implement the Python class `ReferenceData` described below.
Class description:
Implement the ReferenceData class.
Method signatures and docstrings:
- def get_sports(self, session=None): Get all sports. :param session: requests session to be used. :return: list of sports.
- def get_currencies(self, session=None): Get ... | Implement the Python class `ReferenceData` described below.
Class description:
Implement the ReferenceData class.
Method signatures and docstrings:
- def get_sports(self, session=None): Get all sports. :param session: requests session to be used. :return: list of sports.
- def get_currencies(self, session=None): Get ... | dd0937855293010b1fe943ccc2d9f4ebb874b492 | <|skeleton|>
class ReferenceData:
def get_sports(self, session=None):
"""Get all sports. :param session: requests session to be used. :return: list of sports."""
<|body_0|>
def get_currencies(self, session=None):
"""Get currencies accepted. :param session: requests session to be used. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReferenceData:
def get_sports(self, session=None):
"""Get all sports. :param session: requests session to be used. :return: list of sports."""
date_time_sent = datetime.datetime.utcnow()
response = self.request('GET', method='v2/sports', session=session)
return self.process_res... | the_stack_v2_python_sparse | pinnacle/endpoints/referencedata.py | rozzac90/pinnacle | train | 59 | |
b163ea53046504bb96e12c60959c739e8202bd58 | [
"super().__init__(model)\nself.stage_list = ['step'] if not stage_list else stage_list\nself.shuffle = shuffle\nself.shuffle_between_stages = shuffle_between_stages\nself.stage_time = 1 / len(self.stage_list)\nself.seed = seed\nprint('Randomseed: ', self.seed)",
"agent_keys = list(self._agents.keys())\nif self.sh... | <|body_start_0|>
super().__init__(model)
self.stage_list = ['step'] if not stage_list else stage_list
self.shuffle = shuffle
self.shuffle_between_stages = shuffle_between_stages
self.stage_time = 1 / len(self.stage_list)
self.seed = seed
print('Randomseed: ', self... | A scheduler which allows agent activation to be divided into several stages instead of a single `step` method. All agents execute one stage before moving on to the next. Agents must have all the stage methods implemented. Stage methods take a model object as their only argument. This schedule tracks steps and time sepa... | StagedActivation_random | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StagedActivation_random:
"""A scheduler which allows agent activation to be divided into several stages instead of a single `step` method. All agents execute one stage before moving on to the next. Agents must have all the stage methods implemented. Stage methods take a model object as their only... | stack_v2_sparse_classes_36k_train_001417 | 2,251 | no_license | [
{
"docstring": "Create an empty Staged Activation schedule. Args: model: Model object associated with the schedule. stage_list: List of strings of names of stages to run, in the order to run them in. shuffle: If True, shuffle the order of agents each step. shuffle_between_stages: If True, shuffle the agents aft... | 2 | stack_v2_sparse_classes_30k_train_008785 | Implement the Python class `StagedActivation_random` described below.
Class description:
A scheduler which allows agent activation to be divided into several stages instead of a single `step` method. All agents execute one stage before moving on to the next. Agents must have all the stage methods implemented. Stage me... | Implement the Python class `StagedActivation_random` described below.
Class description:
A scheduler which allows agent activation to be divided into several stages instead of a single `step` method. All agents execute one stage before moving on to the next. Agents must have all the stage methods implemented. Stage me... | eb43bdae509fbf100fd1a8499bddb212a3c23613 | <|skeleton|>
class StagedActivation_random:
"""A scheduler which allows agent activation to be divided into several stages instead of a single `step` method. All agents execute one stage before moving on to the next. Agents must have all the stage methods implemented. Stage methods take a model object as their only... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StagedActivation_random:
"""A scheduler which allows agent activation to be divided into several stages instead of a single `step` method. All agents execute one stage before moving on to the next. Agents must have all the stage methods implemented. Stage methods take a model object as their only argument. Th... | the_stack_v2_python_sparse | Codes/Scheduler_StagedActivation_Random.py | prakharmehta95/master_thesis | train | 1 |
654ca8b7292df6eb880b4b68a6a5b0db3564bc39 | [
"super().__init__()\nself.view = View()\nself.publishers = {}\nself.subscribers = {}\nself.view.publishers.itemDoubleClicked.connect(self.register)\nself.view.subscribers.itemClicked.connect(self.update_feed)\nself.view.send_button.clicked.connect(self.send)\nself.view.update_button.clicked.connect(self.update)\np1... | <|body_start_0|>
super().__init__()
self.view = View()
self.publishers = {}
self.subscribers = {}
self.view.publishers.itemDoubleClicked.connect(self.register)
self.view.subscribers.itemClicked.connect(self.update_feed)
self.view.send_button.clicked.connect(self.s... | Control | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Control:
def __init__(self):
"""The GUI's control unit used to update data and process user input"""
<|body_0|>
def update(self):
"""Updates listed publishers, newspapers and subscribers"""
<|body_1|>
def update_feed(self, item, column):
"""Updat... | stack_v2_sparse_classes_36k_train_001418 | 3,768 | no_license | [
{
"docstring": "The GUI's control unit used to update data and process user input",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Updates listed publishers, newspapers and subscribers",
"name": "update",
"signature": "def update(self)"
},
{
"docstring":... | 5 | stack_v2_sparse_classes_30k_train_005049 | Implement the Python class `Control` described below.
Class description:
Implement the Control class.
Method signatures and docstrings:
- def __init__(self): The GUI's control unit used to update data and process user input
- def update(self): Updates listed publishers, newspapers and subscribers
- def update_feed(se... | Implement the Python class `Control` described below.
Class description:
Implement the Control class.
Method signatures and docstrings:
- def __init__(self): The GUI's control unit used to update data and process user input
- def update(self): Updates listed publishers, newspapers and subscribers
- def update_feed(se... | 113cee20f8ac8c94b7cd7ffa2bb6e2c0b1478412 | <|skeleton|>
class Control:
def __init__(self):
"""The GUI's control unit used to update data and process user input"""
<|body_0|>
def update(self):
"""Updates listed publishers, newspapers and subscribers"""
<|body_1|>
def update_feed(self, item, column):
"""Updat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Control:
def __init__(self):
"""The GUI's control unit used to update data and process user input"""
super().__init__()
self.view = View()
self.publishers = {}
self.subscribers = {}
self.view.publishers.itemDoubleClicked.connect(self.register)
self.view.... | the_stack_v2_python_sparse | 13-observer/control/control.py | mreichl-tgm/sew-4 | train | 0 | |
c085289f31151cb3b8ae782250141b9d4c00732e | [
"context = super().get_context_data(**kwargs)\norderby = self.request.GET.get('sort', 'id') or 'id'\nmatch = self.request.GET.get('match', '')\ncontext['attachments'] = attachment_helpers.get_study_attachments(context['study'], orderby, match)\ncontext['match'] = match\nreturn context",
"attachment = self.request... | <|body_start_0|>
context = super().get_context_data(**kwargs)
orderby = self.request.GET.get('sort', 'id') or 'id'
match = self.request.GET.get('match', '')
context['attachments'] = attachment_helpers.get_study_attachments(context['study'], orderby, match)
context['match'] = matc... | StudyAttachments View shows video attachments for the study | StudyAttachments | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudyAttachments:
"""StudyAttachments View shows video attachments for the study"""
def get_context_data(self, **kwargs):
"""In addition to the study, adds several items to the context dictionary. Study results are paginated."""
<|body_0|>
def post(self, request, *args, ... | stack_v2_sparse_classes_36k_train_001419 | 34,217 | permissive | [
{
"docstring": "In addition to the study, adds several items to the context dictionary. Study results are paginated.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Downloads study video",
"name": "post",
"signature": "def post(self, r... | 2 | stack_v2_sparse_classes_30k_train_005961 | Implement the Python class `StudyAttachments` described below.
Class description:
StudyAttachments View shows video attachments for the study
Method signatures and docstrings:
- def get_context_data(self, **kwargs): In addition to the study, adds several items to the context dictionary. Study results are paginated.
-... | Implement the Python class `StudyAttachments` described below.
Class description:
StudyAttachments View shows video attachments for the study
Method signatures and docstrings:
- def get_context_data(self, **kwargs): In addition to the study, adds several items to the context dictionary. Study results are paginated.
-... | 621fbb8b25100a21fd94721d39003b5d4f651dc5 | <|skeleton|>
class StudyAttachments:
"""StudyAttachments View shows video attachments for the study"""
def get_context_data(self, **kwargs):
"""In addition to the study, adds several items to the context dictionary. Study results are paginated."""
<|body_0|>
def post(self, request, *args, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudyAttachments:
"""StudyAttachments View shows video attachments for the study"""
def get_context_data(self, **kwargs):
"""In addition to the study, adds several items to the context dictionary. Study results are paginated."""
context = super().get_context_data(**kwargs)
orderby... | the_stack_v2_python_sparse | exp/views/study.py | enrobyn/lookit-api | train | 0 |
74b423b93468700106c28655b932f7d45879815a | [
"super(NotInPath, self).__init__()\nself.executable = executable\nself.env = env",
"if self.env:\n path_env = self.env.get('PATH')\nelse:\n path_env = os.environ['PATH']\nreturn 'Could not find executable: %s\\nLooked in:\\n%s' % (self.executable, '\\n'.join(path_env.split(os.pathsep)))"
] | <|body_start_0|>
super(NotInPath, self).__init__()
self.executable = executable
self.env = env
<|end_body_0|>
<|body_start_1|>
if self.env:
path_env = self.env.get('PATH')
else:
path_env = os.environ['PATH']
return 'Could not find executable: %s\n... | Custom exception | NotInPath | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotInPath:
"""Custom exception"""
def __init__(self, executable, env=None):
"""NotInPath Init"""
<|body_0|>
def __str__(self):
"""NotInPath String Representation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(NotInPath, self).__init__()
... | stack_v2_sparse_classes_36k_train_001420 | 22,214 | permissive | [
{
"docstring": "NotInPath Init",
"name": "__init__",
"signature": "def __init__(self, executable, env=None)"
},
{
"docstring": "NotInPath String Representation",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `NotInPath` described below.
Class description:
Custom exception
Method signatures and docstrings:
- def __init__(self, executable, env=None): NotInPath Init
- def __str__(self): NotInPath String Representation | Implement the Python class `NotInPath` described below.
Class description:
Custom exception
Method signatures and docstrings:
- def __init__(self, executable, env=None): NotInPath Init
- def __str__(self): NotInPath String Representation
<|skeleton|>
class NotInPath:
"""Custom exception"""
def __init__(self... | efea6fa3744664348717fe5e8df708a3cf392072 | <|skeleton|>
class NotInPath:
"""Custom exception"""
def __init__(self, executable, env=None):
"""NotInPath Init"""
<|body_0|>
def __str__(self):
"""NotInPath String Representation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotInPath:
"""Custom exception"""
def __init__(self, executable, env=None):
"""NotInPath Init"""
super(NotInPath, self).__init__()
self.executable = executable
self.env = env
def __str__(self):
"""NotInPath String Representation"""
if self.env:
... | the_stack_v2_python_sparse | python/qisys/command.py | aldebaran/qibuild | train | 60 |
3a14b7b64950bd89462777f665ec6f1c54246d8f | [
"self.microseconds = microseconds\nself.milliseconds = milliseconds\nself.seconds = seconds",
"wrapped: Callable = wrapped_args[0]\nargs: list = wrapped_args[2] if len(wrapped_args) > 1 else []\nkwargs: dict = wrapped_args[3] if len(wrapped_args) > 2 else {}\n\ndef benchmark() -> Any:\n \"\"\"Iterate over data... | <|body_start_0|>
self.microseconds = microseconds
self.milliseconds = milliseconds
self.seconds = seconds
<|end_body_0|>
<|body_start_1|>
wrapped: Callable = wrapped_args[0]
args: list = wrapped_args[2] if len(wrapped_args) > 1 else []
kwargs: dict = wrapped_args[3] if l... | Log benchmarking times. This decorator will log the time of execution (benchmark_time) to the app.log file. It can be helpful in troubleshooting performance issues with Apps. .. code-block:: python :linenos: :lineno-start: 1 import time @Benchmark() def my_method(): time.sleep(1) | Benchmark | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Benchmark:
"""Log benchmarking times. This decorator will log the time of execution (benchmark_time) to the app.log file. It can be helpful in troubleshooting performance issues with Apps. .. code-block:: python :linenos: :lineno-start: 1 import time @Benchmark() def my_method(): time.sleep(1)"""... | stack_v2_sparse_classes_36k_train_001421 | 2,777 | permissive | [
{
"docstring": "Initialize instance properties.",
"name": "__init__",
"signature": "def __init__(self, microseconds: int=0, milliseconds: int=0, seconds: int=0)"
},
{
"docstring": "Implement __call__ function for decorator. Args: wrapped (callable): The wrapped function which in turns needs to b... | 2 | null | Implement the Python class `Benchmark` described below.
Class description:
Log benchmarking times. This decorator will log the time of execution (benchmark_time) to the app.log file. It can be helpful in troubleshooting performance issues with Apps. .. code-block:: python :linenos: :lineno-start: 1 import time @Benchm... | Implement the Python class `Benchmark` described below.
Class description:
Log benchmarking times. This decorator will log the time of execution (benchmark_time) to the app.log file. It can be helpful in troubleshooting performance issues with Apps. .. code-block:: python :linenos: :lineno-start: 1 import time @Benchm... | 30dc147e40d63d1082ec2a5e6c62005b60c29c37 | <|skeleton|>
class Benchmark:
"""Log benchmarking times. This decorator will log the time of execution (benchmark_time) to the app.log file. It can be helpful in troubleshooting performance issues with Apps. .. code-block:: python :linenos: :lineno-start: 1 import time @Benchmark() def my_method(): time.sleep(1)"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Benchmark:
"""Log benchmarking times. This decorator will log the time of execution (benchmark_time) to the app.log file. It can be helpful in troubleshooting performance issues with Apps. .. code-block:: python :linenos: :lineno-start: 1 import time @Benchmark() def my_method(): time.sleep(1)"""
def __i... | the_stack_v2_python_sparse | tcex/app/decorator/benchmark.py | ThreatConnect-Inc/tcex | train | 24 |
2c2d23dbc363fbf9b88234c804f42a54f9f2f758 | [
"super().__init__(label=label, required=None, description=description, hidden=hidden)\nself.disabled = disabled\nself.collapsed = collapsed\nself.field_group = field_group\nself.fields = collections.OrderedDict()",
"for field_name in self.field_group.__dict__:\n if field_name.startswith('_'):\n continue... | <|body_start_0|>
super().__init__(label=label, required=None, description=description, hidden=hidden)
self.disabled = disabled
self.collapsed = collapsed
self.field_group = field_group
self.fields = collections.OrderedDict()
<|end_body_0|>
<|body_start_1|>
for field_name... | Group field. | GroupField | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupField:
"""Group field."""
def __init__(self, field_group, label=None, description=None, disabled=False, collapsed=False, hidden=False):
"""Construct a group field."""
<|body_0|>
def contribute_to_class(self, process, fields, name):
"""Register this field wit... | stack_v2_sparse_classes_36k_train_001422 | 26,687 | permissive | [
{
"docstring": "Construct a group field.",
"name": "__init__",
"signature": "def __init__(self, field_group, label=None, description=None, disabled=False, collapsed=False, hidden=False)"
},
{
"docstring": "Register this field with a specific process. :param process: Process descriptor instance :... | 4 | stack_v2_sparse_classes_30k_train_016835 | Implement the Python class `GroupField` described below.
Class description:
Group field.
Method signatures and docstrings:
- def __init__(self, field_group, label=None, description=None, disabled=False, collapsed=False, hidden=False): Construct a group field.
- def contribute_to_class(self, process, fields, name): Re... | Implement the Python class `GroupField` described below.
Class description:
Group field.
Method signatures and docstrings:
- def __init__(self, field_group, label=None, description=None, disabled=False, collapsed=False, hidden=False): Construct a group field.
- def contribute_to_class(self, process, fields, name): Re... | d64cd9bc7d77b383771a54e01b5db136abb23767 | <|skeleton|>
class GroupField:
"""Group field."""
def __init__(self, field_group, label=None, description=None, disabled=False, collapsed=False, hidden=False):
"""Construct a group field."""
<|body_0|>
def contribute_to_class(self, process, fields, name):
"""Register this field wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupField:
"""Group field."""
def __init__(self, field_group, label=None, description=None, disabled=False, collapsed=False, hidden=False):
"""Construct a group field."""
super().__init__(label=label, required=None, description=description, hidden=hidden)
self.disabled = disabled... | the_stack_v2_python_sparse | resolwe/process/fields.py | dblenkus/resolwe | train | 0 |
b08b46c13fd325feaf690c387eb089501cfa4deb | [
"answer = list(list())\nif root is None:\n return answer\nself.__traverse(root, answer, 1)\nanswer.reverse()\nreturn answer",
"if node is None:\n return\nif len(answer) < level:\n answer.append(list())\nanswer[level - 1].append(node.val)\nself.__traverse(node.left, answer, level + 1)\nself.__traverse(nod... | <|body_start_0|>
answer = list(list())
if root is None:
return answer
self.__traverse(root, answer, 1)
answer.reverse()
return answer
<|end_body_0|>
<|body_start_1|>
if node is None:
return
if len(answer) < level:
answer.append... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def __traverse(self, node, answer, level):
""":type node: TreeNode :answer: List[List[int]] :level: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_001423 | 1,375 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root)"
},
{
"docstring": ":type node: TreeNode :answer: List[List[int]] :level: int",
"name": "__traverse",
"signature": "def __traverse(self, node, answer,... | 2 | stack_v2_sparse_classes_30k_train_012979 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def __traverse(self, node, answer, level): :type node: TreeNode :answer: List[List[int]] :level: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def __traverse(self, node, answer, level): :type node: TreeNode :answer: List[List[int]] :level: ... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def __traverse(self, node, answer, level):
""":type node: TreeNode :answer: List[List[int]] :level: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
answer = list(list())
if root is None:
return answer
self.__traverse(root, answer, 1)
answer.reverse()
return answer
def __traverse(self, node, answer... | the_stack_v2_python_sparse | leetcode/easy/tree/test_binary_tree_level_order_traversal_ii.py | yenbohuang/online-contest-python | train | 0 | |
407f7e340e34e3feab268415aa994da77b126346 | [
"if children is None:\n children = []\nself.parent = parent\nself.children = children\nself.label = label\nself.number_of_descendants = 1",
"n = 1\nfor child in self.children:\n n += child.compute_number_of_descendants()\nself.number_of_descendants = n\nreturn n",
"if self.parent is None:\n self.depth ... | <|body_start_0|>
if children is None:
children = []
self.parent = parent
self.children = children
self.label = label
self.number_of_descendants = 1
<|end_body_0|>
<|body_start_1|>
n = 1
for child in self.children:
n += child.compute_number... | A class to represent each node in the trees used by _realizer() and _compute_coordinates() when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: parent -- the parent TreeNode of self children -- a list of TreeNode children of self label -- the associat... | TreeNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeNode:
"""A class to represent each node in the trees used by _realizer() and _compute_coordinates() when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: parent -- the parent TreeNode of self children -- a list of TreeNode ch... | stack_v2_sparse_classes_36k_train_001424 | 23,641 | no_license | [
{
"docstring": "INPUT: parent -- the parent TreeNode of self children -- a list of TreeNode children of self label -- the associated realizer vertex label EXAMPLE:: sage: from sage.graphs.schnyder import TreeNode sage: tn = TreeNode(label=5) sage: tn2 = TreeNode(label=2,parent=tn) sage: tn3 = TreeNode(label=3) ... | 4 | stack_v2_sparse_classes_30k_train_018397 | Implement the Python class `TreeNode` described below.
Class description:
A class to represent each node in the trees used by _realizer() and _compute_coordinates() when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: parent -- the parent TreeNode of... | Implement the Python class `TreeNode` described below.
Class description:
A class to represent each node in the trees used by _realizer() and _compute_coordinates() when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: parent -- the parent TreeNode of... | fd0c7c46e6a2da4b84df582e0da0333ce5cf79d9 | <|skeleton|>
class TreeNode:
"""A class to represent each node in the trees used by _realizer() and _compute_coordinates() when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: parent -- the parent TreeNode of self children -- a list of TreeNode ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeNode:
"""A class to represent each node in the trees used by _realizer() and _compute_coordinates() when finding a planar geometric embedding in the grid. Each tree node is doubly linked to its parent and children. INPUT: parent -- the parent TreeNode of self children -- a list of TreeNode children of sel... | the_stack_v2_python_sparse | sage/graphs/schnyder.py | thalespaiva/sagelib | train | 0 |
3bd5a9110174a406b2fb8a158292e2238a175b5f | [
"if not root:\n return\ncurrentLevel, nextLevel = (collections.deque([root]), collections.deque())\nwhile currentLevel:\n node = currentLevel.popleft()\n if node.left:\n nextLevel.append(node.left)\n if node.right:\n nextLevel.append(node.right)\n node.next = currentLevel[0] if currentL... | <|body_start_0|>
if not root:
return
currentLevel, nextLevel = (collections.deque([root]), collections.deque())
while currentLevel:
node = currentLevel.popleft()
if node.left:
nextLevel.append(node.left)
if node.right:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
"""BFS :param root: :return:"""
<|body_0|>
def connect2(self, root):
"""把上面的bfs转换为常数空间 :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return
currentLevel, nex... | stack_v2_sparse_classes_36k_train_001425 | 3,639 | permissive | [
{
"docstring": "BFS :param root: :return:",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": "把上面的bfs转换为常数空间 :param root: :return:",
"name": "connect2",
"signature": "def connect2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000824 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): BFS :param root: :return:
- def connect2(self, root): 把上面的bfs转换为常数空间 :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): BFS :param root: :return:
- def connect2(self, root): 把上面的bfs转换为常数空间 :param root: :return:
<|skeleton|>
class Solution:
def connect(self, root):
... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def connect(self, root):
"""BFS :param root: :return:"""
<|body_0|>
def connect2(self, root):
"""把上面的bfs转换为常数空间 :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root):
"""BFS :param root: :return:"""
if not root:
return
currentLevel, nextLevel = (collections.deque([root]), collections.deque())
while currentLevel:
node = currentLevel.popleft()
if node.left:
... | the_stack_v2_python_sparse | leetcode/hard/Populating_Next_Right_Pointers_in_Each_Node_II.py | shhuan/algorithms | train | 0 | |
b9c8a83ad800a6f7a063fe3d30703d001d93febb | [
"if not rooms or not rooms[0]:\n return\nm, n = (len(rooms), len(rooms[0]))\nbfs = [(i, j, 0) for i in range(m) for j in range(n) if rooms[i][j] == 0]\ndirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\nfor i, j, step in bfs:\n step += 1\n for dir in dirs:\n cur_i = i + dir[0]\n cur_j = j + dir[1]\n ... | <|body_start_0|>
if not rooms or not rooms[0]:
return
m, n = (len(rooms), len(rooms[0]))
bfs = [(i, j, 0) for i in range(m) for j in range(n) if rooms[i][j] == 0]
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i, j, step in bfs:
step += 1
for di... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wallsAndGates1(self, rooms: 'List[List[int]]') -> None:
"""Do not return anything, modify rooms in-place instead."""
<|body_0|>
def wallsAndGates(self, rooms: 'List[List[int]]') -> None:
"""Do not return anything, modify rooms in-place instead."""
... | stack_v2_sparse_classes_36k_train_001426 | 2,498 | no_license | [
{
"docstring": "Do not return anything, modify rooms in-place instead.",
"name": "wallsAndGates1",
"signature": "def wallsAndGates1(self, rooms: 'List[List[int]]') -> None"
},
{
"docstring": "Do not return anything, modify rooms in-place instead.",
"name": "wallsAndGates",
"signature": "... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wallsAndGates1(self, rooms: 'List[List[int]]') -> None: Do not return anything, modify rooms in-place instead.
- def wallsAndGates(self, rooms: 'List[List[int]]') -> None: Do... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wallsAndGates1(self, rooms: 'List[List[int]]') -> None: Do not return anything, modify rooms in-place instead.
- def wallsAndGates(self, rooms: 'List[List[int]]') -> None: Do... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def wallsAndGates1(self, rooms: 'List[List[int]]') -> None:
"""Do not return anything, modify rooms in-place instead."""
<|body_0|>
def wallsAndGates(self, rooms: 'List[List[int]]') -> None:
"""Do not return anything, modify rooms in-place instead."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wallsAndGates1(self, rooms: 'List[List[int]]') -> None:
"""Do not return anything, modify rooms in-place instead."""
if not rooms or not rooms[0]:
return
m, n = (len(rooms), len(rooms[0]))
bfs = [(i, j, 0) for i in range(m) for j in range(n) if rooms[i... | the_stack_v2_python_sparse | BFS/q286_walls_and_gates.py | sevenhe716/LeetCode | train | 0 | |
1d06438614b389af2d22afa85cd98c1c963b3cdc | [
"l = len(s)\nif l == 0:\n return ' '\nif l == 1:\n return s[0]\ntmp_list = [0] * l\nfor i in range(l):\n for j in range(i + 1, l):\n if s[j] == 1:\n continue\n elif s[i] == s[j]:\n tmp_list[j] = 1\n tmp_list[i] = 1\n if tmp_list[i] == 0:\n return s[i... | <|body_start_0|>
l = len(s)
if l == 0:
return ' '
if l == 1:
return s[0]
tmp_list = [0] * l
for i in range(l):
for j in range(i + 1, l):
if s[j] == 1:
continue
elif s[i] == s[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar(self, s: str) -> str:
"""list记录重复 T(n^2); S(n) 超时 :param s: :return:"""
<|body_0|>
def firstUniqChar(self, s: str) -> str:
"""hashmap T(n); S(n) 遍历s, 如果没有找到当前ele, ele: true else false 再遍历一次s, 找true的ele :param s: :return:"""
<|body_... | stack_v2_sparse_classes_36k_train_001427 | 1,419 | no_license | [
{
"docstring": "list记录重复 T(n^2); S(n) 超时 :param s: :return:",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s: str) -> str"
},
{
"docstring": "hashmap T(n); S(n) 遍历s, 如果没有找到当前ele, ele: true else false 再遍历一次s, 找true的ele :param s: :return:",
"name": "firstUniqChar",
"signa... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s: str) -> str: list记录重复 T(n^2); S(n) 超时 :param s: :return:
- def firstUniqChar(self, s: str) -> str: hashmap T(n); S(n) 遍历s, 如果没有找到当前ele, ele: true else ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s: str) -> str: list记录重复 T(n^2); S(n) 超时 :param s: :return:
- def firstUniqChar(self, s: str) -> str: hashmap T(n); S(n) 遍历s, 如果没有找到当前ele, ele: true else ... | b1680014ce3f55ba952a1e64241c0cbb783cc436 | <|skeleton|>
class Solution:
def firstUniqChar(self, s: str) -> str:
"""list记录重复 T(n^2); S(n) 超时 :param s: :return:"""
<|body_0|>
def firstUniqChar(self, s: str) -> str:
"""hashmap T(n); S(n) 遍历s, 如果没有找到当前ele, ele: true else false 再遍历一次s, 找true的ele :param s: :return:"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstUniqChar(self, s: str) -> str:
"""list记录重复 T(n^2); S(n) 超时 :param s: :return:"""
l = len(s)
if l == 0:
return ' '
if l == 1:
return s[0]
tmp_list = [0] * l
for i in range(l):
for j in range(i + 1, l):
... | the_stack_v2_python_sparse | 50.py | sun510001/leetcode_jianzhi_offer_2 | train | 0 | |
96c54229ca98b5cdf74595c1afee28c81b06d39e | [
"qt.QListViewItem.__init__(self, parent)\nself.settings = settings\nself.parent = parent\nself.widget = None\nself.setText(0, settings.name)\nself.setText(1, 'setting')\nself.index = number",
"a = [-1, 1][ascending]\nif self.index < i.index:\n return -1 * a\nelif self.index > i.index:\n return 1 * a\nelse:\... | <|body_start_0|>
qt.QListViewItem.__init__(self, parent)
self.settings = settings
self.parent = parent
self.widget = None
self.setText(0, settings.name)
self.setText(1, 'setting')
self.index = number
<|end_body_0|>
<|body_start_1|>
a = [-1, 1][ascending]
... | Item for displaying a preferences-set in HostsBrowser. | PropertyItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyItem:
"""Item for displaying a preferences-set in HostsBrowser."""
def __init__(self, settings, number, parent):
"""_plugin_settings is the _plugin_settings class to work for parent is the parent ListViewItem (of type ModelObjectListViewItem)"""
<|body_0|>
def co... | stack_v2_sparse_classes_36k_train_001428 | 37,136 | no_license | [
{
"docstring": "_plugin_settings is the _plugin_settings class to work for parent is the parent ListViewItem (of type ModelObjectListViewItem)",
"name": "__init__",
"signature": "def __init__(self, settings, number, parent)"
},
{
"docstring": "Always sort according to the index value.",
"nam... | 2 | null | Implement the Python class `PropertyItem` described below.
Class description:
Item for displaying a preferences-set in HostsBrowser.
Method signatures and docstrings:
- def __init__(self, settings, number, parent): _plugin_settings is the _plugin_settings class to work for parent is the parent ListViewItem (of type M... | Implement the Python class `PropertyItem` described below.
Class description:
Item for displaying a preferences-set in HostsBrowser.
Method signatures and docstrings:
- def __init__(self, settings, number, parent): _plugin_settings is the _plugin_settings class to work for parent is the parent ListViewItem (of type M... | 0cae558d7e22a7911597525a8255391208e035be | <|skeleton|>
class PropertyItem:
"""Item for displaying a preferences-set in HostsBrowser."""
def __init__(self, settings, number, parent):
"""_plugin_settings is the _plugin_settings class to work for parent is the parent ListViewItem (of type ModelObjectListViewItem)"""
<|body_0|>
def co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertyItem:
"""Item for displaying a preferences-set in HostsBrowser."""
def __init__(self, settings, number, parent):
"""_plugin_settings is the _plugin_settings class to work for parent is the parent ListViewItem (of type ModelObjectListViewItem)"""
qt.QListViewItem.__init__(self, par... | the_stack_v2_python_sparse | gui/qt3/hostsbrowser.py | jeffhsta/faraday | train | 1 |
4d999acdc0771ed4a7c0179cae436ba22f8dbeab | [
"self._video_path = video_path\nself._all_frames = []\nself._annotations = []",
"ann_frame = self._annotations[annotation_index]\nframe_num = ann_frame._frame_num\nbbox = ann_frame._bbox\nimage_files = self._all_frames\nassert len(image_files) > 0\nassert frame_num < len(image_files)\nimage = load(image_files[fra... | <|body_start_0|>
self._video_path = video_path
self._all_frames = []
self._annotations = []
<|end_body_0|>
<|body_start_1|>
ann_frame = self._annotations[annotation_index]
frame_num = ann_frame._frame_num
bbox = ann_frame._bbox
image_files = self._all_frames
... | Docstring for video. | video | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class video:
"""Docstring for video."""
def __init__(self, video_path):
"""@video_path: video path"""
<|body_0|>
def load_annotation(self, annotation_index):
"""load annotation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._video_path = video_p... | stack_v2_sparse_classes_36k_train_001429 | 1,551 | permissive | [
{
"docstring": "@video_path: video path",
"name": "__init__",
"signature": "def __init__(self, video_path)"
},
{
"docstring": "load annotation",
"name": "load_annotation",
"signature": "def load_annotation(self, annotation_index)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016291 | Implement the Python class `video` described below.
Class description:
Docstring for video.
Method signatures and docstrings:
- def __init__(self, video_path): @video_path: video path
- def load_annotation(self, annotation_index): load annotation | Implement the Python class `video` described below.
Class description:
Docstring for video.
Method signatures and docstrings:
- def __init__(self, video_path): @video_path: video path
- def load_annotation(self, annotation_index): load annotation
<|skeleton|>
class video:
"""Docstring for video."""
def __in... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class video:
"""Docstring for video."""
def __init__(self, video_path):
"""@video_path: video path"""
<|body_0|>
def load_annotation(self, annotation_index):
"""load annotation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class video:
"""Docstring for video."""
def __init__(self, video_path):
"""@video_path: video path"""
self._video_path = video_path
self._all_frames = []
self._annotations = []
def load_annotation(self, annotation_index):
"""load annotation"""
ann_frame = se... | the_stack_v2_python_sparse | PyTorch/built-in/cv/object_tracking/GOTURN_for_PyTorch/src/goturn/helper/video.py | Ascend/ModelZoo-PyTorch | train | 23 |
455aed008647ca2024e5a503326539191fd8a174 | [
"words.sort()\nvisited, ans = (set(), '')\nfor word in words:\n if len(word) == 1 or word[:-1] in visited:\n visited.add(word)\n if len(ans) < len(word):\n ans = word\nreturn ans",
"trie = Trie()\nfor word in words:\n trie.insert(word)\nreturn trie.longest1()"
] | <|body_start_0|>
words.sort()
visited, ans = (set(), '')
for word in words:
if len(word) == 1 or word[:-1] in visited:
visited.add(word)
if len(ans) < len(word):
ans = word
return ans
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestWord1(self, words):
""":type words: List[str] :rtype: str 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的"""
<|body_0|>
def longestWord(self, words):
""":type words: List[str] :rtype: str 解法2: 字典树 使用两种不同的遍历方式"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_001430 | 4,133 | no_license | [
{
"docstring": ":type words: List[str] :rtype: str 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的",
"name": "longestWord1",
"signature": "def longestWord1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: str 解法2: 字典树 使用两种不同的遍历方式",
"name": "longestWord",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_020700 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestWord1(self, words): :type words: List[str] :rtype: str 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的
- def longestWord(self, words): :type words: List[str] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestWord1(self, words): :type words: List[str] :rtype: str 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的
- def longestWord(self, words): :type words: List[str] :rtyp... | 65bd3cc5b6a6221b7e4d22d2a405fdaf3a08afc0 | <|skeleton|>
class Solution:
def longestWord1(self, words):
""":type words: List[str] :rtype: str 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的"""
<|body_0|>
def longestWord(self, words):
""":type words: List[str] :rtype: str 解法2: 字典树 使用两种不同的遍历方式"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestWord1(self, words):
""":type words: List[str] :rtype: str 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的"""
words.sort()
visited, ans = (set(), '')
for word in words:
if len(word) == 1 or word[:-1] in visited:
visited.add(wo... | the_stack_v2_python_sparse | Week_04/id_26/LeetCode_720_26.py | laocaicaicai/algorithm | train | 0 | |
543e780c1b491041ae1f766f2aae297442c4eb1a | [
"parameters = dict()\nparameters['page'] = GraphQLParam(page, 'PageInput', False)\nparameters['filter'] = GraphQLParam(room_filter, 'LabFilter', False)\nparameters['sort'] = GraphQLParam(sort, 'LabSort', False)\nresponse = self._query(name='getLabs', params=parameters, fields=RoomList.fields())\nreturn RoomList(res... | <|body_start_0|>
parameters = dict()
parameters['page'] = GraphQLParam(page, 'PageInput', False)
parameters['filter'] = GraphQLParam(room_filter, 'LabFilter', False)
parameters['sort'] = GraphQLParam(sort, 'LabSort', False)
response = self._query(name='getLabs', params=parameters... | Mixin to add datacenter room related methods to the GraphQL client | RoomsMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomsMixin:
"""Mixin to add datacenter room related methods to the GraphQL client"""
def get_rooms(self, page: PageInput=None, room_filter: RoomFilter=None, sort: RoomSort=None) -> RoomList:
"""Retrieves a list of datacenter room objects :param page: The requested page from the serve... | stack_v2_sparse_classes_36k_train_001431 | 18,858 | permissive | [
{
"docstring": "Retrieves a list of datacenter room objects :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param room_filter: A filter object to fil... | 4 | stack_v2_sparse_classes_30k_train_000577 | Implement the Python class `RoomsMixin` described below.
Class description:
Mixin to add datacenter room related methods to the GraphQL client
Method signatures and docstrings:
- def get_rooms(self, page: PageInput=None, room_filter: RoomFilter=None, sort: RoomSort=None) -> RoomList: Retrieves a list of datacenter ro... | Implement the Python class `RoomsMixin` described below.
Class description:
Mixin to add datacenter room related methods to the GraphQL client
Method signatures and docstrings:
- def get_rooms(self, page: PageInput=None, room_filter: RoomFilter=None, sort: RoomSort=None) -> RoomList: Retrieves a list of datacenter ro... | 8ea044096bd18aaccbfb81eca4e26ec29895a18c | <|skeleton|>
class RoomsMixin:
"""Mixin to add datacenter room related methods to the GraphQL client"""
def get_rooms(self, page: PageInput=None, room_filter: RoomFilter=None, sort: RoomSort=None) -> RoomList:
"""Retrieves a list of datacenter room objects :param page: The requested page from the serve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoomsMixin:
"""Mixin to add datacenter room related methods to the GraphQL client"""
def get_rooms(self, page: PageInput=None, room_filter: RoomFilter=None, sort: RoomSort=None) -> RoomList:
"""Retrieves a list of datacenter room objects :param page: The requested page from the server. This is an... | the_stack_v2_python_sparse | nebpyclient/api/rooms.py | firefly707/nebpyclient | train | 0 |
1504f31c719fed7f2b9a63c39db6334db4068210 | [
"if authenticate.check_name(message):\n if authenticate.get(message, app):\n self.reply(\"I might have that number I'll look.\")\n attachment = []\n for x in phone_numbers.get(pco_name):\n attachment += x.slack()\n if not attachment:\n attachment = msg_attachment... | <|body_start_0|>
if authenticate.check_name(message):
if authenticate.get(message, app):
self.reply("I might have that number I'll look.")
attachment = []
for x in phone_numbers.get(pco_name):
attachment += x.slack()
... | PcoPeoplePlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PcoPeoplePlugin:
def pco_phone_lookup(self, message, pco_name):
"""!phone | "number for" (name): tells you the phone number of a certain user"""
<|body_0|>
def pco_birthday_lookup(self, message, pco_name):
"""!birthday | "birthday for" (name): tells you the birthday ... | stack_v2_sparse_classes_36k_train_001432 | 8,182 | permissive | [
{
"docstring": "!phone | \"number for\" (name): tells you the phone number of a certain user",
"name": "pco_phone_lookup",
"signature": "def pco_phone_lookup(self, message, pco_name)"
},
{
"docstring": "!birthday | \"birthday for\" (name): tells you the birthday of a certain user",
"name": "... | 4 | stack_v2_sparse_classes_30k_train_005013 | Implement the Python class `PcoPeoplePlugin` described below.
Class description:
Implement the PcoPeoplePlugin class.
Method signatures and docstrings:
- def pco_phone_lookup(self, message, pco_name): !phone | "number for" (name): tells you the phone number of a certain user
- def pco_birthday_lookup(self, message, p... | Implement the Python class `PcoPeoplePlugin` described below.
Class description:
Implement the PcoPeoplePlugin class.
Method signatures and docstrings:
- def pco_phone_lookup(self, message, pco_name): !phone | "number for" (name): tells you the phone number of a certain user
- def pco_birthday_lookup(self, message, p... | 4d9f68daa1e1bf7a68fec5ff094e25766cc99b77 | <|skeleton|>
class PcoPeoplePlugin:
def pco_phone_lookup(self, message, pco_name):
"""!phone | "number for" (name): tells you the phone number of a certain user"""
<|body_0|>
def pco_birthday_lookup(self, message, pco_name):
"""!birthday | "birthday for" (name): tells you the birthday ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PcoPeoplePlugin:
def pco_phone_lookup(self, message, pco_name):
"""!phone | "number for" (name): tells you the phone number of a certain user"""
if authenticate.check_name(message):
if authenticate.get(message, app):
self.reply("I might have that number I'll look.")... | the_stack_v2_python_sparse | plugins/pco/pcopeople.py | Chalta/pcobot | train | 0 | |
1c8a1de2cd2b9fd64cd146d7da1a6be7c6da4cba | [
"self.url = url\nself.name = name\nself.username = None\nif token is not None:\n self.username = token.split('|')[0].replace('un=', '')\nself.headers = dict()\nself.headers['AUTHORIZATION'] = token\nreturn",
"if self.headers['AUTHORIZATION'] is None:\n self.set_authentication_token()\nrequest_data = dict()\... | <|body_start_0|>
self.url = url
self.name = name
self.username = None
if token is not None:
self.username = token.split('|')[0].replace('un=', '')
self.headers = dict()
self.headers['AUTHORIZATION'] = token
return
<|end_body_0|>
<|body_start_1|>
... | Client for SEED web services | SeedClient | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeedClient:
"""Client for SEED web services"""
def __init__(self, url, name, token=None):
"""Initialize object. Parameters ---------- url : str URL of service endpoint name : str Name of service token : str, optional Authentication token for SEED web services, when None get the token... | stack_v2_sparse_classes_36k_train_001433 | 12,188 | permissive | [
{
"docstring": "Initialize object. Parameters ---------- url : str URL of service endpoint name : str Name of service token : str, optional Authentication token for SEED web services, when None get the token from the .patric_config file when calling a method",
"name": "__init__",
"signature": "def __ini... | 3 | stack_v2_sparse_classes_30k_train_008434 | Implement the Python class `SeedClient` described below.
Class description:
Client for SEED web services
Method signatures and docstrings:
- def __init__(self, url, name, token=None): Initialize object. Parameters ---------- url : str URL of service endpoint name : str Name of service token : str, optional Authentica... | Implement the Python class `SeedClient` described below.
Class description:
Client for SEED web services
Method signatures and docstrings:
- def __init__(self, url, name, token=None): Initialize object. Parameters ---------- url : str URL of service endpoint name : str Name of service token : str, optional Authentica... | 89cd62221959fd2dc2952c30de6ecbe2d511479a | <|skeleton|>
class SeedClient:
"""Client for SEED web services"""
def __init__(self, url, name, token=None):
"""Initialize object. Parameters ---------- url : str URL of service endpoint name : str Name of service token : str, optional Authentication token for SEED web services, when None get the token... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeedClient:
"""Client for SEED web services"""
def __init__(self, url, name, token=None):
"""Initialize object. Parameters ---------- url : str URL of service endpoint name : str Name of service token : str, optional Authentication token for SEED web services, when None get the token from the .pa... | the_stack_v2_python_sparse | rs/Database/mackinac/SeedClient.py | sandialabs/RetSynth | train | 4 |
2f318478daa08cbb0cecf17af3a51a13ad9d9f42 | [
"try:\n cls.abrir_conexion()\n sql = 'SELECT cantidad, idTipoArticulo FROM tiposArt_pedidos WHERE idPedido = {};'.format(id)\n cls.cursor.execute(sql)\n cantarts_ = cls.cursor.fetchall()\n cantarts = []\n for a in cant... | <|body_start_0|>
try:
cls.abrir_conexion()
sql = 'SELECT cantidad, idTipoArticulo FROM tiposArt_pedidos WHERE idPedido = {};'.format(id)
cls.cursor.execute(sql)
cantarts_ = cls.cursor.... | DatosCantArticulo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatosCantArticulo:
def get_from_Pid(cls, id, noClose=False):
"""Obtiene los articulos de un pedido de la BD"""
<|body_0|>
def get_PR_stock(cls, id, noClose=False):
"""Obtiene los articulos del stock de un punto de retiro la BD"""
<|body_1|>
def addArticu... | stack_v2_sparse_classes_36k_train_001434 | 3,187 | no_license | [
{
"docstring": "Obtiene los articulos de un pedido de la BD",
"name": "get_from_Pid",
"signature": "def get_from_Pid(cls, id, noClose=False)"
},
{
"docstring": "Obtiene los articulos del stock de un punto de retiro la BD",
"name": "get_PR_stock",
"signature": "def get_PR_stock(cls, id, n... | 3 | stack_v2_sparse_classes_30k_train_002465 | Implement the Python class `DatosCantArticulo` described below.
Class description:
Implement the DatosCantArticulo class.
Method signatures and docstrings:
- def get_from_Pid(cls, id, noClose=False): Obtiene los articulos de un pedido de la BD
- def get_PR_stock(cls, id, noClose=False): Obtiene los articulos del stoc... | Implement the Python class `DatosCantArticulo` described below.
Class description:
Implement the DatosCantArticulo class.
Method signatures and docstrings:
- def get_from_Pid(cls, id, noClose=False): Obtiene los articulos de un pedido de la BD
- def get_PR_stock(cls, id, noClose=False): Obtiene los articulos del stoc... | 57ca674dba4dabd2526c450ba7210933240f19c5 | <|skeleton|>
class DatosCantArticulo:
def get_from_Pid(cls, id, noClose=False):
"""Obtiene los articulos de un pedido de la BD"""
<|body_0|>
def get_PR_stock(cls, id, noClose=False):
"""Obtiene los articulos del stock de un punto de retiro la BD"""
<|body_1|>
def addArticu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatosCantArticulo:
def get_from_Pid(cls, id, noClose=False):
"""Obtiene los articulos de un pedido de la BD"""
try:
cls.abrir_conexion()
sql = 'SELECT cantidad, idTipoArticulo FROM tiposArt_pedidos ... | the_stack_v2_python_sparse | data/data_cant_articulo.py | JoaquinCardonaRuiz/proyecto-final | train | 0 | |
065ba9fa436ff66b2a3fe6e89de680536d36cdbe | [
"opts = self._opts_defaults(**kwargs)\nhandler = setup_logfile_logger(opts['log_file'], opts['log_level_logfile'], log_format=opts['log_fmt_logfile'], date_format=opts['log_datefmt_logfile'])\ntry:\n mapper = StackdioSaltCloudMap(opts)\n mapper.rendered_map = cloud_map\n\n @catch_salt_cloud_map_failures(re... | <|body_start_0|>
opts = self._opts_defaults(**kwargs)
handler = setup_logfile_logger(opts['log_file'], opts['log_level_logfile'], log_format=opts['log_fmt_logfile'], date_format=opts['log_datefmt_logfile'])
try:
mapper = StackdioSaltCloudMap(opts)
mapper.rendered_map = cl... | StackdioSaltCloudClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackdioSaltCloudClient:
def launch_map(self, cloud_map, **kwargs):
"""Runs a map from an already in-memory representation rather than an file on disk."""
<|body_0|>
def destroy_map(self, cloud_map, hosts, **kwargs):
"""Destroy the named VMs"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_001435 | 11,860 | permissive | [
{
"docstring": "Runs a map from an already in-memory representation rather than an file on disk.",
"name": "launch_map",
"signature": "def launch_map(self, cloud_map, **kwargs)"
},
{
"docstring": "Destroy the named VMs",
"name": "destroy_map",
"signature": "def destroy_map(self, cloud_ma... | 3 | null | Implement the Python class `StackdioSaltCloudClient` described below.
Class description:
Implement the StackdioSaltCloudClient class.
Method signatures and docstrings:
- def launch_map(self, cloud_map, **kwargs): Runs a map from an already in-memory representation rather than an file on disk.
- def destroy_map(self, ... | Implement the Python class `StackdioSaltCloudClient` described below.
Class description:
Implement the StackdioSaltCloudClient class.
Method signatures and docstrings:
- def launch_map(self, cloud_map, **kwargs): Runs a map from an already in-memory representation rather than an file on disk.
- def destroy_map(self, ... | 84be621705031d147e104369399b872d5093ef64 | <|skeleton|>
class StackdioSaltCloudClient:
def launch_map(self, cloud_map, **kwargs):
"""Runs a map from an already in-memory representation rather than an file on disk."""
<|body_0|>
def destroy_map(self, cloud_map, hosts, **kwargs):
"""Destroy the named VMs"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StackdioSaltCloudClient:
def launch_map(self, cloud_map, **kwargs):
"""Runs a map from an already in-memory representation rather than an file on disk."""
opts = self._opts_defaults(**kwargs)
handler = setup_logfile_logger(opts['log_file'], opts['log_level_logfile'], log_format=opts['l... | the_stack_v2_python_sparse | stackdio/salt/utils/cloud.py | stackdio/stackdio | train | 9 | |
323be2b4e3d68ed6120941cd72b9760e61b80e01 | [
"self.custom_max_bandwidth = custom_max_bandwidth\nself.custom_bandwidth_local = custom_bandwidth_local\nself.custom_bandwidth_public = custom_bandwidth_public\nself.statistics = statistics",
"mode = Util.get_network_mode(ip_src, ip_dst)\nif self.custom_max_bandwidth != 0:\n bandwidth = self.custom_max_bandwid... | <|body_start_0|>
self.custom_max_bandwidth = custom_max_bandwidth
self.custom_bandwidth_local = custom_bandwidth_local
self.custom_bandwidth_public = custom_bandwidth_public
self.statistics = statistics
<|end_body_0|>
<|body_start_1|>
mode = Util.get_network_mode(ip_src, ip_dst)... | BandwidthController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BandwidthController:
def __init__(self, custom_max_bandwidth: float=0, custom_bandwidth_local: float=0, custom_bandwidth_public: float=0, statistics=None):
""":param custom_max_bandwidth: maximum bandwidth to be set as a hard limit, discarding the pcaps bandwidth :param custom_bandwidth_... | stack_v2_sparse_classes_36k_train_001436 | 2,322 | permissive | [
{
"docstring": ":param custom_max_bandwidth: maximum bandwidth to be set as a hard limit, discarding the pcaps bandwidth :param custom_bandwidth_local: bandwidth minimum for local traffic :param custom_bandwidth_public: bandwidth minimum for public traffic :param statistics: the statistics object of the current... | 2 | stack_v2_sparse_classes_30k_val_000677 | Implement the Python class `BandwidthController` described below.
Class description:
Implement the BandwidthController class.
Method signatures and docstrings:
- def __init__(self, custom_max_bandwidth: float=0, custom_bandwidth_local: float=0, custom_bandwidth_public: float=0, statistics=None): :param custom_max_ban... | Implement the Python class `BandwidthController` described below.
Class description:
Implement the BandwidthController class.
Method signatures and docstrings:
- def __init__(self, custom_max_bandwidth: float=0, custom_bandwidth_local: float=0, custom_bandwidth_public: float=0, statistics=None): :param custom_max_ban... | ba18d555d1c73707d030131f53c751f2405fd551 | <|skeleton|>
class BandwidthController:
def __init__(self, custom_max_bandwidth: float=0, custom_bandwidth_local: float=0, custom_bandwidth_public: float=0, statistics=None):
""":param custom_max_bandwidth: maximum bandwidth to be set as a hard limit, discarding the pcaps bandwidth :param custom_bandwidth_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BandwidthController:
def __init__(self, custom_max_bandwidth: float=0, custom_bandwidth_local: float=0, custom_bandwidth_public: float=0, statistics=None):
""":param custom_max_bandwidth: maximum bandwidth to be set as a hard limit, discarding the pcaps bandwidth :param custom_bandwidth_local: bandwid... | the_stack_v2_python_sparse | code/Core/BandwidthController.py | tklab-tud/ID2T | train | 49 | |
9f1bb1feaf46134c745b053a89994751f99fdc8d | [
"items = Balance.objects.filter(date__lt=date)\ntotal = sum((i.value for i in items))\nreturn total",
"items = Balance.objects.filter(date__year=year, date__month=month)\ntotal = sum((i.value for i in items))\nreturn total"
] | <|body_start_0|>
items = Balance.objects.filter(date__lt=date)
total = sum((i.value for i in items))
return total
<|end_body_0|>
<|body_start_1|>
items = Balance.objects.filter(date__year=year, date__month=month)
total = sum((i.value for i in items))
return total
<|end_b... | Balance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Balance:
def total_balance_before(date):
"""Returns the total value until the date that was given."""
<|body_0|>
def balance_from_month(year, month):
"""Returns the total value from the year and month that was given."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_001437 | 5,267 | permissive | [
{
"docstring": "Returns the total value until the date that was given.",
"name": "total_balance_before",
"signature": "def total_balance_before(date)"
},
{
"docstring": "Returns the total value from the year and month that was given.",
"name": "balance_from_month",
"signature": "def bala... | 2 | stack_v2_sparse_classes_30k_train_000852 | Implement the Python class `Balance` described below.
Class description:
Implement the Balance class.
Method signatures and docstrings:
- def total_balance_before(date): Returns the total value until the date that was given.
- def balance_from_month(year, month): Returns the total value from the year and month that w... | Implement the Python class `Balance` described below.
Class description:
Implement the Balance class.
Method signatures and docstrings:
- def total_balance_before(date): Returns the total value until the date that was given.
- def balance_from_month(year, month): Returns the total value from the year and month that w... | 2f46ba65fb0e376361ff47c86ea7a62c50b6c91b | <|skeleton|>
class Balance:
def total_balance_before(date):
"""Returns the total value until the date that was given."""
<|body_0|>
def balance_from_month(year, month):
"""Returns the total value from the year and month that was given."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Balance:
def total_balance_before(date):
"""Returns the total value until the date that was given."""
items = Balance.objects.filter(date__lt=date)
total = sum((i.value for i in items))
return total
def balance_from_month(year, month):
"""Returns the total value fr... | the_stack_v2_python_sparse | estofadora/statement/models.py | delete/estofadora | train | 6 | |
f1e090e8885f8292128621a3caf280f80891efae | [
"self.instance_generator = instance_generator\nself.labelset_ = {l: i for i, l in enumerate(labels, start=3)}\nself.labelset_[UNK] = 0\nself.labelset_[ROOT] = 1\nself.labelset_[UNRELATED] = 2\nself._zero = zero",
"zlabel = UNK if self._zero else UNRELATED\nfor doc in raw_documents:\n for pair in self.instance_... | <|body_start_0|>
self.instance_generator = instance_generator
self.labelset_ = {l: i for i, l in enumerate(labels, start=3)}
self.labelset_[UNK] = 0
self.labelset_[ROOT] = 1
self.labelset_[UNRELATED] = 2
self._zero = zero
<|end_body_0|>
<|body_start_1|>
zlabel = ... | Label extractor for the STAC corpus. | LabelVectorizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelVectorizer:
"""Label extractor for the STAC corpus."""
def __init__(self, instance_generator, labels, zero=False):
"""instance_generator to enumerate the instances from a doc :type labels: set(string)"""
<|body_0|>
def transform(self, raw_documents):
"""Lear... | stack_v2_sparse_classes_36k_train_001438 | 2,050 | no_license | [
{
"docstring": "instance_generator to enumerate the instances from a doc :type labels: set(string)",
"name": "__init__",
"signature": "def __init__(self, instance_generator, labels, zero=False)"
},
{
"docstring": "Learn the label encoder and return a vector of labels There is one label per insta... | 2 | stack_v2_sparse_classes_30k_train_016183 | Implement the Python class `LabelVectorizer` described below.
Class description:
Label extractor for the STAC corpus.
Method signatures and docstrings:
- def __init__(self, instance_generator, labels, zero=False): instance_generator to enumerate the instances from a doc :type labels: set(string)
- def transform(self,... | Implement the Python class `LabelVectorizer` described below.
Class description:
Label extractor for the STAC corpus.
Method signatures and docstrings:
- def __init__(self, instance_generator, labels, zero=False): instance_generator to enumerate the instances from a doc :type labels: set(string)
- def transform(self,... | c550f4383016e05fe20ad7180a027979e3540d1f | <|skeleton|>
class LabelVectorizer:
"""Label extractor for the STAC corpus."""
def __init__(self, instance_generator, labels, zero=False):
"""instance_generator to enumerate the instances from a doc :type labels: set(string)"""
<|body_0|>
def transform(self, raw_documents):
"""Lear... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelVectorizer:
"""Label extractor for the STAC corpus."""
def __init__(self, instance_generator, labels, zero=False):
"""instance_generator to enumerate the instances from a doc :type labels: set(string)"""
self.instance_generator = instance_generator
self.labelset_ = {l: i for ... | the_stack_v2_python_sparse | educe/stac/learning/doc_vectorizer.py | kowey/educe | train | 1 |
df4aef6ae2d4e9a087de4cb00b5e8d209d0b8cdd | [
"mapped = {}\nextra = {}\nfor key, value in metadata.items():\n if key in _ATTR_MAPPING_DE:\n mapped[_ATTR_MAPPING_DE[key]] = value\n else:\n extra[key] = value\nif 'title' not in mapped:\n mapped['title'] = mapped['ID']\nfor bool_attr in ('multiple', 'ordered'):\n if bool_attr in mapped:\... | <|body_start_0|>
mapped = {}
extra = {}
for key, value in metadata.items():
if key in _ATTR_MAPPING_DE:
mapped[_ATTR_MAPPING_DE[key]] = value
else:
extra[key] = value
if 'title' not in mapped:
mapped['title'] = mapped['I... | Dataclass for entity attribute metadata. | AttributeMetadata | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeMetadata:
"""Dataclass for entity attribute metadata."""
def from_dict(metadata: Dict[str, Union[str, bool]]) -> 'AttributeMetadata':
"""Create a AttributeMetadata instance from an entity dict."""
<|body_0|>
def to_dict(self):
"""Get the attribute metada... | stack_v2_sparse_classes_36k_train_001439 | 14,434 | permissive | [
{
"docstring": "Create a AttributeMetadata instance from an entity dict.",
"name": "from_dict",
"signature": "def from_dict(metadata: Dict[str, Union[str, bool]]) -> 'AttributeMetadata'"
},
{
"docstring": "Get the attribute metadata as entity dict.",
"name": "to_dict",
"signature": "def ... | 2 | null | Implement the Python class `AttributeMetadata` described below.
Class description:
Dataclass for entity attribute metadata.
Method signatures and docstrings:
- def from_dict(metadata: Dict[str, Union[str, bool]]) -> 'AttributeMetadata': Create a AttributeMetadata instance from an entity dict.
- def to_dict(self): Get... | Implement the Python class `AttributeMetadata` described below.
Class description:
Dataclass for entity attribute metadata.
Method signatures and docstrings:
- def from_dict(metadata: Dict[str, Union[str, bool]]) -> 'AttributeMetadata': Create a AttributeMetadata instance from an entity dict.
- def to_dict(self): Get... | 206f9fa646e5b47bacf95a3b9be7e2b72576c9f1 | <|skeleton|>
class AttributeMetadata:
"""Dataclass for entity attribute metadata."""
def from_dict(metadata: Dict[str, Union[str, bool]]) -> 'AttributeMetadata':
"""Create a AttributeMetadata instance from an entity dict."""
<|body_0|>
def to_dict(self):
"""Get the attribute metada... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeMetadata:
"""Dataclass for entity attribute metadata."""
def from_dict(metadata: Dict[str, Union[str, bool]]) -> 'AttributeMetadata':
"""Create a AttributeMetadata instance from an entity dict."""
mapped = {}
extra = {}
for key, value in metadata.items():
... | the_stack_v2_python_sparse | qhana_plugin_runner/plugin_utils/attributes.py | AathmanT/qhana-plugin-runner | train | 0 |
916bccd256044d2f40648b401b3dd8f97c296758 | [
"self.client_ip = client_ip\nself.node_ip = node_ip\nself.server_ip = server_ip\nself.view_id = view_id\nself.view_name = view_name",
"if dictionary is None:\n return None\nclient_ip = dictionary.get('clientIp')\nnode_ip = dictionary.get('nodeIp')\nserver_ip = dictionary.get('serverIp')\nview_id = dictionary.g... | <|body_start_0|>
self.client_ip = client_ip
self.node_ip = node_ip
self.server_ip = server_ip
self.view_id = view_id
self.view_name = view_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
client_ip = dictionary.get('clientIp')
... | Implementation of the 'NfsConnection' model. TODO: type description here. Attributes: client_ip (string): Specifies the Client IP address of the connection. node_ip (string): Specifies a Node IP address where the connection request is received. server_ip (string): Specifies the Server IP address of the connection. This... | NfsConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NfsConnection:
"""Implementation of the 'NfsConnection' model. TODO: type description here. Attributes: client_ip (string): Specifies the Client IP address of the connection. node_ip (string): Specifies a Node IP address where the connection request is received. server_ip (string): Specifies the ... | stack_v2_sparse_classes_36k_train_001440 | 2,341 | permissive | [
{
"docstring": "Constructor for the NfsConnection class",
"name": "__init__",
"signature": "def __init__(self, client_ip=None, node_ip=None, server_ip=None, view_id=None, view_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | stack_v2_sparse_classes_30k_train_002175 | Implement the Python class `NfsConnection` described below.
Class description:
Implementation of the 'NfsConnection' model. TODO: type description here. Attributes: client_ip (string): Specifies the Client IP address of the connection. node_ip (string): Specifies a Node IP address where the connection request is recei... | Implement the Python class `NfsConnection` described below.
Class description:
Implementation of the 'NfsConnection' model. TODO: type description here. Attributes: client_ip (string): Specifies the Client IP address of the connection. node_ip (string): Specifies a Node IP address where the connection request is recei... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NfsConnection:
"""Implementation of the 'NfsConnection' model. TODO: type description here. Attributes: client_ip (string): Specifies the Client IP address of the connection. node_ip (string): Specifies a Node IP address where the connection request is received. server_ip (string): Specifies the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NfsConnection:
"""Implementation of the 'NfsConnection' model. TODO: type description here. Attributes: client_ip (string): Specifies the Client IP address of the connection. node_ip (string): Specifies a Node IP address where the connection request is received. server_ip (string): Specifies the Server IP add... | the_stack_v2_python_sparse | cohesity_management_sdk/models/nfs_connection.py | cohesity/management-sdk-python | train | 24 |
9bb70ce0045a9bbcec0d8d9728949946023bcc5c | [
"super(ParallelCNN, self).__init__()\nself.lseq = nn.ModuleList()\nfor k in para_ker:\n seq = nn.Sequential(nn.Conv1d(4, 4, kernel_size=k, padding='same'), nn.ReLU(), nn.MaxPool1d(pool_kernel), nn.Dropout(drop))\n self.lseq.append(seq)",
"_x = list()\nfor seq in self.lseq:\n x = seq(inputs)\n _x.appen... | <|body_start_0|>
super(ParallelCNN, self).__init__()
self.lseq = nn.ModuleList()
for k in para_ker:
seq = nn.Sequential(nn.Conv1d(4, 4, kernel_size=k, padding='same'), nn.ReLU(), nn.MaxPool1d(pool_kernel), nn.Dropout(drop))
self.lseq.append(seq)
<|end_body_0|>
<|body_sta... | ParallelCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelCNN:
def __init__(self, para_ker, pool_kernel=6, drop=0.5):
"""Multiple CNN layer apply on input and concatenate the output :param para_ker: List of kernel size that will be used :param pool_kernel: Pooling parameter after CNN :param drop: Dropout parameter"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_001441 | 3,458 | permissive | [
{
"docstring": "Multiple CNN layer apply on input and concatenate the output :param para_ker: List of kernel size that will be used :param pool_kernel: Pooling parameter after CNN :param drop: Dropout parameter",
"name": "__init__",
"signature": "def __init__(self, para_ker, pool_kernel=6, drop=0.5)"
... | 2 | stack_v2_sparse_classes_30k_train_005555 | Implement the Python class `ParallelCNN` described below.
Class description:
Implement the ParallelCNN class.
Method signatures and docstrings:
- def __init__(self, para_ker, pool_kernel=6, drop=0.5): Multiple CNN layer apply on input and concatenate the output :param para_ker: List of kernel size that will be used :... | Implement the Python class `ParallelCNN` described below.
Class description:
Implement the ParallelCNN class.
Method signatures and docstrings:
- def __init__(self, para_ker, pool_kernel=6, drop=0.5): Multiple CNN layer apply on input and concatenate the output :param para_ker: List of kernel size that will be used :... | 2c020793335417111442684770009bbdf13a885c | <|skeleton|>
class ParallelCNN:
def __init__(self, para_ker, pool_kernel=6, drop=0.5):
"""Multiple CNN layer apply on input and concatenate the output :param para_ker: List of kernel size that will be used :param pool_kernel: Pooling parameter after CNN :param drop: Dropout parameter"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelCNN:
def __init__(self, para_ker, pool_kernel=6, drop=0.5):
"""Multiple CNN layer apply on input and concatenate the output :param para_ker: List of kernel size that will be used :param pool_kernel: Pooling parameter after CNN :param drop: Dropout parameter"""
super(ParallelCNN, self).... | the_stack_v2_python_sparse | src/Eukaryotic_Promoters_Classification/mouse_tata_deepromoter/DeePromoter.py | Shujun-He/Nucleic-Transformer | train | 15 | |
2d3b1bf59986771116d915e14ed8000eaf35edf1 | [
"if not have_scipy:\n raise RuntimeError('RumPath depends on scipy, which could not be imported')\nself.rotation_factors = rotation_factors\nself.rigid_units = rigid_units\nself.K = []\nself.y = []\nw = dirn.copy().reshape([3, len(dirn) / 3])\nX = x_start.reshape([3, len(dirn) / 3])\nfor I in rigid_units:\n x... | <|body_start_0|>
if not have_scipy:
raise RuntimeError('RumPath depends on scipy, which could not be imported')
self.rotation_factors = rotation_factors
self.rigid_units = rigid_units
self.K = []
self.y = []
w = dirn.copy().reshape([3, len(dirn) / 3])
... | Describes a curved search path, taking into account information about (near-) rigid unit motions (RUMs). One can tag sub-molecules of the system, which are collections of particles that form a (near-)rigid unit. Let x1, ... xn be the positions of one such molecule, then we construct a path of the form xi(t) = xi(0) + (... | RumPath | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RumPath:
"""Describes a curved search path, taking into account information about (near-) rigid unit motions (RUMs). One can tag sub-molecules of the system, which are collections of particles that form a (near-)rigid unit. Let x1, ... xn be the positions of one such molecule, then we construct a... | stack_v2_sparse_classes_36k_train_001442 | 17,455 | no_license | [
{
"docstring": "Initialise a `RumPath` Args: x_start : vector containing the positions in d x nAt shape dirn : search direction, same shape as x_start vector rigid_units : array of arrays of molecule indices rotation_factors : factor by which the rotation of each molecular is accelerated; array of scalars, same... | 2 | null | Implement the Python class `RumPath` described below.
Class description:
Describes a curved search path, taking into account information about (near-) rigid unit motions (RUMs). One can tag sub-molecules of the system, which are collections of particles that form a (near-)rigid unit. Let x1, ... xn be the positions of... | Implement the Python class `RumPath` described below.
Class description:
Describes a curved search path, taking into account information about (near-) rigid unit motions (RUMs). One can tag sub-molecules of the system, which are collections of particles that form a (near-)rigid unit. Let x1, ... xn be the positions of... | 445645e8584e706d61f05619f7ab51358ef1b26a | <|skeleton|>
class RumPath:
"""Describes a curved search path, taking into account information about (near-) rigid unit motions (RUMs). One can tag sub-molecules of the system, which are collections of particles that form a (near-)rigid unit. Let x1, ... xn be the positions of one such molecule, then we construct a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RumPath:
"""Describes a curved search path, taking into account information about (near-) rigid unit motions (RUMs). One can tag sub-molecules of the system, which are collections of particles that form a (near-)rigid unit. Let x1, ... xn be the positions of one such molecule, then we construct a path of the ... | the_stack_v2_python_sparse | venv/Lib/site-packages/ase/utils/linesearcharmijo.py | joliesla/Material-modelling | train | 1 |
9ff0a9d5e878badb56dca68b7b31d21c9f5f5a5e | [
"self.filters = []\nself.validators = []\nself.use_context = use_context",
"if not isinstance(filter, AbstractFilter):\n err = 'Filters must be of type {}'.format(AbstractFilter)\n raise InvalidFilter(err)\nif filter not in self.filters:\n self.filters.append(filter)\nreturn self",
"if not isinstance(v... | <|body_start_0|>
self.filters = []
self.validators = []
self.use_context = use_context
<|end_body_0|>
<|body_start_1|>
if not isinstance(filter, AbstractFilter):
err = 'Filters must be of type {}'.format(AbstractFilter)
raise InvalidFilter(err)
if filter ... | Simple property A single value property on the schema and holds a number of filters and validators for this value | SimpleProperty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleProperty:
"""Simple property A single value property on the schema and holds a number of filters and validators for this value"""
def __init__(self, use_context=True):
"""Initialize property Can optionally accept a flag indicating whether the property should inherit context whe... | stack_v2_sparse_classes_36k_train_001443 | 5,839 | permissive | [
{
"docstring": "Initialize property Can optionally accept a flag indicating whether the property should inherit context when being filtered and validated. This is useful to control how custom context is being passed down when validating graphs with nested schemas. :param use_context: bool, use or ignore passed ... | 5 | null | Implement the Python class `SimpleProperty` described below.
Class description:
Simple property A single value property on the schema and holds a number of filters and validators for this value
Method signatures and docstrings:
- def __init__(self, use_context=True): Initialize property Can optionally accept a flag i... | Implement the Python class `SimpleProperty` described below.
Class description:
Simple property A single value property on the schema and holds a number of filters and validators for this value
Method signatures and docstrings:
- def __init__(self, use_context=True): Initialize property Can optionally accept a flag i... | c598d1af5df40fae65cf3878b8f67accbcd059b7 | <|skeleton|>
class SimpleProperty:
"""Simple property A single value property on the schema and holds a number of filters and validators for this value"""
def __init__(self, use_context=True):
"""Initialize property Can optionally accept a flag indicating whether the property should inherit context whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleProperty:
"""Simple property A single value property on the schema and holds a number of filters and validators for this value"""
def __init__(self, use_context=True):
"""Initialize property Can optionally accept a flag indicating whether the property should inherit context when being filte... | the_stack_v2_python_sparse | shiftschema/property.py | projectshift/shift-schema | train | 2 |
662acf7cea9d6a7993a3f426fac76ac994df8912 | [
"request = request._request\nuser = getattr(request, 'user', None)\nif not user or user.is_anonymous:\n return None\nself.enforce_csrf(request)\nreturn (user, None)",
"def get_response(request):\n return HttpResponse()\nreason = CSRFCheck(get_response).process_view(request, None, (), {})\nif reason:\n ra... | <|body_start_0|>
request = request._request
user = getattr(request, 'user', None)
if not user or user.is_anonymous:
return None
self.enforce_csrf(request)
return (user, None)
<|end_body_0|>
<|body_start_1|>
def get_response(request):
return HttpRe... | Use Django's session framework for authentication. Allows inactive users. | InactiveSessionAuthentication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InactiveSessionAuthentication:
"""Use Django's session framework for authentication. Allows inactive users."""
def authenticate(self, request):
"""Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`."""
<|body_0|>
def enforce_... | stack_v2_sparse_classes_36k_train_001444 | 11,718 | permissive | [
{
"docstring": "Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Enforce CSRF validation for session based authentication.",
"name": "enforce_csrf",
... | 2 | stack_v2_sparse_classes_30k_train_017878 | Implement the Python class `InactiveSessionAuthentication` described below.
Class description:
Use Django's session framework for authentication. Allows inactive users.
Method signatures and docstrings:
- def authenticate(self, request): Returns a `User` if the request session currently has a logged in user. Otherwis... | Implement the Python class `InactiveSessionAuthentication` described below.
Class description:
Use Django's session framework for authentication. Allows inactive users.
Method signatures and docstrings:
- def authenticate(self, request): Returns a `User` if the request session currently has a logged in user. Otherwis... | 67ec527bfc32c715bf9f29d5e01362c4903aebd2 | <|skeleton|>
class InactiveSessionAuthentication:
"""Use Django's session framework for authentication. Allows inactive users."""
def authenticate(self, request):
"""Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`."""
<|body_0|>
def enforce_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InactiveSessionAuthentication:
"""Use Django's session framework for authentication. Allows inactive users."""
def authenticate(self, request):
"""Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`."""
request = request._request
user =... | the_stack_v2_python_sparse | kitsune/sumo/api_utils.py | mozilla/kitsune | train | 1,218 |
def84aaac6ca688bba2356a20d48687f30674fa7 | [
"if hasattr(attribute_names, '__iter__'):\n attribute_names = list(attribute_names)\nelse:\n attribute_names = [attribute_names]\nself.attribute_names = attribute_names\nself.ifnot = ifnot\nself.LABEL = attribute_names",
"coo = [star.more.get(attribute_name, self.ifnot) for attribute_name in self.attribute_... | <|body_start_0|>
if hasattr(attribute_names, '__iter__'):
attribute_names = list(attribute_names)
else:
attribute_names = [attribute_names]
self.attribute_names = attribute_names
self.ifnot = ifnot
self.LABEL = attribute_names
<|end_body_0|>
<|body_start_... | Descriptor which using star's attributes Attributes ----------- attribute_names : iterable, str Keys of star's objects `more` attribute For example: `["pm_ra", "pm_de"]` ifnot : str, NoneType Value of coordinates which will be assigned if there is no `attribute_name` value | PropertyDescr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyDescr:
"""Descriptor which using star's attributes Attributes ----------- attribute_names : iterable, str Keys of star's objects `more` attribute For example: `["pm_ra", "pm_de"]` ifnot : str, NoneType Value of coordinates which will be assigned if there is no `attribute_name` value"""
... | stack_v2_sparse_classes_36k_train_001445 | 1,839 | permissive | [
{
"docstring": "Parameters ----------- attribute_names : iterable, str Keys of star's objects `more` attribute ifnot : str, NoneType Value of coordinates which will be assigned if there is no `attribute_name` value",
"name": "__init__",
"signature": "def __init__(self, attribute_names, ifnot=None)"
},... | 2 | null | Implement the Python class `PropertyDescr` described below.
Class description:
Descriptor which using star's attributes Attributes ----------- attribute_names : iterable, str Keys of star's objects `more` attribute For example: `["pm_ra", "pm_de"]` ifnot : str, NoneType Value of coordinates which will be assigned if t... | Implement the Python class `PropertyDescr` described below.
Class description:
Descriptor which using star's attributes Attributes ----------- attribute_names : iterable, str Keys of star's objects `more` attribute For example: `["pm_ra", "pm_de"]` ifnot : str, NoneType Value of coordinates which will be assigned if t... | a0a51f033cb8adf45296913f0de0aa2568e0530c | <|skeleton|>
class PropertyDescr:
"""Descriptor which using star's attributes Attributes ----------- attribute_names : iterable, str Keys of star's objects `more` attribute For example: `["pm_ra", "pm_de"]` ifnot : str, NoneType Value of coordinates which will be assigned if there is no `attribute_name` value"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertyDescr:
"""Descriptor which using star's attributes Attributes ----------- attribute_names : iterable, str Keys of star's objects `more` attribute For example: `["pm_ra", "pm_de"]` ifnot : str, NoneType Value of coordinates which will be assigned if there is no `attribute_name` value"""
def __init... | the_stack_v2_python_sparse | lcc/stars_processing/descriptors/property_desc.py | pierfra-rocci/LightCurvesClassifier | train | 0 |
75f2d9b533c80b078000b361f8c000ca5f0b874a | [
"QtCore.QObject.__init__(self)\nself._handler = handler\nself._args = args\nself._kwds = kwds\nself._calls_mutex.lock()\nself._calls.append(self)\nself._calls_mutex.unlock()\nself.moveToThread(QtGui.QApplication.instance().thread())\nevent = QtCore.QEvent(_QT_TRAITS_EVENT)\nQtGui.QApplication.instance().postEvent(s... | <|body_start_0|>
QtCore.QObject.__init__(self)
self._handler = handler
self._args = args
self._kwds = kwds
self._calls_mutex.lock()
self._calls.append(self)
self._calls_mutex.unlock()
self.moveToThread(QtGui.QApplication.instance().thread())
event ... | This class dispatches a handler so that it executes in the main GUI thread (similar to the wx function). | _CallAfter | [
"CECILL-B"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CallAfter:
"""This class dispatches a handler so that it executes in the main GUI thread (similar to the wx function)."""
def __init__(self, handler, *args, **kwds):
"""Initialise the call."""
<|body_0|>
def event(self, event):
"""QObject event handler."""
... | stack_v2_sparse_classes_36k_train_001446 | 35,894 | permissive | [
{
"docstring": "Initialise the call.",
"name": "__init__",
"signature": "def __init__(self, handler, *args, **kwds)"
},
{
"docstring": "QObject event handler.",
"name": "event",
"signature": "def event(self, event)"
},
{
"docstring": "Remove the call from the list, so it can be g... | 3 | stack_v2_sparse_classes_30k_train_010705 | Implement the Python class `_CallAfter` described below.
Class description:
This class dispatches a handler so that it executes in the main GUI thread (similar to the wx function).
Method signatures and docstrings:
- def __init__(self, handler, *args, **kwds): Initialise the call.
- def event(self, event): QObject ev... | Implement the Python class `_CallAfter` described below.
Class description:
This class dispatches a handler so that it executes in the main GUI thread (similar to the wx function).
Method signatures and docstrings:
- def __init__(self, handler, *args, **kwds): Initialise the call.
- def event(self, event): QObject ev... | 779e254098b183eb312eb589268c474dd65c5679 | <|skeleton|>
class _CallAfter:
"""This class dispatches a handler so that it executes in the main GUI thread (similar to the wx function)."""
def __init__(self, handler, *args, **kwds):
"""Initialise the call."""
<|body_0|>
def event(self, event):
"""QObject event handler."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CallAfter:
"""This class dispatches a handler so that it executes in the main GUI thread (similar to the wx function)."""
def __init__(self, handler, *args, **kwds):
"""Initialise the call."""
QtCore.QObject.__init__(self)
self._handler = handler
self._args = args
... | the_stack_v2_python_sparse | python/soma/qt_gui/qt_backend.py | populse/soma-base | train | 0 |
1bceac461e57b63663fdd8832e57743ec68d8a51 | [
"to_write = [('user1', 'video1', '1339627945.362114'), ('user1', 'video2', '1339123414.241234'), ('user1', 'video3', '1339511343.342424')]\nexpected = self.duplicate([('video1', 'video2', '0', '1'), ('video1', 'video3', '0', '1'), ('video2', 'video3', '1', '0')])\nself.generic_test(to_write, expected)",
"to_write... | <|body_start_0|>
to_write = [('user1', 'video1', '1339627945.362114'), ('user1', 'video2', '1339123414.241234'), ('user1', 'video3', '1339511343.342424')]
expected = self.duplicate([('video1', 'video2', '0', '1'), ('video1', 'video3', '0', '1'), ('video2', 'video3', '1', '0')])
self.generic_test... | VideoRecommenderTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoRecommenderTest:
def test_one_user_videos(self):
"""Test the reducer if we have only one user"""
<|body_0|>
def test_last_user_has_one(self):
"""Test the case where the last user in the list has only 1 watch."""
<|body_1|>
def test_all_users_have_on... | stack_v2_sparse_classes_36k_train_001447 | 5,692 | no_license | [
{
"docstring": "Test the reducer if we have only one user",
"name": "test_one_user_videos",
"signature": "def test_one_user_videos(self)"
},
{
"docstring": "Test the case where the last user in the list has only 1 watch.",
"name": "test_last_user_has_one",
"signature": "def test_last_use... | 4 | null | Implement the Python class `VideoRecommenderTest` described below.
Class description:
Implement the VideoRecommenderTest class.
Method signatures and docstrings:
- def test_one_user_videos(self): Test the reducer if we have only one user
- def test_last_user_has_one(self): Test the case where the last user in the lis... | Implement the Python class `VideoRecommenderTest` described below.
Class description:
Implement the VideoRecommenderTest class.
Method signatures and docstrings:
- def test_one_user_videos(self): Test the reducer if we have only one user
- def test_last_user_has_one(self): Test the case where the last user in the lis... | c4ad2ad67b497ce411a9e5d6d6db407ee304491f | <|skeleton|>
class VideoRecommenderTest:
def test_one_user_videos(self):
"""Test the reducer if we have only one user"""
<|body_0|>
def test_last_user_has_one(self):
"""Test the case where the last user in the list has only 1 watch."""
<|body_1|>
def test_all_users_have_on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoRecommenderTest:
def test_one_user_videos(self):
"""Test the reducer if we have only one user"""
to_write = [('user1', 'video1', '1339627945.362114'), ('user1', 'video2', '1339123414.241234'), ('user1', 'video3', '1339511343.342424')]
expected = self.duplicate([('video1', 'video2'... | the_stack_v2_python_sparse | map_reduce/py/video_recommendation_reducer_tests.py | summer-liu/analytics | train | 1 | |
3801ed79f7c258e89672eb21a2c6c1d76b473ee8 | [
"subv = SimpleMachineVertex(None, '')\npl = Placement(subv, 0, 0, 1)\nPlacements([pl])",
"pls = Placements()\nself.assertEqual(pls._placements, dict())\nself.assertEqual(pls._machine_vertices, dict())",
"subv = list()\nfor i in range(5):\n subv.append(SimpleMachineVertex(None, ''))\npl = list()\nfor i in ran... | <|body_start_0|>
subv = SimpleMachineVertex(None, '')
pl = Placement(subv, 0, 0, 1)
Placements([pl])
<|end_body_0|>
<|body_start_1|>
pls = Placements()
self.assertEqual(pls._placements, dict())
self.assertEqual(pls._machine_vertices, dict())
<|end_body_1|>
<|body_start_... | tester for placements object in pacman.model.placements.placements | TestPlacements | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPlacements:
"""tester for placements object in pacman.model.placements.placements"""
def test_create_new_placements(self):
"""test creating a placements object :return:"""
<|body_0|>
def test_create_new_empty_placements(self):
"""checks that creating an empty... | stack_v2_sparse_classes_36k_train_001448 | 2,548 | no_license | [
{
"docstring": "test creating a placements object :return:",
"name": "test_create_new_placements",
"signature": "def test_create_new_placements(self)"
},
{
"docstring": "checks that creating an empty placements object is valid :return:",
"name": "test_create_new_empty_placements",
"signa... | 5 | stack_v2_sparse_classes_30k_train_016254 | Implement the Python class `TestPlacements` described below.
Class description:
tester for placements object in pacman.model.placements.placements
Method signatures and docstrings:
- def test_create_new_placements(self): test creating a placements object :return:
- def test_create_new_empty_placements(self): checks t... | Implement the Python class `TestPlacements` described below.
Class description:
tester for placements object in pacman.model.placements.placements
Method signatures and docstrings:
- def test_create_new_placements(self): test creating a placements object :return:
- def test_create_new_empty_placements(self): checks t... | 5c2faba4d823e9341e5c18f61ea9bf8c6e15b687 | <|skeleton|>
class TestPlacements:
"""tester for placements object in pacman.model.placements.placements"""
def test_create_new_placements(self):
"""test creating a placements object :return:"""
<|body_0|>
def test_create_new_empty_placements(self):
"""checks that creating an empty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPlacements:
"""tester for placements object in pacman.model.placements.placements"""
def test_create_new_placements(self):
"""test creating a placements object :return:"""
subv = SimpleMachineVertex(None, '')
pl = Placement(subv, 0, 0, 1)
Placements([pl])
def test... | the_stack_v2_python_sparse | unittests/model_tests/placement_tests/test_placements_model.py | kfriesth/PACMAN | train | 0 |
a7f51d00a4767bea7719cfa72ce2fa42f441d3f1 | [
"if request.dbsession is None:\n raise DBAPIError\nreturn request.dbsession.query(cls).all()",
"if request.dbsession is None:\n raise DBAPIError\nreturn request.dbsession.query(cls).get(pk)",
"if request.dbsession is None:\n raise DBAPIError\nstock = cls(**kwargs)\nrequest.dbsession.add(stock)\nreturn ... | <|body_start_0|>
if request.dbsession is None:
raise DBAPIError
return request.dbsession.query(cls).all()
<|end_body_0|>
<|body_start_1|>
if request.dbsession is None:
raise DBAPIError
return request.dbsession.query(cls).get(pk)
<|end_body_1|>
<|body_start_2|>
... | This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB | Stock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stock:
"""This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB"""
def all(cls, requ... | stack_v2_sparse_classes_36k_train_001449 | 2,531 | permissive | [
{
"docstring": "GET all stocks we have in our DB",
"name": "all",
"signature": "def all(cls, request)"
},
{
"docstring": "Retrieve a single instance from the database by the primary key for that record. pk is used for the primary key",
"name": "one",
"signature": "def one(cls, request=No... | 4 | stack_v2_sparse_classes_30k_train_013427 | Implement the Python class `Stock` described below.
Class description:
This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last upda... | Implement the Python class `Stock` described below.
Class description:
This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last upda... | 1e5993f72d70d55ccab65034c0b2512e96ad57cc | <|skeleton|>
class Stock:
"""This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB"""
def all(cls, requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stock:
"""This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB"""
def all(cls, request):
... | the_stack_v2_python_sparse | stocks_api/models/stock.py | SeattleChris/stocks_api | train | 0 |
855ce65cee85b4f3ebbacee370fa50276fe03de4 | [
"self.dice.append(math.nan)\nself.hausdorff_distance_mm.append(math.nan)\nself.mean_distance_mm.append(math.nan)",
"self.dice.append(dice)\nself.hausdorff_distance_mm.append(hausdorff_distance_mm)\nself.mean_distance_mm.append(mean_distance_mm)"
] | <|body_start_0|>
self.dice.append(math.nan)
self.hausdorff_distance_mm.append(math.nan)
self.mean_distance_mm.append(math.nan)
<|end_body_0|>
<|body_start_1|>
self.dice.append(dice)
self.hausdorff_distance_mm.append(hausdorff_distance_mm)
self.mean_distance_mm.append(mea... | Stores different segmentation metrics, as a list where each list entry represents one class. | SegmentationMetricsPerClass | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationMetricsPerClass:
"""Stores different segmentation metrics, as a list where each list entry represents one class."""
def append_nan(self) -> None:
"""Adds a NaN for all metrics that are stored, indicating that the target class was not present and no output was produced by ... | stack_v2_sparse_classes_36k_train_001450 | 32,709 | permissive | [
{
"docstring": "Adds a NaN for all metrics that are stored, indicating that the target class was not present and no output was produced by the model.",
"name": "append_nan",
"signature": "def append_nan(self) -> None"
},
{
"docstring": "Stores the metrics for a class in the present object. :para... | 2 | null | Implement the Python class `SegmentationMetricsPerClass` described below.
Class description:
Stores different segmentation metrics, as a list where each list entry represents one class.
Method signatures and docstrings:
- def append_nan(self) -> None: Adds a NaN for all metrics that are stored, indicating that the ta... | Implement the Python class `SegmentationMetricsPerClass` described below.
Class description:
Stores different segmentation metrics, as a list where each list entry represents one class.
Method signatures and docstrings:
- def append_nan(self) -> None: Adds a NaN for all metrics that are stored, indicating that the ta... | 12b496093097ef48d5ac8880985c04918d7f76fe | <|skeleton|>
class SegmentationMetricsPerClass:
"""Stores different segmentation metrics, as a list where each list entry represents one class."""
def append_nan(self) -> None:
"""Adds a NaN for all metrics that are stored, indicating that the target class was not present and no output was produced by ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentationMetricsPerClass:
"""Stores different segmentation metrics, as a list where each list entry represents one class."""
def append_nan(self) -> None:
"""Adds a NaN for all metrics that are stored, indicating that the target class was not present and no output was produced by the model."""... | the_stack_v2_python_sparse | InnerEye/ML/metrics.py | MaxCodeXTC/InnerEye-DeepLearning | train | 1 |
b84560ab598f29b0f79df0fc2ea15e0edc487b99 | [
"n = len(matrix[0])\nfor i in range(n):\n for j in range(i + 1, n):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nfor i in range(n):\n for j in range(n // 2):\n matrix[i][j], matrix[i][n - j - 1] = (matrix[i][n - j - 1], matrix[i][j])",
"n = len(matrix)\nfor i in range(n - 1):\n... | <|body_start_0|>
n = len(matrix[0])
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][n - j - 1] = (matrix[i][n - j - 1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate_v2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in... | stack_v2_sparse_classes_36k_train_001451 | 3,508 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate_v2(self, matrix): :type matrix: List[Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate_v2(self, matrix): :type matrix: List[Lis... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate_v2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
n = len(matrix[0])
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i]... | the_stack_v2_python_sparse | src/lt_48.py | oxhead/CodingYourWay | train | 0 | |
e84844a2c9447f9394944f70c7ff3ab731cbdff8 | [
"self.layers = layers_structure\nself.batch_size = batch_size\nself.layers_num = len(layers_structure)\nself.deep_activation = deep_activation\nself.activation = activation\nself.loss = loss\nself.learning_rate = learning_rate\nself.decay = decay\nself.momentum = momentum\nself.kernel_regularization_params = kernel... | <|body_start_0|>
self.layers = layers_structure
self.batch_size = batch_size
self.layers_num = len(layers_structure)
self.deep_activation = deep_activation
self.activation = activation
self.loss = loss
self.learning_rate = learning_rate
self.decay = decay
... | SequentialMLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialMLP:
def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, optimizer='adam', kernel_regularization_params=('l2', 0.01), dropout=0.3, validation_size=0.2, outfile=None, plot_mod... | stack_v2_sparse_classes_36k_train_001452 | 10,575 | no_license | [
{
"docstring": ":param layers_structure: list of int, with the structure of the hidden layers :param loss: str, the name of the loss function :param epochs: int, the number of epochs :param batch_size: int, the size of the batch :param activation: str, the name of the activation function :param deep_activation:... | 2 | stack_v2_sparse_classes_30k_train_020298 | Implement the Python class `SequentialMLP` described below.
Class description:
Implement the SequentialMLP class.
Method signatures and docstrings:
- def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, opti... | Implement the Python class `SequentialMLP` described below.
Class description:
Implement the SequentialMLP class.
Method signatures and docstrings:
- def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, opti... | bb2f1e350140c9d34865ed77f50d4475b515ea7b | <|skeleton|>
class SequentialMLP:
def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, optimizer='adam', kernel_regularization_params=('l2', 0.01), dropout=0.3, validation_size=0.2, outfile=None, plot_mod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequentialMLP:
def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, optimizer='adam', kernel_regularization_params=('l2', 0.01), dropout=0.3, validation_size=0.2, outfile=None, plot_model=False, load... | the_stack_v2_python_sparse | app/simple_mlp.py | agromanou/text-classification-with-nn | train | 0 | |
8ae77dd3bd20febd7b55ee9856d2252ec4e85ae7 | [
"super(Test200SmartSanityUpload005, self).prepare()\nself.logger.info('Preconditions:')\nself.logger.info('1. Open Micro/WINr; ')\nself.logger.info('2. Set up connection with PLC;')",
"super(Test200SmartSanityUpload005, self).process()\nself.logger.info('Step actions:')\nself.logger.info('1. Generate subroutine... | <|body_start_0|>
super(Test200SmartSanityUpload005, self).prepare()
self.logger.info('Preconditions:')
self.logger.info('1. Open Micro/WINr; ')
self.logger.info('2. Set up connection with PLC;')
<|end_body_0|>
<|body_start_1|>
super(Test200SmartSanityUpload005, self).process()
... | Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data logs with the frequency of 1 times 1s; 3. Download all... | Test200SmartSanityUpload005 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test200SmartSanityUpload005:
"""Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data... | stack_v2_sparse_classes_36k_train_001453 | 3,776 | no_license | [
{
"docstring": "the preparation before executing the test steps Args: Example: Return: Author: Cai, Yong IsInterface: False ChangeInfo: Cai, Yong 2019-09-20 create",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "execute the test steps Args: Example: Return: Author: Cai, ... | 3 | stack_v2_sparse_classes_30k_train_008316 | Implement the Python class `Test200SmartSanityUpload005` described below.
Class description:
Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a n... | Implement the Python class `Test200SmartSanityUpload005` described below.
Class description:
Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a n... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class Test200SmartSanityUpload005:
"""Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test200SmartSanityUpload005:
"""Upload datalogs No.: test_200smart_sanity_upload_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; Step actions: 1. Generate subroutine with data logs wizard, the max number of records is 100; 2. Create a new project with program that write data logs with th... | the_stack_v2_python_sparse | test_case/no_piling/sanity/base/upload/test_200smart_sanity_upload_005.py | Lewescaiyong/auto_test_framework | train | 1 |
218d0db19092fcc02f5fe259aa268c0e713883d9 | [
"super(BatchNormalization, self).__init__(layer_type='batch_normalization')\nself.decay = decay\nself.running_mean = None\nself.running_var = None\nself.gamma = None\nself.beta = None\nself.param_shape = None\nself.cache_std = None\nself.cache_xc = None\nself.cache_xn = None\nself.optimizer = optimizer_dict[optimiz... | <|body_start_0|>
super(BatchNormalization, self).__init__(layer_type='batch_normalization')
self.decay = decay
self.running_mean = None
self.running_var = None
self.gamma = None
self.beta = None
self.param_shape = None
self.cache_std = None
self.ca... | 全连接神经网络类 | BatchNormalization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchNormalization:
"""全连接神经网络类"""
def __init__(self, decay=0.9, optimizer='sgd', **k_args):
""":param momentum: 计算全局均值标准差时的冲量"""
<|body_0|>
def build(self, input_shape):
"""根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_001454 | 3,818 | no_license | [
{
"docstring": ":param momentum: 计算全局均值标准差时的冲量",
"name": "__init__",
"signature": "def __init__(self, decay=0.9, optimizer='sgd', **k_args)"
},
{
"docstring": "根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值",
"name": "build",
"signature": "def build(self, input_shape)"
}... | 5 | stack_v2_sparse_classes_30k_train_017870 | Implement the Python class `BatchNormalization` described below.
Class description:
全连接神经网络类
Method signatures and docstrings:
- def __init__(self, decay=0.9, optimizer='sgd', **k_args): :param momentum: 计算全局均值标准差时的冲量
- def build(self, input_shape): 根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值
- def ... | Implement the Python class `BatchNormalization` described below.
Class description:
全连接神经网络类
Method signatures and docstrings:
- def __init__(self, decay=0.9, optimizer='sgd', **k_args): :param momentum: 计算全局均值标准差时的冲量
- def build(self, input_shape): 根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值
- def ... | 9f234a996b99c8e94d8259cd875e69af8ffa9a5c | <|skeleton|>
class BatchNormalization:
"""全连接神经网络类"""
def __init__(self, decay=0.9, optimizer='sgd', **k_args):
""":param momentum: 计算全局均值标准差时的冲量"""
<|body_0|>
def build(self, input_shape):
"""根据input_shape来构建网络模型参数 :param input_shape: 输入形状 :return: 无返回值"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchNormalization:
"""全连接神经网络类"""
def __init__(self, decay=0.9, optimizer='sgd', **k_args):
""":param momentum: 计算全局均值标准差时的冲量"""
super(BatchNormalization, self).__init__(layer_type='batch_normalization')
self.decay = decay
self.running_mean = None
self.running_var... | the_stack_v2_python_sparse | enet/layers/batch_normalization.py | bighead-123/neural_network | train | 0 |
cd3d1bce5b87f875b31bd963f4a1f6bbccc68708 | [
"port = 8773\nconfig = [('ResNetBlockSpace2', {'block_mask': [0]})]\nrlnas = RLNAS(key='lstm', configs=config, server_addr=('', port), is_sync=False, controller_batch_size=1, lstm_num_layers=1, hidden_size=10, temperature=1.0, save_controller=False)\ninput = paddle.static.data(name='input', shape=[None, 3, 32, 32],... | <|body_start_0|>
port = 8773
config = [('ResNetBlockSpace2', {'block_mask': [0]})]
rlnas = RLNAS(key='lstm', configs=config, server_addr=('', port), is_sync=False, controller_batch_size=1, lstm_num_layers=1, hidden_size=10, temperature=1.0, save_controller=False)
input = paddle.static.da... | Test classpaddleslim.nas.RLNAS(key,...) | TestRLNAS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRLNAS:
"""Test classpaddleslim.nas.RLNAS(key,...)"""
def test_RLNAS1(self):
"""classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=("", 8881), is_server=True, is_sync=False, save_controller=None, load_controller=None, **kwargs) :return:"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_001455 | 3,697 | no_license | [
{
"docstring": "classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=(\"\", 8881), is_server=True, is_sync=False, save_controller=None, load_controller=None, **kwargs) :return:",
"name": "test_RLNAS1",
"signature": "def test_RLNAS1(self)"
},
{
"docstring": "is_server=False,is_sync=... | 3 | stack_v2_sparse_classes_30k_train_021081 | Implement the Python class `TestRLNAS` described below.
Class description:
Test classpaddleslim.nas.RLNAS(key,...)
Method signatures and docstrings:
- def test_RLNAS1(self): classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=("", 8881), is_server=True, is_sync=False, save_controller=None, load_control... | Implement the Python class `TestRLNAS` described below.
Class description:
Test classpaddleslim.nas.RLNAS(key,...)
Method signatures and docstrings:
- def test_RLNAS1(self): classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=("", 8881), is_server=True, is_sync=False, save_controller=None, load_control... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestRLNAS:
"""Test classpaddleslim.nas.RLNAS(key,...)"""
def test_RLNAS1(self):
"""classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=("", 8881), is_server=True, is_sync=False, save_controller=None, load_controller=None, **kwargs) :return:"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRLNAS:
"""Test classpaddleslim.nas.RLNAS(key,...)"""
def test_RLNAS1(self):
"""classpaddleslim.nas.RLNAS(key, configs, use_gpu=False, server_addr=("", 8881), is_server=True, is_sync=False, save_controller=None, load_controller=None, **kwargs) :return:"""
port = 8773
config = [... | the_stack_v2_python_sparse | models/PaddleSlim/CI/Slim_CI_all_case/p1_api_case_static/te_api_rl_nas.py | PaddlePaddle/PaddleTest | train | 42 |
a0266aedc1cb8b3ec3e13ebea46c7473f04bf21e | [
"if isinstance(request.auth, ProjectKey):\n return self.respond(status=401)\npaginate_kwargs = {}\ntry:\n environment = self._get_environment_from_request(request, project.organization_id)\nexcept Environment.DoesNotExist:\n queryset = UserReport.objects.none()\nelse:\n queryset = UserReport.objects.fil... | <|body_start_0|>
if isinstance(request.auth, ProjectKey):
return self.respond(status=401)
paginate_kwargs = {}
try:
environment = self._get_environment_from_request(request, project.organization_id)
except Environment.DoesNotExist:
queryset = UserRepor... | ProjectUserReportsEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectUserReportsEndpoint:
def get(self, request: Request, project) -> Response:
"""List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string proj... | stack_v2_sparse_classes_36k_train_001456 | 4,699 | permissive | [
{
"docstring": "List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string project_slug: the slug of the project. :auth: required",
"name": "get",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_test_000477 | Implement the Python class `ProjectUserReportsEndpoint` described below.
Class description:
Implement the ProjectUserReportsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project) -> Response: List a Project's User Feedback `````````````````````````````` Return a list of user feed... | Implement the Python class `ProjectUserReportsEndpoint` described below.
Class description:
Implement the ProjectUserReportsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project) -> Response: List a Project's User Feedback `````````````````````````````` Return a list of user feed... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class ProjectUserReportsEndpoint:
def get(self, request: Request, project) -> Response:
"""List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string proj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectUserReportsEndpoint:
def get(self, request: Request, project) -> Response:
"""List a Project's User Feedback `````````````````````````````` Return a list of user feedback items within this project. :pparam string organization_slug: the slug of the organization. :pparam string project_slug: the ... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_user_reports.py | nagyist/sentry | train | 0 | |
f1c2ca9e9566d40fe18ede187fe45845112b78b3 | [
"self.decor_list = pygame.sprite.Group()\nself.platform_list = pygame.sprite.Group()\nself.enemy_list = pygame.sprite.Group()\nself.exit = pygame.sprite.Group()\nself.obstacles_list = pygame.sprite.Group()\nself.player = player\nself.start = []",
"self.decor_list.update()\nself.platform_list.update()\nself.obstac... | <|body_start_0|>
self.decor_list = pygame.sprite.Group()
self.platform_list = pygame.sprite.Group()
self.enemy_list = pygame.sprite.Group()
self.exit = pygame.sprite.Group()
self.obstacles_list = pygame.sprite.Group()
self.player = player
self.start = []
<|end_bod... | This is a generic super-class used to define a level. Create a child class for each level witj level-specific info. | Level | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Level:
"""This is a generic super-class used to define a level. Create a child class for each level witj level-specific info."""
def __init__(self, player):
"""Pass in a handle to player. Needed for when collide with player"""
<|body_0|>
def update(self, dt):
"""... | stack_v2_sparse_classes_36k_train_001457 | 6,769 | no_license | [
{
"docstring": "Pass in a handle to player. Needed for when collide with player",
"name": "__init__",
"signature": "def __init__(self, player)"
},
{
"docstring": "update everything on this level",
"name": "update",
"signature": "def update(self, dt)"
},
{
"docstring": "draw every... | 4 | stack_v2_sparse_classes_30k_train_008006 | Implement the Python class `Level` described below.
Class description:
This is a generic super-class used to define a level. Create a child class for each level witj level-specific info.
Method signatures and docstrings:
- def __init__(self, player): Pass in a handle to player. Needed for when collide with player
- d... | Implement the Python class `Level` described below.
Class description:
This is a generic super-class used to define a level. Create a child class for each level witj level-specific info.
Method signatures and docstrings:
- def __init__(self, player): Pass in a handle to player. Needed for when collide with player
- d... | a723a0bd26dc9b749a7913f41ff5fec0ceee8af0 | <|skeleton|>
class Level:
"""This is a generic super-class used to define a level. Create a child class for each level witj level-specific info."""
def __init__(self, player):
"""Pass in a handle to player. Needed for when collide with player"""
<|body_0|>
def update(self, dt):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Level:
"""This is a generic super-class used to define a level. Create a child class for each level witj level-specific info."""
def __init__(self, player):
"""Pass in a handle to player. Needed for when collide with player"""
self.decor_list = pygame.sprite.Group()
self.platform_... | the_stack_v2_python_sparse | levels.py | ApyMajul/dynamic-jump-game | train | 0 |
5d07d62b925450da2eb72c4bd3614a8746e59af6 | [
"self._lock = threading.Lock()\nself.traces_per_sec = traces_per_sec\nself.used_this_sec = 0\nself.this_sec = int(time.time())",
"with self._lock:\n now = int(time.time())\n if now != self.this_sec:\n self.used_this_sec = 0\n self.this_sec = now\n if self.used_this_sec >= self.traces_per_se... | <|body_start_0|>
self._lock = threading.Lock()
self.traces_per_sec = traces_per_sec
self.used_this_sec = 0
self.this_sec = int(time.time())
<|end_body_0|>
<|body_start_1|>
with self._lock:
now = int(time.time())
if now != self.this_sec:
se... | Keeps track of the number of sampled segments within a single second. This class is implemented to be thread-safe to achieve accurate sampling. | Reservoir | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reservoir:
"""Keeps track of the number of sampled segments within a single second. This class is implemented to be thread-safe to achieve accurate sampling."""
def __init__(self, traces_per_sec=0):
""":param int traces_per_sec: number of guranteed sampled segments."""
<|body... | stack_v2_sparse_classes_36k_train_001458 | 1,020 | permissive | [
{
"docstring": ":param int traces_per_sec: number of guranteed sampled segments.",
"name": "__init__",
"signature": "def __init__(self, traces_per_sec=0)"
},
{
"docstring": "Returns True if there are segments left within the current second, otherwise return False.",
"name": "take",
"sign... | 2 | stack_v2_sparse_classes_30k_train_020371 | Implement the Python class `Reservoir` described below.
Class description:
Keeps track of the number of sampled segments within a single second. This class is implemented to be thread-safe to achieve accurate sampling.
Method signatures and docstrings:
- def __init__(self, traces_per_sec=0): :param int traces_per_sec... | Implement the Python class `Reservoir` described below.
Class description:
Keeps track of the number of sampled segments within a single second. This class is implemented to be thread-safe to achieve accurate sampling.
Method signatures and docstrings:
- def __init__(self, traces_per_sec=0): :param int traces_per_sec... | 2976b25750d04ebe6dc7d0a3e399444896e82cae | <|skeleton|>
class Reservoir:
"""Keeps track of the number of sampled segments within a single second. This class is implemented to be thread-safe to achieve accurate sampling."""
def __init__(self, traces_per_sec=0):
""":param int traces_per_sec: number of guranteed sampled segments."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reservoir:
"""Keeps track of the number of sampled segments within a single second. This class is implemented to be thread-safe to achieve accurate sampling."""
def __init__(self, traces_per_sec=0):
""":param int traces_per_sec: number of guranteed sampled segments."""
self._lock = thread... | the_stack_v2_python_sparse | aws_xray_sdk/core/sampling/local/reservoir.py | aws/aws-xray-sdk-python | train | 320 |
8da99f0e986222240328b3e58ce5b938f9de8f55 | [
"try:\n input_data = request.data\n input_data['nn_id'] = nnid\n nnManager = NNCommonManager()\n nn_wf_ver_id = nnManager.get_nn_max_ver(nnid) + 1\n input_data['nn_wf_ver_id'] = nn_wf_ver_id\n if nn_wf_ver_id == 1 and input_data['nn_wf_ver_info'] == 'single':\n input_data['active_flag'] = '... | <|body_start_0|>
try:
input_data = request.data
input_data['nn_id'] = nnid
nnManager = NNCommonManager()
nn_wf_ver_id = nnManager.get_nn_max_ver(nnid) + 1
input_data['nn_wf_ver_id'] = nn_wf_ver_id
if nn_wf_ver_id == 1 and input_data['nn_wf_... | CommonNNInfoVersion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonNNInfoVersion:
def post(self, request, nnid):
"""Common Network Version Info Post Method --- # Class Name : CommonNNInfoVersion # Description: Structure : nninfo - <version> - batch version need to define version info under network definition"""
<|body_0|>
def get(self... | stack_v2_sparse_classes_36k_train_001459 | 4,695 | permissive | [
{
"docstring": "Common Network Version Info Post Method --- # Class Name : CommonNNInfoVersion # Description: Structure : nninfo - <version> - batch version need to define version info under network definition",
"name": "post",
"signature": "def post(self, request, nnid)"
},
{
"docstring": "Comm... | 4 | stack_v2_sparse_classes_30k_train_006046 | Implement the Python class `CommonNNInfoVersion` described below.
Class description:
Implement the CommonNNInfoVersion class.
Method signatures and docstrings:
- def post(self, request, nnid): Common Network Version Info Post Method --- # Class Name : CommonNNInfoVersion # Description: Structure : nninfo - <version> ... | Implement the Python class `CommonNNInfoVersion` described below.
Class description:
Implement the CommonNNInfoVersion class.
Method signatures and docstrings:
- def post(self, request, nnid): Common Network Version Info Post Method --- # Class Name : CommonNNInfoVersion # Description: Structure : nninfo - <version> ... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class CommonNNInfoVersion:
def post(self, request, nnid):
"""Common Network Version Info Post Method --- # Class Name : CommonNNInfoVersion # Description: Structure : nninfo - <version> - batch version need to define version info under network definition"""
<|body_0|>
def get(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonNNInfoVersion:
def post(self, request, nnid):
"""Common Network Version Info Post Method --- # Class Name : CommonNNInfoVersion # Description: Structure : nninfo - <version> - batch version need to define version info under network definition"""
try:
input_data = request.data... | the_stack_v2_python_sparse | api/views/common_nninfo_version.py | yurimkoo/tensormsa | train | 1 | |
78edf8a1c884cdff7d1cc499dbb056689aeec205 | [
"object_id = request.GET.get('project_id', None)\nis_view_editing_data = request.GET.get('view_editing_data', False)\npreview_url = u'/termite2/webapp_page/?project_id={}&woid={}'.format(object_id, request.user.id)\nif is_view_editing_data:\n preview_url += '&page_id=preview'\npage_title = pagecreater.get_site_t... | <|body_start_0|>
object_id = request.GET.get('project_id', None)
is_view_editing_data = request.GET.get('view_editing_data', False)
preview_url = u'/termite2/webapp_page/?project_id={}&woid={}'.format(object_id, request.user.id)
if is_view_editing_data:
preview_url += '&page_... | 预览 | TermitePreview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TermitePreview:
"""预览"""
def get(request):
"""预览"""
<|body_0|>
def api_put(request):
"""预览"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
object_id = request.GET.get('project_id', None)
is_view_editing_data = request.GET.get('view_editi... | stack_v2_sparse_classes_36k_train_001460 | 2,848 | no_license | [
{
"docstring": "预览",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "预览",
"name": "api_put",
"signature": "def api_put(request)"
}
] | 2 | null | Implement the Python class `TermitePreview` described below.
Class description:
预览
Method signatures and docstrings:
- def get(request): 预览
- def api_put(request): 预览 | Implement the Python class `TermitePreview` described below.
Class description:
预览
Method signatures and docstrings:
- def get(request): 预览
- def api_put(request): 预览
<|skeleton|>
class TermitePreview:
"""预览"""
def get(request):
"""预览"""
<|body_0|>
def api_put(request):
"""预览"""... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class TermitePreview:
"""预览"""
def get(request):
"""预览"""
<|body_0|>
def api_put(request):
"""预览"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TermitePreview:
"""预览"""
def get(request):
"""预览"""
object_id = request.GET.get('project_id', None)
is_view_editing_data = request.GET.get('view_editing_data', False)
preview_url = u'/termite2/webapp_page/?project_id={}&woid={}'.format(object_id, request.user.id)
i... | the_stack_v2_python_sparse | weapp/termite2/termite_preview.py | chengdg/weizoom | train | 1 |
adb5d2b35caa8bf0337e1d78eae58f7f9714bff9 | [
"actual = testingdoctest.get_divisors(8, [1, 2, 3])\nexpected = [1, 2]\nself.assertEqual(expected, actual)",
"actual = testingdoctest.get_divisors(4, [-2, 0, 2])\nexpected = [-2, 2]\nself.assertEqual(expected, actual)"
] | <|body_start_0|>
actual = testingdoctest.get_divisors(8, [1, 2, 3])
expected = [1, 2]
self.assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
actual = testingdoctest.get_divisors(4, [-2, 0, 2])
expected = [-2, 2]
self.assertEqual(expected, actual)
<|end_body_1... | Example unittest test methods for get_divisors. | TestDivisors | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDivisors:
"""Example unittest test methods for get_divisors."""
def test_divisors_example_1(self):
"""Test get_divisors with 8 and [1, 2, 3]."""
<|body_0|>
def test_divisors_example_2(self):
"""Test get_divisors with 4 and [-2, 0, 2]."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_001461 | 694 | permissive | [
{
"docstring": "Test get_divisors with 8 and [1, 2, 3].",
"name": "test_divisors_example_1",
"signature": "def test_divisors_example_1(self)"
},
{
"docstring": "Test get_divisors with 4 and [-2, 0, 2].",
"name": "test_divisors_example_2",
"signature": "def test_divisors_example_2(self)"
... | 2 | null | Implement the Python class `TestDivisors` described below.
Class description:
Example unittest test methods for get_divisors.
Method signatures and docstrings:
- def test_divisors_example_1(self): Test get_divisors with 8 and [1, 2, 3].
- def test_divisors_example_2(self): Test get_divisors with 4 and [-2, 0, 2]. | Implement the Python class `TestDivisors` described below.
Class description:
Example unittest test methods for get_divisors.
Method signatures and docstrings:
- def test_divisors_example_1(self): Test get_divisors with 8 and [1, 2, 3].
- def test_divisors_example_2(self): Test get_divisors with 4 and [-2, 0, 2].
<|... | fa566235d6b9751f73c69d0d46351a14fcdeb585 | <|skeleton|>
class TestDivisors:
"""Example unittest test methods for get_divisors."""
def test_divisors_example_1(self):
"""Test get_divisors with 8 and [1, 2, 3]."""
<|body_0|>
def test_divisors_example_2(self):
"""Test get_divisors with 4 and [-2, 0, 2]."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDivisors:
"""Example unittest test methods for get_divisors."""
def test_divisors_example_1(self):
"""Test get_divisors with 8 and [1, 2, 3]."""
actual = testingdoctest.get_divisors(8, [1, 2, 3])
expected = [1, 2]
self.assertEqual(expected, actual)
def test_diviso... | the_stack_v2_python_sparse | University-of-Toronto-Crafting-Quality-Code/week2/codes/unittest.py | Mudasirrr/Courses- | train | 2 |
bc4d46732f75a2a555f9885a97c64260cabaf1c7 | [
"root_to_leaf = curr_sum = 0\nwhile root:\n if root.left:\n predecessor = root.left\n steps = 1\n while predecessor.right and predecessor.right is not root:\n predecessor = predecessor.right\n steps += 1\n if not predecessor.right:\n curr_sum = curr_su... | <|body_start_0|>
root_to_leaf = curr_sum = 0
while root:
if root.left:
predecessor = root.left
steps = 1
while predecessor.right and predecessor.right is not root:
predecessor = predecessor.right
steps +=... | RootToLeaf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootToLeaf:
def get_sum(self, root: 'TreeNode') -> int:
"""Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def get__sum(self, root: 'TreeNode') -> int:
"""Approach: Breadth First Search Time Complexity: O(N)... | stack_v2_sparse_classes_36k_train_001462 | 3,287 | no_license | [
{
"docstring": "Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:",
"name": "get_sum",
"signature": "def get_sum(self, root: 'TreeNode') -> int"
},
{
"docstring": "Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(H) :param root:... | 3 | stack_v2_sparse_classes_30k_train_003838 | Implement the Python class `RootToLeaf` described below.
Class description:
Implement the RootToLeaf class.
Method signatures and docstrings:
- def get_sum(self, root: 'TreeNode') -> int: Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def get__sum(self, root: 'TreeNode... | Implement the Python class `RootToLeaf` described below.
Class description:
Implement the RootToLeaf class.
Method signatures and docstrings:
- def get_sum(self, root: 'TreeNode') -> int: Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def get__sum(self, root: 'TreeNode... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class RootToLeaf:
def get_sum(self, root: 'TreeNode') -> int:
"""Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def get__sum(self, root: 'TreeNode') -> int:
"""Approach: Breadth First Search Time Complexity: O(N)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RootToLeaf:
def get_sum(self, root: 'TreeNode') -> int:
"""Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
root_to_leaf = curr_sum = 0
while root:
if root.left:
predecessor = root.left
steps = ... | the_stack_v2_python_sparse | revisited/trees/sum_root_to_leaf_numbers.py | Shiv2157k/leet_code | train | 1 | |
a6cb4bd1c560abaad1a0deaffc2214891c6453fa | [
"super(InputEmbedder, self).__init__()\nself.tf_dim = tf_dim\nself.msa_dim = msa_dim\nself.c_z = c_z\nself.c_m = c_m\nself.linear_tf_z_i = Linear(tf_dim, c_z)\nself.linear_tf_z_j = Linear(tf_dim, c_z)\nself.linear_tf_m = Linear(tf_dim, c_m)\nself.linear_msa_m = Linear(msa_dim, c_m)\nself.relpos_k = relpos_k\nself.n... | <|body_start_0|>
super(InputEmbedder, self).__init__()
self.tf_dim = tf_dim
self.msa_dim = msa_dim
self.c_z = c_z
self.c_m = c_m
self.linear_tf_z_i = Linear(tf_dim, c_z)
self.linear_tf_z_j = Linear(tf_dim, c_z)
self.linear_tf_m = Linear(tf_dim, c_m)
... | Embeds a subset of the input features. Implements Algorithms 3 (InputEmbedder) and 4 (relpos). | InputEmbedder | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputEmbedder:
"""Embeds a subset of the input features. Implements Algorithms 3 (InputEmbedder) and 4 (relpos)."""
def __init__(self, tf_dim: int, msa_dim: int, c_z: int, c_m: int, relpos_k: int, **kwargs):
"""Args: tf_dim: Final dimension of the target features msa_dim: Final dimen... | stack_v2_sparse_classes_36k_train_001463 | 9,577 | permissive | [
{
"docstring": "Args: tf_dim: Final dimension of the target features msa_dim: Final dimension of the MSA features c_z: Pair embedding dimension c_m: MSA embedding dimension relpos_k: Window size used in relative positional encoding",
"name": "__init__",
"signature": "def __init__(self, tf_dim: int, msa_... | 3 | stack_v2_sparse_classes_30k_train_007485 | Implement the Python class `InputEmbedder` described below.
Class description:
Embeds a subset of the input features. Implements Algorithms 3 (InputEmbedder) and 4 (relpos).
Method signatures and docstrings:
- def __init__(self, tf_dim: int, msa_dim: int, c_z: int, c_m: int, relpos_k: int, **kwargs): Args: tf_dim: Fi... | Implement the Python class `InputEmbedder` described below.
Class description:
Embeds a subset of the input features. Implements Algorithms 3 (InputEmbedder) and 4 (relpos).
Method signatures and docstrings:
- def __init__(self, tf_dim: int, msa_dim: int, c_z: int, c_m: int, relpos_k: int, **kwargs): Args: tf_dim: Fi... | 2134cc09b3994b6280e6e3c569dd7d761e4da7a0 | <|skeleton|>
class InputEmbedder:
"""Embeds a subset of the input features. Implements Algorithms 3 (InputEmbedder) and 4 (relpos)."""
def __init__(self, tf_dim: int, msa_dim: int, c_z: int, c_m: int, relpos_k: int, **kwargs):
"""Args: tf_dim: Final dimension of the target features msa_dim: Final dimen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputEmbedder:
"""Embeds a subset of the input features. Implements Algorithms 3 (InputEmbedder) and 4 (relpos)."""
def __init__(self, tf_dim: int, msa_dim: int, c_z: int, c_m: int, relpos_k: int, **kwargs):
"""Args: tf_dim: Final dimension of the target features msa_dim: Final dimension of the M... | the_stack_v2_python_sparse | openfold/model/embedders.py | aqlaboratory/openfold | train | 2,033 |
7c17b7617674cc999674aa9d6d48b12b3684a7ed | [
"stables = []\nfor i in range(len(weight_matrix)):\n if np.all(weight_matrix[i] == 0):\n stables.append(i)\nreturn stables",
"if type(weight_matrix) != np.ndarray:\n initial_state = {k: initial_state[k] for k in weight_matrix.columns}\n weight_matrix = weight_matrix.to_numpy()\nelse:\n warnings... | <|body_start_0|>
stables = []
for i in range(len(weight_matrix)):
if np.all(weight_matrix[i] == 0):
stables.append(i)
return stables
<|end_body_0|>
<|body_start_1|>
if type(weight_matrix) != np.ndarray:
initial_state = {k: initial_state[k] for k i... | The class includes methods for running simulations on top of a defined FCM. Methods: simulate(initial_state: dict, weight_matrix: Union[pd.DataFrame, np.ndarray], transfer: str, inference: str, thresh:float=0.001, iterations:int=50, output_concepts = None, convergence = 'absDiff', **kwargs) | FcmSimulator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FcmSimulator:
"""The class includes methods for running simulations on top of a defined FCM. Methods: simulate(initial_state: dict, weight_matrix: Union[pd.DataFrame, np.ndarray], transfer: str, inference: str, thresh:float=0.001, iterations:int=50, output_concepts = None, convergence = 'absDiff'... | stack_v2_sparse_classes_36k_train_001464 | 6,859 | permissive | [
{
"docstring": "Extract the positions of the stable concepts (concepts with in-degree == 0). Parameters ---------- weight_matrix: numpy.ndarray N*N weight matrix of the FCM. Return ---------- y: numpy.ndarray the positions of the stable concepts (concepts with in-degree == 0)",
"name": "__getStableConcepts"... | 4 | stack_v2_sparse_classes_30k_train_005662 | Implement the Python class `FcmSimulator` described below.
Class description:
The class includes methods for running simulations on top of a defined FCM. Methods: simulate(initial_state: dict, weight_matrix: Union[pd.DataFrame, np.ndarray], transfer: str, inference: str, thresh:float=0.001, iterations:int=50, output_c... | Implement the Python class `FcmSimulator` described below.
Class description:
The class includes methods for running simulations on top of a defined FCM. Methods: simulate(initial_state: dict, weight_matrix: Union[pd.DataFrame, np.ndarray], transfer: str, inference: str, thresh:float=0.001, iterations:int=50, output_c... | 02a7cf246cffd5c2250177e777394a285bf4a03c | <|skeleton|>
class FcmSimulator:
"""The class includes methods for running simulations on top of a defined FCM. Methods: simulate(initial_state: dict, weight_matrix: Union[pd.DataFrame, np.ndarray], transfer: str, inference: str, thresh:float=0.001, iterations:int=50, output_concepts = None, convergence = 'absDiff'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FcmSimulator:
"""The class includes methods for running simulations on top of a defined FCM. Methods: simulate(initial_state: dict, weight_matrix: Union[pd.DataFrame, np.ndarray], transfer: str, inference: str, thresh:float=0.001, iterations:int=50, output_concepts = None, convergence = 'absDiff', **kwargs)""... | the_stack_v2_python_sparse | fcmpy/simulator/simulator.py | ErikSargsyann/FcmBci | train | 0 |
18759b5b56c80fcb8e21d7fb92ec552002ae0ac6 | [
"gym.Wrapper.__init__(self, env)\nself._k = num_frames\nself.img_height = img_height\nself.img_width = img_width\nself.observation_space = gym.spaces.Box(low=0, high=255, shape=(self.img_height, self.img_width, self._k), dtype=np.uint8)",
"gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ncropped_img = gray_i... | <|body_start_0|>
gym.Wrapper.__init__(self, env)
self._k = num_frames
self.img_height = img_height
self.img_width = img_width
self.observation_space = gym.spaces.Box(low=0, high=255, shape=(self.img_height, self.img_width, self._k), dtype=np.uint8)
<|end_body_0|>
<|body_start_1|... | Wrap a gym env, does image processing and frame skipping. | StackFrameEnv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackFrameEnv:
"""Wrap a gym env, does image processing and frame skipping."""
def __init__(self, env, num_frames, img_height, img_width):
"""Initialization."""
<|body_0|>
def _process_image(self, image):
"""Process the image."""
<|body_1|>
def _pad_... | stack_v2_sparse_classes_36k_train_001465 | 2,895 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, env, num_frames, img_height, img_width)"
},
{
"docstring": "Process the image.",
"name": "_process_image",
"signature": "def _process_image(self, image)"
},
{
"docstring": "Pad observation to g... | 5 | null | Implement the Python class `StackFrameEnv` described below.
Class description:
Wrap a gym env, does image processing and frame skipping.
Method signatures and docstrings:
- def __init__(self, env, num_frames, img_height, img_width): Initialization.
- def _process_image(self, image): Process the image.
- def _pad_obse... | Implement the Python class `StackFrameEnv` described below.
Class description:
Wrap a gym env, does image processing and frame skipping.
Method signatures and docstrings:
- def __init__(self, env, num_frames, img_height, img_width): Initialization.
- def _process_image(self, image): Process the image.
- def _pad_obse... | 975a95032ce5b7012d1772c7f1f5cfe606eae839 | <|skeleton|>
class StackFrameEnv:
"""Wrap a gym env, does image processing and frame skipping."""
def __init__(self, env, num_frames, img_height, img_width):
"""Initialization."""
<|body_0|>
def _process_image(self, image):
"""Process the image."""
<|body_1|>
def _pad_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StackFrameEnv:
"""Wrap a gym env, does image processing and frame skipping."""
def __init__(self, env, num_frames, img_height, img_width):
"""Initialization."""
gym.Wrapper.__init__(self, env)
self._k = num_frames
self.img_height = img_height
self.img_width = img_w... | the_stack_v2_python_sparse | blogs/rl-on-gcp/DQN_Breakout/rl_on_gcp/trainer/stack_frame_env.py | GoogleCloudPlatform/training-data-analyst | train | 7,311 |
e94d8964679264d6e5b9a26d94c73a57982fc7bc | [
"new_list = sorted(points, key=lambda point: (point[0], point[1]))\nprint(new_list)\nif len(new_list) <= 0:\n return 0\nend = new_list[0][1]\ncount = 1\nfor i in new_list[1:]:\n if i[0] <= end:\n end = min(end, i[1])\n continue\n else:\n count += 1\n end = i[1]\nreturn count",
... | <|body_start_0|>
new_list = sorted(points, key=lambda point: (point[0], point[1]))
print(new_list)
if len(new_list) <= 0:
return 0
end = new_list[0][1]
count = 1
for i in new_list[1:]:
if i[0] <= end:
end = min(end, i[1])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int 209ms"""
<|body_0|>
def findMinArrowShots_1(self, points):
""":type points: List[List[int]] :rtype: int 122ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_001466 | 2,261 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int 209ms",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int 122ms",
"name": "findMinArrowShots_1",
"signature": "def findMinArrowShots_1(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int 209ms
- def findMinArrowShots_1(self, points): :type points: List[List[int]] :rtype: int 122ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int 209ms
- def findMinArrowShots_1(self, points): :type points: List[List[int]] :rtype: int 122ms
<|s... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int 209ms"""
<|body_0|>
def findMinArrowShots_1(self, points):
""":type points: List[List[int]] :rtype: int 122ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int 209ms"""
new_list = sorted(points, key=lambda point: (point[0], point[1]))
print(new_list)
if len(new_list) <= 0:
return 0
end = new_list[0][1]
count = 1
... | the_stack_v2_python_sparse | Minimum NumberOfArrowsToBurstBalloons_MID_452.py | 953250587/leetcode-python | train | 2 | |
bb07ebdb66d5402b662de1f28720a82e059b8cdc | [
"keys = ['rain_drops', 'drop_length', 'drop_width', 'blurr', 'color']\nif keys[0] in config:\n self.rain_drops = config.get(keys[0])\nif keys[1] in config:\n self.drop_length = config.get(keys[1])\nif keys[2] in config:\n self.drop_width = config.get(keys[2])\nif keys[3] in config:\n self.blurr = config... | <|body_start_0|>
keys = ['rain_drops', 'drop_length', 'drop_width', 'blurr', 'color']
if keys[0] in config:
self.rain_drops = config.get(keys[0])
if keys[1] in config:
self.drop_length = config.get(keys[1])
if keys[2] in config:
self.drop_width = confi... | The weather class is a class used to draw snow and rain onto exsistig pictures Returns: Image.Image: The image returned will have add some noise based on the config file given to the function at instatiaction. | weather | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class weather:
"""The weather class is a class used to draw snow and rain onto exsistig pictures Returns: Image.Image: The image returned will have add some noise based on the config file given to the function at instatiaction."""
def __init__(self, config: dict) -> object:
"""Instatiation... | stack_v2_sparse_classes_36k_train_001467 | 4,132 | no_license | [
{
"docstring": "Instatiation of the class with a config file will overide the default values Args: config (dict): The input should be a dictionary where the key is the name of the variable to change, The value would then be the value refresen by the keyword. keys = ['rain_drops','drop_length','drop_width,'blurr... | 3 | null | Implement the Python class `weather` described below.
Class description:
The weather class is a class used to draw snow and rain onto exsistig pictures Returns: Image.Image: The image returned will have add some noise based on the config file given to the function at instatiaction.
Method signatures and docstrings:
-... | Implement the Python class `weather` described below.
Class description:
The weather class is a class used to draw snow and rain onto exsistig pictures Returns: Image.Image: The image returned will have add some noise based on the config file given to the function at instatiaction.
Method signatures and docstrings:
-... | ba7371cc89b7448782986610b2e531b84fb59481 | <|skeleton|>
class weather:
"""The weather class is a class used to draw snow and rain onto exsistig pictures Returns: Image.Image: The image returned will have add some noise based on the config file given to the function at instatiaction."""
def __init__(self, config: dict) -> object:
"""Instatiation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class weather:
"""The weather class is a class used to draw snow and rain onto exsistig pictures Returns: Image.Image: The image returned will have add some noise based on the config file given to the function at instatiaction."""
def __init__(self, config: dict) -> object:
"""Instatiation of the class... | the_stack_v2_python_sparse | Deprecated_code/weather_old.py | Biksbois/BiksTurePy | train | 0 |
087b92c724b3807537bb10452a42f2bceac59b17 | [
"identifier = f'{ROTKI_EVENT_PREFIX}_{uuid4().hex}'\ntry:\n event_type, event_subtype = GENERIC_TYPE_TO_HISTORY_EVENT_TYPE_MAPPINGS[csv_row['Type']]\nexcept KeyError as e:\n raise UnsupportedCSVEntry(f\"Unsupported entry {csv_row['Type']}. Data: {csv_row}\") from e\nevents: list[HistoryBaseEntry] = []\nasset,... | <|body_start_0|>
identifier = f'{ROTKI_EVENT_PREFIX}_{uuid4().hex}'
try:
event_type, event_subtype = GENERIC_TYPE_TO_HISTORY_EVENT_TYPE_MAPPINGS[csv_row['Type']]
except KeyError as e:
raise UnsupportedCSVEntry(f"Unsupported entry {csv_row['Type']}. Data: {csv_row}") from ... | RotkiGenericEventsImporter | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotkiGenericEventsImporter:
def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None:
"""Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownA... | stack_v2_sparse_classes_36k_train_001468 | 4,809 | permissive | [
{
"docstring": "Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownAsset - KeyError",
"name": "_consume_rotki_event",
"signature": "def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any... | 2 | stack_v2_sparse_classes_30k_train_007897 | Implement the Python class `RotkiGenericEventsImporter` described below.
Class description:
Implement the RotkiGenericEventsImporter class.
Method signatures and docstrings:
- def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None: Consume rotki generic events imp... | Implement the Python class `RotkiGenericEventsImporter` described below.
Class description:
Implement the RotkiGenericEventsImporter class.
Method signatures and docstrings:
- def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None: Consume rotki generic events imp... | 496948458b89afc41458f19d1cba0e971ab67c8b | <|skeleton|>
class RotkiGenericEventsImporter:
def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None:
"""Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownA... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RotkiGenericEventsImporter:
def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None:
"""Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownAsset - KeyErro... | the_stack_v2_python_sparse | rotkehlchen/data_import/importers/rotki_events.py | LefterisJP/rotkehlchen | train | 0 | |
c8fa7be1274593ffe2b7bd288dbee2773b37dfdf | [
"assert self.algo_config.critic.distributional.enabled\ncritic_class = ValueNets.DistributionalActionValueNetwork\ncritic_args = dict(obs_shapes=self.obs_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.critic.layer_dims, value_bounds=self.algo_config.critic.value_bounds, num_atoms=self.algo_config.criti... | <|body_start_0|>
assert self.algo_config.critic.distributional.enabled
critic_class = ValueNets.DistributionalActionValueNetwork
critic_args = dict(obs_shapes=self.obs_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.critic.layer_dims, value_bounds=self.algo_config.critic.value_bounds... | BCQ with distributional critics. Distributional critics output categorical distributions over a discrete set of values instead of expected returns. Some parts of this implementation were adapted from ACME (https://github.com/deepmind/acme). | BCQ_Distributional | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCQ_Distributional:
"""BCQ with distributional critics. Distributional critics output categorical distributions over a discrete set of values instead of expected returns. Some parts of this implementation were adapted from ACME (https://github.com/deepmind/acme)."""
def _create_critics(self)... | stack_v2_sparse_classes_36k_train_001469 | 44,453 | permissive | [
{
"docstring": "Called in @_create_networks to make critic networks.",
"name": "_create_critics",
"signature": "def _create_critics(self)"
},
{
"docstring": "Helper function to get target values for training Q-function with TD-loss. Update from superclass to account for distributional value func... | 3 | null | Implement the Python class `BCQ_Distributional` described below.
Class description:
BCQ with distributional critics. Distributional critics output categorical distributions over a discrete set of values instead of expected returns. Some parts of this implementation were adapted from ACME (https://github.com/deepmind/a... | Implement the Python class `BCQ_Distributional` described below.
Class description:
BCQ with distributional critics. Distributional critics output categorical distributions over a discrete set of values instead of expected returns. Some parts of this implementation were adapted from ACME (https://github.com/deepmind/a... | 2804dd97dd1625ec861298a35cb677129d3bfacc | <|skeleton|>
class BCQ_Distributional:
"""BCQ with distributional critics. Distributional critics output categorical distributions over a discrete set of values instead of expected returns. Some parts of this implementation were adapted from ACME (https://github.com/deepmind/acme)."""
def _create_critics(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BCQ_Distributional:
"""BCQ with distributional critics. Distributional critics output categorical distributions over a discrete set of values instead of expected returns. Some parts of this implementation were adapted from ACME (https://github.com/deepmind/acme)."""
def _create_critics(self):
"""... | the_stack_v2_python_sparse | robomimic/algo/bcq.py | sohams-MASS/robomimic | train | 0 |
74f615ec2c283c321e8402c2c06786ff109a796f | [
"kwargs['max_digits'] = kwargs.get('max_digits', 19)\nself.decimal_places = kwargs['decimal_places'] = kwargs.get('decimal_places', 6)\nkwargs['required'] = kwargs.get('required', False)\nsuper().__init__(*args, **kwargs)",
"amount = super(DecimalField, self).get_value(data)\nif len(str(amount).strip()) == 0:\n ... | <|body_start_0|>
kwargs['max_digits'] = kwargs.get('max_digits', 19)
self.decimal_places = kwargs['decimal_places'] = kwargs.get('decimal_places', 6)
kwargs['required'] = kwargs.get('required', False)
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
amount = sup... | Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py | InvenTreeMoneySerializer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvenTreeMoneySerializer:
"""Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py"""
def __init__(self, *args, **kwargs):
"""Override d... | stack_v2_sparse_classes_36k_train_001470 | 22,975 | permissive | [
{
"docstring": "Override default values.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Test that the returned amount is a valid Decimal.",
"name": "get_value",
"signature": "def get_value(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008462 | Implement the Python class `InvenTreeMoneySerializer` described below.
Class description:
Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py
Method signatures and docs... | Implement the Python class `InvenTreeMoneySerializer` described below.
Class description:
Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py
Method signatures and docs... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class InvenTreeMoneySerializer:
"""Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py"""
def __init__(self, *args, **kwargs):
"""Override d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvenTreeMoneySerializer:
"""Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py"""
def __init__(self, *args, **kwargs):
"""Override default values... | the_stack_v2_python_sparse | InvenTree/InvenTree/serializers.py | inventree/InvenTree | train | 3,077 |
776083780eec9b93713f51c6a6afa7feb62182b5 | [
"res, wl = ([], len(words[0]))\nfor i in range(wl):\n end = begin = i\n pStillNeed = collections.Counter(words)\n counter = len(pStillNeed)\n while end < len(s):\n w = s[end:end + wl]\n pStillNeed[w] -= 1\n if pStillNeed[w] == 0:\n counter -= 1\n end += wl\n ... | <|body_start_0|>
res, wl = ([], len(words[0]))
for i in range(wl):
end = begin = i
pStillNeed = collections.Counter(words)
counter = len(pStillNeed)
while end < len(s):
w = s[end:end + wl]
pStillNeed[w] -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubstring(self, s, words):
""":type s: str :type words: List[str] :rtype: List[int]"""
<|body_0|>
def findSubstringPart2(self, s, words):
""":type s: str :type words: List[str] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_001471 | 2,948 | no_license | [
{
"docstring": ":type s: str :type words: List[str] :rtype: List[int]",
"name": "findSubstring",
"signature": "def findSubstring(self, s, words)"
},
{
"docstring": ":type s: str :type words: List[str] :rtype: List[int]",
"name": "findSubstringPart2",
"signature": "def findSubstringPart2(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstring(self, s, words): :type s: str :type words: List[str] :rtype: List[int]
- def findSubstringPart2(self, s, words): :type s: str :type words: List[str] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstring(self, s, words): :type s: str :type words: List[str] :rtype: List[int]
- def findSubstringPart2(self, s, words): :type s: str :type words: List[str] :rtype: Lis... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def findSubstring(self, s, words):
""":type s: str :type words: List[str] :rtype: List[int]"""
<|body_0|>
def findSubstringPart2(self, s, words):
""":type s: str :type words: List[str] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findSubstring(self, s, words):
""":type s: str :type words: List[str] :rtype: List[int]"""
res, wl = ([], len(words[0]))
for i in range(wl):
end = begin = i
pStillNeed = collections.Counter(words)
counter = len(pStillNeed)
w... | the_stack_v2_python_sparse | substring/substring_w_concatenation_of_all_words.py | gerrycfchang/leetcode-python | train | 2 | |
f267d70559f00a7bdbe13c7c0b5d754ec8fd3a0b | [
"try:\n bucket_id = cls.__get_bucket_id(doc_type)\n url = cls.GET_DOC_URL.format(bucket_id=bucket_id, name=urllib.parse.quote(name, safe=''))\n token = GoogleStorageTokenService.get_token()\n current_app.logger.info('Fetching doc with GET ' + url)\n return cls.__call_api(HTTP_GET, url, token)\nexcept... | <|body_start_0|>
try:
bucket_id = cls.__get_bucket_id(doc_type)
url = cls.GET_DOC_URL.format(bucket_id=bucket_id, name=urllib.parse.quote(name, safe=''))
token = GoogleStorageTokenService.get_token()
current_app.logger.info('Fetching doc with GET ' + url)
... | Google Cloud Storage implmentation. Maintain document storage with Google Cloud Storage API calls. | GoogleStorageService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleStorageService:
"""Google Cloud Storage implmentation. Maintain document storage with Google Cloud Storage API calls."""
def get_document(cls, name: str, doc_type: str=None):
"""Fetch the uniquely named document from cloud storage as binary data."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_001472 | 6,790 | permissive | [
{
"docstring": "Fetch the uniquely named document from cloud storage as binary data.",
"name": "get_document",
"signature": "def get_document(cls, name: str, doc_type: str=None)"
},
{
"docstring": "Delete the uniquely named document from cloud storage (unit testing only).",
"name": "delete_d... | 5 | null | Implement the Python class `GoogleStorageService` described below.
Class description:
Google Cloud Storage implmentation. Maintain document storage with Google Cloud Storage API calls.
Method signatures and docstrings:
- def get_document(cls, name: str, doc_type: str=None): Fetch the uniquely named document from clou... | Implement the Python class `GoogleStorageService` described below.
Class description:
Google Cloud Storage implmentation. Maintain document storage with Google Cloud Storage API calls.
Method signatures and docstrings:
- def get_document(cls, name: str, doc_type: str=None): Fetch the uniquely named document from clou... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class GoogleStorageService:
"""Google Cloud Storage implmentation. Maintain document storage with Google Cloud Storage API calls."""
def get_document(cls, name: str, doc_type: str=None):
"""Fetch the uniquely named document from cloud storage as binary data."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleStorageService:
"""Google Cloud Storage implmentation. Maintain document storage with Google Cloud Storage API calls."""
def get_document(cls, name: str, doc_type: str=None):
"""Fetch the uniquely named document from cloud storage as binary data."""
try:
bucket_id = cls.... | the_stack_v2_python_sparse | ppr-api/src/ppr_api/callback/document_storage/storage_service.py | bcgov/ppr | train | 4 |
1aa546bfbee14f271b80a1ae5b130d8b41aa38a7 | [
"InputFinder.__init__(self, **kwargs)\nself.input_finder_class = input_finder_class\nself.input_finder_params = input_finder_params",
"if not isinstance(self.input_finder_class, list):\n self.input_finder_class = [self.input_finder_class]\nif not isinstance(self.input_finder_params, list):\n self.input_find... | <|body_start_0|>
InputFinder.__init__(self, **kwargs)
self.input_finder_class = input_finder_class
self.input_finder_params = input_finder_params
<|end_body_0|>
<|body_start_1|>
if not isinstance(self.input_finder_class, list):
self.input_finder_class = [self.input_finder_cl... | Pipeline Input Finder It execute in sequence a list of input finder heuristics where the result of previous heuristic is passed as an input to the next heuristic Attributes: input_finder_class (Union[class, list]): list of input finder classes input_finder_params (Union[dict, list]): list of initialization parameters f... | PipelineInputFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineInputFinder:
"""Pipeline Input Finder It execute in sequence a list of input finder heuristics where the result of previous heuristic is passed as an input to the next heuristic Attributes: input_finder_class (Union[class, list]): list of input finder classes input_finder_params (Union[di... | stack_v2_sparse_classes_36k_train_001473 | 2,264 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, input_finder_class, input_finder_params=None, **kwargs)"
},
{
"docstring": "Execute the heuristic Returns: list(GAIndividual): list of encoded control inputs",
"name": "solve",
"signature": "def solve(s... | 2 | stack_v2_sparse_classes_30k_train_005902 | Implement the Python class `PipelineInputFinder` described below.
Class description:
Pipeline Input Finder It execute in sequence a list of input finder heuristics where the result of previous heuristic is passed as an input to the next heuristic Attributes: input_finder_class (Union[class, list]): list of input finde... | Implement the Python class `PipelineInputFinder` described below.
Class description:
Pipeline Input Finder It execute in sequence a list of input finder heuristics where the result of previous heuristic is passed as an input to the next heuristic Attributes: input_finder_class (Union[class, list]): list of input finde... | ce7045918f60c92ce1ed5ca4389b969bf28e6b82 | <|skeleton|>
class PipelineInputFinder:
"""Pipeline Input Finder It execute in sequence a list of input finder heuristics where the result of previous heuristic is passed as an input to the next heuristic Attributes: input_finder_class (Union[class, list]): list of input finder classes input_finder_params (Union[di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelineInputFinder:
"""Pipeline Input Finder It execute in sequence a list of input finder heuristics where the result of previous heuristic is passed as an input to the next heuristic Attributes: input_finder_class (Union[class, list]): list of input finder classes input_finder_params (Union[dict, list]): l... | the_stack_v2_python_sparse | sp/system_controller/optimizer/llc/input_finder/pipeline.py | adysonmaia/phd-sp-dynamic | train | 0 |
aeba5a9277f9fdf5ffc5e1c39baaee92f72ee04c | [
"authorization_response = request.build_absolute_uri()\ntry:\n state = request.GET['state']\n creds = finish_authorize(state=state, request_url=authorization_response)\n Credentials.objects.create_credentials(email=base64_decode(state), **creds)\n return HttpResponse('<p>You are successfully logged in. ... | <|body_start_0|>
authorization_response = request.build_absolute_uri()
try:
state = request.GET['state']
creds = finish_authorize(state=state, request_url=authorization_response)
Credentials.objects.create_credentials(email=base64_decode(state), **creds)
r... | GmailAuthView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GmailAuthView:
def get(self, request, *args, **kwargs):
"""This is for google auth redirect. Returns just 200 code if authentication was successful."""
<|body_0|>
def post(self, request: Request, *args, **kwargs) -> Response:
"""Sends to client authentication url and... | stack_v2_sparse_classes_36k_train_001474 | 3,757 | no_license | [
{
"docstring": "This is for google auth redirect. Returns just 200 code if authentication was successful.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Sends to client authentication url and state Args: kwargs: Additional arguments passed through get ... | 2 | null | Implement the Python class `GmailAuthView` described below.
Class description:
Implement the GmailAuthView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): This is for google auth redirect. Returns just 200 code if authentication was successful.
- def post(self, request: Request, *a... | Implement the Python class `GmailAuthView` described below.
Class description:
Implement the GmailAuthView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): This is for google auth redirect. Returns just 200 code if authentication was successful.
- def post(self, request: Request, *a... | bab909324aa2e4c1c8fff72093d3fcf44aaf4963 | <|skeleton|>
class GmailAuthView:
def get(self, request, *args, **kwargs):
"""This is for google auth redirect. Returns just 200 code if authentication was successful."""
<|body_0|>
def post(self, request: Request, *args, **kwargs) -> Response:
"""Sends to client authentication url and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GmailAuthView:
def get(self, request, *args, **kwargs):
"""This is for google auth redirect. Returns just 200 code if authentication was successful."""
authorization_response = request.build_absolute_uri()
try:
state = request.GET['state']
creds = finish_authori... | the_stack_v2_python_sparse | email_app/views/gmail_token/gmail_auth_view.py | vovapasko/crm | train | 0 | |
e7fc3bf98817e887a33b26ee40f1af7548ec52da | [
"self.no_components = no_components\nself.learning_rate = float(learning_rate)\nself.alpha = float(alpha)\nself.max_count = float(max_count)\nself.max_loss = max_loss\nself.word_vectors = None\nself.word_biases = None\nself.vectors_sum_gradients = None\nself.biases_sum_gradients = None\nself.dictionary = None\nself... | <|body_start_0|>
self.no_components = no_components
self.learning_rate = float(learning_rate)
self.alpha = float(alpha)
self.max_count = float(max_count)
self.max_loss = max_loss
self.word_vectors = None
self.word_biases = None
self.vectors_sum_gradients =... | Class for estimating GloVe word embeddings using the corpus coocurrence matrix. | Glove | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Glove:
"""Class for estimating GloVe word embeddings using the corpus coocurrence matrix."""
def __init__(self, no_components=100, learning_rate=0.05, alpha=0.75, max_count=100, max_loss=10.0, random_state=None):
"""Parameters: - int no_components: number of latent dimensions - float... | stack_v2_sparse_classes_36k_train_001475 | 5,671 | permissive | [
{
"docstring": "Parameters: - int no_components: number of latent dimensions - float learning_rate: learning rate for SGD estimation. - float alpha, float max_count: parameters for the weighting function (see the paper). - float max_loss: the maximum absolute value of calculated gradient for any single co-occur... | 4 | stack_v2_sparse_classes_30k_train_011656 | Implement the Python class `Glove` described below.
Class description:
Class for estimating GloVe word embeddings using the corpus coocurrence matrix.
Method signatures and docstrings:
- def __init__(self, no_components=100, learning_rate=0.05, alpha=0.75, max_count=100, max_loss=10.0, random_state=None): Parameters:... | Implement the Python class `Glove` described below.
Class description:
Class for estimating GloVe word embeddings using the corpus coocurrence matrix.
Method signatures and docstrings:
- def __init__(self, no_components=100, learning_rate=0.05, alpha=0.75, max_count=100, max_loss=10.0, random_state=None): Parameters:... | 3e2b08677a9b6b1a2fc3ebd12b79a03d10a2f15f | <|skeleton|>
class Glove:
"""Class for estimating GloVe word embeddings using the corpus coocurrence matrix."""
def __init__(self, no_components=100, learning_rate=0.05, alpha=0.75, max_count=100, max_loss=10.0, random_state=None):
"""Parameters: - int no_components: number of latent dimensions - float... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Glove:
"""Class for estimating GloVe word embeddings using the corpus coocurrence matrix."""
def __init__(self, no_components=100, learning_rate=0.05, alpha=0.75, max_count=100, max_loss=10.0, random_state=None):
"""Parameters: - int no_components: number of latent dimensions - float learning_rat... | the_stack_v2_python_sparse | Assignments/hw8/glove/glove.py | spacemanidol/CLMS575S19 | train | 0 |
3af3be15db5e294e8d817fd14e2c6425fc9aadf9 | [
"res = super(PayslipOverTime, self).get_inputs(contracts, date_to, date_from)\novertime_type = self.env.ref('sim_ohrms_overtime.hr_salary_rule_overtime')\ncontract = self.contract_id\novertime_id = self.env['hr.overtime'].search([('employee_id', '=', self.employee_id.id), ('contract_id', '=', self.contract_id.id), ... | <|body_start_0|>
res = super(PayslipOverTime, self).get_inputs(contracts, date_to, date_from)
overtime_type = self.env.ref('sim_ohrms_overtime.hr_salary_rule_overtime')
contract = self.contract_id
overtime_id = self.env['hr.overtime'].search([('employee_id', '=', self.employee_id.id), ('... | PayslipOverTime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayslipOverTime:
def get_inputs(self, contracts, date_from, date_to):
"""function used for writing overtime record in payslip input tree."""
<|body_0|>
def action_payslip_done(self):
"""function used for marking paid overtime request."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_001476 | 1,662 | no_license | [
{
"docstring": "function used for writing overtime record in payslip input tree.",
"name": "get_inputs",
"signature": "def get_inputs(self, contracts, date_from, date_to)"
},
{
"docstring": "function used for marking paid overtime request.",
"name": "action_payslip_done",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_009173 | Implement the Python class `PayslipOverTime` described below.
Class description:
Implement the PayslipOverTime class.
Method signatures and docstrings:
- def get_inputs(self, contracts, date_from, date_to): function used for writing overtime record in payslip input tree.
- def action_payslip_done(self): function used... | Implement the Python class `PayslipOverTime` described below.
Class description:
Implement the PayslipOverTime class.
Method signatures and docstrings:
- def get_inputs(self, contracts, date_from, date_to): function used for writing overtime record in payslip input tree.
- def action_payslip_done(self): function used... | 2bdcfca9febe2fc5e72b9644ef92584e4029bf71 | <|skeleton|>
class PayslipOverTime:
def get_inputs(self, contracts, date_from, date_to):
"""function used for writing overtime record in payslip input tree."""
<|body_0|>
def action_payslip_done(self):
"""function used for marking paid overtime request."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PayslipOverTime:
def get_inputs(self, contracts, date_from, date_to):
"""function used for writing overtime record in payslip input tree."""
res = super(PayslipOverTime, self).get_inputs(contracts, date_to, date_from)
overtime_type = self.env.ref('sim_ohrms_overtime.hr_salary_rule_over... | the_stack_v2_python_sparse | customaddons/sim_ohrms_overtime/models/hr_payslip.py | hiepmagenest/democodeluck | train | 0 | |
790514294593b3726bef80bb86fba522e6cf7fc9 | [
"def non_negative_power(x, n):\n if n == 0:\n return 1\n elif n == 1:\n return x\n else:\n res = 1\n for _ in range(n):\n res *= x\n return res\nif x == 0:\n return 0\nif n < 0:\n return 1 / non_negative_power(x, -n)\nelse:\n return non_negative_power(... | <|body_start_0|>
def non_negative_power(x, n):
if n == 0:
return 1
elif n == 1:
return x
else:
res = 1
for _ in range(n):
res *= x
return res
if x == 0:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow1(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow2(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
def myPow3(self, x, n):
""":type x: float :type n: int :rtype: float""... | stack_v2_sparse_classes_36k_train_001477 | 1,590 | no_license | [
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow1",
"signature": "def myPow1(self, x, n)"
},
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow2",
"signature": "def myPow2(self, x, n)"
},
{
"docstring": ":type x: float :type n: in... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow1(self, x, n): :type x: float :type n: int :rtype: float
- def myPow2(self, x, n): :type x: float :type n: int :rtype: float
- def myPow3(self, x, n): :type x: float :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow1(self, x, n): :type x: float :type n: int :rtype: float
- def myPow2(self, x, n): :type x: float :type n: int :rtype: float
- def myPow3(self, x, n): :type x: float :ty... | 8fb6c1d947046dabd58ff8482b2c0b41f39aa988 | <|skeleton|>
class Solution:
def myPow1(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow2(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
def myPow3(self, x, n):
""":type x: float :type n: int :rtype: float""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myPow1(self, x, n):
""":type x: float :type n: int :rtype: float"""
def non_negative_power(x, n):
if n == 0:
return 1
elif n == 1:
return x
else:
res = 1
for _ in range(n):
... | the_stack_v2_python_sparse | Python/LeetCode/50.py | czx94/Algorithms-Collection | train | 2 | |
cff578e7ea29c48d32f4e36d2093366e13469ecd | [
"params = get_params(locals())\nraw_result = await self.api_request('get', params)\nif return_raw_response:\n return raw_result\nresult = StatsGetResponse(**raw_result)\nreturn result",
"params = get_params(locals())\nraw_result = await self.api_request('getPostReach', params)\nif return_raw_response:\n ret... | <|body_start_0|>
params = get_params(locals())
raw_result = await self.api_request('get', params)
if return_raw_response:
return raw_result
result = StatsGetResponse(**raw_result)
return result
<|end_body_0|>
<|body_start_1|>
params = get_params(locals())
... | Stats | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stats:
async def get(self, return_raw_response: bool=False, group_id: typing.Optional[int]=None, app_id: typing.Optional[int]=None, timestamp_from: typing.Optional[int]=None, timestamp_to: typing.Optional[int]=None, interval: typing.Optional[str]=None, intervals_count: typing.Optional[int]=None,... | stack_v2_sparse_classes_36k_train_001478 | 2,511 | permissive | [
{
"docstring": ":param group_id: - Community ID. :param app_id: - Application ID. :param timestamp_from: :param timestamp_to: :param interval: :param intervals_count: :param filters: :param stats_groups: :param extended: :param return_raw_response: - return result at dict :return:",
"name": "get",
"sign... | 3 | stack_v2_sparse_classes_30k_train_017237 | Implement the Python class `Stats` described below.
Class description:
Implement the Stats class.
Method signatures and docstrings:
- async def get(self, return_raw_response: bool=False, group_id: typing.Optional[int]=None, app_id: typing.Optional[int]=None, timestamp_from: typing.Optional[int]=None, timestamp_to: ty... | Implement the Python class `Stats` described below.
Class description:
Implement the Stats class.
Method signatures and docstrings:
- async def get(self, return_raw_response: bool=False, group_id: typing.Optional[int]=None, app_id: typing.Optional[int]=None, timestamp_from: typing.Optional[int]=None, timestamp_to: ty... | d88311a680e52faf04f3a18f9c5b381ee9e94a8f | <|skeleton|>
class Stats:
async def get(self, return_raw_response: bool=False, group_id: typing.Optional[int]=None, app_id: typing.Optional[int]=None, timestamp_from: typing.Optional[int]=None, timestamp_to: typing.Optional[int]=None, interval: typing.Optional[str]=None, intervals_count: typing.Optional[int]=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stats:
async def get(self, return_raw_response: bool=False, group_id: typing.Optional[int]=None, app_id: typing.Optional[int]=None, timestamp_from: typing.Optional[int]=None, timestamp_to: typing.Optional[int]=None, interval: typing.Optional[str]=None, intervals_count: typing.Optional[int]=None, filters: typi... | the_stack_v2_python_sparse | vkwave/api/methods/stats.py | prog1ckg/vkwave | train | 0 | |
44c679df3ca1b985d206603b1192f1d3e55c3762 | [
"if self.count == 0 and (not self.allow_empty_first_page):\n return 0\nhits = min(self.max_result_window, max(1, self.count - self.orphans))\nreturn int(ceil(hits / float(self.per_page)))",
"try:\n number = int(number)\nexcept (TypeError, ValueError):\n raise PageNotAnInteger('That page number is not an ... | <|body_start_0|>
if self.count == 0 and (not self.allow_empty_first_page):
return 0
hits = min(self.max_result_window, max(1, self.count - self.orphans))
return int(ceil(hits / float(self.per_page)))
<|end_body_0|>
<|body_start_1|>
try:
number = int(number)
... | A better paginator for search results The normal Paginator does a .count() query and then a slice. Since ES results contain the total number of results, we can take an optimistic slice and then adjust the count. | ESPaginator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPaginator:
"""A better paginator for search results The normal Paginator does a .count() query and then a slice. Since ES results contain the total number of results, we can take an optimistic slice and then adjust the count."""
def num_pages(self):
"""Returns the total number of p... | stack_v2_sparse_classes_36k_train_001479 | 3,219 | permissive | [
{
"docstring": "Returns the total number of pages.",
"name": "num_pages",
"signature": "def num_pages(self)"
},
{
"docstring": "Validates the given 1-based page number. This class overrides the default behavior and ignores the upper bound.",
"name": "validate_number",
"signature": "def v... | 3 | stack_v2_sparse_classes_30k_train_005479 | Implement the Python class `ESPaginator` described below.
Class description:
A better paginator for search results The normal Paginator does a .count() query and then a slice. Since ES results contain the total number of results, we can take an optimistic slice and then adjust the count.
Method signatures and docstri... | Implement the Python class `ESPaginator` described below.
Class description:
A better paginator for search results The normal Paginator does a .count() query and then a slice. Since ES results contain the total number of results, we can take an optimistic slice and then adjust the count.
Method signatures and docstri... | e0f043bca8a64478e2ba62f877c9dc28620be22f | <|skeleton|>
class ESPaginator:
"""A better paginator for search results The normal Paginator does a .count() query and then a slice. Since ES results contain the total number of results, we can take an optimistic slice and then adjust the count."""
def num_pages(self):
"""Returns the total number of p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESPaginator:
"""A better paginator for search results The normal Paginator does a .count() query and then a slice. Since ES results contain the total number of results, we can take an optimistic slice and then adjust the count."""
def num_pages(self):
"""Returns the total number of pages."""
... | the_stack_v2_python_sparse | src/olympia/amo/pagination.py | mozilla/addons-server | train | 920 |
44b40b5fe641d3e6b46842f191837bd751edbdff | [
"self.key = key\nself.value = value\nself.prev = prev\nself.next = next",
"if self.prev:\n self.prev.next = self.next\nif self.next:\n self.next.prev = self.prev"
] | <|body_start_0|>
self.key = key
self.value = value
self.prev = prev
self.next = next
<|end_body_0|>
<|body_start_1|>
if self.prev:
self.prev.next = self.next
if self.next:
self.next.prev = self.prev
<|end_body_1|>
| CacheNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CacheNode:
def __init__(self, key, value, prev=None, next=None):
"""A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed by key. :param prev [CacheNode] : Previous CacheNode in list, defaults to None :param next [CacheNo... | stack_v2_sparse_classes_36k_train_001480 | 4,360 | permissive | [
{
"docstring": "A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed by key. :param prev [CacheNode] : Previous CacheNode in list, defaults to None :param next [CacheNode] : Next CacheNode in list, defaults to None",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_test_000879 | Implement the Python class `CacheNode` described below.
Class description:
Implement the CacheNode class.
Method signatures and docstrings:
- def __init__(self, key, value, prev=None, next=None): A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed b... | Implement the Python class `CacheNode` described below.
Class description:
Implement the CacheNode class.
Method signatures and docstrings:
- def __init__(self, key, value, prev=None, next=None): A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed b... | b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82 | <|skeleton|>
class CacheNode:
def __init__(self, key, value, prev=None, next=None):
"""A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed by key. :param prev [CacheNode] : Previous CacheNode in list, defaults to None :param next [CacheNo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CacheNode:
def __init__(self, key, value, prev=None, next=None):
"""A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed by key. :param prev [CacheNode] : Previous CacheNode in list, defaults to None :param next [CacheNode] : Next Cac... | the_stack_v2_python_sparse | cs/lambda_cs/03_data_structures/lru_cache/lru_cache_cachenode.py | tobias-fyi/vela | train | 0 | |
c79eaba62753bbf2bc3d7987487e28f92c8d4694 | [
"super().__init__()\nif fcn != 0:\n assert int(log(fcn, 2)) + 1 <= n, 'FCN must be representable for {} bits'.format(n)\nself.fcn = fcn\nself.n = n\nself.size = self.n\nreturn",
"if self.n != 0:\n return self.zfill('{:0b}'.format(self.fcn), self.n)\nelse:\n return ''",
"if self.n != 0:\n text_size =... | <|body_start_0|>
super().__init__()
if fcn != 0:
assert int(log(fcn, 2)) + 1 <= n, 'FCN must be representable for {} bits'.format(n)
self.fcn = fcn
self.n = n
self.size = self.n
return
<|end_body_0|>
<|body_start_1|>
if self.n != 0:
return... | Fragmented Compressed Number (FCN) Class Attributes ---------- fcn : int FCN value as an integer n : int Size of FCN in bits (given according to rule_id) | FragmentedCompressedNumber | [
"LicenseRef-scancode-ietf-trust",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FragmentedCompressedNumber:
"""Fragmented Compressed Number (FCN) Class Attributes ---------- fcn : int FCN value as an integer n : int Size of FCN in bits (given according to rule_id)"""
def __init__(self, fcn, n):
"""W constructor Parameters ---------- fcn : int FCN value as a bool... | stack_v2_sparse_classes_36k_train_001481 | 2,056 | permissive | [
{
"docstring": "W constructor Parameters ---------- fcn : int FCN value as a boolean list n : int Size of FCN in bits (given according to rule_id)",
"name": "__init__",
"signature": "def __init__(self, fcn, n)"
},
{
"docstring": "Returns the bits representation of the SCHC Header Returns -------... | 3 | stack_v2_sparse_classes_30k_train_010458 | Implement the Python class `FragmentedCompressedNumber` described below.
Class description:
Fragmented Compressed Number (FCN) Class Attributes ---------- fcn : int FCN value as an integer n : int Size of FCN in bits (given according to rule_id)
Method signatures and docstrings:
- def __init__(self, fcn, n): W constr... | Implement the Python class `FragmentedCompressedNumber` described below.
Class description:
Fragmented Compressed Number (FCN) Class Attributes ---------- fcn : int FCN value as an integer n : int Size of FCN in bits (given according to rule_id)
Method signatures and docstrings:
- def __init__(self, fcn, n): W constr... | 2b1d9ed7d7c9857cbb362bdee5c77f7234838ddd | <|skeleton|>
class FragmentedCompressedNumber:
"""Fragmented Compressed Number (FCN) Class Attributes ---------- fcn : int FCN value as an integer n : int Size of FCN in bits (given according to rule_id)"""
def __init__(self, fcn, n):
"""W constructor Parameters ---------- fcn : int FCN value as a bool... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FragmentedCompressedNumber:
"""Fragmented Compressed Number (FCN) Class Attributes ---------- fcn : int FCN value as an integer n : int Size of FCN in bits (given according to rule_id)"""
def __init__(self, fcn, n):
"""W constructor Parameters ---------- fcn : int FCN value as a boolean list n : ... | the_stack_v2_python_sparse | fragmentation_layer/code/schc_messages/schc_header/fcn.py | CristianWulfing/PySCHC | train | 0 |
41350bd449cceb764109c9b0b8f6839022b8520e | [
"count = [0, 0, 0]\nfor ele in nums:\n assert 0 <= ele <= 2\n count[ele] += 1\nindex = 0\nfor _ in range(0, count[0]):\n nums[index] = 0\n index += 1\nfor _ in range(0, count[1]):\n nums[index] = 1\n index += 1\nfor _ in range(0, count[2]):\n nums[index] = 2\n index += 1",
"zero, i, two = ... | <|body_start_0|>
count = [0, 0, 0]
for ele in nums:
assert 0 <= ele <= 2
count[ele] += 1
index = 0
for _ in range(0, count[0]):
nums[index] = 0
index += 1
for _ in range(0, count[1]):
nums[index] = 1
index +=... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors_2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""... | stack_v2_sparse_classes_36k_train_001482 | 1,844 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "so... | 2 | stack_v2_sparse_classes_30k_train_006897 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors_2(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors_2(self, nums): :type nums: List[int] :rtype:... | c06f3c86703b5ff7fd3e91e278ac69887a61eb66 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors_2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
count = [0, 0, 0]
for ele in nums:
assert 0 <= ele <= 2
count[ele] += 1
index = 0
for _ in range(0, count[0]):
... | the_stack_v2_python_sparse | 03-array/leetcode_75.py | xiaolinzi-xl/Algorithm-Interview-Study | train | 1 | |
3379efc5c3f11745f1e988ebfe02233a3aa0fed9 | [
"likeable = Likeable.query.filter(and_(Likeable.user_id == user_id, Likeable.likeable_type == likeable_type, Likeable.likeable_id == likeable_id)).first()\nif likeable is None:\n new_likeable = Likeable(user_id=user_id, likeable_type=likeable_type, likeable_id=likeable_id, value=value)\n try:\n db.sess... | <|body_start_0|>
likeable = Likeable.query.filter(and_(Likeable.user_id == user_id, Likeable.likeable_type == likeable_type, Likeable.likeable_id == likeable_id)).first()
if likeable is None:
new_likeable = Likeable(user_id=user_id, likeable_type=likeable_type, likeable_id=likeable_id, value... | Likeables | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Likeables:
def create(self, user_id, likeable_type, likeable_id, value):
"""Like/Dislike a model"""
<|body_0|>
def remove(self, user_id, likeable_type, likeable_id):
"""Remove a Likeable entry"""
<|body_1|>
def getCount(self, likeable_type, likeable_id):... | stack_v2_sparse_classes_36k_train_001483 | 3,032 | no_license | [
{
"docstring": "Like/Dislike a model",
"name": "create",
"signature": "def create(self, user_id, likeable_type, likeable_id, value)"
},
{
"docstring": "Remove a Likeable entry",
"name": "remove",
"signature": "def remove(self, user_id, likeable_type, likeable_id)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_019754 | Implement the Python class `Likeables` described below.
Class description:
Implement the Likeables class.
Method signatures and docstrings:
- def create(self, user_id, likeable_type, likeable_id, value): Like/Dislike a model
- def remove(self, user_id, likeable_type, likeable_id): Remove a Likeable entry
- def getCou... | Implement the Python class `Likeables` described below.
Class description:
Implement the Likeables class.
Method signatures and docstrings:
- def create(self, user_id, likeable_type, likeable_id, value): Like/Dislike a model
- def remove(self, user_id, likeable_type, likeable_id): Remove a Likeable entry
- def getCou... | ae78fff9888b0f68d9403d7f65cba086dabb3802 | <|skeleton|>
class Likeables:
def create(self, user_id, likeable_type, likeable_id, value):
"""Like/Dislike a model"""
<|body_0|>
def remove(self, user_id, likeable_type, likeable_id):
"""Remove a Likeable entry"""
<|body_1|>
def getCount(self, likeable_type, likeable_id):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Likeables:
def create(self, user_id, likeable_type, likeable_id, value):
"""Like/Dislike a model"""
likeable = Likeable.query.filter(and_(Likeable.user_id == user_id, Likeable.likeable_type == likeable_type, Likeable.likeable_id == likeable_id)).first()
if likeable is None:
... | the_stack_v2_python_sparse | api/v1/likeables.py | mythril-io/flask-api | train | 0 | |
943a2bb12d11f45a2215c6ce2aafd97eada8b039 | [
"try:\n parent = aq_parent(aq_inner(self.context))\n if parent.id == 'Members':\n return True\nexcept:\n pass\nreturn False",
"context = aq_inner(self.context)\ntranslations = {}\nif ISiteRoot.providedBy(context) or self.isSpecialFish():\n for c in missing:\n translations[c] = context\ne... | <|body_start_0|>
try:
parent = aq_parent(aq_inner(self.context))
if parent.id == 'Members':
return True
except:
pass
return False
<|end_body_0|>
<|body_start_1|>
context = aq_inner(self.context)
translations = {}
if ISi... | GFBLanguageSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GFBLanguageSelector:
def isSpecialFish(self):
"""Method that returns true if the language selector should be displayed even if the object is not translated. This is the case for the Members folder"""
<|body_0|>
def _translations(self, missing):
"""#10142 Only show th... | stack_v2_sparse_classes_36k_train_001484 | 10,726 | no_license | [
{
"docstring": "Method that returns true if the language selector should be displayed even if the object is not translated. This is the case for the Members folder",
"name": "isSpecialFish",
"signature": "def isSpecialFish(self)"
},
{
"docstring": "#10142 Only show the translation link if the co... | 2 | stack_v2_sparse_classes_30k_train_014124 | Implement the Python class `GFBLanguageSelector` described below.
Class description:
Implement the GFBLanguageSelector class.
Method signatures and docstrings:
- def isSpecialFish(self): Method that returns true if the language selector should be displayed even if the object is not translated. This is the case for th... | Implement the Python class `GFBLanguageSelector` described below.
Class description:
Implement the GFBLanguageSelector class.
Method signatures and docstrings:
- def isSpecialFish(self): Method that returns true if the language selector should be displayed even if the object is not translated. This is the case for th... | 1e0a25eb040e8077e8eafa5072348cdec0a2ade8 | <|skeleton|>
class GFBLanguageSelector:
def isSpecialFish(self):
"""Method that returns true if the language selector should be displayed even if the object is not translated. This is the case for the Members folder"""
<|body_0|>
def _translations(self, missing):
"""#10142 Only show th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GFBLanguageSelector:
def isSpecialFish(self):
"""Method that returns true if the language selector should be displayed even if the object is not translated. This is the case for the Members folder"""
try:
parent = aq_parent(aq_inner(self.context))
if parent.id == 'Membe... | the_stack_v2_python_sparse | gfb/theme/browser/viewlets.py | syslabcomarchive/gfb.theme | train | 0 | |
52a5d62fcccf5911e5875785fa2a864d72050c5b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ProcessEvidence()",
"from .alert_evidence import AlertEvidence\nfrom .detection_status import DetectionStatus\nfrom .file_details import FileDetails\nfrom .user_account import UserAccount\nfrom .alert_evidence import AlertEvidence\nfro... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ProcessEvidence()
<|end_body_0|>
<|body_start_1|>
from .alert_evidence import AlertEvidence
from .detection_status import DetectionStatus
from .file_details import FileDetails
... | ProcessEvidence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence:
"""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 Ret... | stack_v2_sparse_classes_36k_train_001485 | 5,608 | 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: ProcessEvidence",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_007543 | Implement the Python class `ProcessEvidence` described below.
Class description:
Implement the ProcessEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `ProcessEvidence` described below.
Class description:
Implement the ProcessEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ProcessEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence:
"""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 Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence:
"""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: ProcessE... | the_stack_v2_python_sparse | msgraph/generated/models/security/process_evidence.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4c8d201d1380896dc7e8f29f62fbc4ba7402c5e6 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), username=username)\nuser.set_password(password)\nuser.is_active = False\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, username=username, password=password)\nus... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), username=username)
user.set_password(password)
user.is_active = False
user.save(using=self._db)
return user
<|end_body_0|>
... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, username, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password):
"""Creates and saves a superuser with the given em... | stack_v2_sparse_classes_36k_train_001486 | 4,477 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, username, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_001355 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, username, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email, us... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, username, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email, us... | ed12966cddea761d5d5828c1ace890b98229f1bd | <|skeleton|>
class MyUserManager:
def create_user(self, email, username, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password):
"""Creates and saves a superuser with the given em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, email, username, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), use... | the_stack_v2_python_sparse | webapp/models.py | OpsWorld/SimpletourDevops | train | 7 | |
10843307ee80326445ea78fd42c70ef9331d52a4 | [
"state_zip = ' '.join([s for s in (self.state, self.zipcode) if s])\ncity_state_zip = ', '.join([s for s in (self.city, state_zip, self.country) if s])\nreturn '%s %s %s' % (self.address, self.address2, city_state_zip)",
"state_zip = ' '.join([s for s in (self.state_2, self.zipcode_2) if s])\ncity_state_zip = ', ... | <|body_start_0|>
state_zip = ' '.join([s for s in (self.state, self.zipcode) if s])
city_state_zip = ', '.join([s for s in (self.city, state_zip, self.country) if s])
return '%s %s %s' % (self.address, self.address2, city_state_zip)
<|end_body_0|>
<|body_start_1|>
state_zip = ' '.join([... | Person | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Person:
def get_address(self):
"""Returns full address depending on which attributes are available."""
<|body_0|>
def get_alternate_address(self):
"""Returns full alternate address depending on which attributes are available."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_001487 | 7,184 | no_license | [
{
"docstring": "Returns full address depending on which attributes are available.",
"name": "get_address",
"signature": "def get_address(self)"
},
{
"docstring": "Returns full alternate address depending on which attributes are available.",
"name": "get_alternate_address",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_007979 | Implement the Python class `Person` described below.
Class description:
Implement the Person class.
Method signatures and docstrings:
- def get_address(self): Returns full address depending on which attributes are available.
- def get_alternate_address(self): Returns full alternate address depending on which attribut... | Implement the Python class `Person` described below.
Class description:
Implement the Person class.
Method signatures and docstrings:
- def get_address(self): Returns full address depending on which attributes are available.
- def get_alternate_address(self): Returns full alternate address depending on which attribut... | f2ac4ecc076b223c262f2cde4fa3b35b4a5cd54e | <|skeleton|>
class Person:
def get_address(self):
"""Returns full address depending on which attributes are available."""
<|body_0|>
def get_alternate_address(self):
"""Returns full alternate address depending on which attributes are available."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Person:
def get_address(self):
"""Returns full address depending on which attributes are available."""
state_zip = ' '.join([s for s in (self.state, self.zipcode) if s])
city_state_zip = ', '.join([s for s in (self.city, state_zip, self.country) if s])
return '%s %s %s' % (self... | the_stack_v2_python_sparse | tendenci/libs/abstracts/models.py | chendong0444/ams | train | 0 | |
fed6a92acea62f9d42c2d89245118f36812705d4 | [
"MobileText = self.find_element(*self.MobileTextElement)\nMobileText.send_keys(mobilevalue)\nVerifyCodeText = self.find_element(*self.VerifyCodeTextElement)\nVerifyCodeText.send_keys('111222')\nLoginBtn = self.find_element(*self.LoginBtnElement)\nLoginBtn.click()\nlogger.info('LoginBtn is click!')",
"deskBtn = se... | <|body_start_0|>
MobileText = self.find_element(*self.MobileTextElement)
MobileText.send_keys(mobilevalue)
VerifyCodeText = self.find_element(*self.VerifyCodeTextElement)
VerifyCodeText.send_keys('111222')
LoginBtn = self.find_element(*self.LoginBtnElement)
LoginBtn.click... | notice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class notice:
def LoginBtnObj(self, mobilevalue):
"""登录测试账号"""
<|body_0|>
def intoObj(self):
"""进入班级通知"""
<|body_1|>
def addObj(self, text):
"""添加班级通知"""
<|body_2|>
def addvideoObj(self):
"""添加视频"""
<|body_3|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_001488 | 4,142 | no_license | [
{
"docstring": "登录测试账号",
"name": "LoginBtnObj",
"signature": "def LoginBtnObj(self, mobilevalue)"
},
{
"docstring": "进入班级通知",
"name": "intoObj",
"signature": "def intoObj(self)"
},
{
"docstring": "添加班级通知",
"name": "addObj",
"signature": "def addObj(self, text)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_005973 | Implement the Python class `notice` described below.
Class description:
Implement the notice class.
Method signatures and docstrings:
- def LoginBtnObj(self, mobilevalue): 登录测试账号
- def intoObj(self): 进入班级通知
- def addObj(self, text): 添加班级通知
- def addvideoObj(self): 添加视频 | Implement the Python class `notice` described below.
Class description:
Implement the notice class.
Method signatures and docstrings:
- def LoginBtnObj(self, mobilevalue): 登录测试账号
- def intoObj(self): 进入班级通知
- def addObj(self, text): 添加班级通知
- def addvideoObj(self): 添加视频
<|skeleton|>
class notice:
def LoginBtnObj... | c4e11c8aa67306111ca2831a18af4363831af939 | <|skeleton|>
class notice:
def LoginBtnObj(self, mobilevalue):
"""登录测试账号"""
<|body_0|>
def intoObj(self):
"""进入班级通知"""
<|body_1|>
def addObj(self, text):
"""添加班级通知"""
<|body_2|>
def addvideoObj(self):
"""添加视频"""
<|body_3|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class notice:
def LoginBtnObj(self, mobilevalue):
"""登录测试账号"""
MobileText = self.find_element(*self.MobileTextElement)
MobileText.send_keys(mobilevalue)
VerifyCodeText = self.find_element(*self.VerifyCodeTextElement)
VerifyCodeText.send_keys('111222')
LoginBtn = self.... | the_stack_v2_python_sparse | Public/Pages/Notice.py | alexzeger/android_teacher | train | 0 | |
9469a63ad5258bd540c3c37328e5f9186e694d78 | [
"self.cow_list = []\nself.date = date.strftime('%Y/%m/%d')\nself.record_file_path = self.record_file_path + self.date[:4] + '-' + self.date[5:7] + '.csv'\nself.__read_from_db(self.__get_cow_list())",
"dt = datetime.datetime(int(self.date[:4]), int(self.date[5:7]), int(self.date[8:10]))\nprint('reading cow informa... | <|body_start_0|>
self.cow_list = []
self.date = date.strftime('%Y/%m/%d')
self.record_file_path = self.record_file_path + self.date[:4] + '-' + self.date[5:7] + '.csv'
self.__read_from_db(self.__get_cow_list())
<|end_body_0|>
<|body_start_1|>
dt = datetime.datetime(int(self.date... | Cowshed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cowshed:
def __init__(self, date: datetime):
"""その日いた牛を登録する 日付をキーにしてコンストラクタでGPSデータの読み込み"""
<|body_0|>
def __read_from_db(self, cow_id_list):
"""1頭ずつデータベースからGPS情報を読み込む"""
<|body_1|>
def __get_cow_list(self):
"""csvファイルからその日第一放牧場にいた牛の個体番号のリストを取得する"... | stack_v2_sparse_classes_36k_train_001489 | 1,989 | no_license | [
{
"docstring": "その日いた牛を登録する 日付をキーにしてコンストラクタでGPSデータの読み込み",
"name": "__init__",
"signature": "def __init__(self, date: datetime)"
},
{
"docstring": "1頭ずつデータベースからGPS情報を読み込む",
"name": "__read_from_db",
"signature": "def __read_from_db(self, cow_id_list)"
},
{
"docstring": "csvファイルからそ... | 4 | stack_v2_sparse_classes_30k_train_007056 | Implement the Python class `Cowshed` described below.
Class description:
Implement the Cowshed class.
Method signatures and docstrings:
- def __init__(self, date: datetime): その日いた牛を登録する 日付をキーにしてコンストラクタでGPSデータの読み込み
- def __read_from_db(self, cow_id_list): 1頭ずつデータベースからGPS情報を読み込む
- def __get_cow_list(self): csvファイルからその日... | Implement the Python class `Cowshed` described below.
Class description:
Implement the Cowshed class.
Method signatures and docstrings:
- def __init__(self, date: datetime): その日いた牛を登録する 日付をキーにしてコンストラクタでGPSデータの読み込み
- def __read_from_db(self, cow_id_list): 1頭ずつデータベースからGPS情報を読み込む
- def __get_cow_list(self): csvファイルからその日... | 9046329d57ef10b6643c9c6e7dcc3ea9b6294dee | <|skeleton|>
class Cowshed:
def __init__(self, date: datetime):
"""その日いた牛を登録する 日付をキーにしてコンストラクタでGPSデータの読み込み"""
<|body_0|>
def __read_from_db(self, cow_id_list):
"""1頭ずつデータベースからGPS情報を読み込む"""
<|body_1|>
def __get_cow_list(self):
"""csvファイルからその日第一放牧場にいた牛の個体番号のリストを取得する"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cowshed:
def __init__(self, date: datetime):
"""その日いた牛を登録する 日付をキーにしてコンストラクタでGPSデータの読み込み"""
self.cow_list = []
self.date = date.strftime('%Y/%m/%d')
self.record_file_path = self.record_file_path + self.date[:4] + '-' + self.date[5:7] + '.csv'
self.__read_from_db(self.__g... | the_stack_v2_python_sparse | COW_PROJECT/cows/cowshed.py | FUKUSHUN/cow_python | train | 1 | |
50aa354241c37a4f3e6e9094526820aa722c8a60 | [
"self._pi = pi\nself.gpioA = gpioA\nself.gpioB = gpioB\nself.callback = callback\nself.levA = 0\nself.levB = 0\nself.lastGpio = None\nself._pi.set_mode(gpioA, pigpio.INPUT)\nself._pi.set_mode(gpioB, pigpio.INPUT)\nself._pi.set_pull_up_down(gpioA, pigpio.PUD_UP)\nself._pi.set_pull_up_down(gpioB, pigpio.PUD_UP)\nself... | <|body_start_0|>
self._pi = pi
self.gpioA = gpioA
self.gpioB = gpioB
self.callback = callback
self.levA = 0
self.levB = 0
self.lastGpio = None
self._pi.set_mode(gpioA, pigpio.INPUT)
self._pi.set_mode(gpioB, pigpio.INPUT)
self._pi.set_pull_u... | Class to decode mechanical rotary encoder pulses. | Decoder | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Class to decode mechanical rotary encoder pulses."""
def __init__(self, pi, gpioA, gpioB, callback):
"""Instantiate the class with the pi and gpios connected to rotary encoder contacts A and B. The common contact should be connected to ground. The callback is called when ... | stack_v2_sparse_classes_36k_train_001490 | 4,215 | permissive | [
{
"docstring": "Instantiate the class with the pi and gpios connected to rotary encoder contacts A and B. The common contact should be connected to ground. The callback is called when the rotary encoder is turned. It takes one parameter which is +1 for clockwise and -1 for counterclockwise. EXAMPLE import time ... | 3 | stack_v2_sparse_classes_30k_test_000577 | Implement the Python class `Decoder` described below.
Class description:
Class to decode mechanical rotary encoder pulses.
Method signatures and docstrings:
- def __init__(self, pi, gpioA, gpioB, callback): Instantiate the class with the pi and gpios connected to rotary encoder contacts A and B. The common contact sh... | Implement the Python class `Decoder` described below.
Class description:
Class to decode mechanical rotary encoder pulses.
Method signatures and docstrings:
- def __init__(self, pi, gpioA, gpioB, callback): Instantiate the class with the pi and gpios connected to rotary encoder contacts A and B. The common contact sh... | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | <|skeleton|>
class Decoder:
"""Class to decode mechanical rotary encoder pulses."""
def __init__(self, pi, gpioA, gpioB, callback):
"""Instantiate the class with the pi and gpios connected to rotary encoder contacts A and B. The common contact should be connected to ground. The callback is called when ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Class to decode mechanical rotary encoder pulses."""
def __init__(self, pi, gpioA, gpioB, callback):
"""Instantiate the class with the pi and gpios connected to rotary encoder contacts A and B. The common contact should be connected to ground. The callback is called when the rotary en... | the_stack_v2_python_sparse | lib/rotary_encoder.py | bopopescu/ros | train | 0 |
11ffc652f007e0182aa10995303ce88299e7e5ac | [
"if 'reduction' in kwargs:\n raise ValueError('Reduction is not supported in TopKLoss.This will always return the mean!')\nsuper().__init__(reduction='none', **kwargs)\nself.smoothing = smoothing\nif smoothing > 0:\n logger.info(f'Running label smoothing with smoothing: {smoothing}')\nself.num_classes = num_c... | <|body_start_0|>
if 'reduction' in kwargs:
raise ValueError('Reduction is not supported in TopKLoss.This will always return the mean!')
super().__init__(reduction='none', **kwargs)
self.smoothing = smoothing
if smoothing > 0:
logger.info(f'Running label smoothing ... | TopKLossSigmoid | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopKLossSigmoid:
def __init__(self, num_classes: int, topk: float, smoothing: float=0.0, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute BCE loss with one hot (support multi class through one hot, expects pre sigmoid logits!) Args: num_classes: number of clas... | stack_v2_sparse_classes_36k_train_001491 | 8,471 | permissive | [
{
"docstring": "Uses topk percent of values to compute BCE loss with one hot (support multi class through one hot, expects pre sigmoid logits!) Args: num_classes: number of classes topk: percentage of all entries to use for loss computation smoothing: label smoothing loss_weight: scalar to balance multiple loss... | 2 | stack_v2_sparse_classes_30k_train_009683 | Implement the Python class `TopKLossSigmoid` described below.
Class description:
Implement the TopKLossSigmoid class.
Method signatures and docstrings:
- def __init__(self, num_classes: int, topk: float, smoothing: float=0.0, loss_weight: float=1.0, **kwargs): Uses topk percent of values to compute BCE loss with one ... | Implement the Python class `TopKLossSigmoid` described below.
Class description:
Implement the TopKLossSigmoid class.
Method signatures and docstrings:
- def __init__(self, num_classes: int, topk: float, smoothing: float=0.0, loss_weight: float=1.0, **kwargs): Uses topk percent of values to compute BCE loss with one ... | 4f41faa7536dcef8fca7b647dcdca25360e5b58a | <|skeleton|>
class TopKLossSigmoid:
def __init__(self, num_classes: int, topk: float, smoothing: float=0.0, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute BCE loss with one hot (support multi class through one hot, expects pre sigmoid logits!) Args: num_classes: number of clas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopKLossSigmoid:
def __init__(self, num_classes: int, topk: float, smoothing: float=0.0, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute BCE loss with one hot (support multi class through one hot, expects pre sigmoid logits!) Args: num_classes: number of classes topk: perc... | the_stack_v2_python_sparse | nndet/losses/segmentation.py | dboun/nnDetection | train | 1 | |
27ce85fa07bc489e71fb1fc828e0650963228dcb | [
"try:\n translateURL = 'http://fy.webxml.com.cn/webservices/EnglishChinese.asmx/Translator?wordKey=' + str(word)\n r = requests.get(translateURL)\n text = r.text\n if self.isChinese(word):\n message = self.handleCNRequest(text)\n else:\n message = self.handleENRequest(text)\n return ... | <|body_start_0|>
try:
translateURL = 'http://fy.webxml.com.cn/webservices/EnglishChinese.asmx/Translator?wordKey=' + str(word)
r = requests.get(translateURL)
text = r.text
if self.isChinese(word):
message = self.handleCNRequest(text)
el... | 翻译类,负责单词的中英互译。具体操作类。 | Translate | [
"MIT",
"ICU"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Translate:
"""翻译类,负责单词的中英互译。具体操作类。"""
def translate(self, word):
"""翻译单词(返回详细的单词翻译) :param word: 需要被翻译的文本(英汉均可) :return:"""
<|body_0|>
def handleCNRequest(self, text):
"""处理中文的翻译响应 :param text: 响应 :return: 解析后生成字典"""
<|body_1|>
def handleENRequest(se... | stack_v2_sparse_classes_36k_train_001492 | 3,902 | permissive | [
{
"docstring": "翻译单词(返回详细的单词翻译) :param word: 需要被翻译的文本(英汉均可) :return:",
"name": "translate",
"signature": "def translate(self, word)"
},
{
"docstring": "处理中文的翻译响应 :param text: 响应 :return: 解析后生成字典",
"name": "handleCNRequest",
"signature": "def handleCNRequest(self, text)"
},
{
"doc... | 4 | null | Implement the Python class `Translate` described below.
Class description:
翻译类,负责单词的中英互译。具体操作类。
Method signatures and docstrings:
- def translate(self, word): 翻译单词(返回详细的单词翻译) :param word: 需要被翻译的文本(英汉均可) :return:
- def handleCNRequest(self, text): 处理中文的翻译响应 :param text: 响应 :return: 解析后生成字典
- def handleENRequest(self, ... | Implement the Python class `Translate` described below.
Class description:
翻译类,负责单词的中英互译。具体操作类。
Method signatures and docstrings:
- def translate(self, word): 翻译单词(返回详细的单词翻译) :param word: 需要被翻译的文本(英汉均可) :return:
- def handleCNRequest(self, text): 处理中文的翻译响应 :param text: 响应 :return: 解析后生成字典
- def handleENRequest(self, ... | 434efd09edbda7919a3f754374add7f34912fab7 | <|skeleton|>
class Translate:
"""翻译类,负责单词的中英互译。具体操作类。"""
def translate(self, word):
"""翻译单词(返回详细的单词翻译) :param word: 需要被翻译的文本(英汉均可) :return:"""
<|body_0|>
def handleCNRequest(self, text):
"""处理中文的翻译响应 :param text: 响应 :return: 解析后生成字典"""
<|body_1|>
def handleENRequest(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Translate:
"""翻译类,负责单词的中英互译。具体操作类。"""
def translate(self, word):
"""翻译单词(返回详细的单词翻译) :param word: 需要被翻译的文本(英汉均可) :return:"""
try:
translateURL = 'http://fy.webxml.com.cn/webservices/EnglishChinese.asmx/Translator?wordKey=' + str(word)
r = requests.get(translateURL)
... | the_stack_v2_python_sparse | src/Client/SearchSystem/TranslateTools/translateInWebXml.py | Sniper970119/MemoryAssistInPython | train | 28 |
11a72443dfdce4db6dd71ccd35e37422d9a7c62d | [
"if value is self.field.missing_value:\n return ''\nreturn '\\n'.join((to_unicode(v) for v in value))",
"collection_type = self.field._type\nif isinstance(collection_type, tuple):\n collection_type = collection_type[-1]\nif len(value) == 0:\n return self.field.missing_value\nvalue_type = self.field.value... | <|body_start_0|>
if value is self.field.missing_value:
return ''
return '\n'.join((to_unicode(v) for v in value))
<|end_body_0|>
<|body_start_1|>
collection_type = self.field._type
if isinstance(collection_type, tuple):
collection_type = collection_type[-1]
... | Data converter for ITextLinesWidget. | TextLinesConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextLinesConverter:
"""Data converter for ITextLinesWidget."""
def to_widget_value(self, value):
"""Convert from text lines to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConverter"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_001493 | 16,755 | permissive | [
{
"docstring": "Convert from text lines to HTML representation.",
"name": "to_widget_value",
"signature": "def to_widget_value(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "to_field_value",
"signature": "def to_field_value(self, value)"
}
] | 2 | null | Implement the Python class `TextLinesConverter` described below.
Class description:
Data converter for ITextLinesWidget.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from text lines to HTML representation.
- def to_field_value(self, value): See interfaces.IDataConverter | Implement the Python class `TextLinesConverter` described below.
Class description:
Data converter for ITextLinesWidget.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from text lines to HTML representation.
- def to_field_value(self, value): See interfaces.IDataConverter
<|skeleton|>
... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class TextLinesConverter:
"""Data converter for ITextLinesWidget."""
def to_widget_value(self, value):
"""Convert from text lines to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConverter"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextLinesConverter:
"""Data converter for ITextLinesWidget."""
def to_widget_value(self, value):
"""Convert from text lines to HTML representation."""
if value is self.field.missing_value:
return ''
return '\n'.join((to_unicode(v) for v in value))
def to_field_val... | the_stack_v2_python_sparse | src/pyams_form/converter.py | Py-AMS/pyams-form | train | 0 |
03d8b6ef9cd5e1ef1e2c94ecd528b286ebc3e9a6 | [
"m = super(RecipeIngredientForm, self).save(commit=False)\ningredient_name = self.cleaned_data['ingredient_name']\nunit_name = self.cleaned_data['unit_name']\noptional = self.cleaned_data['optional']\ningredient = Ingredient.objects.get_or_create(name__iexact=ingredient_name, defaults={'name': ingredient_name, 'slu... | <|body_start_0|>
m = super(RecipeIngredientForm, self).save(commit=False)
ingredient_name = self.cleaned_data['ingredient_name']
unit_name = self.cleaned_data['unit_name']
optional = self.cleaned_data['optional']
ingredient = Ingredient.objects.get_or_create(name__iexact=ingredie... | A class that defines the form for submission of ingredients associated with a recipe. | RecipeIngredientForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeIngredientForm:
"""A class that defines the form for submission of ingredients associated with a recipe."""
def save(self, commit=True):
"""An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredie... | stack_v2_sparse_classes_36k_train_001494 | 4,228 | no_license | [
{
"docstring": "An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredientForm instance commit -- whether the changes to the form should be committed",
"name": "save",
"signature": "def save(self, commit=True)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_003408 | Implement the Python class `RecipeIngredientForm` described below.
Class description:
A class that defines the form for submission of ingredients associated with a recipe.
Method signatures and docstrings:
- def save(self, commit=True): An overwrite of the form save method that parses the ingredients, units and optio... | Implement the Python class `RecipeIngredientForm` described below.
Class description:
A class that defines the form for submission of ingredients associated with a recipe.
Method signatures and docstrings:
- def save(self, commit=True): An overwrite of the form save method that parses the ingredients, units and optio... | 51396b214a601f5a9cf80e1de3755ab5ebcf6d2e | <|skeleton|>
class RecipeIngredientForm:
"""A class that defines the form for submission of ingredients associated with a recipe."""
def save(self, commit=True):
"""An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecipeIngredientForm:
"""A class that defines the form for submission of ingredients associated with a recipe."""
def save(self, commit=True):
"""An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredientForm instan... | the_stack_v2_python_sparse | recipes/forms.py | kgodey/Bendakai | train | 6 |
dcabc077bea36188fecb33dd6128db2f7454d8a1 | [
"self.class_type = class_type\nself.blender_model_path = os.path.join(cfg.dataset_dir, cfg.dataset_name, '{0}/{0}.ply'.format(class_type))\nself.orig_model_path = os.path.join(cfg.dataset_dir, cfg.origin_dataset_name, '{}/mesh.ply'.format(class_type))\nself.model_aligner = ModelAligner(class_type)",
"rot, tra = (... | <|body_start_0|>
self.class_type = class_type
self.blender_model_path = os.path.join(cfg.dataset_dir, cfg.dataset_name, '{0}/{0}.ply'.format(class_type))
self.orig_model_path = os.path.join(cfg.dataset_dir, cfg.origin_dataset_name, '{}/mesh.ply'.format(class_type))
self.model_aligner = M... | PoseTransformer | PoseTransformer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoseTransformer:
"""PoseTransformer"""
def __init__(self, class_type):
"""__init__"""
<|body_0|>
def orig_pose_to_blender_pose(self, pose):
"""orig_pose_to_blender_pose"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.class_type = class_type... | stack_v2_sparse_classes_36k_train_001495 | 12,892 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, class_type)"
},
{
"docstring": "orig_pose_to_blender_pose",
"name": "orig_pose_to_blender_pose",
"signature": "def orig_pose_to_blender_pose(self, pose)"
}
] | 2 | null | Implement the Python class `PoseTransformer` described below.
Class description:
PoseTransformer
Method signatures and docstrings:
- def __init__(self, class_type): __init__
- def orig_pose_to_blender_pose(self, pose): orig_pose_to_blender_pose | Implement the Python class `PoseTransformer` described below.
Class description:
PoseTransformer
Method signatures and docstrings:
- def __init__(self, class_type): __init__
- def orig_pose_to_blender_pose(self, pose): orig_pose_to_blender_pose
<|skeleton|>
class PoseTransformer:
"""PoseTransformer"""
def _... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class PoseTransformer:
"""PoseTransformer"""
def __init__(self, class_type):
"""__init__"""
<|body_0|>
def orig_pose_to_blender_pose(self, pose):
"""orig_pose_to_blender_pose"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoseTransformer:
"""PoseTransformer"""
def __init__(self, class_type):
"""__init__"""
self.class_type = class_type
self.blender_model_path = os.path.join(cfg.dataset_dir, cfg.dataset_name, '{0}/{0}.ply'.format(class_type))
self.orig_model_path = os.path.join(cfg.dataset_di... | the_stack_v2_python_sparse | official/cv/PVNet/src/evaluation_dataset.py | mindspore-ai/models | train | 301 |
68e64a0b50e48ffba72ec442b8031f578f210cea | [
"params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))\nparams['image_id'] = image_id\nparams['tag_group_id'] = tag_group_id\nparams['tag_id'] = tag_id\nform = MultiGetForm(params)\nif not form.is_valid():\n raise BadRequestException()\nreturn Response(form.submit(request))",
"params = d... | <|body_start_0|>
params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))
params['image_id'] = image_id
params['tag_group_id'] = tag_group_id
params['tag_id'] = tag_id
form = MultiGetForm(params)
if not form.is_valid():
raise BadRequestExce... | Class for rendering the view for creating GeneLinks and searching through the GeneLinks. | GeneLinkList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneLinkList:
"""Class for rendering the view for creating GeneLinks and searching through the GeneLinks."""
def get(self, request, image_id, tag_group_id, tag_id):
"""Method for getting multiple GeneLinks either through search or general listing."""
<|body_0|>
def post(... | stack_v2_sparse_classes_36k_train_001496 | 2,768 | no_license | [
{
"docstring": "Method for getting multiple GeneLinks either through search or general listing.",
"name": "get",
"signature": "def get(self, request, image_id, tag_group_id, tag_id)"
},
{
"docstring": "Method for creating a new GeneLink.",
"name": "post",
"signature": "def post(self, req... | 2 | stack_v2_sparse_classes_30k_val_000395 | Implement the Python class `GeneLinkList` described below.
Class description:
Class for rendering the view for creating GeneLinks and searching through the GeneLinks.
Method signatures and docstrings:
- def get(self, request, image_id, tag_group_id, tag_id): Method for getting multiple GeneLinks either through search... | Implement the Python class `GeneLinkList` described below.
Class description:
Class for rendering the view for creating GeneLinks and searching through the GeneLinks.
Method signatures and docstrings:
- def get(self, request, image_id, tag_group_id, tag_id): Method for getting multiple GeneLinks either through search... | 22c1ce3c5a8e4ed99c2f014672d60ad3c5a4003c | <|skeleton|>
class GeneLinkList:
"""Class for rendering the view for creating GeneLinks and searching through the GeneLinks."""
def get(self, request, image_id, tag_group_id, tag_id):
"""Method for getting multiple GeneLinks either through search or general listing."""
<|body_0|>
def post(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneLinkList:
"""Class for rendering the view for creating GeneLinks and searching through the GeneLinks."""
def get(self, request, image_id, tag_group_id, tag_id):
"""Method for getting multiple GeneLinks either through search or general listing."""
params = dict(((key, val) for key, val... | the_stack_v2_python_sparse | biodig/rest/v2/GeneLinks/views.py | asmariyaz23/BioDIG | train | 0 |
d34bdc3786e4ee98316e59e842478527e62fc4f6 | [
"if data is None:\n if stddev < 1:\n raise ValueError('stddev must be a positive value')\n else:\n self.stddev = float(stddev)\n self.mean = float(mean)\nelif type(data) is not list:\n raise TypeError('data must be a list')\nelif len(data) < 2:\n raise ValueError('data must contain ... | <|body_start_0|>
if data is None:
if stddev < 1:
raise ValueError('stddev must be a positive value')
else:
self.stddev = float(stddev)
self.mean = float(mean)
elif type(data) is not list:
raise TypeError('data must be a ... | class that represents normal distribution class constructor: def __init__(self, data=None, mean=0., stddev=1.) instance attributes: mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution instance methods: def z_score(self, x): calculates the z-score of a given x-value def ... | Normal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Normal:
"""class that represents normal distribution class constructor: def __init__(self, data=None, mean=0., stddev=1.) instance attributes: mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution instance methods: def z_score(self, x): calculates t... | stack_v2_sparse_classes_36k_train_001497 | 3,746 | no_license | [
{
"docstring": "class constructor parameters: data [list]: data to be used to estimate the distibution mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution Sets the instance attributes mean and stddev as floats If data is not given: Use the given mean and stddev ... | 5 | stack_v2_sparse_classes_30k_train_010224 | Implement the Python class `Normal` described below.
Class description:
class that represents normal distribution class constructor: def __init__(self, data=None, mean=0., stddev=1.) instance attributes: mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution instance meth... | Implement the Python class `Normal` described below.
Class description:
class that represents normal distribution class constructor: def __init__(self, data=None, mean=0., stddev=1.) instance attributes: mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution instance meth... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class Normal:
"""class that represents normal distribution class constructor: def __init__(self, data=None, mean=0., stddev=1.) instance attributes: mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution instance methods: def z_score(self, x): calculates t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Normal:
"""class that represents normal distribution class constructor: def __init__(self, data=None, mean=0., stddev=1.) instance attributes: mean [float]: the mean of the distribution stddev [float]: the standard deviation of the distribution instance methods: def z_score(self, x): calculates the z-score of... | the_stack_v2_python_sparse | math/0x03-probability/normal.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
c800ac64134d99ebb25866bd399b2fb0cc5ef359 | [
"import bisect as bi\nM = []\nfor r in matrix:\n M.extend(r)\nidx = bi.bisect_left(M, target)\nif idx <= len(M) - 1 and M[idx] == target:\n return True\nreturn False",
"for r in range(len(matrix)):\n if not matrix[r]:\n return False\n if target > matrix[r][-1]:\n continue\n if target ... | <|body_start_0|>
import bisect as bi
M = []
for r in matrix:
M.extend(r)
idx = bi.bisect_left(M, target)
if idx <= len(M) - 1 and M[idx] == target:
return True
return False
<|end_body_0|>
<|body_start_1|>
for r in range(len(matrix)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool convert matrix to a long sorted list then do a binary search."""
<|body_0|>
def rewrite(self, matrix, target):
""":type matrix: List[List[int]] :type tar... | stack_v2_sparse_classes_36k_train_001498 | 1,784 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool convert matrix to a long sorted list then do a binary search.",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bo... | 2 | stack_v2_sparse_classes_30k_train_008929 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool convert matrix to a long sorted list then do a binary search.
- def rewrite(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool convert matrix to a long sorted list then do a binary search.
- def rewrite(s... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool convert matrix to a long sorted list then do a binary search."""
<|body_0|>
def rewrite(self, matrix, target):
""":type matrix: List[List[int]] :type tar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool convert matrix to a long sorted list then do a binary search."""
import bisect as bi
M = []
for r in matrix:
M.extend(r)
idx = bi.bisect_left(M,... | the_stack_v2_python_sparse | co_ms/74_Search_a_2D_Matrix.py | vsdrun/lc_public | train | 6 | |
1b13d14b4bcf9651d3d39dc94b1c36b3bb17b559 | [
"if '<s>' in vocab:\n del vocab['<s>']\nif '<pad>' in vocab:\n del vocab['<pad>']\nif '</s>' in vocab:\n del vocab['</s>']\nif '<unk>' in vocab:\n del vocab['<unk>']\nword2id = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}\nid2word = {0: '<s>', 1: '<pad>', 2: '</s>', 3: '<unk>'}\nsorted_word2id = sorted... | <|body_start_0|>
if '<s>' in vocab:
del vocab['<s>']
if '<pad>' in vocab:
del vocab['<pad>']
if '</s>' in vocab:
del vocab['</s>']
if '<unk>' in vocab:
del vocab['<unk>']
word2id = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}
... | Data Iterator. | DataIterator | [
"MIT",
"BSD-3-Clause",
"LGPL-2.1-or-later",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataIterator:
"""Data Iterator."""
def _trim_vocab(vocab, vocab_size):
"""Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word li... | stack_v2_sparse_classes_36k_train_001499 | 22,581 | permissive | [
{
"docstring": "Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word list.",
"name": "_trim_vocab",
"signature": "def _trim_vocab(vocab, vocab_size)"... | 2 | stack_v2_sparse_classes_30k_train_019274 | Implement the Python class `DataIterator` described below.
Class description:
Data Iterator.
Method signatures and docstrings:
- def _trim_vocab(vocab, vocab_size): Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(l... | Implement the Python class `DataIterator` described below.
Class description:
Data Iterator.
Method signatures and docstrings:
- def _trim_vocab(vocab, vocab_size): Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(l... | f5c40c3199552f6824e1aa6db10905acc1bf6d60 | <|skeleton|>
class DataIterator:
"""Data Iterator."""
def _trim_vocab(vocab, vocab_size):
"""Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataIterator:
"""Data Iterator."""
def _trim_vocab(vocab, vocab_size):
"""Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word list."""
... | the_stack_v2_python_sparse | utils_nlp/models/gensen/utils.py | pemukl/german-bertabs | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.