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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fbd6e241e9fd92db5bd850723de93acaafb418d8 | [
"dane_rang = cls.DANE['rangi']\nliczebniki = cls.DANE['liczebniki']\nlista_rang = []\nfor ranga_dane in dane_rang:\n lista_rang.append(Ranga(ranga_dane['nazwa'], ranga_dane['symbol'], range(ranga_dane['zakres'][0], ranga_dane['zakres'][1]), ranga_dane['sila_ognia'], ranga_dane['nazwy_statkow'], liczebniki[:], ra... | <|body_start_0|>
dane_rang = cls.DANE['rangi']
liczebniki = cls.DANE['liczebniki']
lista_rang = []
for ranga_dane in dane_rang:
lista_rang.append(Ranga(ranga_dane['nazwa'], ranga_dane['symbol'], range(ranga_dane['zakres'][0], ranga_dane['zakres'][1]), ranga_dane['sila_ognia']... | Parsuj dane zapisane w plikach. | Parser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parsuj dane zapisane w plikach."""
def podaj_rangi(cls):
"""Podaj sparsowane obiekty klasy 'statki.ranga.Ranga'."""
<|body_0|>
def podaj_minmax_kolumny(cls):
"""Podaj sparsowane minimalną i maksymalną liczbę kolumn planszy."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_009400 | 3,423 | permissive | [
{
"docstring": "Podaj sparsowane obiekty klasy 'statki.ranga.Ranga'.",
"name": "podaj_rangi",
"signature": "def podaj_rangi(cls)"
},
{
"docstring": "Podaj sparsowane minimalną i maksymalną liczbę kolumn planszy.",
"name": "podaj_minmax_kolumny",
"signature": "def podaj_minmax_kolumny(cls... | 6 | stack_v2_sparse_classes_30k_train_011444 | Implement the Python class `Parser` described below.
Class description:
Parsuj dane zapisane w plikach.
Method signatures and docstrings:
- def podaj_rangi(cls): Podaj sparsowane obiekty klasy 'statki.ranga.Ranga'.
- def podaj_minmax_kolumny(cls): Podaj sparsowane minimalną i maksymalną liczbę kolumn planszy.
- def p... | Implement the Python class `Parser` described below.
Class description:
Parsuj dane zapisane w plikach.
Method signatures and docstrings:
- def podaj_rangi(cls): Podaj sparsowane obiekty klasy 'statki.ranga.Ranga'.
- def podaj_minmax_kolumny(cls): Podaj sparsowane minimalną i maksymalną liczbę kolumn planszy.
- def p... | aa1e6954536feb29a66b69ab6a2d8fbd7ee37420 | <|skeleton|>
class Parser:
"""Parsuj dane zapisane w plikach."""
def podaj_rangi(cls):
"""Podaj sparsowane obiekty klasy 'statki.ranga.Ranga'."""
<|body_0|>
def podaj_minmax_kolumny(cls):
"""Podaj sparsowane minimalną i maksymalną liczbę kolumn planszy."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parsuj dane zapisane w plikach."""
def podaj_rangi(cls):
"""Podaj sparsowane obiekty klasy 'statki.ranga.Ranga'."""
dane_rang = cls.DANE['rangi']
liczebniki = cls.DANE['liczebniki']
lista_rang = []
for ranga_dane in dane_rang:
lista_rang.appe... | the_stack_v2_python_sparse | statki/pamiec.py | z33kz33k/statki | train | 0 |
19d7954eefdd314a0546ca74b30348ed3f4ec1d1 | [
"Logging.trace('>>: %7.3f', timeInSeconds)\nremainingTime = timeInSeconds\nhours, remainingTime = divmod(remainingTime, 3600)\nminutes, remainingTime = divmod(remainingTime, 60)\nseconds, remainingTime = divmod(remainingTime, 1)\nmilliseconds = 1000 * remainingTime\nresult = '%02d:%02d:%02d,%03d' % (hours, minutes,... | <|body_start_0|>
Logging.trace('>>: %7.3f', timeInSeconds)
remainingTime = timeInSeconds
hours, remainingTime = divmod(remainingTime, 3600)
minutes, remainingTime = divmod(remainingTime, 60)
seconds, remainingTime = divmod(remainingTime, 1)
milliseconds = 1000 * remaining... | This class provides services to shift an SRT subtitle line list by some duration. | _SubtitleShifter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SubtitleShifter:
"""This class provides services to shift an SRT subtitle line list by some duration."""
def _formatTime(cls, timeInSeconds: Real) -> String:
"""Returns <timeInSeconds> in SRT format with HH:MM:SS,000."""
<|body_0|>
def _scanTime(cls, timeString: String)... | stack_v2_sparse_classes_36k_train_009401 | 14,609 | permissive | [
{
"docstring": "Returns <timeInSeconds> in SRT format with HH:MM:SS,000.",
"name": "_formatTime",
"signature": "def _formatTime(cls, timeInSeconds: Real) -> String"
},
{
"docstring": "Returns time in seconds in SRT format with HH:MM:SS,000 as float seconds.",
"name": "_scanTime",
"signat... | 3 | stack_v2_sparse_classes_30k_train_021276 | Implement the Python class `_SubtitleShifter` described below.
Class description:
This class provides services to shift an SRT subtitle line list by some duration.
Method signatures and docstrings:
- def _formatTime(cls, timeInSeconds: Real) -> String: Returns <timeInSeconds> in SRT format with HH:MM:SS,000.
- def _s... | Implement the Python class `_SubtitleShifter` described below.
Class description:
This class provides services to shift an SRT subtitle line list by some duration.
Method signatures and docstrings:
- def _formatTime(cls, timeInSeconds: Real) -> String: Returns <timeInSeconds> in SRT format with HH:MM:SS,000.
- def _s... | b20b14f49f9c32836e7453e48c3a9ba13411d2bf | <|skeleton|>
class _SubtitleShifter:
"""This class provides services to shift an SRT subtitle line list by some duration."""
def _formatTime(cls, timeInSeconds: Real) -> String:
"""Returns <timeInSeconds> in SRT format with HH:MM:SS,000."""
<|body_0|>
def _scanTime(cls, timeString: String)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _SubtitleShifter:
"""This class provides services to shift an SRT subtitle line list by some duration."""
def _formatTime(cls, timeInSeconds: Real) -> String:
"""Returns <timeInSeconds> in SRT format with HH:MM:SS,000."""
Logging.trace('>>: %7.3f', timeInSeconds)
remainingTime = t... | the_stack_v2_python_sparse | build/lib/lilypondtobvc/src/convertermodules/videoaudiocombiner.py | prof-spock/LilypondToBandVideoConverter | train | 13 |
247d36b220343c4375fd90358fd0ca3914295b36 | [
"self.transect_data = []\nif type(filenames) == str:\n filenames = [filenames]\nif replace != None:\n assert len(replace) == 2, 'Replace must contain 2 elements'\n replace = (str(replace[0]), replace[1])\n for name in filenames:\n self.transect_data.append(replace_vals(name, replace, delim=delim)... | <|body_start_0|>
self.transect_data = []
if type(filenames) == str:
filenames = [filenames]
if replace != None:
assert len(replace) == 2, 'Replace must contain 2 elements'
replace = (str(replace[0]), replace[1])
for name in filenames:
... | This class handles data that are similar to the Breeding Bird survey data. One column has the species ID, one column has stop and all the other columns have transects. This class can handle data with "n" nestings, not just two. For example, the data could have location, transect and stop. The "stop" data should all be ... | Transect_Data | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transect_Data:
"""This class handles data that are similar to the Breeding Bird survey data. One column has the species ID, one column has stop and all the other columns have transects. This class can handle data with "n" nestings, not just two. For example, the data could have location, transect... | stack_v2_sparse_classes_36k_train_009402 | 38,174 | permissive | [
{
"docstring": "Parameters ---------- filenames : list A list of filenames delim : string The file delimiter replace : tuple A tuple of length 2. The first element is a string which represents the missing values that you would like to replace. The second element is the value with which you would like to replace... | 4 | stack_v2_sparse_classes_30k_train_018138 | Implement the Python class `Transect_Data` described below.
Class description:
This class handles data that are similar to the Breeding Bird survey data. One column has the species ID, one column has stop and all the other columns have transects. This class can handle data with "n" nestings, not just two. For example,... | Implement the Python class `Transect_Data` described below.
Class description:
This class handles data that are similar to the Breeding Bird survey data. One column has the species ID, one column has stop and all the other columns have transects. This class can handle data with "n" nestings, not just two. For example,... | af697619c30a37b28b90becc2676d59f803fc9e6 | <|skeleton|>
class Transect_Data:
"""This class handles data that are similar to the Breeding Bird survey data. One column has the species ID, one column has stop and all the other columns have transects. This class can handle data with "n" nestings, not just two. For example, the data could have location, transect... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transect_Data:
"""This class handles data that are similar to the Breeding Bird survey data. One column has the species ID, one column has stop and all the other columns have transects. This class can handle data with "n" nestings, not just two. For example, the data could have location, transect and stop. Th... | the_stack_v2_python_sparse | utils/format_data.py | gavinsimpson/macroeco | train | 0 |
181ef701f8e4c4460418dd8d503432f4a879cf80 | [
"if 0 < x < 231 and 0 < y < 231:\n return bin(x ^ y).count('1')\nelse:\n return 0",
"z = x ^ y\ncount = 0\nwhile z != 0:\n if z & 1 == 1:\n count += 1\n z = z >> 1\nreturn count",
"count = 0\nz = x ^ y\nwhile z != 0:\n count += 1\n z = z & z - 1\nreturn count"
] | <|body_start_0|>
if 0 < x < 231 and 0 < y < 231:
return bin(x ^ y).count('1')
else:
return 0
<|end_body_0|>
<|body_start_1|>
z = x ^ y
count = 0
while z != 0:
if z & 1 == 1:
count += 1
z = z >> 1
return coun... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingdistance(self, x, y):
""":param x: int :param y: int :return: int"""
<|body_0|>
def hammingdistance2(self, x, y):
""":param x: int :param y: int :return: int"""
<|body_1|>
def hammingdistance3(self, x, y):
""":param x: int :p... | stack_v2_sparse_classes_36k_train_009403 | 1,355 | no_license | [
{
"docstring": ":param x: int :param y: int :return: int",
"name": "hammingdistance",
"signature": "def hammingdistance(self, x, y)"
},
{
"docstring": ":param x: int :param y: int :return: int",
"name": "hammingdistance2",
"signature": "def hammingdistance2(self, x, y)"
},
{
"doc... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingdistance(self, x, y): :param x: int :param y: int :return: int
- def hammingdistance2(self, x, y): :param x: int :param y: int :return: int
- def hammingdistance3(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingdistance(self, x, y): :param x: int :param y: int :return: int
- def hammingdistance2(self, x, y): :param x: int :param y: int :return: int
- def hammingdistance3(self... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def hammingdistance(self, x, y):
""":param x: int :param y: int :return: int"""
<|body_0|>
def hammingdistance2(self, x, y):
""":param x: int :param y: int :return: int"""
<|body_1|>
def hammingdistance3(self, x, y):
""":param x: int :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingdistance(self, x, y):
""":param x: int :param y: int :return: int"""
if 0 < x < 231 and 0 < y < 231:
return bin(x ^ y).count('1')
else:
return 0
def hammingdistance2(self, x, y):
""":param x: int :param y: int :return: int"""
... | the_stack_v2_python_sparse | leetcode/45_hammingdistance.py | Yara7L/python_algorithm | train | 0 | |
f928ed48e87a09faeb30f15339711baae2bb837d | [
"self._cache = None\nfor child in self.children:\n child._reset_cache()",
"self._reset_cache()\nname = f'_export_{lang}'\nif hasattr(self, name):\n try:\n return getattr(self, name)(hook=hook, result_name=result_name)\n except TypeError as e:\n raise TypeError(f\"Signature of '{name}' is wr... | <|body_start_0|>
self._cache = None
for child in self.children:
child._reset_cache()
<|end_body_0|>
<|body_start_1|>
self._reset_cache()
name = f'_export_{lang}'
if hasattr(self, name):
try:
return getattr(self, name)(hook=hook, result_nam... | Extends the API to automatically look for exporters. | AutoAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoAction:
"""Extends the API to automatically look for exporters."""
def _reset_cache(self):
"""A same node may appear at different places in the graph. It means the output is used twice. However, we don't want to include the code to generate that same output twice. We cache it and... | stack_v2_sparse_classes_36k_train_009404 | 3,487 | permissive | [
{
"docstring": "A same node may appear at different places in the graph. It means the output is used twice. However, we don't want to include the code to generate that same output twice. We cache it and keep some information about it.",
"name": "_reset_cache",
"signature": "def _reset_cache(self)"
},
... | 3 | stack_v2_sparse_classes_30k_test_000812 | Implement the Python class `AutoAction` described below.
Class description:
Extends the API to automatically look for exporters.
Method signatures and docstrings:
- def _reset_cache(self): A same node may appear at different places in the graph. It means the output is used twice. However, we don't want to include the... | Implement the Python class `AutoAction` described below.
Class description:
Extends the API to automatically look for exporters.
Method signatures and docstrings:
- def _reset_cache(self): A same node may appear at different places in the graph. It means the output is used twice. However, we don't want to include the... | 27d6da4ecdd76e18292f265fde61d19b66937a5c | <|skeleton|>
class AutoAction:
"""Extends the API to automatically look for exporters."""
def _reset_cache(self):
"""A same node may appear at different places in the graph. It means the output is used twice. However, we don't want to include the code to generate that same output twice. We cache it and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoAction:
"""Extends the API to automatically look for exporters."""
def _reset_cache(self):
"""A same node may appear at different places in the graph. It means the output is used twice. However, we don't want to include the code to generate that same output twice. We cache it and keep some in... | the_stack_v2_python_sparse | mlprodict/grammar/grammar_sklearn/grammar/api_extension.py | sdpython/mlprodict | train | 60 |
8290f7c7dc8710df3fbb168b4e5bbf78b37d54cb | [
"control_palette = control_instance.palette()\ncontrol_value = control_instance.value()\ncolor = QtCore.Qt.white\nred = QtGui.QColor(255, 220, 220)\nyellow = QtGui.QColor(255, 255, 200)\nis_valid = False\nif control_value in (b'', None, traits.Undefined):\n if control_instance.optional:\n color = yellow\n... | <|body_start_0|>
control_palette = control_instance.palette()
control_value = control_instance.value()
color = QtCore.Qt.white
red = QtGui.QColor(255, 220, 220)
yellow = QtGui.QColor(255, 255, 200)
is_valid = False
if control_value in (b'', None, traits.Undefined)... | Control to enter a bytes string. | BytesControlWidget | [
"CECILL-B"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BytesControlWidget:
"""Control to enter a bytes string."""
def is_valid(control_instance, *args, **kwargs):
"""Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance... | stack_v2_sparse_classes_36k_train_009405 | 4,616 | permissive | [
{
"docstring": "Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance: QLineEdit (mandatory) the control widget we want to validate Returns ------- out: bool True if the control value is valid... | 2 | null | Implement the Python class `BytesControlWidget` described below.
Class description:
Control to enter a bytes string.
Method signatures and docstrings:
- def is_valid(control_instance, *args, **kwargs): Method to check if the new control value is correct. If the new entered value is not correct, the backroung control ... | Implement the Python class `BytesControlWidget` described below.
Class description:
Control to enter a bytes string.
Method signatures and docstrings:
- def is_valid(control_instance, *args, **kwargs): Method to check if the new control value is correct. If the new entered value is not correct, the backroung control ... | 779e254098b183eb312eb589268c474dd65c5679 | <|skeleton|>
class BytesControlWidget:
"""Control to enter a bytes string."""
def is_valid(control_instance, *args, **kwargs):
"""Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BytesControlWidget:
"""Control to enter a bytes string."""
def is_valid(control_instance, *args, **kwargs):
"""Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance: QLineEdit (... | the_stack_v2_python_sparse | python/soma/qt_gui/controls/Bytes.py | populse/soma-base | train | 0 |
7d7a6319c51776404ac0ff30766ac6dd8fe6ccf9 | [
"self.broker_handler = broker_handler\nself.order_id = 0\nself.events = events\nself.fill_dict = {}",
"try:\n order_id = response['order_id']\nexcept:\n order_id = -1\nself.fill_dict[str(order_id)] = {}\nfd = self.fill_dict[str(order_id)]\nfd['symbol'] = event.symbol\nfd['timestamp'] = response['timestamp']... | <|body_start_0|>
self.broker_handler = broker_handler
self.order_id = 0
self.events = events
self.fill_dict = {}
<|end_body_0|>
<|body_start_1|>
try:
order_id = response['order_id']
except:
order_id = -1
self.fill_dict[str(order_id)] = {}
... | . | MetatraderExecutionHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetatraderExecutionHandler:
"""."""
def __init__(self, context, events, broker_handler):
"""Initialises the handler, setting the event queues up internally. Parameters: events - The Queue of Event objects."""
<|body_0|>
def create_fill(self, response, event):
"""... | stack_v2_sparse_classes_36k_train_009406 | 3,325 | no_license | [
{
"docstring": "Initialises the handler, setting the event queues up internally. Parameters: events - The Queue of Event objects.",
"name": "__init__",
"signature": "def __init__(self, context, events, broker_handler)"
},
{
"docstring": "Handles the creation of the FillEvent that will be placed ... | 3 | null | Implement the Python class `MetatraderExecutionHandler` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, context, events, broker_handler): Initialises the handler, setting the event queues up internally. Parameters: events - The Queue of Event objects.
- def create_fill(sel... | Implement the Python class `MetatraderExecutionHandler` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, context, events, broker_handler): Initialises the handler, setting the event queues up internally. Parameters: events - The Queue of Event objects.
- def create_fill(sel... | 1b88117961a3912aa9b2c0326aa5081a884d0a8d | <|skeleton|>
class MetatraderExecutionHandler:
"""."""
def __init__(self, context, events, broker_handler):
"""Initialises the handler, setting the event queues up internally. Parameters: events - The Queue of Event objects."""
<|body_0|>
def create_fill(self, response, event):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetatraderExecutionHandler:
"""."""
def __init__(self, context, events, broker_handler):
"""Initialises the handler, setting the event queues up internally. Parameters: events - The Queue of Event objects."""
self.broker_handler = broker_handler
self.order_id = 0
self.even... | the_stack_v2_python_sparse | htr/core/execution/metatrader.py | mglcampos/trader | train | 0 |
69f674fbe02b4bb587a634fa80ac1144dd354f90 | [
"if releaselevel not in self._specifiers:\n raise ValueError(f'''Value \"{releaselevel}\" for releaselevel not in ({','.join(sorted(self._specifiers.keys()))})''')\nself.major, self.minor, self.micro = (major, minor, micro)\nself.releaselevel, self.serial, self.label = (releaselevel, serial, label)",
"items = ... | <|body_start_0|>
if releaselevel not in self._specifiers:
raise ValueError(f'''Value "{releaselevel}" for releaselevel not in ({','.join(sorted(self._specifiers.keys()))})''')
self.major, self.minor, self.micro = (major, minor, micro)
self.releaselevel, self.serial, self.label = (rel... | This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported. | Version | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Version:
"""This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported."""
def __init__(self, major, mi... | stack_v2_sparse_classes_36k_train_009407 | 6,479 | permissive | [
{
"docstring": "Create new version object. Provided arguments are stored in public class attributes by the same name. Args: major (int): Major version minor (int): Minor version micro (int): Micro (aka patchlevel) version releaselevel (str): Optional PEP 440 specifier serial (int): Optional number associated wi... | 3 | stack_v2_sparse_classes_30k_train_014625 | Implement the Python class `Version` described below.
Class description:
This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supporte... | Implement the Python class `Version` described below.
Class description:
This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supporte... | deacf4c422bc9e50cb347e11a8cbfa0195bd4274 | <|skeleton|>
class Version:
"""This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported."""
def __init__(self, major, mi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Version:
"""This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported."""
def __init__(self, major, minor, micro, r... | the_stack_v2_python_sparse | idaes/ver.py | IDAES/idaes-pse | train | 173 |
53ebd6aa0a2eec35b5a4844b36b6b452a925caaa | [
"logger.debug('Init container received terminate request, terminating.')\nawait error('Init container received terminating request.', self.communicator)\nfor task in asyncio.all_tasks():\n task.cancel()",
"await self.communicator.update_status('PP')\nmissing_data = (await self.communicator.missing_data_locatio... | <|body_start_0|>
logger.debug('Init container received terminate request, terminating.')
await error('Init container received terminating request.', self.communicator)
for task in asyncio.all_tasks():
task.cancel()
<|end_body_0|>
<|body_start_1|>
await self.communicator.upda... | Protocol class. | InitProtocol | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitProtocol:
"""Protocol class."""
async def post_terminate(self, message: Message, identity: PeerIdentity):
"""Handle post-terminate command."""
<|body_0|>
async def transfer_missing_data(self):
"""Transfer missing data. :raises DataTransferError: when data tra... | stack_v2_sparse_classes_36k_train_009408 | 12,909 | permissive | [
{
"docstring": "Handle post-terminate command.",
"name": "post_terminate",
"signature": "async def post_terminate(self, message: Message, identity: PeerIdentity)"
},
{
"docstring": "Transfer missing data. :raises DataTransferError: when data transfer error occurs.",
"name": "transfer_missing... | 2 | null | Implement the Python class `InitProtocol` described below.
Class description:
Protocol class.
Method signatures and docstrings:
- async def post_terminate(self, message: Message, identity: PeerIdentity): Handle post-terminate command.
- async def transfer_missing_data(self): Transfer missing data. :raises DataTransfe... | Implement the Python class `InitProtocol` described below.
Class description:
Protocol class.
Method signatures and docstrings:
- async def post_terminate(self, message: Message, identity: PeerIdentity): Handle post-terminate command.
- async def transfer_missing_data(self): Transfer missing data. :raises DataTransfe... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class InitProtocol:
"""Protocol class."""
async def post_terminate(self, message: Message, identity: PeerIdentity):
"""Handle post-terminate command."""
<|body_0|>
async def transfer_missing_data(self):
"""Transfer missing data. :raises DataTransferError: when data tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitProtocol:
"""Protocol class."""
async def post_terminate(self, message: Message, identity: PeerIdentity):
"""Handle post-terminate command."""
logger.debug('Init container received terminate request, terminating.')
await error('Init container received terminating request.', se... | the_stack_v2_python_sparse | resolwe/flow/executors/init_container.py | genialis/resolwe | train | 35 |
bc1b6eadf626558edb0e134e6c91ad242a012af1 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted. | PredictionServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictionServiceServicer:
"""AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted."""
def Predict(self, request, context):
"""Perform an online prediction. The prediction result will be dir... | stack_v2_sparse_classes_36k_train_009409 | 4,461 | permissive | [
{
"docstring": "Perform an online prediction. The prediction result will be directly returned in the response. Available for following ML problems, and their expected request payloads: * Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. * Image Object Detection - Image in .JPEG... | 2 | stack_v2_sparse_classes_30k_train_002986 | Implement the Python class `PredictionServiceServicer` described below.
Class description:
AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted.
Method signatures and docstrings:
- def Predict(self, request, context): Perfor... | Implement the Python class `PredictionServiceServicer` described below.
Class description:
AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted.
Method signatures and docstrings:
- def Predict(self, request, context): Perfor... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class PredictionServiceServicer:
"""AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted."""
def Predict(self, request, context):
"""Perform an online prediction. The prediction result will be dir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredictionServiceServicer:
"""AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted."""
def Predict(self, request, context):
"""Perform an online prediction. The prediction result will be directly returne... | the_stack_v2_python_sparse | automl/google/cloud/automl_v1/proto/prediction_service_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
dd0748fddbaba406b8d42ca4620c5a9618b5d2a5 | [
"response = self.client.get('/profiles/')\nself.assertEqual(response.status_code, 302)\nuser = User.objects.create(username='testuser')\nuser.set_password('12345')\nuser.save()\nlogged_in = self.client.login(username='testuser', password='12345')\nresponse = self.client.get('/profiles/')\nself.assertEqual(response.... | <|body_start_0|>
response = self.client.get('/profiles/')
self.assertEqual(response.status_code, 302)
user = User.objects.create(username='testuser')
user.set_password('12345')
user.save()
logged_in = self.client.login(username='testuser', password='12345')
respon... | TestView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestView:
def test_profiles(self):
"""testing if the profile page works and template used"""
<|body_0|>
def test_show_correct_orders(self):
"""testing if orders shown are correctly associated to profile"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009410 | 2,441 | no_license | [
{
"docstring": "testing if the profile page works and template used",
"name": "test_profiles",
"signature": "def test_profiles(self)"
},
{
"docstring": "testing if orders shown are correctly associated to profile",
"name": "test_show_correct_orders",
"signature": "def test_show_correct_o... | 2 | stack_v2_sparse_classes_30k_train_006290 | Implement the Python class `TestView` described below.
Class description:
Implement the TestView class.
Method signatures and docstrings:
- def test_profiles(self): testing if the profile page works and template used
- def test_show_correct_orders(self): testing if orders shown are correctly associated to profile | Implement the Python class `TestView` described below.
Class description:
Implement the TestView class.
Method signatures and docstrings:
- def test_profiles(self): testing if the profile page works and template used
- def test_show_correct_orders(self): testing if orders shown are correctly associated to profile
<|... | e61dde21f68e84c312016fd2672c138b60b76344 | <|skeleton|>
class TestView:
def test_profiles(self):
"""testing if the profile page works and template used"""
<|body_0|>
def test_show_correct_orders(self):
"""testing if orders shown are correctly associated to profile"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestView:
def test_profiles(self):
"""testing if the profile page works and template used"""
response = self.client.get('/profiles/')
self.assertEqual(response.status_code, 302)
user = User.objects.create(username='testuser')
user.set_password('12345')
user.save... | the_stack_v2_python_sparse | profiles/test_views.py | Code-Institute-Submissions/furnitart | train | 0 | |
3c50a64ffc3294bbe3e19cff20596dfe35a5a8b1 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceConfigurationSettingState()",
"from .compliance_status import ComplianceStatus\nfrom .setting_source import SettingSource\nfrom .compliance_status import ComplianceStatus\nfrom .setting_source import SettingSource\nfields: Dict[s... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceConfigurationSettingState()
<|end_body_0|>
<|body_start_1|>
from .compliance_status import ComplianceStatus
from .setting_source import SettingSource
from .compliance_statu... | Device Configuration Setting State for a given device. | DeviceConfigurationSettingState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceConfigurationSettingState:
"""Device Configuration Setting State for a given device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState:
"""Creates a new instance of the appropriate class based on discriminator value ... | stack_v2_sparse_classes_36k_train_009411 | 5,456 | 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: DeviceConfigurationSettingState",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | stack_v2_sparse_classes_30k_train_017934 | Implement the Python class `DeviceConfigurationSettingState` described below.
Class description:
Device Configuration Setting State for a given device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState: Creates a new instan... | Implement the Python class `DeviceConfigurationSettingState` described below.
Class description:
Device Configuration Setting State for a given device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState: Creates a new instan... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceConfigurationSettingState:
"""Device Configuration Setting State for a given device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState:
"""Creates a new instance of the appropriate class based on discriminator value ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceConfigurationSettingState:
"""Device Configuration Setting State for a given device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceConfigurationSettingState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_n... | the_stack_v2_python_sparse | msgraph/generated/models/device_configuration_setting_state.py | microsoftgraph/msgraph-sdk-python | train | 135 |
3c443c73e0c6e0fbe502ba53a459ed98b2730e84 | [
"self.error = error\nself.finished = finished\nself.host_name = host_name\nself.mount_volumes_info_proto = mount_volumes_info_proto\nself.slave_task_start_time_usecs = slave_task_start_time_usecs\nself.target_entity = target_entity\nself.use_existing_agent = use_existing_agent\nself.vmware_params = vmware_params",
... | <|body_start_0|>
self.error = error
self.finished = finished
self.host_name = host_name
self.mount_volumes_info_proto = mount_volumes_info_proto
self.slave_task_start_time_usecs = slave_task_start_time_usecs
self.target_entity = target_entity
self.use_existing_age... | Implementation of the 'DestroyMountVolumesTaskInfoProto' model. TODO: type description here. Attributes: error (ErrorProto): If an error is encountered during destroy it is set here. finished (bool): This will be set to true if the task is complete on the slave. host_name (string): This is the host name of the ESXi hos... | DestroyMountVolumesTaskInfoProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestroyMountVolumesTaskInfoProto:
"""Implementation of the 'DestroyMountVolumesTaskInfoProto' model. TODO: type description here. Attributes: error (ErrorProto): If an error is encountered during destroy it is set here. finished (bool): This will be set to true if the task is complete on the slav... | stack_v2_sparse_classes_36k_train_009412 | 4,998 | permissive | [
{
"docstring": "Constructor for the DestroyMountVolumesTaskInfoProto class",
"name": "__init__",
"signature": "def __init__(self, error=None, finished=None, host_name=None, mount_volumes_info_proto=None, slave_task_start_time_usecs=None, target_entity=None, use_existing_agent=None, vmware_params=None)"
... | 2 | null | Implement the Python class `DestroyMountVolumesTaskInfoProto` described below.
Class description:
Implementation of the 'DestroyMountVolumesTaskInfoProto' model. TODO: type description here. Attributes: error (ErrorProto): If an error is encountered during destroy it is set here. finished (bool): This will be set to t... | Implement the Python class `DestroyMountVolumesTaskInfoProto` described below.
Class description:
Implementation of the 'DestroyMountVolumesTaskInfoProto' model. TODO: type description here. Attributes: error (ErrorProto): If an error is encountered during destroy it is set here. finished (bool): This will be set to t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DestroyMountVolumesTaskInfoProto:
"""Implementation of the 'DestroyMountVolumesTaskInfoProto' model. TODO: type description here. Attributes: error (ErrorProto): If an error is encountered during destroy it is set here. finished (bool): This will be set to true if the task is complete on the slav... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DestroyMountVolumesTaskInfoProto:
"""Implementation of the 'DestroyMountVolumesTaskInfoProto' model. TODO: type description here. Attributes: error (ErrorProto): If an error is encountered during destroy it is set here. finished (bool): This will be set to true if the task is complete on the slave. host_name ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/destroy_mount_volumes_task_info_proto.py | cohesity/management-sdk-python | train | 24 |
99ff28c15a424c48a656e3b376a68f138aea0272 | [
"n = len(words)\nll = len(S)\ndp = {}\n\ndef is_sub(X, Y):\n i = 0\n j = 0\n nx = len(X)\n ny = len(Y)\n if nx > ny:\n return False\n while i < nx and j < ny:\n if X[i] == Y[j]:\n i += 1\n j += 1\n else:\n j += 1\n if i == nx:\n retur... | <|body_start_0|>
n = len(words)
ll = len(S)
dp = {}
def is_sub(X, Y):
i = 0
j = 0
nx = len(X)
ny = len(Y)
if nx > ny:
return False
while i < nx and j < ny:
if X[i] == Y[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numMatchingSubseqTLE(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009413 | 1,952 | no_license | [
{
"docstring": ":type S: str :type words: List[str] :rtype: int",
"name": "numMatchingSubseqTLE",
"signature": "def numMatchingSubseqTLE(self, S, words)"
},
{
"docstring": ":type S: str :type words: List[str] :rtype: int",
"name": "numMatchingSubseq",
"signature": "def numMatchingSubseq(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseqTLE(self, S, words): :type S: str :type words: List[str] :rtype: int
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseqTLE(self, S, words): :type S: str :type words: List[str] :rtype: int
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def numMatchingSubseqTLE(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numMatchingSubseqTLE(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
n = len(words)
ll = len(S)
dp = {}
def is_sub(X, Y):
i = 0
j = 0
nx = len(X)
ny = len(Y)
if nx > ny:
... | the_stack_v2_python_sparse | python/leetcode.792.py | CalvinNeo/LeetCode | train | 3 | |
2ffda30198272d1efa3691bde8149362c8c260e6 | [
"self.store = {}\nfor s in range(len(words)):\n if self.store.has_key(words[s]):\n self.store[words[s]].append(s)\n else:\n self.store[words[s]] = [s]",
"res = sys.maxint\nfor a in self.store[word1]:\n for b in self.store[word2]:\n res = min(res, abs(b - a))\nreturn res"
] | <|body_start_0|>
self.store = {}
for s in range(len(words)):
if self.store.has_key(words[s]):
self.store[words[s]].append(s)
else:
self.store[words[s]] = [s]
<|end_body_0|>
<|body_start_1|>
res = sys.maxint
for a in self.store[word... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_009414 | 1,801 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 507ed2efeff7818ca9cf53a8ee7fb80d3c530d67 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.store = {}
for s in range(len(words)):
if self.store.has_key(words[s]):
self.store[words[s]].append(s)
else:
self.stor... | the_stack_v2_python_sparse | Leetcode/Design/#244-Shortest Word Distance II/main.py | qizongjun/Algorithms-1 | train | 0 | |
703232a621d6c94a7c084dfac8099e2a409e4695 | [
"osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)\nself.deploy._CheckDeployType()\nself.assertTrue(self.getCopyPath('envoy_shell'))\nself.assertFalse(self.getCopyPath('app_shell'))\nself.assertFalse(self.getCopyPath('chrome'))",
"osutils.Touch(os.path.join(self.deploy.optio... | <|body_start_0|>
osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)
self.deploy._CheckDeployType()
self.assertTrue(self.getCopyPath('envoy_shell'))
self.assertFalse(self.getCopyPath('app_shell'))
self.assertFalse(self.getCopyPath('chrome'))
<... | Test detection of deployment type using build dir. | TestDeploymentType | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDeploymentType:
"""Test detection of deployment type using build dir."""
def testEnvoyDetection(self):
"""Check for an envoy deployment"""
<|body_0|>
def testAppShellDetection(self):
"""Check for an app_shell deployment"""
<|body_1|>
def testChro... | stack_v2_sparse_classes_36k_train_009415 | 13,041 | permissive | [
{
"docstring": "Check for an envoy deployment",
"name": "testEnvoyDetection",
"signature": "def testEnvoyDetection(self)"
},
{
"docstring": "Check for an app_shell deployment",
"name": "testAppShellDetection",
"signature": "def testAppShellDetection(self)"
},
{
"docstring": "Chec... | 4 | stack_v2_sparse_classes_30k_train_006089 | Implement the Python class `TestDeploymentType` described below.
Class description:
Test detection of deployment type using build dir.
Method signatures and docstrings:
- def testEnvoyDetection(self): Check for an envoy deployment
- def testAppShellDetection(self): Check for an app_shell deployment
- def testChromeAn... | Implement the Python class `TestDeploymentType` described below.
Class description:
Test detection of deployment type using build dir.
Method signatures and docstrings:
- def testEnvoyDetection(self): Check for an envoy deployment
- def testAppShellDetection(self): Check for an app_shell deployment
- def testChromeAn... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TestDeploymentType:
"""Test detection of deployment type using build dir."""
def testEnvoyDetection(self):
"""Check for an envoy deployment"""
<|body_0|>
def testAppShellDetection(self):
"""Check for an app_shell deployment"""
<|body_1|>
def testChro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDeploymentType:
"""Test detection of deployment type using build dir."""
def testEnvoyDetection(self):
"""Check for an envoy deployment"""
osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)
self.deploy._CheckDeployType()
self.asser... | the_stack_v2_python_sparse | third_party/chromite/scripts/deploy_chrome_unittest.py | metux/chromium-suckless | train | 5 |
b6ddebe8dc5e5e78ff829ed644eb53446b0c43b4 | [
"if not len(nums):\n return\nindex = len(nums) - 2\nwhile index >= 0 and nums[index] >= nums[index + 1]:\n index -= 1\nif index >= 0:\n i = index + 1\n while i < len(nums) and nums[i] > nums[index]:\n i += 1\n nums[i - 1], nums[index] = (nums[index], nums[i - 1])\nleft, right = (index + 1, len... | <|body_start_0|>
if not len(nums):
return
index = len(nums) - 2
while index >= 0 and nums[index] >= nums[index + 1]:
index -= 1
if index >= 0:
i = index + 1
while i < len(nums) and nums[i] > nums[index]:
i += 1
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_009416 | 1,580 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermutation(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_005062 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def permuteUnique(self, nums): :type nums: List[int] :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def permuteUnique(self, nums): :type nums: List[int] :... | 9b82e3bd1b404e3cff31469986577ceec3924f73 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
if not len(nums):
return
index = len(nums) - 2
while index >= 0 and nums[index] >= nums[index + 1]:
index -= 1
... | the_stack_v2_python_sparse | Python/47PermutationsII.py | Qiumy/leetcode | train | 0 | |
d89c81ab826f5cc7e6bad3d06318c0fc63b2f5ea | [
"import logging\nlogging.getLogger('transformers').setLevel(logging.ERROR)\nimport os\nos.environ['TOKENIZERS_PARALLELISM'] = 'false'\nimport transformers\nself.tokenizer = transformers.BertTokenizer.from_pretrained('mymusise/EasternFantasyNoval')\nself.lm = transformers.TFGPT2LMHeadModel.from_pretrained('mymusise/... | <|body_start_0|>
import logging
logging.getLogger('transformers').setLevel(logging.ERROR)
import os
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
import transformers
self.tokenizer = transformers.BertTokenizer.from_pretrained('mymusise/EasternFantasyNoval')
self.... | GPT2LMCH | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPT2LMCH:
def __init__(self):
""":Package Requirements: * **torch** (if use_tf = False) * **tensorflow** >= 2.0.0 (if use_tf = True) * **transformers**"""
<|body_0|>
def __call__(self, sent):
""":param str sent: A sentence. :return: Fluency (ppl). :rtype: float"""
... | stack_v2_sparse_classes_36k_train_009417 | 1,330 | permissive | [
{
"docstring": ":Package Requirements: * **torch** (if use_tf = False) * **tensorflow** >= 2.0.0 (if use_tf = True) * **transformers**",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param str sent: A sentence. :return: Fluency (ppl). :rtype: float",
"name": "__ca... | 2 | stack_v2_sparse_classes_30k_train_010423 | Implement the Python class `GPT2LMCH` described below.
Class description:
Implement the GPT2LMCH class.
Method signatures and docstrings:
- def __init__(self): :Package Requirements: * **torch** (if use_tf = False) * **tensorflow** >= 2.0.0 (if use_tf = True) * **transformers**
- def __call__(self, sent): :param str ... | Implement the Python class `GPT2LMCH` described below.
Class description:
Implement the GPT2LMCH class.
Method signatures and docstrings:
- def __init__(self): :Package Requirements: * **torch** (if use_tf = False) * **tensorflow** >= 2.0.0 (if use_tf = True) * **transformers**
- def __call__(self, sent): :param str ... | 412d1b2777dea5009fe97ac264044bfda65dfa5d | <|skeleton|>
class GPT2LMCH:
def __init__(self):
""":Package Requirements: * **torch** (if use_tf = False) * **tensorflow** >= 2.0.0 (if use_tf = True) * **transformers**"""
<|body_0|>
def __call__(self, sent):
""":param str sent: A sentence. :return: Fluency (ppl). :rtype: float"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GPT2LMCH:
def __init__(self):
""":Package Requirements: * **torch** (if use_tf = False) * **tensorflow** >= 2.0.0 (if use_tf = True) * **transformers**"""
import logging
logging.getLogger('transformers').setLevel(logging.ERROR)
import os
os.environ['TOKENIZERS_PARALLELI... | the_stack_v2_python_sparse | OpenAttack/metric/gptlmch.py | sigma-random/OpenAttack | train | 0 | |
9ee3951d484d64a80b375ea232066c783ef16238 | [
"if self.mask is not None:\n return kl_div_mask(self.b_np, x.as_array(), self.eta_np, self.mask)\nreturn kl_div(self.b_np, x.as_array(), self.eta_np)",
"if self.mask is not None:\n return kl_convex_conjugate_mask(x.as_array(), self.b_np, self.eta_np, self.mask)\nreturn kl_convex_conjugate(x.as_array(), self... | <|body_start_0|>
if self.mask is not None:
return kl_div_mask(self.b_np, x.as_array(), self.eta_np, self.mask)
return kl_div(self.b_np, x.as_array(), self.eta_np)
<|end_body_0|>
<|body_start_1|>
if self.mask is not None:
return kl_convex_conjugate_mask(x.as_array(), self... | KullbackLeibler_numba | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KullbackLeibler_numba:
def __call__(self, x):
"""Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\eta\\geq0`."""
<|body_0|>
def convex_conjugate(self, x):
""... | stack_v2_sparse_classes_36k_train_009418 | 18,813 | permissive | [
{
"docstring": "Returns the value of the KullbackLeibler function at :math:`(b, x + \\\\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\\\eta\\\\geq0`.",
"name": "__call__",
"signature": "def __call__(self, x)"
},
{
"docstring": "Returns the value of the ... | 5 | stack_v2_sparse_classes_30k_train_021132 | Implement the Python class `KullbackLeibler_numba` described below.
Class description:
Implement the KullbackLeibler_numba class.
Method signatures and docstrings:
- def __call__(self, x): Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only... | Implement the Python class `KullbackLeibler_numba` described below.
Class description:
Implement the KullbackLeibler_numba class.
Method signatures and docstrings:
- def __call__(self, x): Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only... | b0503d1b24cc71d937bbb780602d8778b36b0e77 | <|skeleton|>
class KullbackLeibler_numba:
def __call__(self, x):
"""Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\eta\\geq0`."""
<|body_0|>
def convex_conjugate(self, x):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KullbackLeibler_numba:
def __call__(self, x):
"""Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\eta\\geq0`."""
if self.mask is not None:
return kl_div_mask(self.b_np, x.a... | the_stack_v2_python_sparse | Wrappers/Python/cil/optimisation/functions/KullbackLeibler.py | TomographicImaging/CIL | train | 72 | |
0c1f1699415939acb3ee0917cb75d5e6be96bbc3 | [
"if not root:\n return None\nnode = TreeNode(root.val)\nif root.children:\n curr = node.left = self.encode(root.children[0])\n for child in root.children[1:]:\n curr.right = self.encode(child)\n curr = curr.right\nreturn node",
"if not root:\n return None\nnode = Node(root.val, [])\nif r... | <|body_start_0|>
if not root:
return None
node = TreeNode(root.val)
if root.children:
curr = node.left = self.encode(root.children[0])
for child in root.children[1:]:
curr.right = self.encode(child)
curr = curr.right
ret... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, root):
"""Decodes your binary tree to an n-ary tree. :type root: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_009419 | 1,709 | no_license | [
{
"docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode",
"name": "encode",
"signature": "def encode(self, root)"
},
{
"docstring": "Decodes your binary tree to an n-ary tree. :type root: TreeNode :rtype: Node",
"name": "decode",
"signature": "def decode... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, root): Decodes your binary tree to an n-ary tree. :type root: TreeN... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, root): Decodes your binary tree to an n-ary tree. :type root: TreeN... | 6fec95b9b4d735727160905e754a698513bfb7d8 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, root):
"""Decodes your binary tree to an n-ary tree. :type root: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
if not root:
return None
node = TreeNode(root.val)
if root.children:
curr = node.left = self.encode(root.children[0])
for child in ... | the_stack_v2_python_sparse | leetcode/tree/encode-n-ary-tree-to-binary-tree.py | jwyx3/practices | train | 2 | |
0b96698f108e36feba88af61b8ce6b592d5e8d72 | [
"error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError}\nerror_map.update(kwargs.pop('error_map', {}) or {})\n_headers = kwargs.pop('headers', {}) or {}\n_params = kwargs.pop('params', {}) or {}\ncls: ClsType[JSON] = kwargs.pop('cls', None)\... | <|body_start_0|>
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError}
error_map.update(kwargs.pop('error_map', {}) or {})
_headers = kwargs.pop('headers', {}) or {}
_params = kwargs.pop('params', {}) or {}
... | ServiceBusManagementClientOperationsMixin | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceBusManagementClientOperationsMixin:
async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON:
"""Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type top... | stack_v2_sparse_classes_36k_train_009420 | 37,944 | permissive | [
{
"docstring": "Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type topic_name: str :keyword skip: Default value is 0. :paramtype skip: int :keyword top: Default value is 100. :paramtype top: int :return: JSON :rtype: JSON :raises ... | 3 | stack_v2_sparse_classes_30k_train_013084 | Implement the Python class `ServiceBusManagementClientOperationsMixin` described below.
Class description:
Implement the ServiceBusManagementClientOperationsMixin class.
Method signatures and docstrings:
- async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: Get su... | Implement the Python class `ServiceBusManagementClientOperationsMixin` described below.
Class description:
Implement the ServiceBusManagementClientOperationsMixin class.
Method signatures and docstrings:
- async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON: Get su... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class ServiceBusManagementClientOperationsMixin:
async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON:
"""Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type top... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceBusManagementClientOperationsMixin:
async def list_subscriptions(self, topic_name: str, *, skip: int=0, top: int=100, **kwargs: Any) -> JSON:
"""Get subscriptions. Get the details about the subscriptions of the given topic. :param topic_name: name of the topic. Required. :type topic_name: str :... | the_stack_v2_python_sparse | sdk/servicebus/azure-servicebus/azure/servicebus/management/_generated/aio/operations/_operations.py | Azure/azure-sdk-for-python | train | 4,046 | |
44d205d41866237008de7ca406626e21753ac164 | [
"self.meldings_kode_field = meldings_kode_field\nself.meldings_tekst_field = meldings_tekst_field\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nmeldings_kode_field = dictionary.get('meldingsKodeField')\nmeldings_tekst_field = dictionary.get('meldingsTekstField')\n... | <|body_start_0|>
self.meldings_kode_field = meldings_kode_field
self.meldings_tekst_field = meldings_tekst_field
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
meldings_kode_field = dictionary.get... | Implementation of the 'Meldinger' model. TODO: type model description here. Attributes: meldings_kode_field (int): TODO: type description here. meldings_tekst_field (string): TODO: type description here. | Meldinger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meldinger:
"""Implementation of the 'Meldinger' model. TODO: type model description here. Attributes: meldings_kode_field (int): TODO: type description here. meldings_tekst_field (string): TODO: type description here."""
def __init__(self, meldings_kode_field=None, meldings_tekst_field=None,... | stack_v2_sparse_classes_36k_train_009421 | 2,224 | permissive | [
{
"docstring": "Constructor for the Meldinger class",
"name": "__init__",
"signature": "def __init__(self, meldings_kode_field=None, meldings_tekst_field=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti... | 2 | null | Implement the Python class `Meldinger` described below.
Class description:
Implementation of the 'Meldinger' model. TODO: type model description here. Attributes: meldings_kode_field (int): TODO: type description here. meldings_tekst_field (string): TODO: type description here.
Method signatures and docstrings:
- def... | Implement the Python class `Meldinger` described below.
Class description:
Implementation of the 'Meldinger' model. TODO: type model description here. Attributes: meldings_kode_field (int): TODO: type description here. meldings_tekst_field (string): TODO: type description here.
Method signatures and docstrings:
- def... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Meldinger:
"""Implementation of the 'Meldinger' model. TODO: type model description here. Attributes: meldings_kode_field (int): TODO: type description here. meldings_tekst_field (string): TODO: type description here."""
def __init__(self, meldings_kode_field=None, meldings_tekst_field=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Meldinger:
"""Implementation of the 'Meldinger' model. TODO: type model description here. Attributes: meldings_kode_field (int): TODO: type description here. meldings_tekst_field (string): TODO: type description here."""
def __init__(self, meldings_kode_field=None, meldings_tekst_field=None, additional_p... | the_stack_v2_python_sparse | idfy_rest_client/models/meldinger.py | dealflowteam/Idfy | train | 0 |
605143394e369df1ca0387070e4805c6d39ae4bd | [
"expressions = [('a&b', ['a', 'b'], 'a&b'), ('a&b&c', ['a', 'b'], ''), ('a|b', ['a'], 'a'), ('a|b|c', ['a', 'b'], 'a'), ('(a&b)|c', ['a', 'b'], '(a&b)'), ('(a&b)|c', ['c'], 'c'), ('(a|b)&c', ['a', 'c'], '(a)&c'), ('(a|b)&c', ['a'], ''), ('(a&b)|(b&c)', ['b', 'c'], '(b&c)'), ('(a|b)&(c|d)', ['a', 'd'], '(a)&(d)'), (... | <|body_start_0|>
expressions = [('a&b', ['a', 'b'], 'a&b'), ('a&b&c', ['a', 'b'], ''), ('a|b', ['a'], 'a'), ('a|b|c', ['a', 'b'], 'a'), ('(a&b)|c', ['a', 'b'], '(a&b)'), ('(a&b)|c', ['c'], 'c'), ('(a|b)&c', ['a', 'c'], '(a)&c'), ('(a|b)&c', ['a'], ''), ('(a&b)|(b&c)', ['b', 'c'], '(b&c)'), ('(a|b)&(c|d)', ['a',... | SecretVisTreeTest | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretVisTreeTest:
def test_optimal_path(self):
"""Test the optimal path functionality"""
<|body_0|>
def test_compute_shares(self):
"""Tests computing the shares"""
<|body_1|>
def test_encrypt_decrypt(self):
"""Tests encrypting and decrypting the... | stack_v2_sparse_classes_36k_train_009422 | 5,692 | permissive | [
{
"docstring": "Test the optimal path functionality",
"name": "test_optimal_path",
"signature": "def test_optimal_path(self)"
},
{
"docstring": "Tests computing the shares",
"name": "test_compute_shares",
"signature": "def test_compute_shares(self)"
},
{
"docstring": "Tests encry... | 3 | stack_v2_sparse_classes_30k_train_012689 | Implement the Python class `SecretVisTreeTest` described below.
Class description:
Implement the SecretVisTreeTest class.
Method signatures and docstrings:
- def test_optimal_path(self): Test the optimal path functionality
- def test_compute_shares(self): Tests computing the shares
- def test_encrypt_decrypt(self): T... | Implement the Python class `SecretVisTreeTest` described below.
Class description:
Implement the SecretVisTreeTest class.
Method signatures and docstrings:
- def test_optimal_path(self): Test the optimal path functionality
- def test_compute_shares(self): Tests computing the shares
- def test_encrypt_decrypt(self): T... | eb61250886e51647bd1edb6d8f4fa7f83eb0bc81 | <|skeleton|>
class SecretVisTreeTest:
def test_optimal_path(self):
"""Test the optimal path functionality"""
<|body_0|>
def test_compute_shares(self):
"""Tests computing the shares"""
<|body_1|>
def test_encrypt_decrypt(self):
"""Tests encrypting and decrypting the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecretVisTreeTest:
def test_optimal_path(self):
"""Test the optimal path functionality"""
expressions = [('a&b', ['a', 'b'], 'a&b'), ('a&b&c', ['a', 'b'], ''), ('a|b', ['a'], 'a'), ('a|b|c', ['a', 'b'], 'a'), ('(a&b)|c', ['a', 'b'], '(a&b)'), ('(a&b)|c', ['c'], 'c'), ('(a|b)&c', ['a', 'c'], '(... | the_stack_v2_python_sparse | pace/encryption/visibility/secret_vis_tree_test.py | Global-localhost/PACE-python | train | 0 | |
97fbad6a51ca3515536ecb3d988865b3fbf8e6ff | [
"if kwargs is not None:\n self.selection = kwargs.pop('selection', None)\n self.fitness = kwargs.pop('fitness', None)\n self.mutation = kwargs.pop('mutation', None)\n self.crossover = kwargs.pop('crossover', None)\n self.genomes = kwargs.pop('genomes', None)\n self.termCon = kwargs.pop('termCon', ... | <|body_start_0|>
if kwargs is not None:
self.selection = kwargs.pop('selection', None)
self.fitness = kwargs.pop('fitness', None)
self.mutation = kwargs.pop('mutation', None)
self.crossover = kwargs.pop('crossover', None)
self.genomes = kwargs.pop('gen... | GeneticAlgorithm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneticAlgorithm:
def __init__(self, **kwargs):
"""Creates a genetic algorithm. Keyword Arguments: selection {callable} -- Selection function used fitness {callable} -- Fitness function used mutation {callable} -- Mutation function used genomes {Genomes} -- First generation of genomes te... | stack_v2_sparse_classes_36k_train_009423 | 4,002 | permissive | [
{
"docstring": "Creates a genetic algorithm. Keyword Arguments: selection {callable} -- Selection function used fitness {callable} -- Fitness function used mutation {callable} -- Mutation function used genomes {Genomes} -- First generation of genomes termCon {callable} -- Termination condition callback {callabl... | 3 | stack_v2_sparse_classes_30k_train_003976 | Implement the Python class `GeneticAlgorithm` described below.
Class description:
Implement the GeneticAlgorithm class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a genetic algorithm. Keyword Arguments: selection {callable} -- Selection function used fitness {callable} -- Fitness functi... | Implement the Python class `GeneticAlgorithm` described below.
Class description:
Implement the GeneticAlgorithm class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a genetic algorithm. Keyword Arguments: selection {callable} -- Selection function used fitness {callable} -- Fitness functi... | e41718e5a8e0e3039d161800da70e56bd50a1b97 | <|skeleton|>
class GeneticAlgorithm:
def __init__(self, **kwargs):
"""Creates a genetic algorithm. Keyword Arguments: selection {callable} -- Selection function used fitness {callable} -- Fitness function used mutation {callable} -- Mutation function used genomes {Genomes} -- First generation of genomes te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneticAlgorithm:
def __init__(self, **kwargs):
"""Creates a genetic algorithm. Keyword Arguments: selection {callable} -- Selection function used fitness {callable} -- Fitness function used mutation {callable} -- Mutation function used genomes {Genomes} -- First generation of genomes termCon {callabl... | the_stack_v2_python_sparse | code/genetic_algorithm/genetic_algorithm_class.py | ahillbs/minimum_scan_cover | train | 0 | |
d005558ccb96764cc0a13447a44630ba80046cd9 | [
"self.portrayal_method = portrayal_method\nself.canvas_height = canvas_height\nself.canvas_width = canvas_width\nnew_element = 'new Simple_Continuous_Module({}, {})'.format(self.canvas_width, self.canvas_height)\nself.js_code = 'elements.push(' + new_element + ');'",
"space_state = []\nfor obj in model.schedule.a... | <|body_start_0|>
self.portrayal_method = portrayal_method
self.canvas_height = canvas_height
self.canvas_width = canvas_width
new_element = 'new Simple_Continuous_Module({}, {})'.format(self.canvas_width, self.canvas_height)
self.js_code = 'elements.push(' + new_element + ');'
<|... | SimpleCanvas | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleCanvas:
def __init__(self, portrayal_method, canvas_height=500, canvas_width=500):
"""Instantiate a new SimpleCanvas"""
<|body_0|>
def render(self, model):
"""Creates space in which the agents exist."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009424 | 7,183 | no_license | [
{
"docstring": "Instantiate a new SimpleCanvas",
"name": "__init__",
"signature": "def __init__(self, portrayal_method, canvas_height=500, canvas_width=500)"
},
{
"docstring": "Creates space in which the agents exist.",
"name": "render",
"signature": "def render(self, model)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000453 | Implement the Python class `SimpleCanvas` described below.
Class description:
Implement the SimpleCanvas class.
Method signatures and docstrings:
- def __init__(self, portrayal_method, canvas_height=500, canvas_width=500): Instantiate a new SimpleCanvas
- def render(self, model): Creates space in which the agents exi... | Implement the Python class `SimpleCanvas` described below.
Class description:
Implement the SimpleCanvas class.
Method signatures and docstrings:
- def __init__(self, portrayal_method, canvas_height=500, canvas_width=500): Instantiate a new SimpleCanvas
- def render(self, model): Creates space in which the agents exi... | 18166af285d2a40f903bc178f5c37b7d758fb0bd | <|skeleton|>
class SimpleCanvas:
def __init__(self, portrayal_method, canvas_height=500, canvas_width=500):
"""Instantiate a new SimpleCanvas"""
<|body_0|>
def render(self, model):
"""Creates space in which the agents exist."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleCanvas:
def __init__(self, portrayal_method, canvas_height=500, canvas_width=500):
"""Instantiate a new SimpleCanvas"""
self.portrayal_method = portrayal_method
self.canvas_height = canvas_height
self.canvas_width = canvas_width
new_element = 'new Simple_Continuou... | the_stack_v2_python_sparse | alternative_models/boids.py | sowasser/fish-shoaling-model | train | 1 | |
924963f46c7c665d7d7cb546def8fc70383489a9 | [
"self.infn = infn\nself.pdf_input = PdfReader(open(infn, 'rb'))\nself.page_count = len(self.pdf_input.pages)",
"if startpage > endpage or endpage > self.page_count:\n raise ValueError('page_count > endpage > startpage')\npdf_output = PdfWriter()\nfor i in range(startpage, endpage):\n pdf_output.add_page(sel... | <|body_start_0|>
self.infn = infn
self.pdf_input = PdfReader(open(infn, 'rb'))
self.page_count = len(self.pdf_input.pages)
<|end_body_0|>
<|body_start_1|>
if startpage > endpage or endpage > self.page_count:
raise ValueError('page_count > endpage > startpage')
pdf_ou... | PDFSplit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDFSplit:
def __init__(self, infn):
"""infn: 切分的pdf"""
<|body_0|>
def page2page(self, startpage, endpage):
"""startpage: 从startpage页开始切分,默认从第一页开始切分 endpage:直到endpage页切分结束"""
<|body_1|>
def filenum(self, outfnnum=2):
"""outfnnum: 切分后的pdf数量,默认两份"""... | stack_v2_sparse_classes_36k_train_009425 | 3,769 | no_license | [
{
"docstring": "infn: 切分的pdf",
"name": "__init__",
"signature": "def __init__(self, infn)"
},
{
"docstring": "startpage: 从startpage页开始切分,默认从第一页开始切分 endpage:直到endpage页切分结束",
"name": "page2page",
"signature": "def page2page(self, startpage, endpage)"
},
{
"docstring": "outfnnum: 切分... | 4 | stack_v2_sparse_classes_30k_train_018084 | Implement the Python class `PDFSplit` described below.
Class description:
Implement the PDFSplit class.
Method signatures and docstrings:
- def __init__(self, infn): infn: 切分的pdf
- def page2page(self, startpage, endpage): startpage: 从startpage页开始切分,默认从第一页开始切分 endpage:直到endpage页切分结束
- def filenum(self, outfnnum=2): ou... | Implement the Python class `PDFSplit` described below.
Class description:
Implement the PDFSplit class.
Method signatures and docstrings:
- def __init__(self, infn): infn: 切分的pdf
- def page2page(self, startpage, endpage): startpage: 从startpage页开始切分,默认从第一页开始切分 endpage:直到endpage页切分结束
- def filenum(self, outfnnum=2): ou... | 42afa8f806b0c6b5525177fafb6be22945ac8501 | <|skeleton|>
class PDFSplit:
def __init__(self, infn):
"""infn: 切分的pdf"""
<|body_0|>
def page2page(self, startpage, endpage):
"""startpage: 从startpage页开始切分,默认从第一页开始切分 endpage:直到endpage页切分结束"""
<|body_1|>
def filenum(self, outfnnum=2):
"""outfnnum: 切分后的pdf数量,默认两份"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PDFSplit:
def __init__(self, infn):
"""infn: 切分的pdf"""
self.infn = infn
self.pdf_input = PdfReader(open(infn, 'rb'))
self.page_count = len(self.pdf_input.pages)
def page2page(self, startpage, endpage):
"""startpage: 从startpage页开始切分,默认从第一页开始切分 endpage:直到endpage页切分结束... | the_stack_v2_python_sparse | pdfs/PDFSpliteMerge.py | wnma3mz/Tools | train | 13 | |
870aa82868c4b5f20eac2502ebd45c5a8e53e21d | [
"logger.info('Generating Druid spec for dataset at: %s', datasetLocation)\nlogger.info('Schema for dataset: %s', datasetSchema)\nreturn json.dumps({'type': 'index', 'spec': {'dataSchema': {'dataSource': datasourceName, 'timestampSpec': {'column': DruidIngestionSpecGenerator._getTimestampColumn(datasetSchema), 'form... | <|body_start_0|>
logger.info('Generating Druid spec for dataset at: %s', datasetLocation)
logger.info('Schema for dataset: %s', datasetSchema)
return json.dumps({'type': 'index', 'spec': {'dataSchema': {'dataSource': datasourceName, 'timestampSpec': {'column': DruidIngestionSpecGenerator._getTim... | Class to handle functionality around Druid ingestion spec generation | DruidIngestionSpecGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DruidIngestionSpecGenerator:
"""Class to handle functionality around Druid ingestion spec generation"""
def getIngestionSpec(datasetLocation, datasourceName, datasetSchema):
"""Method to generate Druid ingestion spec Method doesn't support complex druid data types right now. :param d... | stack_v2_sparse_classes_36k_train_009426 | 9,076 | permissive | [
{
"docstring": "Method to generate Druid ingestion spec Method doesn't support complex druid data types right now. :param datasetLocation: S3 location of the dataset :param datasourceName Name of the dataset :param datasetSchema The schema of the dataset :returns DruidSpec",
"name": "getIngestionSpec",
... | 5 | stack_v2_sparse_classes_30k_train_000924 | Implement the Python class `DruidIngestionSpecGenerator` described below.
Class description:
Class to handle functionality around Druid ingestion spec generation
Method signatures and docstrings:
- def getIngestionSpec(datasetLocation, datasourceName, datasetSchema): Method to generate Druid ingestion spec Method doe... | Implement the Python class `DruidIngestionSpecGenerator` described below.
Class description:
Class to handle functionality around Druid ingestion spec generation
Method signatures and docstrings:
- def getIngestionSpec(datasetLocation, datasourceName, datasetSchema): Method to generate Druid ingestion spec Method doe... | cf765e822c2aaefb546ed8a9507ac4a0b0b9ce73 | <|skeleton|>
class DruidIngestionSpecGenerator:
"""Class to handle functionality around Druid ingestion spec generation"""
def getIngestionSpec(datasetLocation, datasourceName, datasetSchema):
"""Method to generate Druid ingestion spec Method doesn't support complex druid data types right now. :param d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DruidIngestionSpecGenerator:
"""Class to handle functionality around Druid ingestion spec generation"""
def getIngestionSpec(datasetLocation, datasourceName, datasetSchema):
"""Method to generate Druid ingestion spec Method doesn't support complex druid data types right now. :param datasetLocatio... | the_stack_v2_python_sparse | api/utils/druidSpecGenerator.py | rberrelleza/cuelake | train | 0 |
6f35c5e5ba72f8a39a58c76e5bb0983cdb192018 | [
"resp = SimpleResponse()\nto_id = req.account_id\ntry:\n account = get_current_user()\n services.connections.send_request(account.id, to_id)\n return resp.ToMessage()\nexcept exp.ServiceExp as e:\n handle_exception(e)",
"resp = SimpleResponse()\nfrom_id = req.account_id\ntry:\n account = get_curren... | <|body_start_0|>
resp = SimpleResponse()
to_id = req.account_id
try:
account = get_current_user()
services.connections.send_request(account.id, to_id)
return resp.ToMessage()
except exp.ServiceExp as e:
handle_exception(e)
<|end_body_0|>
<... | ConnectionsApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionsApi:
def request(self, req):
"""Send a connection request to a user. :param req.account_id: (int) ID of the account receiving the request."""
<|body_0|>
def accept(self, req):
"""Accept a connection request from a user. :param req.account_id: (int) ID of t... | stack_v2_sparse_classes_36k_train_009427 | 4,566 | no_license | [
{
"docstring": "Send a connection request to a user. :param req.account_id: (int) ID of the account receiving the request.",
"name": "request",
"signature": "def request(self, req)"
},
{
"docstring": "Accept a connection request from a user. :param req.account_id: (int) ID of the account that se... | 6 | stack_v2_sparse_classes_30k_train_018898 | Implement the Python class `ConnectionsApi` described below.
Class description:
Implement the ConnectionsApi class.
Method signatures and docstrings:
- def request(self, req): Send a connection request to a user. :param req.account_id: (int) ID of the account receiving the request.
- def accept(self, req): Accept a c... | Implement the Python class `ConnectionsApi` described below.
Class description:
Implement the ConnectionsApi class.
Method signatures and docstrings:
- def request(self, req): Send a connection request to a user. :param req.account_id: (int) ID of the account receiving the request.
- def accept(self, req): Accept a c... | 1d6522069da3e5a6de41ce948b04872d0a994cca | <|skeleton|>
class ConnectionsApi:
def request(self, req):
"""Send a connection request to a user. :param req.account_id: (int) ID of the account receiving the request."""
<|body_0|>
def accept(self, req):
"""Accept a connection request from a user. :param req.account_id: (int) ID of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectionsApi:
def request(self, req):
"""Send a connection request to a user. :param req.account_id: (int) ID of the account receiving the request."""
resp = SimpleResponse()
to_id = req.account_id
try:
account = get_current_user()
services.connections... | the_stack_v2_python_sparse | controllers/api/connections.py | venvadlamani/HumanLink | train | 0 | |
c53e6027db9ebcd94313c99c6ad79231c79e3b52 | [
"if not self.find_element_and_action(By.ID, self.comment_page_title_bar_back_button_id, self.action.click, '返回按钮') == 0:\n log_utils.F_ERROR('点击失败')\n return 1",
"title = self.find_element_and_action(By.ID, self.comment_page_title_bar_title_id, self.action.get_text, '评论页的标题')\nif title == 1 or title == 2:\n... | <|body_start_0|>
if not self.find_element_and_action(By.ID, self.comment_page_title_bar_back_button_id, self.action.click, '返回按钮') == 0:
log_utils.F_ERROR('点击失败')
return 1
<|end_body_0|>
<|body_start_1|>
title = self.find_element_and_action(By.ID, self.comment_page_title_bar_tit... | comment_page | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class comment_page:
def click_comment_page_title_bar_back_button(self):
"""点击评论页面的返回按钮"""
<|body_0|>
def get_comment_page_title_bar_title_text(self):
"""获取评论页的标题 返回值: 1:获取失败 title:正常结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.find_eleme... | stack_v2_sparse_classes_36k_train_009428 | 1,234 | no_license | [
{
"docstring": "点击评论页面的返回按钮",
"name": "click_comment_page_title_bar_back_button",
"signature": "def click_comment_page_title_bar_back_button(self)"
},
{
"docstring": "获取评论页的标题 返回值: 1:获取失败 title:正常结果",
"name": "get_comment_page_title_bar_title_text",
"signature": "def get_comment_page_tit... | 2 | stack_v2_sparse_classes_30k_train_011067 | Implement the Python class `comment_page` described below.
Class description:
Implement the comment_page class.
Method signatures and docstrings:
- def click_comment_page_title_bar_back_button(self): 点击评论页面的返回按钮
- def get_comment_page_title_bar_title_text(self): 获取评论页的标题 返回值: 1:获取失败 title:正常结果 | Implement the Python class `comment_page` described below.
Class description:
Implement the comment_page class.
Method signatures and docstrings:
- def click_comment_page_title_bar_back_button(self): 点击评论页面的返回按钮
- def get_comment_page_title_bar_title_text(self): 获取评论页的标题 返回值: 1:获取失败 title:正常结果
<|skeleton|>
class com... | d951dbbfde9394b39a9bf0d3a81012798ee36c26 | <|skeleton|>
class comment_page:
def click_comment_page_title_bar_back_button(self):
"""点击评论页面的返回按钮"""
<|body_0|>
def get_comment_page_title_bar_title_text(self):
"""获取评论页的标题 返回值: 1:获取失败 title:正常结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class comment_page:
def click_comment_page_title_bar_back_button(self):
"""点击评论页面的返回按钮"""
if not self.find_element_and_action(By.ID, self.comment_page_title_bar_back_button_id, self.action.click, '返回按钮') == 0:
log_utils.F_ERROR('点击失败')
return 1
def get_comment_page_title... | the_stack_v2_python_sparse | baidu_music_test/page_info/comment_page.py | lzdgogogo/baidumusic_test | train | 0 | |
15e9d6855f50fbdf03672b1d72d70bcf19a0a59b | [
"from haalpr import HAAlpr\nsuper().__init__(region=region, confidence=confidence)\nself._api = HAAlpr(binary=binary, country=region)",
"result = self._api.recognize_byte(image)\nf_plates = {}\nfor found in result:\n for plate, confidence in found.items():\n if confidence >= self._confidence:\n ... | <|body_start_0|>
from haalpr import HAAlpr
super().__init__(region=region, confidence=confidence)
self._api = HAAlpr(binary=binary, country=region)
<|end_body_0|>
<|body_start_1|>
result = self._api.recognize_byte(image)
f_plates = {}
for found in result:
for... | Use local openalpr library to parse licences plate. | OpenalprApiLocal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenalprApiLocal:
"""Use local openalpr library to parse licences plate."""
def __init__(self, region, confidence, binary):
"""Init local api processing."""
<|body_0|>
def process_image(self, image, event_callback):
"""Callback for processing image."""
<|... | stack_v2_sparse_classes_36k_train_009429 | 14,090 | permissive | [
{
"docstring": "Init local api processing.",
"name": "__init__",
"signature": "def __init__(self, region, confidence, binary)"
},
{
"docstring": "Callback for processing image.",
"name": "process_image",
"signature": "def process_image(self, image, event_callback)"
}
] | 2 | null | Implement the Python class `OpenalprApiLocal` described below.
Class description:
Use local openalpr library to parse licences plate.
Method signatures and docstrings:
- def __init__(self, region, confidence, binary): Init local api processing.
- def process_image(self, image, event_callback): Callback for processing... | Implement the Python class `OpenalprApiLocal` described below.
Class description:
Use local openalpr library to parse licences plate.
Method signatures and docstrings:
- def __init__(self, region, confidence, binary): Init local api processing.
- def process_image(self, image, event_callback): Callback for processing... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class OpenalprApiLocal:
"""Use local openalpr library to parse licences plate."""
def __init__(self, region, confidence, binary):
"""Init local api processing."""
<|body_0|>
def process_image(self, image, event_callback):
"""Callback for processing image."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenalprApiLocal:
"""Use local openalpr library to parse licences plate."""
def __init__(self, region, confidence, binary):
"""Init local api processing."""
from haalpr import HAAlpr
super().__init__(region=region, confidence=confidence)
self._api = HAAlpr(binary=binary, c... | the_stack_v2_python_sparse | homeassistant/components/openalpr.py | Smart-Torvy/torvy-home-assistant | train | 2 |
0a5ae43102ffbfe98b10a5ac3454de8d92ed1f97 | [
"super().__init__('http', create_session, **kwargs)\nself.host = host\nself.port = port\nself.site: web.BaseSite = None",
"app_args = {}\nif self.max_message_size:\n app_args['client_max_size'] = self.max_message_size\napp = web.Application(**app_args)\napp.add_routes([web.get('/', self.invite_message_handler)... | <|body_start_0|>
super().__init__('http', create_session, **kwargs)
self.host = host
self.port = port
self.site: web.BaseSite = None
<|end_body_0|>
<|body_start_1|>
app_args = {}
if self.max_message_size:
app_args['client_max_size'] = self.max_message_size
... | Http Transport class. | HttpTransport | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpTransport:
"""Http Transport class."""
def __init__(self, host: str, port: int, create_session, **kwargs) -> None:
"""Initialize an inbound HTTP transport instance. Args: host: Host to listen on port: Port to listen on create_session: Method to create a new inbound session"""
... | stack_v2_sparse_classes_36k_train_009430 | 4,854 | permissive | [
{
"docstring": "Initialize an inbound HTTP transport instance. Args: host: Host to listen on port: Port to listen on create_session: Method to create a new inbound session",
"name": "__init__",
"signature": "def __init__(self, host: str, port: int, create_session, **kwargs) -> None"
},
{
"docstr... | 6 | null | Implement the Python class `HttpTransport` described below.
Class description:
Http Transport class.
Method signatures and docstrings:
- def __init__(self, host: str, port: int, create_session, **kwargs) -> None: Initialize an inbound HTTP transport instance. Args: host: Host to listen on port: Port to listen on crea... | Implement the Python class `HttpTransport` described below.
Class description:
Http Transport class.
Method signatures and docstrings:
- def __init__(self, host: str, port: int, create_session, **kwargs) -> None: Initialize an inbound HTTP transport instance. Args: host: Host to listen on port: Port to listen on crea... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class HttpTransport:
"""Http Transport class."""
def __init__(self, host: str, port: int, create_session, **kwargs) -> None:
"""Initialize an inbound HTTP transport instance. Args: host: Host to listen on port: Port to listen on create_session: Method to create a new inbound session"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpTransport:
"""Http Transport class."""
def __init__(self, host: str, port: int, create_session, **kwargs) -> None:
"""Initialize an inbound HTTP transport instance. Args: host: Host to listen on port: Port to listen on create_session: Method to create a new inbound session"""
super().... | the_stack_v2_python_sparse | aries_cloudagent/transport/inbound/http.py | hyperledger/aries-cloudagent-python | train | 370 |
ce952a93cd42a3c011881d31531be59a61a69d83 | [
"extloader = ExtensionLoader()\npipeline = Pipeline(extloader.cats_container)\npipeline.new_category('Preprocessing', 1)\nstandard = Category('Preprocessing')\nself.assertEqual(pipeline.executed_cats[1].name, standard.name)",
"extloader = ExtensionLoader()\npipeline = Pipeline(extloader.cats_container)\ncat1 = pi... | <|body_start_0|>
extloader = ExtensionLoader()
pipeline = Pipeline(extloader.cats_container)
pipeline.new_category('Preprocessing', 1)
standard = Category('Preprocessing')
self.assertEqual(pipeline.executed_cats[1].name, standard.name)
<|end_body_0|>
<|body_start_1|>
ext... | Test_Pipeline | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Pipeline:
def test_new_Category(self):
"""Testing if the new_category(position) method insert in the executed_cats list at that position a new Category object"""
<|body_0|>
def test_move_category(self):
"""Testing if after creating 2 categories in the pipeline a... | stack_v2_sparse_classes_36k_train_009431 | 4,101 | permissive | [
{
"docstring": "Testing if the new_category(position) method insert in the executed_cats list at that position a new Category object",
"name": "test_new_Category",
"signature": "def test_new_Category(self)"
},
{
"docstring": "Testing if after creating 2 categories in the pipeline and moving one ... | 6 | stack_v2_sparse_classes_30k_train_014101 | Implement the Python class `Test_Pipeline` described below.
Class description:
Implement the Test_Pipeline class.
Method signatures and docstrings:
- def test_new_Category(self): Testing if the new_category(position) method insert in the executed_cats list at that position a new Category object
- def test_move_catego... | Implement the Python class `Test_Pipeline` described below.
Class description:
Implement the Test_Pipeline class.
Method signatures and docstrings:
- def test_new_Category(self): Testing if the new_category(position) method insert in the executed_cats list at that position a new Category object
- def test_move_catego... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class Test_Pipeline:
def test_new_Category(self):
"""Testing if the new_category(position) method insert in the executed_cats list at that position a new Category object"""
<|body_0|>
def test_move_category(self):
"""Testing if after creating 2 categories in the pipeline a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_Pipeline:
def test_new_Category(self):
"""Testing if the new_category(position) method insert in the executed_cats list at that position a new Category object"""
extloader = ExtensionLoader()
pipeline = Pipeline(extloader.cats_container)
pipeline.new_category('Preprocessin... | the_stack_v2_python_sparse | nefi2/unittests/unittest_model/Test_Pipeline.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 | |
cb91ea3b58f15fbb5019b2210a4bbd5533639cf7 | [
"n = len(nums)\nif n < 3:\n return False\nflag_num = 2 ** 31\nmin_value = nums[0]\nfor i in range(1, n):\n if nums[i] > flag_num:\n return True\n if nums[i] > min_value:\n flag_num = min(nums[i], flag_num)\n min_value = min(min_value, nums[i])\nreturn False",
"if len(nums) < 3:\n retu... | <|body_start_0|>
n = len(nums)
if n < 3:
return False
flag_num = 2 ** 31
min_value = nums[0]
for i in range(1, n):
if nums[i] > flag_num:
return True
if nums[i] > min_value:
flag_num = min(nums[i], flag_num)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:"""
<|body_0|>
def increasingTriplet2(self, nums: List[int]) -> bool:
"""20221011 Runti... | stack_v2_sparse_classes_36k_train_009432 | 1,941 | permissive | [
{
"docstring": "2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums: List[int]) -> bool"
},
{
"docstring": "20221011 Runtime: 897 ms, faster than 64.93% Mem... | 2 | stack_v2_sparse_classes_30k_train_009713 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums: List[int]) -> bool: 2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:
- def incr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums: List[int]) -> bool: 2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:
- def incr... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:"""
<|body_0|>
def increasingTriplet2(self, nums: List[int]) -> bool:
"""20221011 Runti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:"""
n = len(nums)
if n < 3:
return False
flag_num = 2 ** 31
min_value = nums[0... | the_stack_v2_python_sparse | src/334-IncreasingTripletSubsequence.py | Jiezhi/myleetcode | train | 1 | |
d4e64a98de5a58c7fd5ddbd72b6e1516adfe6f4b | [
"if Singleton.__instance == None:\n Singleton()\nreturn Singleton.__instance",
"if Singleton.__instance != None:\n raise Exception('This class is a singleton!')\nelse:\n Singleton.__instance = self"
] | <|body_start_0|>
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
<|end_body_0|>
<|body_start_1|>
if Singleton.__instance != None:
raise Exception('This class is a singleton!')
else:
Singleton.__instance = self
<|end_body_1|>
| Singleton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Singleton.__instance == None:
Singleton()
return Single... | stack_v2_sparse_classes_36k_train_009433 | 1,319 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002649 | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class Singleton:
def getInstance():
"""Static access me... | ed5f232f6737bc9f750d704455442f239d4f0561 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Singleton:
def getInstance():
"""Static access method."""
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
"""Virtually private constructor."""
if Singleton.__instance != None:
raise Exception('Thi... | the_stack_v2_python_sparse | codes/design_pattern/02_singleton.py | Ziaeemehr/workshop_scripting | train | 4 | |
4ebaa59aaab045a27d370bbd1385c59dc7805c8c | [
"super(IterateAllClients, self).__init__(**kwargs)\nself.client_chunksize = client_chunksize\nself.max_age = max_age",
"client_list = GetAllClients(token=self.token)\nlogging.debug('Got %d clients', len(client_list))\nfor client_group in utils.Grouper(client_list, self.client_chunksize):\n for fd in aff4.FACTO... | <|body_start_0|>
super(IterateAllClients, self).__init__(**kwargs)
self.client_chunksize = client_chunksize
self.max_age = max_age
<|end_body_0|>
<|body_start_1|>
client_list = GetAllClients(token=self.token)
logging.debug('Got %d clients', len(client_list))
for client_g... | Class to iterate over all GRR Client objects. | IterateAllClients | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterateAllClients:
"""Class to iterate over all GRR Client objects."""
def __init__(self, max_age, client_chunksize=25, **kwargs):
"""Iterate over all clients in a threadpool. Args: max_age: Maximum age in seconds of clients to check. client_chunksize: A function to call with each cl... | stack_v2_sparse_classes_36k_train_009434 | 12,525 | permissive | [
{
"docstring": "Iterate over all clients in a threadpool. Args: max_age: Maximum age in seconds of clients to check. client_chunksize: A function to call with each client urn. **kwargs: Arguments passed to init.",
"name": "__init__",
"signature": "def __init__(self, max_age, client_chunksize=25, **kwarg... | 2 | null | Implement the Python class `IterateAllClients` described below.
Class description:
Class to iterate over all GRR Client objects.
Method signatures and docstrings:
- def __init__(self, max_age, client_chunksize=25, **kwargs): Iterate over all clients in a threadpool. Args: max_age: Maximum age in seconds of clients to... | Implement the Python class `IterateAllClients` described below.
Class description:
Class to iterate over all GRR Client objects.
Method signatures and docstrings:
- def __init__(self, max_age, client_chunksize=25, **kwargs): Iterate over all clients in a threadpool. Args: max_age: Maximum age in seconds of clients to... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class IterateAllClients:
"""Class to iterate over all GRR Client objects."""
def __init__(self, max_age, client_chunksize=25, **kwargs):
"""Iterate over all clients in a threadpool. Args: max_age: Maximum age in seconds of clients to check. client_chunksize: A function to call with each cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IterateAllClients:
"""Class to iterate over all GRR Client objects."""
def __init__(self, max_age, client_chunksize=25, **kwargs):
"""Iterate over all clients in a threadpool. Args: max_age: Maximum age in seconds of clients to check. client_chunksize: A function to call with each client urn. **k... | the_stack_v2_python_sparse | lib/export_utils.py | defaultnamehere/grr | train | 3 |
259814434573ce1e15470e55c1a5095876714357 | [
"self.cred = cred['firewall']\nself.debug = cred['debug']\nself.logger = logger.IemlAVLogger(__name__, debug=self.debug)",
"if check_root():\n engineObj = FirewallEngine(cred=self.cred, debug=self.debug)\n engineObj.startEngine()\n self.logger.log('Firewall started', logtype='info')\nelse:\n self.logg... | <|body_start_0|>
self.cred = cred['firewall']
self.debug = cred['debug']
self.logger = logger.IemlAVLogger(__name__, debug=self.debug)
<|end_body_0|>
<|body_start_1|>
if check_root():
engineObj = FirewallEngine(cred=self.cred, debug=self.debug)
engineObj.startEng... | IemlAVFirewall Class. | IemlAVFirewall | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IemlAVFirewall:
"""IemlAVFirewall Class."""
def __init__(self, cred=None, debug=None):
"""Initialize IemlAVFirewall."""
<|body_0|>
def start_firewall(self):
"""Start firewall engine."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.cred = cr... | stack_v2_sparse_classes_36k_train_009435 | 1,020 | permissive | [
{
"docstring": "Initialize IemlAVFirewall.",
"name": "__init__",
"signature": "def __init__(self, cred=None, debug=None)"
},
{
"docstring": "Start firewall engine.",
"name": "start_firewall",
"signature": "def start_firewall(self)"
}
] | 2 | null | Implement the Python class `IemlAVFirewall` described below.
Class description:
IemlAVFirewall Class.
Method signatures and docstrings:
- def __init__(self, cred=None, debug=None): Initialize IemlAVFirewall.
- def start_firewall(self): Start firewall engine. | Implement the Python class `IemlAVFirewall` described below.
Class description:
IemlAVFirewall Class.
Method signatures and docstrings:
- def __init__(self, cred=None, debug=None): Initialize IemlAVFirewall.
- def start_firewall(self): Start firewall engine.
<|skeleton|>
class IemlAVFirewall:
"""IemlAVFirewall C... | 8d397a3d59e067176269c5e84d73bf53951b7b3f | <|skeleton|>
class IemlAVFirewall:
"""IemlAVFirewall Class."""
def __init__(self, cred=None, debug=None):
"""Initialize IemlAVFirewall."""
<|body_0|>
def start_firewall(self):
"""Start firewall engine."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IemlAVFirewall:
"""IemlAVFirewall Class."""
def __init__(self, cred=None, debug=None):
"""Initialize IemlAVFirewall."""
self.cred = cred['firewall']
self.debug = cred['debug']
self.logger = logger.IemlAVLogger(__name__, debug=self.debug)
def start_firewall(self):
... | the_stack_v2_python_sparse | iemlav/lib/firewall/iemlAVFirewall.py | GouravRDutta/IemLabsAV | train | 0 |
fa8580dfcfd6019a1faa29bb1100a9a279c12aa6 | [
"if not isinstance(style_image, np.ndarray) or style_image.ndim != 3 or style_image.shape[-1] != 3:\n raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')\nif not isinstance(content_image, np.ndarray) or content_image.ndim != 3 or content_image.shape[-1] != 3:\n raise TypeError('content... | <|body_start_0|>
if not isinstance(style_image, np.ndarray) or style_image.ndim != 3 or style_image.shape[-1] != 3:
raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')
if not isinstance(content_image, np.ndarray) or content_image.ndim != 3 or content_image.shape[-1] !... | class | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor"""
<|body_0|>
def scale_image(image):
"""method"""
<|body_1|>
def load_model(self):
"""method"""
<|body_2|>
def gram_matrix(in... | stack_v2_sparse_classes_36k_train_009436 | 3,025 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"
},
{
"docstring": "method",
"name": "scale_image",
"signature": "def scale_image(image)"
},
{
"docstring": "method",
"name": "load_model",
... | 4 | stack_v2_sparse_classes_30k_train_016388 | Implement the Python class `NST` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor
- def scale_image(image): method
- def load_model(self): method
- def gram_matrix(input_layer): method | Implement the Python class `NST` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor
- def scale_image(image): method
- def load_model(self): method
- def gram_matrix(input_layer): method
<|skeleton|>
class N... | b5e8f1253309567ca7be71b9575a150de1be3820 | <|skeleton|>
class NST:
"""class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor"""
<|body_0|>
def scale_image(image):
"""method"""
<|body_1|>
def load_model(self):
"""method"""
<|body_2|>
def gram_matrix(in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NST:
"""class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor"""
if not isinstance(style_image, np.ndarray) or style_image.ndim != 3 or style_image.shape[-1] != 3:
raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/2-neural_style.py | jadsm98/holbertonschool-machine_learning | train | 0 |
d4ac757df193b54f9e9780f899fc0d1d00fd3da4 | [
"BaseReciprocalTimeSeriesTransformer.__init__(self, estimator.context_length)\nif not isinstance(estimator, TimeSeriesDifference):\n raise TypeError(f'estimator must be of type TimeSeriesDifference not {type(estimator)}.')\nself.estimator = estimator",
"if not hasattr(self.estimator, 'X_'):\n raise RuntimeE... | <|body_start_0|>
BaseReciprocalTimeSeriesTransformer.__init__(self, estimator.context_length)
if not isinstance(estimator, TimeSeriesDifference):
raise TypeError(f'estimator must be of type TimeSeriesDifference not {type(estimator)}.')
self.estimator = estimator
<|end_body_0|>
<|bod... | Computes the reverse of @see cl TimeSeriesDifference. | TimeSeriesDifferenceInv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSeriesDifferenceInv:
"""Computes the reverse of @see cl TimeSeriesDifference."""
def __init__(self, estimator):
"""@param estimator of type @see cl TimeSeriesDifference"""
<|body_0|>
def fit(self, X=None, y=None, sample_weight=None):
"""Checks that estimator ... | stack_v2_sparse_classes_36k_train_009437 | 3,477 | permissive | [
{
"docstring": "@param estimator of type @see cl TimeSeriesDifference",
"name": "__init__",
"signature": "def __init__(self, estimator)"
},
{
"docstring": "Checks that estimator is fitted.",
"name": "fit",
"signature": "def fit(self, X=None, y=None, sample_weight=None)"
},
{
"doc... | 3 | null | Implement the Python class `TimeSeriesDifferenceInv` described below.
Class description:
Computes the reverse of @see cl TimeSeriesDifference.
Method signatures and docstrings:
- def __init__(self, estimator): @param estimator of type @see cl TimeSeriesDifference
- def fit(self, X=None, y=None, sample_weight=None): C... | Implement the Python class `TimeSeriesDifferenceInv` described below.
Class description:
Computes the reverse of @see cl TimeSeriesDifference.
Method signatures and docstrings:
- def __init__(self, estimator): @param estimator of type @see cl TimeSeriesDifference
- def fit(self, X=None, y=None, sample_weight=None): C... | 4b610bacaafff835a30880f2fb955fff3b087ad5 | <|skeleton|>
class TimeSeriesDifferenceInv:
"""Computes the reverse of @see cl TimeSeriesDifference."""
def __init__(self, estimator):
"""@param estimator of type @see cl TimeSeriesDifference"""
<|body_0|>
def fit(self, X=None, y=None, sample_weight=None):
"""Checks that estimator ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeSeriesDifferenceInv:
"""Computes the reverse of @see cl TimeSeriesDifference."""
def __init__(self, estimator):
"""@param estimator of type @see cl TimeSeriesDifference"""
BaseReciprocalTimeSeriesTransformer.__init__(self, estimator.context_length)
if not isinstance(estimator,... | the_stack_v2_python_sparse | mlinsights/timeseries/preprocessing.py | sdpython/mlinsights | train | 64 |
09bda5321bb55a9789b1eb419333f2cae879e905 | [
"self.debug = debug\nself.log = None\nself.config = None\nself.database = None",
"self.log = LogSystem(self)\nself.log.debug('Log system loaded.')\nself.config = Config(self)\nif not self.config.start():\n return False\nself.log.debug('Config loaded.')\ntry:\n self.database = Mysql(self, self.config.db_host... | <|body_start_0|>
self.debug = debug
self.log = None
self.config = None
self.database = None
<|end_body_0|>
<|body_start_1|>
self.log = LogSystem(self)
self.log.debug('Log system loaded.')
self.config = Config(self)
if not self.config.start():
... | yarus app | App | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""yarus app"""
def __init__(self, debug=False):
"""init"""
<|body_0|>
def start(self):
"""setup the context"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.debug = debug
self.log = None
self.config = None
self.... | stack_v2_sparse_classes_36k_train_009438 | 1,041 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "setup the context",
"name": "start",
"signature": "def start(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002006 | Implement the Python class `App` described below.
Class description:
yarus app
Method signatures and docstrings:
- def __init__(self, debug=False): init
- def start(self): setup the context | Implement the Python class `App` described below.
Class description:
yarus app
Method signatures and docstrings:
- def __init__(self, debug=False): init
- def start(self): setup the context
<|skeleton|>
class App:
"""yarus app"""
def __init__(self, debug=False):
"""init"""
<|body_0|>
de... | c10068b692e331ff5210ee42cd68d4ddfd78f88b | <|skeleton|>
class App:
"""yarus app"""
def __init__(self, debug=False):
"""init"""
<|body_0|>
def start(self):
"""setup the context"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class App:
"""yarus app"""
def __init__(self, debug=False):
"""init"""
self.debug = debug
self.log = None
self.config = None
self.database = None
def start(self):
"""setup the context"""
self.log = LogSystem(self)
self.log.debug('Log system l... | the_stack_v2_python_sparse | common/yarus/common/app.py | alexandreborgo/yarus | train | 1 |
c83a4b3aff84f9b635d3419adc8679da01a1b5d8 | [
"self.predictor = predictor\nself.augment_size = augment_size\nself.score = score",
"try:\n predictor = copy.deepcopy(self.predictor)\n predictor.fit(X_train, Y_train, augmenter, self.augment_size)\n return self.score(Y_test, predictor.predict(X_test))\nexcept Exception as e:\n print(e)\n return np... | <|body_start_0|>
self.predictor = predictor
self.augment_size = augment_size
self.score = score
<|end_body_0|>
<|body_start_1|>
try:
predictor = copy.deepcopy(self.predictor)
predictor.fit(X_train, Y_train, augmenter, self.augment_size)
return self.sc... | A score probe template to evaluate an augmenter using a predictor with a ``scikit-learn``-like interface. | AugSklearnScore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugSklearnScore:
"""A score probe template to evaluate an augmenter using a predictor with a ``scikit-learn``-like interface."""
def __init__(self, predictor: AugPredictorBase, augment_size, score=mean_squared_error):
"""Parameters: predictor: the predictor class. augment_size: the d... | stack_v2_sparse_classes_36k_train_009439 | 1,912 | permissive | [
{
"docstring": "Parameters: predictor: the predictor class. augment_size: the desired maximum size of the augmentation. score: the score metric to quantify the accuracy of the predictions.",
"name": "__init__",
"signature": "def __init__(self, predictor: AugPredictorBase, augment_size, score=mean_square... | 2 | stack_v2_sparse_classes_30k_train_019315 | Implement the Python class `AugSklearnScore` described below.
Class description:
A score probe template to evaluate an augmenter using a predictor with a ``scikit-learn``-like interface.
Method signatures and docstrings:
- def __init__(self, predictor: AugPredictorBase, augment_size, score=mean_squared_error): Parame... | Implement the Python class `AugSklearnScore` described below.
Class description:
A score probe template to evaluate an augmenter using a predictor with a ``scikit-learn``-like interface.
Method signatures and docstrings:
- def __init__(self, predictor: AugPredictorBase, augment_size, score=mean_squared_error): Parame... | 2878ced51cfe473aad8fbc1886e2b65dfc9fc060 | <|skeleton|>
class AugSklearnScore:
"""A score probe template to evaluate an augmenter using a predictor with a ``scikit-learn``-like interface."""
def __init__(self, predictor: AugPredictorBase, augment_size, score=mean_squared_error):
"""Parameters: predictor: the predictor class. augment_size: the d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AugSklearnScore:
"""A score probe template to evaluate an augmenter using a predictor with a ``scikit-learn``-like interface."""
def __init__(self, predictor: AugPredictorBase, augment_size, score=mean_squared_error):
"""Parameters: predictor: the predictor class. augment_size: the desired maximu... | the_stack_v2_python_sparse | causal_da/api_support/validator/scores.py | SoldierY/few-shot-domain-adaptation-by-causal-mechanism-transfer | train | 0 |
c5fb65e1f817982556c16501ba58eaad232509c5 | [
"super(GroupL1Norm, self).__init__()\nassert reg_lambda >= 0, 'regularization weight should be 0 or positive'\nassert isinstance(groups, list), 'groups needs to be a list'\nself.reg_lambda = reg_lambda\nself.groups = groups\nself.stabilizing_val = stabilizing_val",
"squared = net.Sqr(param)\nreduced_sum = net.Red... | <|body_start_0|>
super(GroupL1Norm, self).__init__()
assert reg_lambda >= 0, 'regularization weight should be 0 or positive'
assert isinstance(groups, list), 'groups needs to be a list'
self.reg_lambda = reg_lambda
self.groups = groups
self.stabilizing_val = stabilizing_v... | Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the members of each group 2. Scale each l2 norm ... | GroupL1Norm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupL1Norm:
"""Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the membe... | stack_v2_sparse_classes_36k_train_009440 | 11,669 | permissive | [
{
"docstring": "Args: reg_lambda: The weight of the regularization term. groups: A list of integers describing the size of each group. The length of the list is the number of groups. Optional Args: stabilizing_val: The computation of GroupL1Norm involves the Sqrt operator. When values are small, its gradient ca... | 2 | stack_v2_sparse_classes_30k_val_001089 | Implement the Python class `GroupL1Norm` described below.
Class description:
Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: ... | Implement the Python class `GroupL1Norm` described below.
Class description:
Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: ... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class GroupL1Norm:
"""Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the membe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupL1Norm:
"""Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the members of each gr... | the_stack_v2_python_sparse | pytorch/source/caffe2/python/regularizer.py | ryfeus/lambda-packs | train | 1,283 |
939b9b016d1e04b0e2dba3d9d777ca43422aad6f | [
"from kolibri.core.auth.tasks import begin_request_soud_sync\nif get_device_setting('subset_of_users_device', default=False) and (not network_location.subset_of_users_device):\n for user_id in _learner_ids():\n begin_request_soud_sync(network_location.base_url, user_id)",
"from kolibri.core.auth.tasks i... | <|body_start_0|>
from kolibri.core.auth.tasks import begin_request_soud_sync
if get_device_setting('subset_of_users_device', default=False) and (not network_location.subset_of_users_device):
for user_id in _learner_ids():
begin_request_soud_sync(network_location.base_url, use... | NetworkDiscoveryForSoUDHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkDiscoveryForSoUDHook:
def on_connect(self, network_location):
""":type network_location: kolibri.core.discovery.models.NetworkLocation"""
<|body_0|>
def on_disconnect(self, network_location):
""":type network_location: kolibri.core.discovery.models.NetworkLoca... | stack_v2_sparse_classes_36k_train_009441 | 5,300 | permissive | [
{
"docstring": ":type network_location: kolibri.core.discovery.models.NetworkLocation",
"name": "on_connect",
"signature": "def on_connect(self, network_location)"
},
{
"docstring": ":type network_location: kolibri.core.discovery.models.NetworkLocation",
"name": "on_disconnect",
"signatu... | 2 | null | Implement the Python class `NetworkDiscoveryForSoUDHook` described below.
Class description:
Implement the NetworkDiscoveryForSoUDHook class.
Method signatures and docstrings:
- def on_connect(self, network_location): :type network_location: kolibri.core.discovery.models.NetworkLocation
- def on_disconnect(self, netw... | Implement the Python class `NetworkDiscoveryForSoUDHook` described below.
Class description:
Implement the NetworkDiscoveryForSoUDHook class.
Method signatures and docstrings:
- def on_connect(self, network_location): :type network_location: kolibri.core.discovery.models.NetworkLocation
- def on_disconnect(self, netw... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class NetworkDiscoveryForSoUDHook:
def on_connect(self, network_location):
""":type network_location: kolibri.core.discovery.models.NetworkLocation"""
<|body_0|>
def on_disconnect(self, network_location):
""":type network_location: kolibri.core.discovery.models.NetworkLoca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkDiscoveryForSoUDHook:
def on_connect(self, network_location):
""":type network_location: kolibri.core.discovery.models.NetworkLocation"""
from kolibri.core.auth.tasks import begin_request_soud_sync
if get_device_setting('subset_of_users_device', default=False) and (not network_l... | the_stack_v2_python_sparse | kolibri/plugins/learn/kolibri_plugin.py | learningequality/kolibri | train | 689 | |
851f8bb8b89a25f6aa867ab837ff8417aa6f79fa | [
"err_msg = {'status': 0, 'code': 0, 'message': '有误'}\nif check_request_method(request) == RequestMethod.GET:\n province = get_request_args(request, 'province')\n province = conversion_args_type({province: str})\n if not province:\n response = err_msg\n else:\n response = cache.get(province... | <|body_start_0|>
err_msg = {'status': 0, 'code': 0, 'message': '有误'}
if check_request_method(request) == RequestMethod.GET:
province = get_request_args(request, 'province')
province = conversion_args_type({province: str})
if not province:
response = er... | AreaInfoDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AreaInfoDetail:
def get_city_queryset(request):
"""获取省份下所有城市列表 景区地理基本信息--链接格式: http://127.0.0.1:8000/attractions/api/getCitysByProvince?province=广东省 :param request: :return:"""
<|body_0|>
def get_scenic_queryset(request):
"""获取城市下所有地区列表 景区数据---flag=1的景点暂时不公开--链接格式: h... | stack_v2_sparse_classes_36k_train_009442 | 6,080 | no_license | [
{
"docstring": "获取省份下所有城市列表 景区地理基本信息--链接格式: http://127.0.0.1:8000/attractions/api/getCitysByProvince?province=广东省 :param request: :return:",
"name": "get_city_queryset",
"signature": "def get_city_queryset(request)"
},
{
"docstring": "获取城市下所有地区列表 景区数据---flag=1的景点暂时不公开--链接格式: http://127.0.0.1:800... | 4 | stack_v2_sparse_classes_30k_train_018313 | Implement the Python class `AreaInfoDetail` described below.
Class description:
Implement the AreaInfoDetail class.
Method signatures and docstrings:
- def get_city_queryset(request): 获取省份下所有城市列表 景区地理基本信息--链接格式: http://127.0.0.1:8000/attractions/api/getCitysByProvince?province=广东省 :param request: :return:
- def get_s... | Implement the Python class `AreaInfoDetail` described below.
Class description:
Implement the AreaInfoDetail class.
Method signatures and docstrings:
- def get_city_queryset(request): 获取省份下所有城市列表 景区地理基本信息--链接格式: http://127.0.0.1:8000/attractions/api/getCitysByProvince?province=广东省 :param request: :return:
- def get_s... | 200fbbdb016f592618e0a9fcd64f981dbf46cd3f | <|skeleton|>
class AreaInfoDetail:
def get_city_queryset(request):
"""获取省份下所有城市列表 景区地理基本信息--链接格式: http://127.0.0.1:8000/attractions/api/getCitysByProvince?province=广东省 :param request: :return:"""
<|body_0|>
def get_scenic_queryset(request):
"""获取城市下所有地区列表 景区数据---flag=1的景点暂时不公开--链接格式: h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AreaInfoDetail:
def get_city_queryset(request):
"""获取省份下所有城市列表 景区地理基本信息--链接格式: http://127.0.0.1:8000/attractions/api/getCitysByProvince?province=广东省 :param request: :return:"""
err_msg = {'status': 0, 'code': 0, 'message': '有误'}
if check_request_method(request) == RequestMethod.GET:
... | the_stack_v2_python_sparse | digitalsmart/attractions/areainfomation_view.py | LianZS/digitalsmart | train | 1 | |
59a054ba522a7537f96aef423dadaa5fd93a062a | [
"self.EQUAL = '='\nself.SEMICOLON = ';'\nself.BARKER = '1'\nself.comp = {'0': '110101010', '1': '110111111', '-1': '110111010', 'D': '110001100', 'A': '110110000', 'M': '111110000', '!D': '110001101', '!A': '110110001', '!M': '111110001', '-D': '110001111', '-A': '110110011', '-M': '111110011', 'D+1': '110011111', ... | <|body_start_0|>
self.EQUAL = '='
self.SEMICOLON = ';'
self.BARKER = '1'
self.comp = {'0': '110101010', '1': '110111111', '-1': '110111010', 'D': '110001100', 'A': '110110000', 'M': '111110000', '!D': '110001101', '!A': '110110001', '!M': '111110001', '-D': '110001111', '-A': '110110011'... | This class is responsible for parsing C commands | CCommandParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CCommandParser:
"""This class is responsible for parsing C commands"""
def __init__(self):
"""set initial values"""
<|body_0|>
def run(self, lst, table={}):
"""go over the lines and replace the c instructions with their binary form :param lst: file lines :param t... | stack_v2_sparse_classes_36k_train_009443 | 2,909 | no_license | [
{
"docstring": "set initial values",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "go over the lines and replace the c instructions with their binary form :param lst: file lines :param table: symbols dictionary",
"name": "run",
"signature": "def run(self, lst, ... | 2 | stack_v2_sparse_classes_30k_train_018435 | Implement the Python class `CCommandParser` described below.
Class description:
This class is responsible for parsing C commands
Method signatures and docstrings:
- def __init__(self): set initial values
- def run(self, lst, table={}): go over the lines and replace the c instructions with their binary form :param lst... | Implement the Python class `CCommandParser` described below.
Class description:
This class is responsible for parsing C commands
Method signatures and docstrings:
- def __init__(self): set initial values
- def run(self, lst, table={}): go over the lines and replace the c instructions with their binary form :param lst... | 2170c0fd15afc950a8f5ef2289716a01515daaaf | <|skeleton|>
class CCommandParser:
"""This class is responsible for parsing C commands"""
def __init__(self):
"""set initial values"""
<|body_0|>
def run(self, lst, table={}):
"""go over the lines and replace the c instructions with their binary form :param lst: file lines :param t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CCommandParser:
"""This class is responsible for parsing C commands"""
def __init__(self):
"""set initial values"""
self.EQUAL = '='
self.SEMICOLON = ';'
self.BARKER = '1'
self.comp = {'0': '110101010', '1': '110111111', '-1': '110111010', 'D': '110001100', 'A': '1... | the_stack_v2_python_sparse | projects/06/Assembler/CCommandParser.py | DaniNem/N2T_Zilber_Neimark | train | 0 |
be7f1e42134442a1101c4990da8094948717a9a3 | [
"if low > high:\n return False\nmid = (low + high) // 2\nif data[mid] == target:\n return True\nif target < data[mid]:\n return self.recur_binary_search(data, target, low, mid - 1)\nelse:\n return self.recur_binary_search(data, target, mid + 1, high)",
"while low <= high:\n mid = (low + high) // 2\... | <|body_start_0|>
if low > high:
return False
mid = (low + high) // 2
if data[mid] == target:
return True
if target < data[mid]:
return self.recur_binary_search(data, target, low, mid - 1)
else:
return self.recur_binary_search(data, ... | 二分查找,时间复杂度O(logn) | BinarySearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySearch:
"""二分查找,时间复杂度O(logn)"""
def recur_binary_search(self, data: list, target: int, low: int, high: int) -> bool:
"""用递归实现二分查找"""
<|body_0|>
def loop_binary_search(self, data: list, target: int, low: int, high: int) -> bool:
"""通过循环实现二分查找"""
<|bo... | stack_v2_sparse_classes_36k_train_009444 | 1,918 | no_license | [
{
"docstring": "用递归实现二分查找",
"name": "recur_binary_search",
"signature": "def recur_binary_search(self, data: list, target: int, low: int, high: int) -> bool"
},
{
"docstring": "通过循环实现二分查找",
"name": "loop_binary_search",
"signature": "def loop_binary_search(self, data: list, target: int, ... | 3 | stack_v2_sparse_classes_30k_train_008804 | Implement the Python class `BinarySearch` described below.
Class description:
二分查找,时间复杂度O(logn)
Method signatures and docstrings:
- def recur_binary_search(self, data: list, target: int, low: int, high: int) -> bool: 用递归实现二分查找
- def loop_binary_search(self, data: list, target: int, low: int, high: int) -> bool: 通过循环实... | Implement the Python class `BinarySearch` described below.
Class description:
二分查找,时间复杂度O(logn)
Method signatures and docstrings:
- def recur_binary_search(self, data: list, target: int, low: int, high: int) -> bool: 用递归实现二分查找
- def loop_binary_search(self, data: list, target: int, low: int, high: int) -> bool: 通过循环实... | 2c640fc178d9f0d5693da4cbc1caeaa937fc5df3 | <|skeleton|>
class BinarySearch:
"""二分查找,时间复杂度O(logn)"""
def recur_binary_search(self, data: list, target: int, low: int, high: int) -> bool:
"""用递归实现二分查找"""
<|body_0|>
def loop_binary_search(self, data: list, target: int, low: int, high: int) -> bool:
"""通过循环实现二分查找"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinarySearch:
"""二分查找,时间复杂度O(logn)"""
def recur_binary_search(self, data: list, target: int, low: int, high: int) -> bool:
"""用递归实现二分查找"""
if low > high:
return False
mid = (low + high) // 2
if data[mid] == target:
return True
if target < da... | the_stack_v2_python_sparse | more/binary_search/binary_search.py | eggplanty/basicAlgorithm | train | 0 |
8cf3d606094100af657b459573438099bb80cfd9 | [
"super().__init__('synthetic_facial_image_generation_node')\nself.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 10)\nself.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)\nself._cv_bridge = CvBridge()\nself.ID = 0\nself.args = args\nself.path_in = args.path_in\nse... | <|body_start_0|>
super().__init__('synthetic_facial_image_generation_node')
self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 10)
self.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)
self._cv_bridge = CvBridge()
self.ID = 0
... | SyntheticDataGeneratorNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyntheticDataGeneratorNode:
def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_... | stack_v2_sparse_classes_36k_train_009445 | 9,414 | permissive | [
{
"docstring": "Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_rgb_image_topic: Topic to which we are publishing the synthetic facial image (if None, no image is published) :type output_r... | 2 | stack_v2_sparse_classes_30k_train_000118 | Implement the Python class `SyntheticDataGeneratorNode` described below.
Class description:
Implement the SyntheticDataGeneratorNode class.
Method signatures and docstrings:
- def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'): Creates a ROS Node for... | Implement the Python class `SyntheticDataGeneratorNode` described below.
Class description:
Implement the SyntheticDataGeneratorNode class.
Method signatures and docstrings:
- def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'): Creates a ROS Node for... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class SyntheticDataGeneratorNode:
def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SyntheticDataGeneratorNode:
def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topi... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_data_generation/opendr_data_generation/synthetic_facial_generation_node.py | opendr-eu/opendr | train | 535 | |
4df0936617cc8af13ab377883ff4c18fc813272c | [
"command = 'net-dvs'\npylogger.info('Getting IPFIX configuration using: %s' % command)\nipfix_table_attributes_map = {'idle timeout': 'idle_timeout', 'active timeout': 'flow_timeout', 'sampling rate': 'packet_sample_probability'}\nresult = client_object.execute_cmd_get_schema(command, ipfix_table_attributes_map, cl... | <|body_start_0|>
command = 'net-dvs'
pylogger.info('Getting IPFIX configuration using: %s' % command)
ipfix_table_attributes_map = {'idle timeout': 'idle_timeout', 'active timeout': 'flow_timeout', 'sampling rate': 'packet_sample_probability'}
result = client_object.execute_cmd_get_schem... | ESX55NSXImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESX55NSXImpl:
def get_ipfix_config(cls, client_object, **kwargs):
"""Returns the IPFIX configuration from an ESX host obtained using the net-dvs command. Sample output: switch b6 92 12 50 38 2c 99 5d-2a e4 56 c5 c6 fb e6 05 (etherswitch) max ports: 1536 global properties: com.vmware.comm... | stack_v2_sparse_classes_36k_train_009446 | 3,189 | no_license | [
{
"docstring": "Returns the IPFIX configuration from an ESX host obtained using the net-dvs command. Sample output: switch b6 92 12 50 38 2c 99 5d-2a e4 56 c5 c6 fb e6 05 (etherswitch) max ports: 1536 global properties: com.vmware.common.version = 0x64. 0. 0. 0 propType = CONFIG com.vmware.common.opaqueDvs = tr... | 2 | null | Implement the Python class `ESX55NSXImpl` described below.
Class description:
Implement the ESX55NSXImpl class.
Method signatures and docstrings:
- def get_ipfix_config(cls, client_object, **kwargs): Returns the IPFIX configuration from an ESX host obtained using the net-dvs command. Sample output: switch b6 92 12 50... | Implement the Python class `ESX55NSXImpl` described below.
Class description:
Implement the ESX55NSXImpl class.
Method signatures and docstrings:
- def get_ipfix_config(cls, client_object, **kwargs): Returns the IPFIX configuration from an ESX host obtained using the net-dvs command. Sample output: switch b6 92 12 50... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class ESX55NSXImpl:
def get_ipfix_config(cls, client_object, **kwargs):
"""Returns the IPFIX configuration from an ESX host obtained using the net-dvs command. Sample output: switch b6 92 12 50 38 2c 99 5d-2a e4 56 c5 c6 fb e6 05 (etherswitch) max ports: 1536 global properties: com.vmware.comm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESX55NSXImpl:
def get_ipfix_config(cls, client_object, **kwargs):
"""Returns the IPFIX configuration from an ESX host obtained using the net-dvs command. Sample output: switch b6 92 12 50 38 2c 99 5d-2a e4 56 c5 c6 fb e6 05 (etherswitch) max ports: 1536 global properties: com.vmware.common.version = 0... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/vsphere/esx/cli/esx55_nsx_impl.py | Cloudxtreme/MyProject | train | 0 | |
189ee5e58d0b3a6d7b98ef016260f6f1f35350f8 | [
"random.seed(1)\nself.grid_lat = np.random.rand(1000) * 5 * random.choice([-1, 1]) + -59.1868\nself.grid_long = np.random.rand(1000) * 5 * random.choice([-1, 1]) + 57.1794\nself.grid_dates = np.random.rand(1000) * 5 * random.choice([-1, 1]) + 5.1083 * 10 ** 3\nself.grid_z_values = np.random.rand(1000) * 5 * random.... | <|body_start_0|>
random.seed(1)
self.grid_lat = np.random.rand(1000) * 5 * random.choice([-1, 1]) + -59.1868
self.grid_long = np.random.rand(1000) * 5 * random.choice([-1, 1]) + 57.1794
self.grid_dates = np.random.rand(1000) * 5 * random.choice([-1, 1]) + 5.1083 * 10 ** 3
self.gr... | Test cases for find_besthist function | FindBestHistTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindBestHistTestCase:
"""Test cases for find_besthist function"""
def setUp(self):
"""Set up for the tests. Creates 1000 historical random data points that are the float data points +/- 5. This could fail randomly if, by pure chance, none of the generated data is in the ellipse, so u... | stack_v2_sparse_classes_36k_train_009447 | 5,447 | no_license | [
{
"docstring": "Set up for the tests. Creates 1000 historical random data points that are the float data points +/- 5. This could fail randomly if, by pure chance, none of the generated data is in the ellipse, so use pseudo random numbers just in case :return: nothing",
"name": "setUp",
"signature": "de... | 5 | stack_v2_sparse_classes_30k_train_009995 | Implement the Python class `FindBestHistTestCase` described below.
Class description:
Test cases for find_besthist function
Method signatures and docstrings:
- def setUp(self): Set up for the tests. Creates 1000 historical random data points that are the float data points +/- 5. This could fail randomly if, by pure c... | Implement the Python class `FindBestHistTestCase` described below.
Class description:
Test cases for find_besthist function
Method signatures and docstrings:
- def setUp(self): Set up for the tests. Creates 1000 historical random data points that are the float data points +/- 5. This could fail randomly if, by pure c... | 3944e9783d58422d2d10bbc95f9706e168550034 | <|skeleton|>
class FindBestHistTestCase:
"""Test cases for find_besthist function"""
def setUp(self):
"""Set up for the tests. Creates 1000 historical random data points that are the float data points +/- 5. This could fail randomly if, by pure chance, none of the generated data is in the ellipse, so u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindBestHistTestCase:
"""Test cases for find_besthist function"""
def setUp(self):
"""Set up for the tests. Creates 1000 historical random data points that are the float data points +/- 5. This could fail randomly if, by pure chance, none of the generated data is in the ellipse, so use pseudo ran... | the_stack_v2_python_sparse | ow_calibration/find_besthist/find_besthist_test.py | gmaze/argodmqc_owc | train | 0 |
ad348972f1000131c537436478b1d79b9c00950b | [
"self.num_filters = num_filters\nself.input_dim = input_dim\nself._build_layer_components()\nsuper(InceptionResnetB, self).__init__(**kwargs)",
"self.conv_block1 = [Conv2D(self.num_filters, kernel_size=1, strides=1, padding='same', activation=tf.nn.relu)]\nself.conv_block2 = [Conv2D(filters=self.num_filters, kern... | <|body_start_0|>
self.num_filters = num_filters
self.input_dim = input_dim
self._build_layer_components()
super(InceptionResnetB, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
self.conv_block1 = [Conv2D(self.num_filters, kernel_size=1, strides=1, padding='same', activ... | Variant B of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connections are additionally used and have been shown ... | InceptionResnetB | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionResnetB:
"""Variant B of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connection... | stack_v2_sparse_classes_36k_train_009448 | 17,354 | permissive | [
{
"docstring": "Parameters ---------- num_filters: int, Number of convolutional filters input_dim: int, Number of channels in the input.",
"name": "__init__",
"signature": "def __init__(self, num_filters, input_dim, **kwargs)"
},
{
"docstring": "Builds the layers components and set _layers attri... | 3 | null | Implement the Python class `InceptionResnetB` described below.
Class description:
Variant B of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different sc... | Implement the Python class `InceptionResnetB` described below.
Class description:
Variant B of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different sc... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class InceptionResnetB:
"""Variant B of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connection... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InceptionResnetB:
"""Variant B of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connections are additio... | the_stack_v2_python_sparse | deepchem/models/chemnet_layers.py | deepchem/deepchem | train | 4,876 |
f67e856e3a214f16995e72315320e0e4bd18d652 | [
"q = deque()\nif not root:\n return ''\nlevel_order = []\nq.append(root)\nwhile q:\n node = q.popleft()\n if node:\n level_order.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n level_order.append('null')\nwhile level_order[-1] == 'null':\n leve... | <|body_start_0|>
q = deque()
if not root:
return ''
level_order = []
q.append(root)
while q:
node = q.popleft()
if node:
level_order.append(str(node.val))
q.append(node.left)
q.append(node.right)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_009449 | 1,868 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006457 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 82d3b703e42908cd3e8960e737e7081460691d64 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
q = deque()
if not root:
return ''
level_order = []
q.append(root)
while q:
node = q.popleft()
if node:
... | the_stack_v2_python_sparse | serialize_deserialize_binary_tree/serialize_deserialize_bin_tree.py | pandeconscious/leetcode | train | 0 | |
4e7bfd3134bd5a68bf6189a8287b0bb5ff6b849f | [
"self.BELOW_LOW_THRESHOLD = -1\nself.BETWEEN_THRESHOLDS = -2\ntorch._assert(low_threshold <= high_threshold, 'low_threshold should be <= high_threshold')\nself.high_threshold = high_threshold\nself.low_threshold = low_threshold\nself.allow_low_quality_matches = allow_low_quality_matches",
"if match_quality_matrix... | <|body_start_0|>
self.BELOW_LOW_THRESHOLD = -1
self.BETWEEN_THRESHOLDS = -2
torch._assert(low_threshold <= high_threshold, 'low_threshold should be <= high_threshold')
self.high_threshold = high_threshold
self.low_threshold = low_threshold
self.allow_low_quality_matches =... | This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be assigned to zero or more predicted elements. Matching is based on the MxN match_quality_matrix, that characterizes how well each (ground-tru... | Matcher | [
"BSD-3-Clause",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matcher:
"""This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be assigned to zero or more predicted elements. Matching is based on the MxN match_quality_matrix, that char... | stack_v2_sparse_classes_36k_train_009450 | 22,127 | permissive | [
{
"docstring": "Args: high_threshold (float): quality values greater than or equal to this value are candidate matches. low_threshold (float): a lower quality threshold used to stratify matches into three levels: 1) matches >= high_threshold 2) BETWEEN_THRESHOLDS matches in [low_threshold, high_threshold) 3) BE... | 3 | stack_v2_sparse_classes_30k_train_015532 | Implement the Python class `Matcher` described below.
Class description:
This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be assigned to zero or more predicted elements. Matching is based on ... | Implement the Python class `Matcher` described below.
Class description:
This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be assigned to zero or more predicted elements. Matching is based on ... | 1f94320d8db8d102214a7dc02c22fa65ee9ac58a | <|skeleton|>
class Matcher:
"""This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be assigned to zero or more predicted elements. Matching is based on the MxN match_quality_matrix, that char... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Matcher:
"""This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will have exactly zero or one matches; each ground-truth element may be assigned to zero or more predicted elements. Matching is based on the MxN match_quality_matrix, that characterizes how... | the_stack_v2_python_sparse | torchvision/models/detection/_utils.py | pytorch/vision | train | 15,620 |
e9c40dcd362a9460ae71be3cf3caec7ccee12c67 | [
"try:\n data_stream = pkgutil.get_data('scattertext', 'data/rotten_tomatoes_corpus.csv.bz2')\nexcept:\n url = ROTTEN_TOMATOES_DATA_URL\n data_stream = urlopen(url).read()\nreturn pd.read_csv(io.BytesIO(bz2.decompress(data_stream)))",
"try:\n data_stream = pkgutil.get_data('scattertext', 'data/rotten_t... | <|body_start_0|>
try:
data_stream = pkgutil.get_data('scattertext', 'data/rotten_tomatoes_corpus.csv.bz2')
except:
url = ROTTEN_TOMATOES_DATA_URL
data_stream = urlopen(url).read()
return pd.read_csv(io.BytesIO(bz2.decompress(data_stream)))
<|end_body_0|>
<|bo... | Derived from the sentiment polarity/subjectivity datasets from http://www.cs.cornell.edu/people/pabo/movie-review-data/ Bo Pang and Lillian Lee. ``A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimum Cuts'', Proceedings of the ACL, 2004. | RottenTomatoes | [
"MIT",
"CC-BY-NC-SA-4.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RottenTomatoes:
"""Derived from the sentiment polarity/subjectivity datasets from http://www.cs.cornell.edu/people/pabo/movie-review-data/ Bo Pang and Lillian Lee. ``A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimum Cuts'', Proceedings of the ACL, 2004.... | stack_v2_sparse_classes_36k_train_009451 | 5,362 | permissive | [
{
"docstring": "Returns ------- pd.DataFrame I.e., >>> convention_df.iloc[0] category plot filename subjectivity_html/obj/2002/Abandon.html text A senior at an elite college (Katie Holmes), a... movie_name abandon",
"name": "get_data",
"signature": "def get_data()"
},
{
"docstring": "Returns all... | 2 | stack_v2_sparse_classes_30k_train_014593 | Implement the Python class `RottenTomatoes` described below.
Class description:
Derived from the sentiment polarity/subjectivity datasets from http://www.cs.cornell.edu/people/pabo/movie-review-data/ Bo Pang and Lillian Lee. ``A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimu... | Implement the Python class `RottenTomatoes` described below.
Class description:
Derived from the sentiment polarity/subjectivity datasets from http://www.cs.cornell.edu/people/pabo/movie-review-data/ Bo Pang and Lillian Lee. ``A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimu... | b41e3a875faf6dd886e49e524345202432db1b21 | <|skeleton|>
class RottenTomatoes:
"""Derived from the sentiment polarity/subjectivity datasets from http://www.cs.cornell.edu/people/pabo/movie-review-data/ Bo Pang and Lillian Lee. ``A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimum Cuts'', Proceedings of the ACL, 2004.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RottenTomatoes:
"""Derived from the sentiment polarity/subjectivity datasets from http://www.cs.cornell.edu/people/pabo/movie-review-data/ Bo Pang and Lillian Lee. ``A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimum Cuts'', Proceedings of the ACL, 2004."""
def ... | the_stack_v2_python_sparse | scattertext/SampleCorpora.py | JasonKessler/scattertext | train | 2,187 |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"self.action: Action = kargs.pop('action')\nsuper().__init__(*args, **kargs)\nself.set_field_from_dict('subject')\nif len(settings.CANVAS_INFO_DICT) > 1:\n self.fields['target_url'] = forms.ChoiceField(initial=self._FormWithPayload__form_info.get('target_url', None), required=True, choices=[('', '---')] + [(key,... | <|body_start_0|>
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
self.set_field_from_dict('subject')
if len(settings.CANVAS_INFO_DICT) > 1:
self.fields['target_url'] = forms.ChoiceField(initial=self._FormWithPayload__form_info.get('target_url', None... | Form to process information to run a Canvas Email action. | CanvasEmailActionForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasEmailActionForm:
"""Form to process information to run a Canvas Email action."""
def __init__(self, *args, **kargs):
"""Store the action and modify certain field data."""
<|body_0|>
def clean(self):
"""Store the target_url if not part of the form"""
... | stack_v2_sparse_classes_36k_train_009452 | 20,237 | permissive | [
{
"docstring": "Store the action and modify certain field data.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Store the target_url if not part of the form",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016277 | Implement the Python class `CanvasEmailActionForm` described below.
Class description:
Form to process information to run a Canvas Email action.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store the action and modify certain field data.
- def clean(self): Store the target_url if not part o... | Implement the Python class `CanvasEmailActionForm` described below.
Class description:
Form to process information to run a Canvas Email action.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store the action and modify certain field data.
- def clean(self): Store the target_url if not part o... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class CanvasEmailActionForm:
"""Form to process information to run a Canvas Email action."""
def __init__(self, *args, **kargs):
"""Store the action and modify certain field data."""
<|body_0|>
def clean(self):
"""Store the target_url if not part of the form"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanvasEmailActionForm:
"""Form to process information to run a Canvas Email action."""
def __init__(self, *args, **kargs):
"""Store the action and modify certain field data."""
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
self.set_field_from_d... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
df64285ffbd552fb2c301897099c1cd8cfcd36db | [
"try:\n user = self.context['user']\n reaction = ReactionPost.objects.get(user=user)\n reaction.delete()\n post = self.context['post']\n post.reactions -= 1\n post.save()\nexcept ReactionPost.DoesNotExist:\n return data",
"user = self.context['user']\npost = self.context['post']\nreaction_pos... | <|body_start_0|>
try:
user = self.context['user']
reaction = ReactionPost.objects.get(user=user)
reaction.delete()
post = self.context['post']
post.reactions -= 1
post.save()
except ReactionPost.DoesNotExist:
return data... | Reaction post model serializer. | ReactionPostModelSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReactionPostModelSerializer:
"""Reaction post model serializer."""
def validate(self, data):
"""verify that the user's reaction does not exist yet."""
<|body_0|>
def create(self, data):
"""Create a reaction post."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_009453 | 4,185 | no_license | [
{
"docstring": "verify that the user's reaction does not exist yet.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Create a reaction post.",
"name": "create",
"signature": "def create(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019832 | Implement the Python class `ReactionPostModelSerializer` described below.
Class description:
Reaction post model serializer.
Method signatures and docstrings:
- def validate(self, data): verify that the user's reaction does not exist yet.
- def create(self, data): Create a reaction post. | Implement the Python class `ReactionPostModelSerializer` described below.
Class description:
Reaction post model serializer.
Method signatures and docstrings:
- def validate(self, data): verify that the user's reaction does not exist yet.
- def create(self, data): Create a reaction post.
<|skeleton|>
class ReactionP... | fae5c0b2e388239e2e32a3fbf52aa7cfd48a7cbb | <|skeleton|>
class ReactionPostModelSerializer:
"""Reaction post model serializer."""
def validate(self, data):
"""verify that the user's reaction does not exist yet."""
<|body_0|>
def create(self, data):
"""Create a reaction post."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReactionPostModelSerializer:
"""Reaction post model serializer."""
def validate(self, data):
"""verify that the user's reaction does not exist yet."""
try:
user = self.context['user']
reaction = ReactionPost.objects.get(user=user)
reaction.delete()
... | the_stack_v2_python_sparse | facebook/app/posts/serializers/reactions.py | ricagome/Api-Facebook-Clone | train | 0 |
d37c5a53aa46a706f3d0e7d54fde0c7ed069cf97 | [
"if root is None:\n return None\nif root.val == val:\n return root\nelif val < root.val:\n return self.searchBST(root.left, val)\nelse:\n return self.searchBST(root.right, val)",
"if not root:\n return None\nif root.val == val:\n return root\nelif val < root.val:\n return self.searchBST2(root... | <|body_start_0|>
if root is None:
return None
if root.val == val:
return root
elif val < root.val:
return self.searchBST(root.left, val)
else:
return self.searchBST(root.right, val)
<|end_body_0|>
<|body_start_1|>
if not root:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_0|>
def searchBST2(self, root, val):
""":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_009454 | 2,333 | no_license | [
{
"docstring": ":type root: TreeNode :type val: int :rtype: TreeNode",
"name": "searchBST",
"signature": "def searchBST(self, root, val)"
},
{
"docstring": ":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)",
"name": "searchBST2",
"signature": "def searchBST2(self,... | 2 | stack_v2_sparse_classes_30k_train_004023 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode
- def searchBST2(self, root, val): :param root: :param val: :return: Recursion Space: O(logn)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode
- def searchBST2(self, root, val): :param root: :param val: :return: Recursion Space: O(logn)... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def searchBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_0|>
def searchBST2(self, root, val):
""":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
if root is None:
return None
if root.val == val:
return root
elif val < root.val:
return self.searchBST(root.left, val)
else:
... | the_stack_v2_python_sparse | algo/tree/search_in_binary_search_tree.py | xys234/coding-problems | train | 0 | |
f143ab870b4a94aaaca38a8ba58c508148bdc5ea | [
"from rmgpy.chemkin import load_chemkin_file\nfolder = os.path.join(os.path.dirname(rmgpy.__file__), 'tools/data/various_kinetics')\nchemkin_path = os.path.join(folder, 'chem_annotated.inp')\ndictionary_path = os.path.join(folder, 'species_dictionary.txt')\ntransport_path = os.path.join(folder, 'tran.dat')\nspecies... | <|body_start_0|>
from rmgpy.chemkin import load_chemkin_file
folder = os.path.join(os.path.dirname(rmgpy.__file__), 'tools/data/various_kinetics')
chemkin_path = os.path.join(folder, 'chem_annotated.inp')
dictionary_path = os.path.join(folder, 'species_dictionary.txt')
transport_... | Contains unit tests for the conversion of RMG species and reaction objects to Cantera objects. | RMGToCanteraTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMGToCanteraTest:
"""Contains unit tests for the conversion of RMG species and reaction objects to Cantera objects."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_species_conversion(self):
"""Test that species ob... | stack_v2_sparse_classes_36k_train_009455 | 5,853 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that species objects convert properly",
"name": "test_species_conversion",
"signature": "def test_species_conversion(self)"
},
{
"docstrin... | 3 | null | Implement the Python class `RMGToCanteraTest` described below.
Class description:
Contains unit tests for the conversion of RMG species and reaction objects to Cantera objects.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_species_conversion(self):... | Implement the Python class `RMGToCanteraTest` described below.
Class description:
Contains unit tests for the conversion of RMG species and reaction objects to Cantera objects.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_species_conversion(self):... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class RMGToCanteraTest:
"""Contains unit tests for the conversion of RMG species and reaction objects to Cantera objects."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_species_conversion(self):
"""Test that species ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RMGToCanteraTest:
"""Contains unit tests for the conversion of RMG species and reaction objects to Cantera objects."""
def setUp(self):
"""A function run before each unit test in this class."""
from rmgpy.chemkin import load_chemkin_file
folder = os.path.join(os.path.dirname(rmgpy... | the_stack_v2_python_sparse | rmgpy/tools/canteramodelTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
d0842a76fef5e5a66e10ccec6f48daffaf1c5a92 | [
"params = request.query_params.dict()\nvariety = params.get('variety')\nsidebars = Sidebar.objects.filter(variety=variety).order_by('-priority', 'id')\ndata = [{'sidebar_id': sidebar.id, 'sidebar_name': sidebar.name} for sidebar in sidebars]\nreturn BackstageHTTPResponse(BackstageHTTPResponse.API_HTTP_CODE_NORMAL, ... | <|body_start_0|>
params = request.query_params.dict()
variety = params.get('variety')
sidebars = Sidebar.objects.filter(variety=variety).order_by('-priority', 'id')
data = [{'sidebar_id': sidebar.id, 'sidebar_name': sidebar.name} for sidebar in sidebars]
return BackstageHTTPRespo... | ChartSidebarView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChartSidebarView:
def get(self, request):
"""获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True"""
<|body_0|>
def post(self, request):
"""新增侧边栏 --- parameters: - name: variety description: 品种 paramType: form required: True - name:... | stack_v2_sparse_classes_36k_train_009456 | 16,279 | no_license | [
{
"docstring": "获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增侧边栏 --- parameters: - name: variety description: 品种 paramType: form required: True - name: sidebar_name description:... | 4 | stack_v2_sparse_classes_30k_train_020627 | Implement the Python class `ChartSidebarView` described below.
Class description:
Implement the ChartSidebarView class.
Method signatures and docstrings:
- def get(self, request): 获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True
- def post(self, request): 新增侧边栏 --- parameters: -... | Implement the Python class `ChartSidebarView` described below.
Class description:
Implement the ChartSidebarView class.
Method signatures and docstrings:
- def get(self, request): 获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True
- def post(self, request): 新增侧边栏 --- parameters: -... | c50def8cde58fd4663032b860eb058302cbac6da | <|skeleton|>
class ChartSidebarView:
def get(self, request):
"""获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True"""
<|body_0|>
def post(self, request):
"""新增侧边栏 --- parameters: - name: variety description: 品种 paramType: form required: True - name:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChartSidebarView:
def get(self, request):
"""获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True"""
params = request.query_params.dict()
variety = params.get('variety')
sidebars = Sidebar.objects.filter(variety=variety).order_by('-priority', ... | the_stack_v2_python_sparse | src/api/chart/views.py | fan1018wen/Alpha | train | 0 | |
8b479297a5b767e4010a5aa636cce6fb61b27a58 | [
"self.code = code\nself.desc = desc\nself.suffixes = {}",
"if suffix is None:\n suffix = ''\nif suffix not in self.suffixes:\n self.suffixes[suffix] = {'link': set(), 'desc': None}\nif link is not None:\n self.suffixes[suffix]['link'].add(link)\nif desc is not None:\n self.suffixes[suffix]['desc'] = d... | <|body_start_0|>
self.code = code
self.desc = desc
self.suffixes = {}
<|end_body_0|>
<|body_start_1|>
if suffix is None:
suffix = ''
if suffix not in self.suffixes:
self.suffixes[suffix] = {'link': set(), 'desc': None}
if link is not None:
... | Class for details of one error or warning code. | Code | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Code:
"""Class for details of one error or warning code."""
def __init__(self, code, desc):
"""Initialize Code object."""
<|body_0|>
def add_suffix(self, suffix, link=None, desc=None):
"""Add details for one code suffix, which may be None."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_009457 | 6,348 | permissive | [
{
"docstring": "Initialize Code object.",
"name": "__init__",
"signature": "def __init__(self, code, desc)"
},
{
"docstring": "Add details for one code suffix, which may be None.",
"name": "add_suffix",
"signature": "def add_suffix(self, suffix, link=None, desc=None)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_020564 | Implement the Python class `Code` described below.
Class description:
Class for details of one error or warning code.
Method signatures and docstrings:
- def __init__(self, code, desc): Initialize Code object.
- def add_suffix(self, suffix, link=None, desc=None): Add details for one code suffix, which may be None.
- ... | Implement the Python class `Code` described below.
Class description:
Class for details of one error or warning code.
Method signatures and docstrings:
- def __init__(self, code, desc): Initialize Code object.
- def add_suffix(self, suffix, link=None, desc=None): Add details for one code suffix, which may be None.
- ... | 8ad83ce9dc078b0e224e47e9358059e7cd49f610 | <|skeleton|>
class Code:
"""Class for details of one error or warning code."""
def __init__(self, code, desc):
"""Initialize Code object."""
<|body_0|>
def add_suffix(self, suffix, link=None, desc=None):
"""Add details for one code suffix, which may be None."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Code:
"""Class for details of one error or warning code."""
def __init__(self, code, desc):
"""Initialize Code object."""
self.code = code
self.desc = desc
self.suffixes = {}
def add_suffix(self, suffix, link=None, desc=None):
"""Add details for one code suffi... | the_stack_v2_python_sparse | extract_codes.py | zimeon/ocfl-py | train | 16 |
61689ed8a450c34a05d69ac74f857a86846d35a4 | [
"dp = {}\nres = 0\nA_set = set(A)\nfor i in range(len(A)):\n for j in range(i):\n if A[i] - A[j] < A[j] and A[i] - A[j] in A_set:\n dp[A[j], A[i]] = dp.get((A[i] - A[j], A[j]), 2) + 1\n if dp.get((A[j], A[i]), 0) > res:\n res = dp.get((A[j], A[i]), 0)\nreturn res",
"... | <|body_start_0|>
dp = {}
res = 0
A_set = set(A)
for i in range(len(A)):
for j in range(i):
if A[i] - A[j] < A[j] and A[i] - A[j] in A_set:
dp[A[j], A[i]] = dp.get((A[i] - A[j], A[j]), 2) + 1
if dp.get((A[j], A[i]), 0) > ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
"""This is the DP solution. The intuition is dp[a, b] = dp[b-a, a] + 1 if dp[b-a, a] does not exist but b-a is in A, then set dp[a, b] to 3 :type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseqOld(self, A):
"... | stack_v2_sparse_classes_36k_train_009458 | 13,963 | permissive | [
{
"docstring": "This is the DP solution. The intuition is dp[a, b] = dp[b-a, a] + 1 if dp[b-a, a] does not exist but b-a is in A, then set dp[a, b] to 3 :type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq",
"signature": "def lenLongestFibSubseq(self, A)"
},
{
"docstring": ":type A: Lis... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): This is the DP solution. The intuition is dp[a, b] = dp[b-a, a] + 1 if dp[b-a, a] does not exist but b-a is in A, then set dp[a, b] to 3 :type A... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): This is the DP solution. The intuition is dp[a, b] = dp[b-a, a] + 1 if dp[b-a, a] does not exist but b-a is in A, then set dp[a, b] to 3 :type A... | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
"""This is the DP solution. The intuition is dp[a, b] = dp[b-a, a] + 1 if dp[b-a, a] does not exist but b-a is in A, then set dp[a, b] to 3 :type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseqOld(self, A):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lenLongestFibSubseq(self, A):
"""This is the DP solution. The intuition is dp[a, b] = dp[b-a, a] + 1 if dp[b-a, a] does not exist but b-a is in A, then set dp[a, b] to 3 :type A: List[int] :rtype: int"""
dp = {}
res = 0
A_set = set(A)
for i in range(len(A)... | the_stack_v2_python_sparse | Leetcode/873.length-of-longest-fibonacci-subsequence.py | EdwaRen/Competitve-Programming | train | 1 | |
61d0b3819e5ac37ac4b5f5b9c19ababe7fbf21c2 | [
"s, t = (sorted(s), sorted(t))\nn = len(s)\nfor i in range(n):\n if s[i] != t[i]:\n return t[i]\nreturn t[-1]",
"char_count = Counter(s)\nfor char in t:\n if not char_count[char] or char not in char_count:\n return char\n char_count[char] -= 1",
"value = 0\nn = len(s)\nfor i in range(n):\... | <|body_start_0|>
s, t = (sorted(s), sorted(t))
n = len(s)
for i in range(n):
if s[i] != t[i]:
return t[i]
return t[-1]
<|end_body_0|>
<|body_start_1|>
char_count = Counter(s)
for char in t:
if not char_count[char] or char not in ch... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_diff_1(self, s, t):
"""Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s)."""
<|body_0|>
def find_diff_2(self, s, t):
"""Use hash map to count the characters in string s, then compar... | stack_v2_sparse_classes_36k_train_009459 | 2,403 | no_license | [
{
"docstring": "Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).",
"name": "find_diff_1",
"signature": "def find_diff_1(self, s, t)"
},
{
"docstring": "Use hash map to count the characters in string s, then compare it with char... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_diff_1(self, s, t): Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).
- def find_diff_2(self, s, t): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_diff_1(self, s, t): Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s).
- def find_diff_2(self, s, t): ... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def find_diff_1(self, s, t):
"""Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s)."""
<|body_0|>
def find_diff_2(self, s, t):
"""Use hash map to count the characters in string s, then compar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find_diff_1(self, s, t):
"""Sort the strings and find first different letter. Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(s)."""
s, t = (sorted(s), sorted(t))
n = len(s)
for i in range(n):
if s[i] != t[i]:
return t[i... | the_stack_v2_python_sparse | Bit_Manipulation/find_difference.py | vladn90/Algorithms | train | 0 | |
e077f84c2d042395e9c949d5fe3d6a1a6c54b65d | [
"m, n = (len(word1), len(word2))\ndp_matrix = [[0] * (n + 1) for i in range(m + 1)]\nfor i in range(m + 1):\n dp_matrix[i][0] = i\nfor j in range(n + 1):\n dp_matrix[0][j] = j\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp_matrix[i][j] = dp_... | <|body_start_0|>
m, n = (len(word1), len(word2))
dp_matrix = [[0] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
dp_matrix[i][0] = i
for j in range(n + 1):
dp_matrix[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_0|>
def minDistance_Recursion_Memoization(self, word1, word2, memo={}):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_009460 | 1,889 | no_license | [
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "minDistance",
"signature": "def minDistance(self, word1, word2)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "minDistance_Recursion_Memoization",
"signature": "def minDistance_Recursio... | 2 | stack_v2_sparse_classes_30k_train_018985 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
- def minDistance_Recursion_Memoization(self, word1, word2, memo={}): :type word1: str :type wo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
- def minDistance_Recursion_Memoization(self, word1, word2, memo={}): :type word1: str :type wo... | cc02c326eed2c2d0707743dd0b92f428ee275974 | <|skeleton|>
class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_0|>
def minDistance_Recursion_Memoization(self, word1, word2, memo={}):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
m, n = (len(word1), len(word2))
dp_matrix = [[0] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
dp_matrix[i][0] = i
for j in range(n + 1):
... | the_stack_v2_python_sparse | 72-edit-distance/72-edit-distance.py | ankitfirebolt/leetcode | train | 0 | |
1da293b76c309768c723658147d76b82f9a5f133 | [
"self.gain_dict = gain_dict\nself.sensor_reading_dict = sensor_reading_dict\nself.set_point_dict = set_point_dict\nself.time_log = time_log\nself.val_log = val_log\nself.pitch_controller = PID_lib.PID()\nself.roll_controller = PID_lib.PID()\nself.yaw_controller = PID_lib.PID()\nself.pitch_controller.setMemberData(*... | <|body_start_0|>
self.gain_dict = gain_dict
self.sensor_reading_dict = sensor_reading_dict
self.set_point_dict = set_point_dict
self.time_log = time_log
self.val_log = val_log
self.pitch_controller = PID_lib.PID()
self.roll_controller = PID_lib.PID()
self.... | A class to run the PID control for the quadcopter. This class houses all the controllers for stabilizing flight and manages them by updating their control loop. This task has specific timing requirements | PIDControlTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIDControlTask:
"""A class to run the PID control for the quadcopter. This class houses all the controllers for stabilizing flight and manages them by updating their control loop. This task has specific timing requirements"""
def __init__(self, gain_dict, sensor_reading_dict, set_point_dict,... | stack_v2_sparse_classes_36k_train_009461 | 5,691 | no_license | [
{
"docstring": "Constructor for the PID control class. :param gain_dict: A ProtectedData dictionary containing the key values \"roll\",\"pitch\",\"yaw\", and \"thrust\" which have sub-dictionaries containing keys \"P\",\"I\", \"D\", \"windup_guard\", and \"sample_time\" which contain the gain values. Using the ... | 3 | stack_v2_sparse_classes_30k_train_006632 | Implement the Python class `PIDControlTask` described below.
Class description:
A class to run the PID control for the quadcopter. This class houses all the controllers for stabilizing flight and manages them by updating their control loop. This task has specific timing requirements
Method signatures and docstrings:
... | Implement the Python class `PIDControlTask` described below.
Class description:
A class to run the PID control for the quadcopter. This class houses all the controllers for stabilizing flight and manages them by updating their control loop. This task has specific timing requirements
Method signatures and docstrings:
... | 4be3c9dd4dc2ef1c9d74502ad30900627fe5f862 | <|skeleton|>
class PIDControlTask:
"""A class to run the PID control for the quadcopter. This class houses all the controllers for stabilizing flight and manages them by updating their control loop. This task has specific timing requirements"""
def __init__(self, gain_dict, sensor_reading_dict, set_point_dict,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PIDControlTask:
"""A class to run the PID control for the quadcopter. This class houses all the controllers for stabilizing flight and manages them by updating their control loop. This task has specific timing requirements"""
def __init__(self, gain_dict, sensor_reading_dict, set_point_dict, output_list,... | the_stack_v2_python_sparse | src/pid_controller_task.py | mfgeorge/pyCopter | train | 5 |
0303d05288fcc9821ea2cc34833b42ce20c68f68 | [
"def helper(node):\n if not node:\n return ''\n if not node.children:\n return str(node.val)\n res = str(node.val) + '['\n for i in range(len(node.children) - 1):\n res += helper(node.children[i])\n res += ' '\n res += helper(node.children[-1])\n res += ']'\n return ... | <|body_start_0|>
def helper(node):
if not node:
return ''
if not node.children:
return str(node.val)
res = str(node.val) + '['
for i in range(len(node.children) - 1):
res += helper(node.children[i])
r... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_009462 | 1,792 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_003703 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 90fd00246707b23d60a5d13b5a89d5b5f64ad008 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
def helper(node):
if not node:
return ''
if not node.children:
return str(node.val)
res = str(node.val) + '... | the_stack_v2_python_sparse | python_solution/0428.py | Dongzi-dq394/leetcode | train | 0 | |
a0879888212976926daeb80e9f56db97f7ac03b0 | [
"if operation == 'update' and self.request.authenticated_role != self.context.author:\n self.request.errors.add('url', 'role', 'Can update document only author')\n self.request.errors.status = 403\n raise error_handler(self.request)\nif self.request.validated['tender_status'] not in ['active.qualification'... | <|body_start_0|>
if operation == 'update' and self.request.authenticated_role != self.context.author:
self.request.errors.add('url', 'role', 'Can update document only author')
self.request.errors.status = 403
raise error_handler(self.request)
if self.request.validated... | TenderAwardComplaintDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to u... | stack_v2_sparse_classes_36k_train_009463 | 3,708 | permissive | [
{
"docstring": "TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to use different validators on methods according to procedure type.",
"name": "validate_complaint_d... | 4 | null | Implement the Python class `TenderAwardComplaintDocumentResource` described below.
Class description:
Implement the TenderAwardComplaintDocumentResource class.
Method signatures and docstrings:
- def validate_complaint_document(self, operation): TODO move validators This class is inherited in limited and openeu (qual... | Implement the Python class `TenderAwardComplaintDocumentResource` described below.
Class description:
Implement the TenderAwardComplaintDocumentResource class.
Method signatures and docstrings:
- def validate_complaint_document(self, operation): TODO move validators This class is inherited in limited and openeu (qual... | f901e1d8913cb10fee044dc267ef7c0f42c6a947 | <|skeleton|>
class TenderAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenderAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to use different v... | the_stack_v2_python_sparse | src/openprocurement/tender/open/views/award_complaint_document.py | ProzorroUKR/openprocurement.api | train | 14 | |
a2d5ba4a37c7f1b6b066eaa2b252e070df19ea64 | [
"super().__init__()\nself.q_proj = nn.Linear(q_in_dim, qk_dim)\nself.k_proj = nn.Linear(kv_in_dim, qk_dim)\nself.v_proj = nn.Linear(kv_in_dim, v_dim)\nself.scale = qk_dim ** 0.5\nself.out = nn.Linear(v_dim, out_dim)",
"q = self.q_proj(q)\nk = self.k_proj(s)\nv = self.v_proj(s)\nattn_score = torch.einsum('bqh,bsh-... | <|body_start_0|>
super().__init__()
self.q_proj = nn.Linear(q_in_dim, qk_dim)
self.k_proj = nn.Linear(kv_in_dim, qk_dim)
self.v_proj = nn.Linear(kv_in_dim, v_dim)
self.scale = qk_dim ** 0.5
self.out = nn.Linear(v_dim, out_dim)
<|end_body_0|>
<|body_start_1|>
q = ... | KeyValueAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyValueAttention:
def __init__(self, q_in_dim, qk_dim, kv_in_dim, v_dim, out_dim):
"""qkv attention. Assume that key source == value source. params: q_in_dim: query in dim. = decoder hidden dim. qk_dim: query & key dim. it should be same. kv_in_dim: key value in dim. = encoder hidden di... | stack_v2_sparse_classes_36k_train_009464 | 4,057 | no_license | [
{
"docstring": "qkv attention. Assume that key source == value source. params: q_in_dim: query in dim. = decoder hidden dim. qk_dim: query & key dim. it should be same. kv_in_dim: key value in dim. = encoder hidden dim. v_dim: value dim. out_dim: final attention out dim.",
"name": "__init__",
"signature... | 2 | stack_v2_sparse_classes_30k_train_011163 | Implement the Python class `KeyValueAttention` described below.
Class description:
Implement the KeyValueAttention class.
Method signatures and docstrings:
- def __init__(self, q_in_dim, qk_dim, kv_in_dim, v_dim, out_dim): qkv attention. Assume that key source == value source. params: q_in_dim: query in dim. = decode... | Implement the Python class `KeyValueAttention` described below.
Class description:
Implement the KeyValueAttention class.
Method signatures and docstrings:
- def __init__(self, q_in_dim, qk_dim, kv_in_dim, v_dim, out_dim): qkv attention. Assume that key source == value source. params: q_in_dim: query in dim. = decode... | 54dcd23112d452b856e4f8000cf697d352cfec05 | <|skeleton|>
class KeyValueAttention:
def __init__(self, q_in_dim, qk_dim, kv_in_dim, v_dim, out_dim):
"""qkv attention. Assume that key source == value source. params: q_in_dim: query in dim. = decoder hidden dim. qk_dim: query & key dim. it should be same. kv_in_dim: key value in dim. = encoder hidden di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyValueAttention:
def __init__(self, q_in_dim, qk_dim, kv_in_dim, v_dim, out_dim):
"""qkv attention. Assume that key source == value source. params: q_in_dim: query in dim. = decoder hidden dim. qk_dim: query & key dim. it should be same. kv_in_dim: key value in dim. = encoder hidden dim. v_dim: valu... | the_stack_v2_python_sparse | models/rnn/attention.py | khanrc/pt.seq2seq | train | 3 | |
9c4bbb198531aec71f4c05e9076e814dea77be9a | [
"super().__init__('temperature', device)\nif is_water:\n self._attr_translation_key = 'water_temperature'",
"if self._device.temperature is None:\n return None\nreturn round(self._device.temperature, 1)"
] | <|body_start_0|>
super().__init__('temperature', device)
if is_water:
self._attr_translation_key = 'water_temperature'
<|end_body_0|>
<|body_start_1|>
if self._device.temperature is None:
return None
return round(self._device.temperature, 1)
<|end_body_1|>
| Monitors the temperature. | FloTemperatureSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloTemperatureSensor:
"""Monitors the temperature."""
def __init__(self, device, is_water):
"""Initialize the temperature sensor."""
<|body_0|>
def native_value(self) -> float | None:
"""Return the current temperature."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_009465 | 6,155 | permissive | [
{
"docstring": "Initialize the temperature sensor.",
"name": "__init__",
"signature": "def __init__(self, device, is_water)"
},
{
"docstring": "Return the current temperature.",
"name": "native_value",
"signature": "def native_value(self) -> float | None"
}
] | 2 | stack_v2_sparse_classes_30k_train_019180 | Implement the Python class `FloTemperatureSensor` described below.
Class description:
Monitors the temperature.
Method signatures and docstrings:
- def __init__(self, device, is_water): Initialize the temperature sensor.
- def native_value(self) -> float | None: Return the current temperature. | Implement the Python class `FloTemperatureSensor` described below.
Class description:
Monitors the temperature.
Method signatures and docstrings:
- def __init__(self, device, is_water): Initialize the temperature sensor.
- def native_value(self) -> float | None: Return the current temperature.
<|skeleton|>
class Flo... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class FloTemperatureSensor:
"""Monitors the temperature."""
def __init__(self, device, is_water):
"""Initialize the temperature sensor."""
<|body_0|>
def native_value(self) -> float | None:
"""Return the current temperature."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloTemperatureSensor:
"""Monitors the temperature."""
def __init__(self, device, is_water):
"""Initialize the temperature sensor."""
super().__init__('temperature', device)
if is_water:
self._attr_translation_key = 'water_temperature'
def native_value(self) -> flo... | the_stack_v2_python_sparse | homeassistant/components/flo/sensor.py | home-assistant/core | train | 35,501 |
0573ca78872eec37eeed929768b62cd86cc7fb11 | [
"self.log = logging.getLogger('%s.%s.%s.msg-%d' % (__name__, self.__class__.__name__, mailbox.name, msg_key))\nself.mailbox = mailbox\nself.msg_key = msg_key\nself.seq_max = seq_max\nself.uid_max = uid_max\nself.msg_number = msg_number\nself.mailbox_sequences = sequences\nself.path = os.path.join(mailbox.mailbox._p... | <|body_start_0|>
self.log = logging.getLogger('%s.%s.%s.msg-%d' % (__name__, self.__class__.__name__, mailbox.name, msg_key))
self.mailbox = mailbox
self.msg_key = msg_key
self.seq_max = seq_max
self.uid_max = uid_max
self.msg_number = msg_number
self.mailbox_sequ... | When running searches on we store various bits of context information that the IMAPSearch object may need to determine if a specific message is matched or not. | SearchContext | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchContext:
"""When running searches on we store various bits of context information that the IMAPSearch object may need to determine if a specific message is matched or not."""
def __init__(self, mailbox, msg_key, msg_number, seq_max, uid_max, sequences):
"""A container to hold t... | stack_v2_sparse_classes_36k_train_009466 | 18,739 | permissive | [
{
"docstring": "A container to hold the contextual information an IMAPSearch objects to actually perform its matching function. Arguments: - `mailbox`: The mailbox the message lives in - `msg_key`: The message key (mailbox.get_message(msg_key)) - `msg_number`: The imap message number for this message - `seq_max... | 5 | stack_v2_sparse_classes_30k_train_005531 | Implement the Python class `SearchContext` described below.
Class description:
When running searches on we store various bits of context information that the IMAPSearch object may need to determine if a specific message is matched or not.
Method signatures and docstrings:
- def __init__(self, mailbox, msg_key, msg_nu... | Implement the Python class `SearchContext` described below.
Class description:
When running searches on we store various bits of context information that the IMAPSearch object may need to determine if a specific message is matched or not.
Method signatures and docstrings:
- def __init__(self, mailbox, msg_key, msg_nu... | dabbb5d815d67fe0b6dc07d7d0c32fa01df5d26a | <|skeleton|>
class SearchContext:
"""When running searches on we store various bits of context information that the IMAPSearch object may need to determine if a specific message is matched or not."""
def __init__(self, mailbox, msg_key, msg_number, seq_max, uid_max, sequences):
"""A container to hold t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchContext:
"""When running searches on we store various bits of context information that the IMAPSearch object may need to determine if a specific message is matched or not."""
def __init__(self, mailbox, msg_key, msg_number, seq_max, uid_max, sequences):
"""A container to hold the contextual... | the_stack_v2_python_sparse | asimap/search.py | scanner/asimap | train | 37 |
77c4c796f039e5a17a6609866f63155632a4c443 | [
"n, m = data.shape\nself.n_detections = n\nself.dimension = m\nself.last_frame = -1\nself.is_ordered = True\nfor i in range(1, n):\n frame1 = data[i - 1][0]\n frame2 = data[i][0]\n if frame2 < frame1:\n self.is_ordered = False\n if frame2 > self.last_frame:\n self.last_frame = int(frame2)\... | <|body_start_0|>
n, m = data.shape
self.n_detections = n
self.dimension = m
self.last_frame = -1
self.is_ordered = True
for i in range(1, n):
frame1 = data[i - 1][0]
frame2 = data[i][0]
if frame2 < frame1:
self.is_ordere... | representation of a video | VideoData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoData:
"""representation of a video"""
def __init__(self, data):
"""data: {np.array} [ (frame, ....), ... ]"""
<|body_0|>
def get_n_first_frames(self, n):
"""n: {int} get frames from 1 ... n"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n,... | stack_v2_sparse_classes_36k_train_009467 | 1,109 | permissive | [
{
"docstring": "data: {np.array} [ (frame, ....), ... ]",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "n: {int} get frames from 1 ... n",
"name": "get_n_first_frames",
"signature": "def get_n_first_frames(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003706 | Implement the Python class `VideoData` described below.
Class description:
representation of a video
Method signatures and docstrings:
- def __init__(self, data): data: {np.array} [ (frame, ....), ... ]
- def get_n_first_frames(self, n): n: {int} get frames from 1 ... n | Implement the Python class `VideoData` described below.
Class description:
representation of a video
Method signatures and docstrings:
- def __init__(self, data): data: {np.array} [ (frame, ....), ... ]
- def get_n_first_frames(self, n): n: {int} get frames from 1 ... n
<|skeleton|>
class VideoData:
"""represent... | 0245a0861b257fdaf12fcce59c2c8e4f52acc88b | <|skeleton|>
class VideoData:
"""representation of a video"""
def __init__(self, data):
"""data: {np.array} [ (frame, ....), ... ]"""
<|body_0|>
def get_n_first_frames(self, n):
"""n: {int} get frames from 1 ... n"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoData:
"""representation of a video"""
def __init__(self, data):
"""data: {np.array} [ (frame, ....), ... ]"""
n, m = data.shape
self.n_detections = n
self.dimension = m
self.last_frame = -1
self.is_ordered = True
for i in range(1, n):
... | the_stack_v2_python_sparse | cabbage/data/video.py | stasysp/cabbage | train | 0 |
28ad1c9fb2a257c91e3f8c59fc172407c68dd02b | [
"Base.__init__(self, target, opts)\nself.host, self.port, self.scheme, self.path = self._parse_url(self.target)\nreturn",
"opts = f'-d {self.target} --timeout 5 --threads 15'\nopts += f\" --agent '{self.useragent}'\"\nif self.opts['cookies']:\n opts += f\" --cookies '{self.cookies}'\"\nif self.opts['web_user']... | <|body_start_0|>
Base.__init__(self, target, opts)
self.host, self.port, self.scheme, self.path = self._parse_url(self.target)
return
<|end_body_0|>
<|body_start_1|>
opts = f'-d {self.target} --timeout 5 --threads 15'
opts += f" --agent '{self.useragent}'"
if self.opts['... | Typo3 CMD module | Typo3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Typo3:
"""Typo3 CMD module"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def typo_enumerator(self):
"""DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Base.... | stack_v2_sparse_classes_36k_train_009468 | 2,247 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, target, opts)"
},
{
"docstring": "DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator",
"name": "typo_enumerator",
"signature": "def typo_enumerator(self)"
}
] | 2 | null | Implement the Python class `Typo3` described below.
Class description:
Typo3 CMD module
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def typo_enumerator(self): DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator | Implement the Python class `Typo3` described below.
Class description:
Typo3 CMD module
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def typo_enumerator(self): DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator
<|skeleton|>
class Typo3:
"""Typo3 CMD module... | ddc052c8d7d43a60fc00ea40d85111d5bd7a282e | <|skeleton|>
class Typo3:
"""Typo3 CMD module"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def typo_enumerator(self):
"""DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Typo3:
"""Typo3 CMD module"""
def __init__(self, target, opts):
"""init"""
Base.__init__(self, target, opts)
self.host, self.port, self.scheme, self.path = self._parse_url(self.target)
return
def typo_enumerator(self):
"""DESCR: Enumerate Typo3 version and ext... | the_stack_v2_python_sparse | src/modules/web/typo3.py | noptrix/nullscan | train | 52 |
00409614a706234a19745bc7040e5370a9d956d7 | [
"pivot, end, res = (-1, 0, 0)\nfor i, j in sorted(clips):\n if end >= T or i > end:\n break\n elif pivot < i:\n res, pivot = (res + 1, end)\n end = max(end, j)\nreturn res if end >= T else -1",
"dp = [float('inf')] * 101\ndp[0] = 0\nfor start, end in sorted(clips):\n for i in range(start... | <|body_start_0|>
pivot, end, res = (-1, 0, 0)
for i, j in sorted(clips):
if end >= T or i > end:
break
elif pivot < i:
res, pivot = (res + 1, end)
end = max(end, j)
return res if end >= T else -1
<|end_body_0|>
<|body_start_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def videoStitching_1(self, clips, T):
"""pivot : merge된 범위의 이전 end. end : 여러 범위들의 가장 오른쪽 값."""
<|body_0|>
def videoStitching(self, clips, T):
"""start 가 작은 순서대로 sorting을 먼저해야 DP를 앞에서부터 진행할 수 있다. DP[i] 는 0~i 까지 만들기 위한 최소한의 clip 개수"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_009469 | 1,257 | no_license | [
{
"docstring": "pivot : merge된 범위의 이전 end. end : 여러 범위들의 가장 오른쪽 값.",
"name": "videoStitching_1",
"signature": "def videoStitching_1(self, clips, T)"
},
{
"docstring": "start 가 작은 순서대로 sorting을 먼저해야 DP를 앞에서부터 진행할 수 있다. DP[i] 는 0~i 까지 만들기 위한 최소한의 clip 개수",
"name": "videoStitching",
"signat... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def videoStitching_1(self, clips, T): pivot : merge된 범위의 이전 end. end : 여러 범위들의 가장 오른쪽 값.
- def videoStitching(self, clips, T): start 가 작은 순서대로 sorting을 먼저해야 DP를 앞에서부터 진행할 수 있다. D... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def videoStitching_1(self, clips, T): pivot : merge된 범위의 이전 end. end : 여러 범위들의 가장 오른쪽 값.
- def videoStitching(self, clips, T): start 가 작은 순서대로 sorting을 먼저해야 DP를 앞에서부터 진행할 수 있다. D... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def videoStitching_1(self, clips, T):
"""pivot : merge된 범위의 이전 end. end : 여러 범위들의 가장 오른쪽 값."""
<|body_0|>
def videoStitching(self, clips, T):
"""start 가 작은 순서대로 sorting을 먼저해야 DP를 앞에서부터 진행할 수 있다. DP[i] 는 0~i 까지 만들기 위한 최소한의 clip 개수"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def videoStitching_1(self, clips, T):
"""pivot : merge된 범위의 이전 end. end : 여러 범위들의 가장 오른쪽 값."""
pivot, end, res = (-1, 0, 0)
for i, j in sorted(clips):
if end >= T or i > end:
break
elif pivot < i:
res, pivot = (res + 1, ... | the_stack_v2_python_sparse | Leetcode/1024.py | hanwgyu/algorithm_problem_solving | train | 5 | |
adc62f0d938247a8ed867dc196b7b8ece20f0e01 | [
"if not root:\n return True\n\ndef dfs(left: TreeNode, right: TreeNode) -> bool:\n if not left and (not right):\n return True\n elif not left or not right:\n return False\n elif left.val != right.val:\n return False\n return dfs(left.left, right.right) and dfs(left.right, right.l... | <|body_start_0|>
if not root:
return True
def dfs(left: TreeNode, right: TreeNode) -> bool:
if not left and (not right):
return True
elif not left or not right:
return False
elif left.val != right.val:
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
"""DFS"""
<|body_0|>
def isSymmetricBFS(self, root: TreeNode) -> bool:
"""BFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
def dfs(left: TreeNo... | stack_v2_sparse_classes_36k_train_009470 | 2,301 | no_license | [
{
"docstring": "DFS",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root: TreeNode) -> bool"
},
{
"docstring": "BFS",
"name": "isSymmetricBFS",
"signature": "def isSymmetricBFS(self, root: TreeNode) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_005636 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root: TreeNode) -> bool: DFS
- def isSymmetricBFS(self, root: TreeNode) -> bool: BFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root: TreeNode) -> bool: DFS
- def isSymmetricBFS(self, root: TreeNode) -> bool: BFS
<|skeleton|>
class Solution:
def isSymmetric(self, root: TreeNode... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
"""DFS"""
<|body_0|>
def isSymmetricBFS(self, root: TreeNode) -> bool:
"""BFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
"""DFS"""
if not root:
return True
def dfs(left: TreeNode, right: TreeNode) -> bool:
if not left and (not right):
return True
elif not left or not right:
return... | the_stack_v2_python_sparse | 101.对称二叉树/solution.py | QtTao/daily_leetcode | train | 0 | |
a5406448bd238cff202007f677dbf2c3bf59b04b | [
"super(ClusterPool, self).__init__(host_list)\nself.command_context = zmq.Context()\nself.command_socket = self.command_context.socket(zmq.PUB)\nself.command_socket.connect(command_url)",
"if chunksize == None:\n chunksize = self.chunksize\nif cache_functions == None:\n cache_functions = self.cache_function... | <|body_start_0|>
super(ClusterPool, self).__init__(host_list)
self.command_context = zmq.Context()
self.command_socket = self.command_context.socket(zmq.PUB)
self.command_socket.connect(command_url)
<|end_body_0|>
<|body_start_1|>
if chunksize == None:
chunksize = se... | Client for the Gearman task farm. | ClusterPool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterPool:
"""Client for the Gearman task farm."""
def __init__(self, host_list=None, command_url=None):
"""Create a new cluster pool. :param host_list: Gearman job server URLs. :type host_list: list of str :param str command_url: ZMQ channel for command messages."""
<|body... | stack_v2_sparse_classes_36k_train_009471 | 13,162 | permissive | [
{
"docstring": "Create a new cluster pool. :param host_list: Gearman job server URLs. :type host_list: list of str :param str command_url: ZMQ channel for command messages.",
"name": "__init__",
"signature": "def __init__(self, host_list=None, command_url=None)"
},
{
"docstring": "Apply a functi... | 4 | stack_v2_sparse_classes_30k_train_014660 | Implement the Python class `ClusterPool` described below.
Class description:
Client for the Gearman task farm.
Method signatures and docstrings:
- def __init__(self, host_list=None, command_url=None): Create a new cluster pool. :param host_list: Gearman job server URLs. :type host_list: list of str :param str command... | Implement the Python class `ClusterPool` described below.
Class description:
Client for the Gearman task farm.
Method signatures and docstrings:
- def __init__(self, host_list=None, command_url=None): Create a new cluster pool. :param host_list: Gearman job server URLs. :type host_list: list of str :param str command... | 6931b146245afbadd4f77bd16f7a892dddff38cb | <|skeleton|>
class ClusterPool:
"""Client for the Gearman task farm."""
def __init__(self, host_list=None, command_url=None):
"""Create a new cluster pool. :param host_list: Gearman job server URLs. :type host_list: list of str :param str command_url: ZMQ channel for command messages."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterPool:
"""Client for the Gearman task farm."""
def __init__(self, host_list=None, command_url=None):
"""Create a new cluster pool. :param host_list: Gearman job server URLs. :type host_list: list of str :param str command_url: ZMQ channel for command messages."""
super(ClusterPool, ... | the_stack_v2_python_sparse | glimpse/pools/gearman_cluster/pool.py | NhanHo/glimpse-project | train | 0 |
9136e52db0499c4f3428ae1e9d321fb345afccdf | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | SSHServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHServiceServicer:
def SSHUploadPack(self, request_iterator, context):
"""To forward 'git upload-pack' to Gitaly for SSH sessions"""
<|body_0|>
def SSHReceivePack(self, request_iterator, context):
"""To forward 'git receive-pack' to Gitaly for SSH sessions"""
... | stack_v2_sparse_classes_36k_train_009472 | 3,094 | permissive | [
{
"docstring": "To forward 'git upload-pack' to Gitaly for SSH sessions",
"name": "SSHUploadPack",
"signature": "def SSHUploadPack(self, request_iterator, context)"
},
{
"docstring": "To forward 'git receive-pack' to Gitaly for SSH sessions",
"name": "SSHReceivePack",
"signature": "def S... | 3 | stack_v2_sparse_classes_30k_train_017462 | Implement the Python class `SSHServiceServicer` described below.
Class description:
Implement the SSHServiceServicer class.
Method signatures and docstrings:
- def SSHUploadPack(self, request_iterator, context): To forward 'git upload-pack' to Gitaly for SSH sessions
- def SSHReceivePack(self, request_iterator, conte... | Implement the Python class `SSHServiceServicer` described below.
Class description:
Implement the SSHServiceServicer class.
Method signatures and docstrings:
- def SSHUploadPack(self, request_iterator, context): To forward 'git upload-pack' to Gitaly for SSH sessions
- def SSHReceivePack(self, request_iterator, conte... | 1d2400593fa7fa261b15c1c7f3494daf009586f8 | <|skeleton|>
class SSHServiceServicer:
def SSHUploadPack(self, request_iterator, context):
"""To forward 'git upload-pack' to Gitaly for SSH sessions"""
<|body_0|>
def SSHReceivePack(self, request_iterator, context):
"""To forward 'git receive-pack' to Gitaly for SSH sessions"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSHServiceServicer:
def SSHUploadPack(self, request_iterator, context):
"""To forward 'git upload-pack' to Gitaly for SSH sessions"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented... | the_stack_v2_python_sparse | glartifacts/gitaly/proto/ssh_pb2_grpc.py | TimothySprague/glartifacts | train | 0 | |
5a9daab4114da3539b8233b71115e085b5a9a4fe | [
"ignored = request.GET.get('ignored', False)\nsort = request.GET.get('sort')\nsort_fields = ['created_date', 'invite__times_used', 'invite__invitees__created_date', 'answer']\nif not sort in sort_fields + ['-{:s}'.format(f) for f in sort_fields]:\n sort = '-created_date'\nrequests = models.InviteRequest.objects.... | <|body_start_0|>
ignored = request.GET.get('ignored', False)
sort = request.GET.get('sort')
sort_fields = ['created_date', 'invite__times_used', 'invite__invitees__created_date', 'answer']
if not sort in sort_fields + ['-{:s}'.format(f) for f in sort_fields]:
sort = '-created... | grant invites like the benevolent lord you are | ManageInviteRequests | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageInviteRequests:
"""grant invites like the benevolent lord you are"""
def get(self, request):
"""view a list of requests"""
<|body_0|>
def post(self, request):
"""send out an invite"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ignored = ... | stack_v2_sparse_classes_36k_train_009473 | 6,414 | no_license | [
{
"docstring": "view a list of requests",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "send out an invite",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012946 | Implement the Python class `ManageInviteRequests` described below.
Class description:
grant invites like the benevolent lord you are
Method signatures and docstrings:
- def get(self, request): view a list of requests
- def post(self, request): send out an invite | Implement the Python class `ManageInviteRequests` described below.
Class description:
grant invites like the benevolent lord you are
Method signatures and docstrings:
- def get(self, request): view a list of requests
- def post(self, request): send out an invite
<|skeleton|>
class ManageInviteRequests:
"""grant ... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class ManageInviteRequests:
"""grant invites like the benevolent lord you are"""
def get(self, request):
"""view a list of requests"""
<|body_0|>
def post(self, request):
"""send out an invite"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageInviteRequests:
"""grant invites like the benevolent lord you are"""
def get(self, request):
"""view a list of requests"""
ignored = request.GET.get('ignored', False)
sort = request.GET.get('sort')
sort_fields = ['created_date', 'invite__times_used', 'invite__invitee... | the_stack_v2_python_sparse | bookwyrm/views/admin/invite.py | bookwyrm-social/bookwyrm | train | 1,398 |
ef912dc56fbf72ceb34a1e695b7cb3bef1540c80 | [
"job = self.job_manager.get_job(train_id)\nif job is None:\n raise TrainJobNotExistError(train_id)\nif drop_empty:\n samples = self._query_samples(job, labels, sorted_name, sorted_type, prediction_types, drop_type=ExplanationKeys.HOC.value)\nelse:\n samples = self._query_samples(job, labels, sorted_name, s... | <|body_start_0|>
job = self.job_manager.get_job(train_id)
if job is None:
raise TrainJobNotExistError(train_id)
if drop_empty:
samples = self._query_samples(job, labels, sorted_name, sorted_type, prediction_types, drop_type=ExplanationKeys.HOC.value)
else:
... | Hierarchical occlusion encapsulator. | HierarchicalOcclusionEncap | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HierarchicalOcclusionEncap:
"""Hierarchical occlusion encapsulator."""
def query_hierarchical_occlusion(self, train_id, labels, limit, offset, sorted_name, sorted_type, prediction_types=None, drop_empty=True):
"""Query hierarchical occlusion results. Args: train_id (str): Job ID. lab... | stack_v2_sparse_classes_36k_train_009474 | 4,389 | permissive | [
{
"docstring": "Query hierarchical occlusion results. Args: train_id (str): Job ID. labels (list[str]): Label filter. limit (int): Maximum number of items to be returned. offset (int): Page offset. sorted_name (str): Field to be sorted. sorted_type (str): Sorting order, 'ascending' or 'descending'. prediction_t... | 2 | stack_v2_sparse_classes_30k_train_000667 | Implement the Python class `HierarchicalOcclusionEncap` described below.
Class description:
Hierarchical occlusion encapsulator.
Method signatures and docstrings:
- def query_hierarchical_occlusion(self, train_id, labels, limit, offset, sorted_name, sorted_type, prediction_types=None, drop_empty=True): Query hierarch... | Implement the Python class `HierarchicalOcclusionEncap` described below.
Class description:
Hierarchical occlusion encapsulator.
Method signatures and docstrings:
- def query_hierarchical_occlusion(self, train_id, labels, limit, offset, sorted_name, sorted_type, prediction_types=None, drop_empty=True): Query hierarch... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class HierarchicalOcclusionEncap:
"""Hierarchical occlusion encapsulator."""
def query_hierarchical_occlusion(self, train_id, labels, limit, offset, sorted_name, sorted_type, prediction_types=None, drop_empty=True):
"""Query hierarchical occlusion results. Args: train_id (str): Job ID. lab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HierarchicalOcclusionEncap:
"""Hierarchical occlusion encapsulator."""
def query_hierarchical_occlusion(self, train_id, labels, limit, offset, sorted_name, sorted_type, prediction_types=None, drop_empty=True):
"""Query hierarchical occlusion results. Args: train_id (str): Job ID. labels (list[str... | the_stack_v2_python_sparse | mindinsight/explainer/encapsulator/hierarchical_occlusion_encap.py | mindspore-ai/mindinsight | train | 224 |
d43992334faec2940927570c73e5551c48922cb5 | [
"chemin = getcwd() + os.sep.join(('primaires', 'autoquetes', 'types', nom, 'editeur.yml'))\nif not os.path.exists(chemin):\n return None\nif not os.path.isfile(chemin):\n raise os.error(chemin + \" n'est pas un fichier\")\nif not os.access(chemin, os.R_OK):\n raise os.error(chemin + ' ne peut être lu')\nwi... | <|body_start_0|>
chemin = getcwd() + os.sep.join(('primaires', 'autoquetes', 'types', nom, 'editeur.yml'))
if not os.path.exists(chemin):
return None
if not os.path.isfile(chemin):
raise os.error(chemin + " n'est pas un fichier")
if not os.access(chemin, os.R_OK):... | Cette classe contient des méthodes pour valider les éditeurs autoquête. Les méthodes définies dans cette classes sont des méthodes abstraites : cette classe n'est qu'une enveloppe contenant plusieurs fonctionnalités. Voici les différentes méthodes à utiliser dans l'ordre : get_config -- retourne la configuration de l'é... | ValidateurEditeur | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidateurEditeur:
"""Cette classe contient des méthodes pour valider les éditeurs autoquête. Les méthodes définies dans cette classes sont des méthodes abstraites : cette classe n'est qu'une enveloppe contenant plusieurs fonctionnalités. Voici les différentes méthodes à utiliser dans l'ordre : g... | stack_v2_sparse_classes_36k_train_009475 | 7,132 | permissive | [
{
"docstring": "Retourne, si peut être chargée, la configuration YAML de l'éditeur. On doit préciser en paramètre : nom -- le nom du répertoire dans laquel récupérer l'information Est retourné : None si le fichier ne peut être trouvée Une liste de dictionnaires permettant d'étendre la configuration Si une erreu... | 3 | null | Implement the Python class `ValidateurEditeur` described below.
Class description:
Cette classe contient des méthodes pour valider les éditeurs autoquête. Les méthodes définies dans cette classes sont des méthodes abstraites : cette classe n'est qu'une enveloppe contenant plusieurs fonctionnalités. Voici les différent... | Implement the Python class `ValidateurEditeur` described below.
Class description:
Cette classe contient des méthodes pour valider les éditeurs autoquête. Les méthodes définies dans cette classes sont des méthodes abstraites : cette classe n'est qu'une enveloppe contenant plusieurs fonctionnalités. Voici les différent... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class ValidateurEditeur:
"""Cette classe contient des méthodes pour valider les éditeurs autoquête. Les méthodes définies dans cette classes sont des méthodes abstraites : cette classe n'est qu'une enveloppe contenant plusieurs fonctionnalités. Voici les différentes méthodes à utiliser dans l'ordre : g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidateurEditeur:
"""Cette classe contient des méthodes pour valider les éditeurs autoquête. Les méthodes définies dans cette classes sont des méthodes abstraites : cette classe n'est qu'une enveloppe contenant plusieurs fonctionnalités. Voici les différentes méthodes à utiliser dans l'ordre : get_config -- ... | the_stack_v2_python_sparse | src/primaires/autoquetes/v_editeur.py | vincent-lg/tsunami | train | 5 |
ad2fd511e1073b47f541f1a9c2ada5414f3f3ff9 | [
"self._gv = gv\nself._dlg = ElevatioBandsDialog()\nself._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)\nself._dlg.move(self._gv.elevationBandsPos)\nself._dlg.okButton.clicked.connect(self.setBands)\nself._dlg.cancelButton.clicked.connect(self._dlg.close)\nself._dlg.elevBandsThreshold... | <|body_start_0|>
self._gv = gv
self._dlg = ElevatioBandsDialog()
self._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self._dlg.move(self._gv.elevationBandsPos)
self._dlg.okButton.clicked.connect(self.setBands)
self._dlg.cancelButton.clicked... | Form and functions for defining elevation bands. | ElevationBands | [
"MIT",
"GPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElevationBands:
"""Form and functions for defining elevation bands."""
def __init__(self, gv):
"""Initialise class variables."""
<|body_0|>
def run(self):
"""Run the form."""
<|body_1|>
def setBands(self):
"""Save bands definition."""
... | stack_v2_sparse_classes_36k_train_009476 | 2,977 | permissive | [
{
"docstring": "Initialise class variables.",
"name": "__init__",
"signature": "def __init__(self, gv)"
},
{
"docstring": "Run the form.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Save bands definition.",
"name": "setBands",
"signature": "def setBand... | 3 | stack_v2_sparse_classes_30k_train_005857 | Implement the Python class `ElevationBands` described below.
Class description:
Form and functions for defining elevation bands.
Method signatures and docstrings:
- def __init__(self, gv): Initialise class variables.
- def run(self): Run the form.
- def setBands(self): Save bands definition. | Implement the Python class `ElevationBands` described below.
Class description:
Form and functions for defining elevation bands.
Method signatures and docstrings:
- def __init__(self, gv): Initialise class variables.
- def run(self): Run the form.
- def setBands(self): Save bands definition.
<|skeleton|>
class Eleva... | ddb3de70708687ca3167ec4b72ac432426175f45 | <|skeleton|>
class ElevationBands:
"""Form and functions for defining elevation bands."""
def __init__(self, gv):
"""Initialise class variables."""
<|body_0|>
def run(self):
"""Run the form."""
<|body_1|>
def setBands(self):
"""Save bands definition."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElevationBands:
"""Form and functions for defining elevation bands."""
def __init__(self, gv):
"""Initialise class variables."""
self._gv = gv
self._dlg = ElevatioBandsDialog()
self._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self... | the_stack_v2_python_sparse | qswatplus/elevationbands.py | celray/swatplus-automatic-workflow | train | 11 |
9f66a29b51c9a3ff4895581fd03cdeb5e6075cf4 | [
"result = []\nsynsets = wn.synsets(word)\nfor synset in synsets:\n hypernyms = synset.hypernyms()\n for hyp in hypernyms:\n result.append(hyp.lemmas()[0].name())\nreturn set(result)",
"results = []\nfor word in words:\n hypernyms = self.get_hypernyms_for_single_word(word)\n for hypernym in hype... | <|body_start_0|>
result = []
synsets = wn.synsets(word)
for synset in synsets:
hypernyms = synset.hypernyms()
for hyp in hypernyms:
result.append(hyp.lemmas()[0].name())
return set(result)
<|end_body_0|>
<|body_start_1|>
results = []
... | Generate labels for the topic models with wordnet. | ExtrensicTopicLabeler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtrensicTopicLabeler:
"""Generate labels for the topic models with wordnet."""
def get_hypernyms_for_single_word(self, word):
"""Get all the hypernyms for the synsets of a given word of a certain topic :param word: a word from a topic :type string :return: set of hypernyms for the g... | stack_v2_sparse_classes_36k_train_009477 | 3,555 | no_license | [
{
"docstring": "Get all the hypernyms for the synsets of a given word of a certain topic :param word: a word from a topic :type string :return: set of hypernyms for the given word",
"name": "get_hypernyms_for_single_word",
"signature": "def get_hypernyms_for_single_word(self, word)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_020131 | Implement the Python class `ExtrensicTopicLabeler` described below.
Class description:
Generate labels for the topic models with wordnet.
Method signatures and docstrings:
- def get_hypernyms_for_single_word(self, word): Get all the hypernyms for the synsets of a given word of a certain topic :param word: a word from... | Implement the Python class `ExtrensicTopicLabeler` described below.
Class description:
Generate labels for the topic models with wordnet.
Method signatures and docstrings:
- def get_hypernyms_for_single_word(self, word): Get all the hypernyms for the synsets of a given word of a certain topic :param word: a word from... | 34cdff618595bdb495d0cd7b23e543e089ea0c41 | <|skeleton|>
class ExtrensicTopicLabeler:
"""Generate labels for the topic models with wordnet."""
def get_hypernyms_for_single_word(self, word):
"""Get all the hypernyms for the synsets of a given word of a certain topic :param word: a word from a topic :type string :return: set of hypernyms for the g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtrensicTopicLabeler:
"""Generate labels for the topic models with wordnet."""
def get_hypernyms_for_single_word(self, word):
"""Get all the hypernyms for the synsets of a given word of a certain topic :param word: a word from a topic :type string :return: set of hypernyms for the given word"""
... | the_stack_v2_python_sparse | src/Automati_Topic_Labeling_Wordnet/extrinsic_topic_labler.py | ga65duy/Topic-Modeling | train | 0 |
0ba27183e05221117b702e01069a9691ddb96e7f | [
"from jina.logging.predefined import default_logger\n_meta_config = get_default_metas()\n_meta_config.update(data.get('metas', {}))\nif _meta_config:\n data['metas'] = _meta_config\ncls._init_from_yaml = True\nif dataclasses.is_dataclass(cls):\n obj = cls(**data.get('with', {}))\n cls.__bases__[0].__init__... | <|body_start_0|>
from jina.logging.predefined import default_logger
_meta_config = get_default_metas()
_meta_config.update(data.get('metas', {}))
if _meta_config:
data['metas'] = _meta_config
cls._init_from_yaml = True
if dataclasses.is_dataclass(cls):
... | Legacy parser for executor. | ExecutorLegacyParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutorLegacyParser:
"""Legacy parser for executor."""
def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor':
""":param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml... | stack_v2_sparse_classes_36k_train_009478 | 4,515 | permissive | [
{
"docstring": ":param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml file loaded as python dict :param runtime_args: Optional runtime_args to be directly passed without being parsed into a yaml config :return: the Flow YAML parser given the syntax version nu... | 3 | stack_v2_sparse_classes_30k_train_014670 | Implement the Python class `ExecutorLegacyParser` described below.
Class description:
Legacy parser for executor.
Method signatures and docstrings:
- def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': :param cls: target class type to parse into, must... | Implement the Python class `ExecutorLegacyParser` described below.
Class description:
Legacy parser for executor.
Method signatures and docstrings:
- def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': :param cls: target class type to parse into, must... | 23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71 | <|skeleton|>
class ExecutorLegacyParser:
"""Legacy parser for executor."""
def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor':
""":param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecutorLegacyParser:
"""Legacy parser for executor."""
def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor':
""":param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml file loaded ... | the_stack_v2_python_sparse | jina/jaml/parsers/executor/legacy.py | jina-ai/jina | train | 20,687 |
913d1824de14a6c850658c3c2dcc90b6b5609580 | [
"templateLoader = jinja2.FileSystemLoader(searchpath=basePath)\ntemplateEnv = jinja2.Environment(loader=templateLoader)\nself.templateCode = templateEnv.get_template('kernel.cu')\nself.init(numSamples, numTest, numFeatures, k)",
"self.NUM_SAMPLES = numSamples\nself.NUM_TEST = numTest\nself.NUM_FEATURES = numFeatu... | <|body_start_0|>
templateLoader = jinja2.FileSystemLoader(searchpath=basePath)
templateEnv = jinja2.Environment(loader=templateLoader)
self.templateCode = templateEnv.get_template('kernel.cu')
self.init(numSamples, numTest, numFeatures, k)
<|end_body_0|>
<|body_start_1|>
self.NU... | Leave-one-out scorer using K nearest neighbour algorithm as the target function for the characteristic selection problem. Implemented upon PyCUDA. | knnLooGPU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class knnLooGPU:
"""Leave-one-out scorer using K nearest neighbour algorithm as the target function for the characteristic selection problem. Implemented upon PyCUDA."""
def __init__(self, numSamples, numTest, numFeatures, k):
"""Constructor of the class. Arguments: numSamples: Number of t... | stack_v2_sparse_classes_36k_train_009479 | 8,936 | no_license | [
{
"docstring": "Constructor of the class. Arguments: numSamples: Number of the training samples in the input data. numTest: Number of the test samples in the input data. numFeatures: Number of features of each sample. k: Number of neighbours used to label the test sample. Returns the scorer with the environment... | 4 | stack_v2_sparse_classes_30k_train_018711 | Implement the Python class `knnLooGPU` described below.
Class description:
Leave-one-out scorer using K nearest neighbour algorithm as the target function for the characteristic selection problem. Implemented upon PyCUDA.
Method signatures and docstrings:
- def __init__(self, numSamples, numTest, numFeatures, k): Con... | Implement the Python class `knnLooGPU` described below.
Class description:
Leave-one-out scorer using K nearest neighbour algorithm as the target function for the characteristic selection problem. Implemented upon PyCUDA.
Method signatures and docstrings:
- def __init__(self, numSamples, numTest, numFeatures, k): Con... | 6612f5623c73cc28ab7178776085569e7c9a36e8 | <|skeleton|>
class knnLooGPU:
"""Leave-one-out scorer using K nearest neighbour algorithm as the target function for the characteristic selection problem. Implemented upon PyCUDA."""
def __init__(self, numSamples, numTest, numFeatures, k):
"""Constructor of the class. Arguments: numSamples: Number of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class knnLooGPU:
"""Leave-one-out scorer using K nearest neighbour algorithm as the target function for the characteristic selection problem. Implemented upon PyCUDA."""
def __init__(self, numSamples, numTest, numFeatures, k):
"""Constructor of the class. Arguments: numSamples: Number of the training s... | the_stack_v2_python_sparse | P3/software/BIN/knnLooGPU.py | grivasgervilla/MH | train | 0 |
6ce2c8b3dd53c70b165b3ed55338590705cd88a9 | [
"articles = queryset\nfor article in articles:\n article.like_count = LikeActivity.get_like_count(article)\n article.dislike_count = LikeActivity.get_dislike_count(article)\n article.save()",
"articles = queryset\nfor article in articles:\n article.viewed_count = ViewHistory.total_viewed_count(article... | <|body_start_0|>
articles = queryset
for article in articles:
article.like_count = LikeActivity.get_like_count(article)
article.dislike_count = LikeActivity.get_dislike_count(article)
article.save()
<|end_body_0|>
<|body_start_1|>
articles = queryset
... | 한마음 어드민 설정 클래스입니다. | HanmaumAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HanmaumAdmin:
"""한마음 어드민 설정 클래스입니다."""
def reset_like_and_dislike_counter(modeladmin, request, queryset):
"""좋아요/싫어요 캐시 카운터를 쿼리를 날려 다시 설정한다."""
<|body_0|>
def reset_viewed_counter(modeladmin, request, queryset):
"""조회수 캐시 카운터를 쿼리를 날려 다시 설정한다."""
<|body_1|... | stack_v2_sparse_classes_36k_train_009480 | 1,598 | no_license | [
{
"docstring": "좋아요/싫어요 캐시 카운터를 쿼리를 날려 다시 설정한다.",
"name": "reset_like_and_dislike_counter",
"signature": "def reset_like_and_dislike_counter(modeladmin, request, queryset)"
},
{
"docstring": "조회수 캐시 카운터를 쿼리를 날려 다시 설정한다.",
"name": "reset_viewed_counter",
"signature": "def reset_viewed_cou... | 2 | stack_v2_sparse_classes_30k_train_012526 | Implement the Python class `HanmaumAdmin` described below.
Class description:
한마음 어드민 설정 클래스입니다.
Method signatures and docstrings:
- def reset_like_and_dislike_counter(modeladmin, request, queryset): 좋아요/싫어요 캐시 카운터를 쿼리를 날려 다시 설정한다.
- def reset_viewed_counter(modeladmin, request, queryset): 조회수 캐시 카운터를 쿼리를 날려 다시 설정한다. | Implement the Python class `HanmaumAdmin` described below.
Class description:
한마음 어드민 설정 클래스입니다.
Method signatures and docstrings:
- def reset_like_and_dislike_counter(modeladmin, request, queryset): 좋아요/싫어요 캐시 카운터를 쿼리를 날려 다시 설정한다.
- def reset_viewed_counter(modeladmin, request, queryset): 조회수 캐시 카운터를 쿼리를 날려 다시 설정한다.... | 283aea2b971df31d0e4e06f82bf47f001e86a517 | <|skeleton|>
class HanmaumAdmin:
"""한마음 어드민 설정 클래스입니다."""
def reset_like_and_dislike_counter(modeladmin, request, queryset):
"""좋아요/싫어요 캐시 카운터를 쿼리를 날려 다시 설정한다."""
<|body_0|>
def reset_viewed_counter(modeladmin, request, queryset):
"""조회수 캐시 카운터를 쿼리를 날려 다시 설정한다."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HanmaumAdmin:
"""한마음 어드민 설정 클래스입니다."""
def reset_like_and_dislike_counter(modeladmin, request, queryset):
"""좋아요/싫어요 캐시 카운터를 쿼리를 날려 다시 설정한다."""
articles = queryset
for article in articles:
article.like_count = LikeActivity.get_like_count(article)
article.di... | the_stack_v2_python_sparse | hanmaum/admin.py | hanalum-dev/hanalum_web | train | 0 |
f856fb31f5d243083d6fc979d428b252247af40f | [
"old = len(nums)\ni = 0\ntemp = 0\nwhile i < len(nums) and i + temp != len(nums) - 1:\n if nums[i] == 0:\n nums.remove(0)\n nums.append(0)\n temp += 1\n i -= 1\n i += 1",
"pos = 0\nfor i in range(len(nums)):\n if nums[i] != 0:\n nums[pos], nums[i] = (nums[i], nums[pos])... | <|body_start_0|>
old = len(nums)
i = 0
temp = 0
while i < len(nums) and i + temp != len(nums) - 1:
if nums[i] == 0:
nums.remove(0)
nums.append(0)
temp += 1
i -= 1
i += 1
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_009481 | 815 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes1",
"signature": "def moveZeroes1(self,... | 2 | stack_v2_sparse_classes_30k_train_009665 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes1(self, nums: List[int]) -> None: Do not return anything, mod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes1(self, nums: List[int]) -> None: Do not return anything, mod... | 57b01f9917c51e36c66724904d70479743320279 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
old = len(nums)
i = 0
temp = 0
while i < len(nums) and i + temp != len(nums) - 1:
if nums[i] == 0:
nums.remove(0)
... | the_stack_v2_python_sparse | python/leetcode/algorithms/easy/283-移动零.py | fare-xzy/LeetCode | train | 0 | |
4d4bb353640feb56a1e2dc1b2ebc7102e9519e62 | [
"self.memo = {}\nfor i, item in enumerate(arr):\n if item not in self.memo:\n self.memo[item] = []\n self.memo[item].append(i)",
"for k in self.memo.keys():\n if len(self.memo[k]) < threshold:\n continue\n idx1 = bisect.bisect_left(self.memo[k], left)\n idx2 = bisect.bisect_left(self.... | <|body_start_0|>
self.memo = {}
for i, item in enumerate(arr):
if item not in self.memo:
self.memo[item] = []
self.memo[item].append(i)
<|end_body_0|>
<|body_start_1|>
for k in self.memo.keys():
if len(self.memo[k]) < threshold:
... | MajorityChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.memo =... | stack_v2_sparse_classes_36k_train_009482 | 2,215 | no_license | [
{
"docstring": ":type arr: List[int]",
"name": "__init__",
"signature": "def __init__(self, arr)"
},
{
"docstring": ":type left: int :type right: int :type threshold: int :rtype: int",
"name": "query",
"signature": "def query(self, left, right, threshold)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000696 | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int
<|skelet... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
self.memo = {}
for i, item in enumerate(arr):
if item not in self.memo:
self.memo[item] = []
self.memo[item].append(i)
def query(self, left, right, threshold):
""":... | the_stack_v2_python_sparse | python/leetcode/binary_search/1157_online_majority.py | Levintsky/topcoder | train | 0 | |
db0d47e29f3a501aa6b13b6391449864f236ad7f | [
"with open(filename, newline='') as csvfile:\n dict_list = []\n csv_data = csv.reader(csvfile)\n headers = next(csv_data, None)\n if headers[0].startswith(''):\n headers[0] = headers[0][3:]\n for row in csv_data:\n row_dict = {column: row[index] for index, column in enumerate(headers... | <|body_start_0|>
with open(filename, newline='') as csvfile:
dict_list = []
csv_data = csv.reader(csvfile)
headers = next(csv_data, None)
if headers[0].startswith(''):
headers[0] = headers[0][3:]
for row in csv_data:
... | Class to manage the MongoDB. | Database | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
"""Class to manage the MongoDB."""
def _import_csv(self, filename):
"""Returns a list of dictionaries. One dictionary for each row of data in a csv file. :param filename: csv file :return: list of dictionaries"""
<|body_0|>
def _add_bulk_data(self, collection, ... | stack_v2_sparse_classes_36k_train_009483 | 7,588 | no_license | [
{
"docstring": "Returns a list of dictionaries. One dictionary for each row of data in a csv file. :param filename: csv file :return: list of dictionaries",
"name": "_import_csv",
"signature": "def _import_csv(self, filename)"
},
{
"docstring": "Adds bulk data to the database. :param collection:... | 6 | stack_v2_sparse_classes_30k_train_012046 | Implement the Python class `Database` described below.
Class description:
Class to manage the MongoDB.
Method signatures and docstrings:
- def _import_csv(self, filename): Returns a list of dictionaries. One dictionary for each row of data in a csv file. :param filename: csv file :return: list of dictionaries
- def _... | Implement the Python class `Database` described below.
Class description:
Class to manage the MongoDB.
Method signatures and docstrings:
- def _import_csv(self, filename): Returns a list of dictionaries. One dictionary for each row of data in a csv file. :param filename: csv file :return: list of dictionaries
- def _... | 7b5dab79ab34f708d10ab04385203157855bbde5 | <|skeleton|>
class Database:
"""Class to manage the MongoDB."""
def _import_csv(self, filename):
"""Returns a list of dictionaries. One dictionary for each row of data in a csv file. :param filename: csv file :return: list of dictionaries"""
<|body_0|>
def _add_bulk_data(self, collection, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Database:
"""Class to manage the MongoDB."""
def _import_csv(self, filename):
"""Returns a list of dictionaries. One dictionary for each row of data in a csv file. :param filename: csv file :return: list of dictionaries"""
with open(filename, newline='') as csvfile:
dict_list ... | the_stack_v2_python_sparse | students/DiannaTingg/lessons/lesson10/assignment/database.py | dtingg/PythonCert220Assign | train | 1 |
6d13259a8be7c420455a8b33c9160cbfd1f7c376 | [
"super(Stack, self).__init__(filename=filename)\nif input_voxel_size is not None and stack_size is not None and (cell_params is not None):\n self.generate(cell_params, input_voxel_size, stack_size)",
"stack_size_pix = np.int_(np.round_(np.array(stack_size) / np.array(input_voxel_size)))\nif 'size' not in cell_... | <|body_start_0|>
super(Stack, self).__init__(filename=filename)
if input_voxel_size is not None and stack_size is not None and (cell_params is not None):
self.generate(cell_params, input_voxel_size, stack_size)
<|end_body_0|>
<|body_start_1|>
stack_size_pix = np.int_(np.round_(np.ar... | Class for a 3D multicellular stack. | Stack | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stack:
"""Class for a 3D multicellular stack."""
def __init__(self, filename=None, input_voxel_size=None, stack_size=None, cell_params=None):
"""Initializes the Stack class. Parameters ---------- filename: str, optional Path used to load the cell image. If None or non-existent, no im... | stack_v2_sparse_classes_36k_train_009484 | 5,089 | permissive | [
{
"docstring": "Initializes the Stack class. Parameters ---------- filename: str, optional Path used to load the cell image. If None or non-existent, no image will be loaded. Default is None. input_voxel_size : scalar or sequence of scalars, optional Voxel size used to generate the stack. If None, no stack will... | 3 | stack_v2_sparse_classes_30k_train_005709 | Implement the Python class `Stack` described below.
Class description:
Class for a 3D multicellular stack.
Method signatures and docstrings:
- def __init__(self, filename=None, input_voxel_size=None, stack_size=None, cell_params=None): Initializes the Stack class. Parameters ---------- filename: str, optional Path us... | Implement the Python class `Stack` described below.
Class description:
Class for a 3D multicellular stack.
Method signatures and docstrings:
- def __init__(self, filename=None, input_voxel_size=None, stack_size=None, cell_params=None): Initializes the Stack class. Parameters ---------- filename: str, optional Path us... | 3b83758a8956e93879734292e27ea1259c9e54fe | <|skeleton|>
class Stack:
"""Class for a 3D multicellular stack."""
def __init__(self, filename=None, input_voxel_size=None, stack_size=None, cell_params=None):
"""Initializes the Stack class. Parameters ---------- filename: str, optional Path used to load the cell image. If None or non-existent, no im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stack:
"""Class for a 3D multicellular stack."""
def __init__(self, filename=None, input_voxel_size=None, stack_size=None, cell_params=None):
"""Initializes the Stack class. Parameters ---------- filename: str, optional Path used to load the cell image. If None or non-existent, no image will be l... | the_stack_v2_python_sparse | DeconvTest/classes/stack.py | applied-systems-biology/DeconvTest | train | 6 |
9589a47bd34b78dc096b895378410a6fe6eaf639 | [
"if not str(uuid).isdigit() or int(uuid) <= 0:\n api.logger.error(f'[{datetime.now()}], movies, put, \"id\": {uuid}, Error: \"Wrong movie ID')\n return ({'Error': 'Wrong movie ID'}, 404)\nuuid = int(uuid)\nmovie = Movie.query.filter_by(id=uuid).first()\nif not movie:\n api.logger.error(f'[{datetime.now()}]... | <|body_start_0|>
if not str(uuid).isdigit() or int(uuid) <= 0:
api.logger.error(f'[{datetime.now()}], movies, put, "id": {uuid}, Error: "Wrong movie ID')
return ({'Error': 'Wrong movie ID'}, 404)
uuid = int(uuid)
movie = Movie.query.filter_by(id=uuid).first()
if n... | Movie Api | MovieApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieApi:
"""Movie Api"""
def get(self, uuid=None):
"""Output a single movie"""
<|body_0|>
def put(self, uuid: int):
"""Changing a movie"""
<|body_1|>
def delete(uuid: int):
"""Delete a movie"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_009485 | 12,285 | no_license | [
{
"docstring": "Output a single movie",
"name": "get",
"signature": "def get(self, uuid=None)"
},
{
"docstring": "Changing a movie",
"name": "put",
"signature": "def put(self, uuid: int)"
},
{
"docstring": "Delete a movie",
"name": "delete",
"signature": "def delete(uuid:... | 3 | stack_v2_sparse_classes_30k_val_001109 | Implement the Python class `MovieApi` described below.
Class description:
Movie Api
Method signatures and docstrings:
- def get(self, uuid=None): Output a single movie
- def put(self, uuid: int): Changing a movie
- def delete(uuid: int): Delete a movie | Implement the Python class `MovieApi` described below.
Class description:
Movie Api
Method signatures and docstrings:
- def get(self, uuid=None): Output a single movie
- def put(self, uuid: int): Changing a movie
- def delete(uuid: int): Delete a movie
<|skeleton|>
class MovieApi:
"""Movie Api"""
def get(se... | b3a021bff8112a3eb81f553b3eb0df751a488adb | <|skeleton|>
class MovieApi:
"""Movie Api"""
def get(self, uuid=None):
"""Output a single movie"""
<|body_0|>
def put(self, uuid: int):
"""Changing a movie"""
<|body_1|>
def delete(uuid: int):
"""Delete a movie"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovieApi:
"""Movie Api"""
def get(self, uuid=None):
"""Output a single movie"""
if not str(uuid).isdigit() or int(uuid) <= 0:
api.logger.error(f'[{datetime.now()}], movies, put, "id": {uuid}, Error: "Wrong movie ID')
return ({'Error': 'Wrong movie ID'}, 404)
... | the_stack_v2_python_sparse | app/resources/movies.py | cyr1z/api-movie-library- | train | 1 |
fe04f8f27abd7d992079e7cdd9e976070ed1cbbd | [
"if not output.writable():\n raise ValueError('output must be writable')\nself._output = output\nself._line_style = '{}\\t{}\\n'",
"positions = ','.join([str(i) for i in positions])\nline = self._line_style.format(query_name, positions)\nself._output.write(line)"
] | <|body_start_0|>
if not output.writable():
raise ValueError('output must be writable')
self._output = output
self._line_style = '{}\t{}\n'
<|end_body_0|>
<|body_start_1|>
positions = ','.join([str(i) for i in positions])
line = self._line_style.format(query_name, pos... | A SequencingErrorWriter is an object that writes observations of sequencing errors to an output source. | SequencingErrorWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequencingErrorWriter:
"""A SequencingErrorWriter is an object that writes observations of sequencing errors to an output source."""
def __init__(self, output):
"""Create a SequencingErrorWriter. :param output: the output sink to write to :raises ValueError: if output is not writable... | stack_v2_sparse_classes_36k_train_009486 | 922 | no_license | [
{
"docstring": "Create a SequencingErrorWriter. :param output: the output sink to write to :raises ValueError: if output is not writable",
"name": "__init__",
"signature": "def __init__(self, output)"
},
{
"docstring": "Write an oberved set of sequencing errors. :param query_name: the query name... | 2 | stack_v2_sparse_classes_30k_train_002840 | Implement the Python class `SequencingErrorWriter` described below.
Class description:
A SequencingErrorWriter is an object that writes observations of sequencing errors to an output source.
Method signatures and docstrings:
- def __init__(self, output): Create a SequencingErrorWriter. :param output: the output sink ... | Implement the Python class `SequencingErrorWriter` described below.
Class description:
A SequencingErrorWriter is an object that writes observations of sequencing errors to an output source.
Method signatures and docstrings:
- def __init__(self, output): Create a SequencingErrorWriter. :param output: the output sink ... | ff058a636dce69a6b42e1b7534c5a9bea840330d | <|skeleton|>
class SequencingErrorWriter:
"""A SequencingErrorWriter is an object that writes observations of sequencing errors to an output source."""
def __init__(self, output):
"""Create a SequencingErrorWriter. :param output: the output sink to write to :raises ValueError: if output is not writable... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequencingErrorWriter:
"""A SequencingErrorWriter is an object that writes observations of sequencing errors to an output source."""
def __init__(self, output):
"""Create a SequencingErrorWriter. :param output: the output sink to write to :raises ValueError: if output is not writable"""
i... | the_stack_v2_python_sparse | seqerrdemo/writer.py | bklein345/seqerrdemo | train | 0 |
cccf8ceae7e98109063c9c23aeb34957a83957d3 | [
"assert type_of_offer in ('sale', 'rent'), \"Type of offer must be 'sale' or 'rent'\"\nassert type_of_prop in ('houses', 'apartments'), \"Type of prop must be 'houses' or 'apartments'\"\nself.level = level\nself.state = state\nself.label = state\nif self.level > 0:\n self.label = url.split('/')[-2] if url[-1] ==... | <|body_start_0|>
assert type_of_offer in ('sale', 'rent'), "Type of offer must be 'sale' or 'rent'"
assert type_of_prop in ('houses', 'apartments'), "Type of prop must be 'houses' or 'apartments'"
self.level = level
self.state = state
self.label = state
if self.level > 0:... | Class to define a real estate market, defined by estate, purchase or rent, houses or apartments, the url of the market and the level of recursion. | Market | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Market:
"""Class to define a real estate market, defined by estate, purchase or rent, houses or apartments, the url of the market and the level of recursion."""
def __init__(self, state, type_of_offer, type_of_prop, url=None, level=0):
"""Recursive initializer of the Market class. In... | stack_v2_sparse_classes_36k_train_009487 | 19,853 | no_license | [
{
"docstring": "Recursive initializer of the Market class. Inputs: state: (State of Mexico) str type_of_offer: ('sale' or 'rent') str type_of_prop: ('houses' or 'apartments') str url: str level: int",
"name": "__init__",
"signature": "def __init__(self, state, type_of_offer, type_of_prop, url=None, leve... | 5 | stack_v2_sparse_classes_30k_train_019171 | Implement the Python class `Market` described below.
Class description:
Class to define a real estate market, defined by estate, purchase or rent, houses or apartments, the url of the market and the level of recursion.
Method signatures and docstrings:
- def __init__(self, state, type_of_offer, type_of_prop, url=None... | Implement the Python class `Market` described below.
Class description:
Class to define a real estate market, defined by estate, purchase or rent, houses or apartments, the url of the market and the level of recursion.
Method signatures and docstrings:
- def __init__(self, state, type_of_offer, type_of_prop, url=None... | 89f2e134bd65ee36b5c1b6d3ce5613b92c6f5e6b | <|skeleton|>
class Market:
"""Class to define a real estate market, defined by estate, purchase or rent, houses or apartments, the url of the market and the level of recursion."""
def __init__(self, state, type_of_offer, type_of_prop, url=None, level=0):
"""Recursive initializer of the Market class. In... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Market:
"""Class to define a real estate market, defined by estate, purchase or rent, houses or apartments, the url of the market and the level of recursion."""
def __init__(self, state, type_of_offer, type_of_prop, url=None, level=0):
"""Recursive initializer of the Market class. Inputs: state: ... | the_stack_v2_python_sparse | Scraping/Scripts/crawler.py | andrebestrada/Machine-Learning-Final-Project | train | 3 |
d3ebb64f680106e837368ddaa9a670149ac51eac | [
"super(MultiHeadAttention, self).__init__()\nself.n_head = n_head\nself.d_model = d_model\nself.d_k = d_k\nself.d_v = d_v\nself.linear_q = nn.Linear(d_model, n_head * d_k)\nself.linear_k = nn.Linear(d_model, n_head * d_k)\nself.linear_v = nn.Linear(d_model, n_head * d_v)\nself.linear_o = nn.Linear(n_head * d_v, d_m... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.linear_q = nn.Linear(d_model, n_head * d_k)
self.linear_k = nn.Linear(d_model, n_head * d_k)
self.linear_v = nn.Linea... | Multi-head Attention | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Multi-head Attention"""
def __init__(self, n_head, d_model, d_k, d_v, drop_rate=0.1):
"""paper setting: n_head = 8, d_k = d_v = d_model / n_head = 64 Multi-head attention allows the model to jointly attend to information from different representation subspaces ... | stack_v2_sparse_classes_36k_train_009488 | 5,289 | no_license | [
{
"docstring": "paper setting: n_head = 8, d_k = d_v = d_model / n_head = 64 Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. with a single attention head, averaging inhibits this.",
"name": "__init__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_000566 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi-head Attention
Method signatures and docstrings:
- def __init__(self, n_head, d_model, d_k, d_v, drop_rate=0.1): paper setting: n_head = 8, d_k = d_v = d_model / n_head = 64 Multi-head attention allows the model to jointly atten... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi-head Attention
Method signatures and docstrings:
- def __init__(self, n_head, d_model, d_k, d_v, drop_rate=0.1): paper setting: n_head = 8, d_k = d_v = d_model / n_head = 64 Multi-head attention allows the model to jointly atten... | 9c1e4988e5aba3d2b971074590ce49e50c3aa823 | <|skeleton|>
class MultiHeadAttention:
"""Multi-head Attention"""
def __init__(self, n_head, d_model, d_k, d_v, drop_rate=0.1):
"""paper setting: n_head = 8, d_k = d_v = d_model / n_head = 64 Multi-head attention allows the model to jointly attend to information from different representation subspaces ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""Multi-head Attention"""
def __init__(self, n_head, d_model, d_k, d_v, drop_rate=0.1):
"""paper setting: n_head = 8, d_k = d_v = d_model / n_head = 64 Multi-head attention allows the model to jointly attend to information from different representation subspaces at different ... | the_stack_v2_python_sparse | transformer/sublayers.py | simonjisu/annotated-transformer-kr | train | 17 |
74eb72cc3b5e0a4bc8eee418f7dd15a5a6a03dc6 | [
"for i in range(len(nums)):\n least = target - nums[i]\n if least in nums:\n if nums.index(least) != i:\n return [i, nums.index(least)]",
"if not nums:\n return\nh = {}\nfor i, n in enumerate(nums):\n h[n] = i\nfor i, n in enumerate(nums):\n if target - n in h.keys() and i != h[ta... | <|body_start_0|>
for i in range(len(nums)):
least = target - nums[i]
if least in nums:
if nums.index(least) != i:
return [i, nums.index(least)]
<|end_body_0|>
<|body_start_1|>
if not nums:
return
h = {}
for i, n in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int] 寻找数组中和为target的两个数 先求差,在到数组里找这个差值"""
<|body_0|>
def twoSumTwoHash(self, nums, target):
"""两趟遍历的hash需要处理可能是同一个"""
<|body_1|>
def twoSumOneHash(self, nums... | stack_v2_sparse_classes_36k_train_009489 | 1,310 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int] 寻找数组中和为target的两个数 先求差,在到数组里找这个差值",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": "两趟遍历的hash需要处理可能是同一个",
"name": "twoSumTwoHash",
"signature": "def twoSumTwoHash(self, nums, targe... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] 寻找数组中和为target的两个数 先求差,在到数组里找这个差值
- def twoSumTwoHash(self, nums, target): 两趟遍历的hash需要处理可... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] 寻找数组中和为target的两个数 先求差,在到数组里找这个差值
- def twoSumTwoHash(self, nums, target): 两趟遍历的hash需要处理可... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int] 寻找数组中和为target的两个数 先求差,在到数组里找这个差值"""
<|body_0|>
def twoSumTwoHash(self, nums, target):
"""两趟遍历的hash需要处理可能是同一个"""
<|body_1|>
def twoSumOneHash(self, nums... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int] 寻找数组中和为target的两个数 先求差,在到数组里找这个差值"""
for i in range(len(nums)):
least = target - nums[i]
if least in nums:
if nums.index(least) != i:
... | the_stack_v2_python_sparse | ArrayOperation/SumOfTwoNumbers.py | Philex5/codingPractice | train | 0 | |
86b4d576315d9603c2b98d08eb40655ff2e2695b | [
"if self.default != '':\n if self.value == '':\n self.value = self.default\nelif self.value == '' and self.required:\n raise ValidationError('Required.')\nif self.value != '' and self.type == self.TYPE_FLOAT:\n try:\n float(self.value)\n except Exception:\n raise ValidationError('Va... | <|body_start_0|>
if self.default != '':
if self.value == '':
self.value = self.default
elif self.value == '' and self.required:
raise ValidationError('Required.')
if self.value != '' and self.type == self.TYPE_FLOAT:
try:
float(... | Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.TYPE_UUID description(str): Short descrip... | CustomSetting | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSetting:
"""Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.... | stack_v2_sparse_classes_36k_train_009490 | 45,827 | permissive | [
{
"docstring": "Validate prior to saving changes.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Get the value, automatically casting it to the correct type.",
"name": "get_value",
"signature": "def get_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000551 | Implement the Python class `CustomSetting` described below.
Class description:
Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, Cus... | Implement the Python class `CustomSetting` described below.
Class description:
Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, Cus... | e9365fa55ec25d7658a75ca7fb0632013374d876 | <|skeleton|>
class CustomSetting:
"""Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomSetting:
"""Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.TYPE_UUID des... | the_stack_v2_python_sparse | tethys_apps/models.py | tethysplatform/tethys | train | 95 |
a5696522f2bf0c42bcbbd1057e5fa82693b0e2f2 | [
"self.capture_tail_logs = capture_tail_logs\nself.is_auto_sync_enabled = is_auto_sync_enabled\nself.keep_cdc = keep_cdc\nself.keep_offline = keep_offline\nself.new_database_name = new_database_name\nself.new_instance_name = new_instance_name\nself.overwrite_policy = overwrite_policy\nself.restore_time_secs = restor... | <|body_start_0|>
self.capture_tail_logs = capture_tail_logs
self.is_auto_sync_enabled = is_auto_sync_enabled
self.keep_cdc = keep_cdc
self.keep_offline = keep_offline
self.new_database_name = new_database_name
self.new_instance_name = new_instance_name
self.overwr... | Implementation of the 'SqlRestoreParameters' model. Specifies the parameters specific the Application Server instance. Attributes: capture_tail_logs (bool): Set this to true if tail logs are to be captured before the restore operation. This is only applicable if we are restoring the SQL database to its hosting Protecti... | SqlRestoreParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqlRestoreParameters:
"""Implementation of the 'SqlRestoreParameters' model. Specifies the parameters specific the Application Server instance. Attributes: capture_tail_logs (bool): Set this to true if tail logs are to be captured before the restore operation. This is only applicable if we are re... | stack_v2_sparse_classes_36k_train_009491 | 7,588 | permissive | [
{
"docstring": "Constructor for the SqlRestoreParameters class",
"name": "__init__",
"signature": "def __init__(self, capture_tail_logs=None, is_auto_sync_enabled=None, keep_cdc=None, keep_offline=None, new_database_name=None, new_instance_name=None, overwrite_policy=None, restore_time_secs=None, target... | 2 | null | Implement the Python class `SqlRestoreParameters` described below.
Class description:
Implementation of the 'SqlRestoreParameters' model. Specifies the parameters specific the Application Server instance. Attributes: capture_tail_logs (bool): Set this to true if tail logs are to be captured before the restore operatio... | Implement the Python class `SqlRestoreParameters` described below.
Class description:
Implementation of the 'SqlRestoreParameters' model. Specifies the parameters specific the Application Server instance. Attributes: capture_tail_logs (bool): Set this to true if tail logs are to be captured before the restore operatio... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SqlRestoreParameters:
"""Implementation of the 'SqlRestoreParameters' model. Specifies the parameters specific the Application Server instance. Attributes: capture_tail_logs (bool): Set this to true if tail logs are to be captured before the restore operation. This is only applicable if we are re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqlRestoreParameters:
"""Implementation of the 'SqlRestoreParameters' model. Specifies the parameters specific the Application Server instance. Attributes: capture_tail_logs (bool): Set this to true if tail logs are to be captured before the restore operation. This is only applicable if we are restoring the S... | the_stack_v2_python_sparse | cohesity_management_sdk/models/sql_restore_parameters.py | cohesity/management-sdk-python | train | 24 |
213cbe25c6108db4fc6e01cadcf0cbc389d70e9a | [
"urls = ['https://www.roshpit.ca/items']\nfor url in urls:\n yield scrapy.Request(url=url, callback=self.parse_item_type)",
"for item_type_row in response.css('.item-filter-buttons>a.button-link:not([href*=\"arcana\"])'):\n item_type = ItemType()\n item_type['id'] = item_type_row.css('div::attr(data-slot... | <|body_start_0|>
urls = ['https://www.roshpit.ca/items']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse_item_type)
<|end_body_0|>
<|body_start_1|>
for item_type_row in response.css('.item-filter-buttons>a.button-link:not([href*="arcana"])'):
item_type... | CollectItemInfoSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectItemInfoSpider:
def start_requests(self) -> None:
"""開始爬取 Returns: None"""
<|body_0|>
def parse_item_type(self, response) -> None:
"""爬取的道具類型資料 Args: response: 取得的頁面資料 Returns: None"""
<|body_1|>
def parse_item(self, response):
"""爬取的道具資料 ... | stack_v2_sparse_classes_36k_train_009492 | 4,107 | no_license | [
{
"docstring": "開始爬取 Returns: None",
"name": "start_requests",
"signature": "def start_requests(self) -> None"
},
{
"docstring": "爬取的道具類型資料 Args: response: 取得的頁面資料 Returns: None",
"name": "parse_item_type",
"signature": "def parse_item_type(self, response) -> None"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_train_013218 | Implement the Python class `CollectItemInfoSpider` described below.
Class description:
Implement the CollectItemInfoSpider class.
Method signatures and docstrings:
- def start_requests(self) -> None: 開始爬取 Returns: None
- def parse_item_type(self, response) -> None: 爬取的道具類型資料 Args: response: 取得的頁面資料 Returns: None
- de... | Implement the Python class `CollectItemInfoSpider` described below.
Class description:
Implement the CollectItemInfoSpider class.
Method signatures and docstrings:
- def start_requests(self) -> None: 開始爬取 Returns: None
- def parse_item_type(self, response) -> None: 爬取的道具類型資料 Args: response: 取得的頁面資料 Returns: None
- de... | 412c2b310549ba2ae45a413331627acdcf512b52 | <|skeleton|>
class CollectItemInfoSpider:
def start_requests(self) -> None:
"""開始爬取 Returns: None"""
<|body_0|>
def parse_item_type(self, response) -> None:
"""爬取的道具類型資料 Args: response: 取得的頁面資料 Returns: None"""
<|body_1|>
def parse_item(self, response):
"""爬取的道具資料 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollectItemInfoSpider:
def start_requests(self) -> None:
"""開始爬取 Returns: None"""
urls = ['https://www.roshpit.ca/items']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse_item_type)
def parse_item_type(self, response) -> None:
"""爬取的道具類型資料 Arg... | the_stack_v2_python_sparse | RoshpitCrawler/RoshpitCrawler/spiders/collect_item_info_spider.py | edensquall/RoshpitCrawler | train | 0 | |
b959dfe9dea97c8279d3c0009a31b330ef8f8522 | [
"self._brains = collections.OrderedDict()\nself._size = size\nself._hparam_defaults_populator_and_validator = hparam_defaults_populator_and_validator",
"hparams = self._hparam_defaults_populator_and_validator(hparams)\nkey = str(brain_spec) + str(hparams)\nbrain = self._brains.get(key)\nif brain:\n falken_logg... | <|body_start_0|>
self._brains = collections.OrderedDict()
self._size = size
self._hparam_defaults_populator_and_validator = hparam_defaults_populator_and_validator
<|end_body_0|>
<|body_start_1|>
hparams = self._hparam_defaults_populator_and_validator(hparams)
key = str(brain_sp... | Least Recently Used (LRU) cache of brain instances. | BrainCache | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrainCache:
"""Least Recently Used (LRU) cache of brain instances."""
def __init__(self, hparam_defaults_populator_and_validator, size=8):
"""Initialize the cache. Args: hparam_defaults_populator_and_validator: Callable that takes a dictionary of hyperparameters, validates them, popu... | stack_v2_sparse_classes_36k_train_009493 | 3,449 | permissive | [
{
"docstring": "Initialize the cache. Args: hparam_defaults_populator_and_validator: Callable that takes a dictionary of hyperparameters, validates them, populates the dictionary with defaults and returns the validated dictionary. size: Number of brains to cache.",
"name": "__init__",
"signature": "def ... | 2 | null | Implement the Python class `BrainCache` described below.
Class description:
Least Recently Used (LRU) cache of brain instances.
Method signatures and docstrings:
- def __init__(self, hparam_defaults_populator_and_validator, size=8): Initialize the cache. Args: hparam_defaults_populator_and_validator: Callable that ta... | Implement the Python class `BrainCache` described below.
Class description:
Least Recently Used (LRU) cache of brain instances.
Method signatures and docstrings:
- def __init__(self, hparam_defaults_populator_and_validator, size=8): Initialize the cache. Args: hparam_defaults_populator_and_validator: Callable that ta... | 26ab377a6853463b2efce40970e54d44b91e79ca | <|skeleton|>
class BrainCache:
"""Least Recently Used (LRU) cache of brain instances."""
def __init__(self, hparam_defaults_populator_and_validator, size=8):
"""Initialize the cache. Args: hparam_defaults_populator_and_validator: Callable that takes a dictionary of hyperparameters, validates them, popu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrainCache:
"""Least Recently Used (LRU) cache of brain instances."""
def __init__(self, hparam_defaults_populator_and_validator, size=8):
"""Initialize the cache. Args: hparam_defaults_populator_and_validator: Callable that takes a dictionary of hyperparameters, validates them, populates the dic... | the_stack_v2_python_sparse | service/learner/brains/brain_cache.py | stewartmiles/falken | train | 1 |
7b4b8e8025355b855f03c2de2be7896ca8821e69 | [
"self.marketsymbol = '%5EGSPC'\nself.dataframe = web.DataReader(self.marketsymbol, 'yahoo', starttime, endtime)\nself.close_price = self.dataframe['Adj Close']",
"market_firstday = self.close_price[0]\nself.dataframe['market_%chg'] = (self.close_price - market_firstday) / market_firstday\nchange_price_percent = s... | <|body_start_0|>
self.marketsymbol = '%5EGSPC'
self.dataframe = web.DataReader(self.marketsymbol, 'yahoo', starttime, endtime)
self.close_price = self.dataframe['Adj Close']
<|end_body_0|>
<|body_start_1|>
market_firstday = self.close_price[0]
self.dataframe['market_%chg'] = (se... | Generate a class that can describe the market, providing the percent change of close price for the comparison with stock. | Market | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Market:
"""Generate a class that can describe the market, providing the percent change of close price for the comparison with stock."""
def __init__(self, starttime, endtime):
"""Constructor: We use the input of start date and end date to obtain the market data from yahoo finance. In... | stack_v2_sparse_classes_36k_train_009494 | 1,768 | no_license | [
{
"docstring": "Constructor: We use the input of start date and end date to obtain the market data from yahoo finance. In this case, the dates are all valid. Because we only use market class in the stock class functions. stock.starttime and stock.endtime has been checked. Input: starttime(datetime): the start t... | 2 | null | Implement the Python class `Market` described below.
Class description:
Generate a class that can describe the market, providing the percent change of close price for the comparison with stock.
Method signatures and docstrings:
- def __init__(self, starttime, endtime): Constructor: We use the input of start date and ... | Implement the Python class `Market` described below.
Class description:
Generate a class that can describe the market, providing the percent change of close price for the comparison with stock.
Method signatures and docstrings:
- def __init__(self, starttime, endtime): Constructor: We use the input of start date and ... | 7764590d3a25a28abd8115228aef8a187cc4ffe4 | <|skeleton|>
class Market:
"""Generate a class that can describe the market, providing the percent change of close price for the comparison with stock."""
def __init__(self, starttime, endtime):
"""Constructor: We use the input of start date and end date to obtain the market data from yahoo finance. In... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Market:
"""Generate a class that can describe the market, providing the percent change of close price for the comparison with stock."""
def __init__(self, starttime, endtime):
"""Constructor: We use the input of start date and end date to obtain the market data from yahoo finance. In this case, t... | the_stack_v2_python_sparse | yl2612/StocksPackage/MarketClass.py | xz1082/final_project | train | 0 |
a680d344ef39130720925c990a7aa6481069cb78 | [
"super().__init__()\nself.inner_blocks = []\nself.layer_blocks = []\nfor idx, in_channels in enumerate(feature_channels):\n inner_block = 'fpn_inner{}'.format(idx + 2)\n layer_block = 'fpn_layer{}'.format(idx + 2)\n if in_channels == 0:\n continue\n inner_block_module = conv_uniform(in_channels, ... | <|body_start_0|>
super().__init__()
self.inner_blocks = []
self.layer_blocks = []
for idx, in_channels in enumerate(feature_channels):
inner_block = 'fpn_inner{}'.format(idx + 2)
layer_block = 'fpn_layer{}'.format(idx + 2)
if in_channels == 0:
... | Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive | RetinaNetFPN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetinaNetFPN:
"""Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive"""
def __init__(self, feature_channels, out_channels=256):
"""Arguments: in_channels_list (list[int]): number of ch... | stack_v2_sparse_classes_36k_train_009495 | 17,582 | no_license | [
{
"docstring": "Arguments: in_channels_list (list[int]): number of channels for each feature map that will be fed out_channels (int): number of channels of the FPN representation top_blocks (nn.Module or None): if provided, an extra operation will be performed on the output of the last (smallest resolution) FPN... | 2 | null | Implement the Python class `RetinaNetFPN` described below.
Class description:
Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive
Method signatures and docstrings:
- def __init__(self, feature_channels, out_channels=25... | Implement the Python class `RetinaNetFPN` described below.
Class description:
Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive
Method signatures and docstrings:
- def __init__(self, feature_channels, out_channels=25... | 2f3c4ffd82677b10e1a859ef7c1638d08d658131 | <|skeleton|>
class RetinaNetFPN:
"""Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive"""
def __init__(self, feature_channels, out_channels=256):
"""Arguments: in_channels_list (list[int]): number of ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetinaNetFPN:
"""Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive"""
def __init__(self, feature_channels, out_channels=256):
"""Arguments: in_channels_list (list[int]): number of channels for ea... | the_stack_v2_python_sparse | models/fpns.py | pustar/myDetection | train | 0 |
efc23a48c3ad9eef9f925c3d0af1777f04c22908 | [
"max_count = 0\nfor i in range(len(heights)):\n for j in range(i + 1, len(heights) + 1):\n area = min(heights[i:j]) * (j - i)\n max_count = max(area, max_count)\nreturn max_count",
"max_count = 0\nfor i, v in enumerate(heights):\n length = 1\n for j in range(i - 1, -1, -1):\n if heig... | <|body_start_0|>
max_count = 0
for i in range(len(heights)):
for j in range(i + 1, len(heights) + 1):
area = min(heights[i:j]) * (j - i)
max_count = max(area, max_count)
return max_count
<|end_body_0|>
<|body_start_1|>
max_count = 0
fo... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def _____largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
def __largestRectangleArea(self, heights):
... | stack_v2_sparse_classes_36k_train_009496 | 4,319 | permissive | [
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "_largestRectangleArea",
"signature": "def _largestRectangleArea(self, heights)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "_____largestRectangleArea",
"signature": "def _____largestRectangleArea(self,... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def _____largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def __larges... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def _____largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def __larges... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def _____largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
def __largestRectangleArea(self, heights):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
max_count = 0
for i in range(len(heights)):
for j in range(i + 1, len(heights) + 1):
area = min(heights[i:j]) * (j - i)
max_count = max(area, max_c... | the_stack_v2_python_sparse | 84.largest-rectangle-in-histogram.py | windard/leeeeee | train | 0 | |
8cf3a70ee87241c6df31c06ad7deaff45f313f02 | [
"t = [x.split(',') for x in transactions]\nt.sort(key=lambda x: (x[0], int(x[1])))\ni = 0\nret = set()\nwhile i < len(t):\n j = i + 1\n duplicate = False\n while j < len(t) and t[j][0] == t[i][0] and (int(t[j][1]) - int(t[i][1]) <= 60):\n if t[j][3] != t[i][3]:\n duplicate = True\n ... | <|body_start_0|>
t = [x.split(',') for x in transactions]
t.sort(key=lambda x: (x[0], int(x[1])))
i = 0
ret = set()
while i < len(t):
j = i + 1
duplicate = False
while j < len(t) and t[j][0] == t[i][0] and (int(t[j][1]) - int(t[i][1]) <= 60):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_0|>
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_009497 | 3,895 | no_license | [
{
"docstring": ":type transactions: List[str] :rtype: List[str]",
"name": "invalidTransactions",
"signature": "def invalidTransactions(self, transactions)"
},
{
"docstring": ":type transactions: List[str] :rtype: List[str]",
"name": "invalidTransactions",
"signature": "def invalidTransac... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: List[str]
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: List[str]
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: ... | 988b427b95181ca5a6da081b9ca790fbb4f8c252 | <|skeleton|>
class Solution:
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_0|>
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
t = [x.split(',') for x in transactions]
t.sort(key=lambda x: (x[0], int(x[1])))
i = 0
ret = set()
while i < len(t):
j = i + 1
du... | the_stack_v2_python_sparse | problem1169.py | meetgadoya/leetcode-sol | train | 1 | |
41344d7104ad075dfa03a776858b7a8fd8c0c07f | [
"self.width = img_width\nself.height = img_height\nself.IMAGES_DIR = IMAGES_DIR",
"if base_canvas is None:\n canvas = np.ones((self.height, self.width, 3)) * 255\nelse:\n canvas = base_canvas\nbounding_box = world.get_bounding_box()\nobstacles = [self._get_polygon_opencv_coords(obs, bounding_box) for obs in... | <|body_start_0|>
self.width = img_width
self.height = img_height
self.IMAGES_DIR = IMAGES_DIR
<|end_body_0|>
<|body_start_1|>
if base_canvas is None:
canvas = np.ones((self.height, self.width, 3)) * 255
else:
canvas = base_canvas
bounding_box = wo... | VisuWorld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisuWorld:
def __init__(self, img_width, img_height, IMAGES_DIR):
"""Initialize visualization Args: img_width: width of OpenCV canvas (pixels) img_height: height of OpenCV canvas (pixels)"""
<|body_0|>
def draw(self, world, robot_pose, filename, base_canvas=None):
""... | stack_v2_sparse_classes_36k_train_009498 | 4,283 | no_license | [
{
"docstring": "Initialize visualization Args: img_width: width of OpenCV canvas (pixels) img_height: height of OpenCV canvas (pixels)",
"name": "__init__",
"signature": "def __init__(self, img_width, img_height, IMAGES_DIR)"
},
{
"docstring": "Draws the world with the robot at robot_pose and sa... | 5 | stack_v2_sparse_classes_30k_train_003050 | Implement the Python class `VisuWorld` described below.
Class description:
Implement the VisuWorld class.
Method signatures and docstrings:
- def __init__(self, img_width, img_height, IMAGES_DIR): Initialize visualization Args: img_width: width of OpenCV canvas (pixels) img_height: height of OpenCV canvas (pixels)
- ... | Implement the Python class `VisuWorld` described below.
Class description:
Implement the VisuWorld class.
Method signatures and docstrings:
- def __init__(self, img_width, img_height, IMAGES_DIR): Initialize visualization Args: img_width: width of OpenCV canvas (pixels) img_height: height of OpenCV canvas (pixels)
- ... | 4f2f48130ec3ae0af1b15d6d2df7da3cb339178d | <|skeleton|>
class VisuWorld:
def __init__(self, img_width, img_height, IMAGES_DIR):
"""Initialize visualization Args: img_width: width of OpenCV canvas (pixels) img_height: height of OpenCV canvas (pixels)"""
<|body_0|>
def draw(self, world, robot_pose, filename, base_canvas=None):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisuWorld:
def __init__(self, img_width, img_height, IMAGES_DIR):
"""Initialize visualization Args: img_width: width of OpenCV canvas (pixels) img_height: height of OpenCV canvas (pixels)"""
self.width = img_width
self.height = img_height
self.IMAGES_DIR = IMAGES_DIR
def d... | the_stack_v2_python_sparse | python_code/projetS7_lib/visu_world.py | TariqBerrada/Robot-Navigation | train | 0 | |
888f8d30eafb54a3a3b15c30e988ee44c2ead35b | [
"self.inline_class = config.get('inline_class', '')\nself.latex2svg = latex2svg\nInlineProcessor.__init__(self, pattern, md)",
"escapes = m.group(1)\nif not escapes:\n escapes = m.group(4)\nif escapes:\n return (escapes.replace('\\\\\\\\', self.ESCAPED_BSLASH), m.start(0), m.end(0))\nlatex = m.group(3)\nif ... | <|body_start_0|>
self.inline_class = config.get('inline_class', '')
self.latex2svg = latex2svg
InlineProcessor.__init__(self, pattern, md)
<|end_body_0|>
<|body_start_1|>
escapes = m.group(1)
if not escapes:
escapes = m.group(4)
if escapes:
return... | MathSvg inline pattern handler. | InlineMathSvgPattern | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InlineMathSvgPattern:
"""MathSvg inline pattern handler."""
def __init__(self, pattern, config, latex2svg, md):
"""Initialize."""
<|body_0|>
def handleMatch(self, m, data):
"""Handle inline content."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009499 | 22,334 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, pattern, config, latex2svg, md)"
},
{
"docstring": "Handle inline content.",
"name": "handleMatch",
"signature": "def handleMatch(self, m, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018982 | Implement the Python class `InlineMathSvgPattern` described below.
Class description:
MathSvg inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config, latex2svg, md): Initialize.
- def handleMatch(self, m, data): Handle inline content. | Implement the Python class `InlineMathSvgPattern` described below.
Class description:
MathSvg inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config, latex2svg, md): Initialize.
- def handleMatch(self, m, data): Handle inline content.
<|skeleton|>
class InlineMathSvgPattern:
... | 45c862669d8d4e72c95f6b278819379a1c1e68d4 | <|skeleton|>
class InlineMathSvgPattern:
"""MathSvg inline pattern handler."""
def __init__(self, pattern, config, latex2svg, md):
"""Initialize."""
<|body_0|>
def handleMatch(self, m, data):
"""Handle inline content."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InlineMathSvgPattern:
"""MathSvg inline pattern handler."""
def __init__(self, pattern, config, latex2svg, md):
"""Initialize."""
self.inline_class = config.get('inline_class', '')
self.latex2svg = latex2svg
InlineProcessor.__init__(self, pattern, md)
def handleMatch(... | the_stack_v2_python_sparse | pylbm_ui/widgets/mdx_math_svg.py | gouarin/pylbm_ui | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.