blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
99994b10ce19355f3621eb6aaf7f4948c9f51257 | [
"try:\n parser.add_argument('--max-complexity', default=10, type=int, help='Max complexity threshold')\nexcept ArgumentError:\n pass",
"params = ctx.get_params('mccabe')\noptions = ctx.options\nif options:\n params.setdefault('max-complexity', options.max_complexity)\nMcCabeChecker.max_complexity = int(p... | <|body_start_0|>
try:
parser.add_argument('--max-complexity', default=10, type=int, help='Max complexity threshold')
except ArgumentError:
pass
<|end_body_0|>
<|body_start_1|>
params = ctx.get_params('mccabe')
options = ctx.options
if options:
... | Run complexity checking. | Linter | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linter:
"""Run complexity checking."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Run Mccabe code checker."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try... | stack_v2_sparse_classes_10k_train_004400 | 1,355 | permissive | [
{
"docstring": "Add --max-complexity option.",
"name": "add_args",
"signature": "def add_args(cls, parser: ArgumentParser)"
},
{
"docstring": "Run Mccabe code checker.",
"name": "run_check",
"signature": "def run_check(self, ctx: RunContext)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000913 | Implement the Python class `Linter` described below.
Class description:
Run complexity checking.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Run Mccabe code checker. | Implement the Python class `Linter` described below.
Class description:
Run complexity checking.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Run Mccabe code checker.
<|skeleton|>
class Linter:
"""Run complexit... | 53ad214de0aa9534e59bcd5f97d9d723d16cfdb8 | <|skeleton|>
class Linter:
"""Run complexity checking."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Run Mccabe code checker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Linter:
"""Run complexity checking."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
try:
parser.add_argument('--max-complexity', default=10, type=int, help='Max complexity threshold')
except ArgumentError:
pass
def run_... | the_stack_v2_python_sparse | pylama/lint/pylama_mccabe.py | klen/pylama | train | 1,022 |
3bd0351821970c475d87327494d672eeaa24358b | [
"if sys.version_info.major >= 3:\n if isinstance(recipients, abc.KeysView):\n recipients = [x for x in recipients]\nif isinstance(recipients, dict):\n recipients = [x for x in recipients]\nif not isinstance(recipients, list):\n recipients = recipients.split(',')\nif not len(recipients):\n raise V... | <|body_start_0|>
if sys.version_info.major >= 3:
if isinstance(recipients, abc.KeysView):
recipients = [x for x in recipients]
if isinstance(recipients, dict):
recipients = [x for x in recipients]
if not isinstance(recipients, list):
recipients... | ToolsOSD | [
"EFL-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
<|b... | stack_v2_sparse_classes_10k_train_004401 | 12,939 | permissive | [
{
"docstring": "Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())",
"name": "get_message_recipientgroups",
"signature": "def get_message_recipientgroups(bot... | 3 | stack_v2_sparse_classes_30k_train_000116 | Implement the Python class `ToolsOSD` described below.
Class description:
Implement the ToolsOSD class.
Method signatures and docstrings:
- def get_message_recipientgroups(bot, recipients, text_method): Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a com... | Implement the Python class `ToolsOSD` described below.
Class description:
Implement the ToolsOSD class.
Method signatures and docstrings:
- def get_message_recipientgroups(bot, recipients, text_method): Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a com... | 816dddc88943b9194f3f0aa6558759eedd585343 | <|skeleton|>
class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
if sys.version_in... | the_stack_v2_python_sparse | sopel_modules/SpiceBot/osd.py | SpiceBot/SpiceBot | train | 1 | |
d3d39ef733a4b03992e0b1fed1edd813ab3e305e | [
"self.cast: Type[T] = cast\nself.delimiter = delimiter\nself.strip = strip\nself.post_process = post_process",
"if isinstance(value, (tuple, list)):\n value = ''.join((str(v) + self.delimiter for v in value))[:-1]\n\ndef transform(s):\n return self.cast(s.strip(self.strip))\nsplitter = shlex(value, posix=Tr... | <|body_start_0|>
self.cast: Type[T] = cast
self.delimiter = delimiter
self.strip = strip
self.post_process = post_process
<|end_body_0|>
<|body_start_1|>
if isinstance(value, (tuple, list)):
value = ''.join((str(v) + self.delimiter for v in value))[:-1]
def ... | Produces a csv parser that return a list of transformed elements. From python-decouple. | Csv | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Csv:
"""Produces a csv parser that return a list of transformed elements. From python-decouple."""
def __init__(self, cast: Type[T]=str, delimiter=',', strip=string.whitespace, post_process=list):
"""Parameters: cast -- callable that transforms the item just before it's added to the ... | stack_v2_sparse_classes_10k_train_004402 | 7,619 | permissive | [
{
"docstring": "Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters chars passed to shlex. strip -- string of non-relevant characters to be passed to str.strip after the split. post_process -- callable to post process all casted values. Def... | 2 | stack_v2_sparse_classes_30k_train_002104 | Implement the Python class `Csv` described below.
Class description:
Produces a csv parser that return a list of transformed elements. From python-decouple.
Method signatures and docstrings:
- def __init__(self, cast: Type[T]=str, delimiter=',', strip=string.whitespace, post_process=list): Parameters: cast -- callabl... | Implement the Python class `Csv` described below.
Class description:
Produces a csv parser that return a list of transformed elements. From python-decouple.
Method signatures and docstrings:
- def __init__(self, cast: Type[T]=str, delimiter=',', strip=string.whitespace, post_process=list): Parameters: cast -- callabl... | ab7ac9ceeaf4ea06dfbbd1280be4430d4ac6d684 | <|skeleton|>
class Csv:
"""Produces a csv parser that return a list of transformed elements. From python-decouple."""
def __init__(self, cast: Type[T]=str, delimiter=',', strip=string.whitespace, post_process=list):
"""Parameters: cast -- callable that transforms the item just before it's added to the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Csv:
"""Produces a csv parser that return a list of transformed elements. From python-decouple."""
def __init__(self, cast: Type[T]=str, delimiter=',', strip=string.whitespace, post_process=list):
"""Parameters: cast -- callable that transforms the item just before it's added to the list. delimit... | the_stack_v2_python_sparse | DeepFilterNet/df/config.py | oucxlw/DeepFilterNet | train | 1 |
d1e5836b5759bfd33b8cf61fe35951e782072722 | [
"if query and query not in force_text(field.field_name).lower():\n return False\nelse:\n return True",
"if self.field_types and field.field_type not in self.field_types:\n return False\nelse:\n return self._query_is_match(field, query)"
] | <|body_start_0|>
if query and query not in force_text(field.field_name).lower():
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
if self.field_types and field.field_type not in self.field_types:
return False
else:
return sel... | Defines autocomplete rules for source on the Container admin page. | FilterFieldsAutocompleteBase | [
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterFieldsAutocompleteBase:
"""Defines autocomplete rules for source on the Container admin page."""
def _query_is_match(field, query):
"""Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string."""
<|b... | stack_v2_sparse_classes_10k_train_004403 | 6,425 | permissive | [
{
"docstring": "Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string.",
"name": "_query_is_match",
"signature": "def _query_is_match(field, query)"
},
{
"docstring": "Takes a DataField and a query string. Returns a Boolea... | 2 | null | Implement the Python class `FilterFieldsAutocompleteBase` described below.
Class description:
Defines autocomplete rules for source on the Container admin page.
Method signatures and docstrings:
- def _query_is_match(field, query): Takes a DataField and a query string. Returns a Boolean indicating whether the DataFie... | Implement the Python class `FilterFieldsAutocompleteBase` described below.
Class description:
Defines autocomplete rules for source on the Container admin page.
Method signatures and docstrings:
- def _query_is_match(field, query): Takes a DataField and a query string. Returns a Boolean indicating whether the DataFie... | a379a134c0c5af14df4ed2afa066c1626506b754 | <|skeleton|>
class FilterFieldsAutocompleteBase:
"""Defines autocomplete rules for source on the Container admin page."""
def _query_is_match(field, query):
"""Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FilterFieldsAutocompleteBase:
"""Defines autocomplete rules for source on the Container admin page."""
def _query_is_match(field, query):
"""Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string."""
if query and que... | the_stack_v2_python_sparse | Incident-Response/Tools/cyphon/cyphon/bottler/tastes/autocomplete_light_registry.py | foss2cyber/Incident-Playbook | train | 1 |
eb7780bb46c5c5f1464dc0958bfb33eb4229828e | [
"try:\n self.fetch_component_api_public_key()\n self.init_settings()\nexcept ProgrammingError as e:\n logger.info(f'init settings failed, err_msg -> {e}.')\nreturn True",
"if any([settings.BKPAAS_MAJOR_VERSION == env_constants.BkPaaSVersion.V3.value, settings.BK_BACKEND_CONFIG]):\n logger.info('[JWT] ... | <|body_start_0|>
try:
self.fetch_component_api_public_key()
self.init_settings()
except ProgrammingError as e:
logger.info(f'init settings failed, err_msg -> {e}.')
return True
<|end_body_0|>
<|body_start_1|>
if any([settings.BKPAAS_MAJOR_VERSION == e... | ApiConfig | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiConfig:
def ready(self):
"""初始化部分配置,主要目的是为了SaaS和后台共用部分配置"""
<|body_0|>
def fetch_component_api_public_key(cls):
"""获取JWT公钥并存储到全局配置中"""
<|body_1|>
def init_settings(cls):
"""初始化配置,读取DB后写入settings内存中,避免多次查表"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_10k_train_004404 | 4,404 | permissive | [
{
"docstring": "初始化部分配置,主要目的是为了SaaS和后台共用部分配置",
"name": "ready",
"signature": "def ready(self)"
},
{
"docstring": "获取JWT公钥并存储到全局配置中",
"name": "fetch_component_api_public_key",
"signature": "def fetch_component_api_public_key(cls)"
},
{
"docstring": "初始化配置,读取DB后写入settings内存中,避免多次查表... | 3 | null | Implement the Python class `ApiConfig` described below.
Class description:
Implement the ApiConfig class.
Method signatures and docstrings:
- def ready(self): 初始化部分配置,主要目的是为了SaaS和后台共用部分配置
- def fetch_component_api_public_key(cls): 获取JWT公钥并存储到全局配置中
- def init_settings(cls): 初始化配置,读取DB后写入settings内存中,避免多次查表 | Implement the Python class `ApiConfig` described below.
Class description:
Implement the ApiConfig class.
Method signatures and docstrings:
- def ready(self): 初始化部分配置,主要目的是为了SaaS和后台共用部分配置
- def fetch_component_api_public_key(cls): 获取JWT公钥并存储到全局配置中
- def init_settings(cls): 初始化配置,读取DB后写入settings内存中,避免多次查表
<|skeleton|... | 72d2104783443bff26c752c5bd934a013b302b6d | <|skeleton|>
class ApiConfig:
def ready(self):
"""初始化部分配置,主要目的是为了SaaS和后台共用部分配置"""
<|body_0|>
def fetch_component_api_public_key(cls):
"""获取JWT公钥并存储到全局配置中"""
<|body_1|>
def init_settings(cls):
"""初始化配置,读取DB后写入settings内存中,避免多次查表"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApiConfig:
def ready(self):
"""初始化部分配置,主要目的是为了SaaS和后台共用部分配置"""
try:
self.fetch_component_api_public_key()
self.init_settings()
except ProgrammingError as e:
logger.info(f'init settings failed, err_msg -> {e}.')
return True
def fetch_comp... | the_stack_v2_python_sparse | apps/node_man/apps.py | TencentBlueKing/bk-nodeman | train | 54 | |
c2c5e005b3c3de4be0b46cac6045f476cfe468f5 | [
"try:\n payload = jwt.decode(data, settings.SECRET_KEY, algorithm=['HS256'])\nexcept jwt.ExpiredSignatureError:\n raise serializers.ValidationError('Verification link has expired')\nexcept jwt.exceptions.PyJWTError:\n raise serializers.ValidationError('Invalidad token')\nif payload['type'] != 'email_confir... | <|body_start_0|>
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithm=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('Verification link has expired')
except jwt.exceptions.PyJWTError:
raise serializers.ValidationError(... | Account verification serializer. | AccountVerificationSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_10k_train_004405 | 7,359 | permissive | [
{
"docstring": "Verify token is valid.",
"name": "validate_token",
"signature": "def validate_token(self, data)"
},
{
"docstring": "Update user's verified status.",
"name": "save",
"signature": "def save(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007045 | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def save(self): Update user's verified status. | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def save(self): Update user's verified status.
<|skeleton|>
class AccountVerificationSerializer:... | 5c37c6876ca13b5794ac44e0342b810426acbc76 | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithm=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.... | the_stack_v2_python_sparse | hisitter/users/serializers/users.py | babysitter-finder/backend | train | 1 |
062aaa0efecafac8e8ea4d32d8801c2602edb756 | [
"if stamp is None or stamp.size == 0:\n return\nstamp_width = stamp.shape[0]\nif len(stamp.shape) == 1:\n stamp_width = int(math.sqrt(stamp.shape[0]))\nif stamp.size != stamp_width * stamp_width:\n raise ValueError('Expected square stamp, but found {stamp.shape}')\nif axes is None:\n fig = plt.figure()\... | <|body_start_0|>
if stamp is None or stamp.size == 0:
return
stamp_width = stamp.shape[0]
if len(stamp.shape) == 1:
stamp_width = int(math.sqrt(stamp.shape[0]))
if stamp.size != stamp_width * stamp_width:
raise ValueError('Expected square stamp, but fo... | ResultsVisualizer | [
"BSD-2-Clause-Views",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultsVisualizer:
def plot_single_stamp(stamp, axes=None):
"""Plot a single stamp image. Parameters ---------- stamp : np.array The numpy array containing the stamp's pixel values. axes : matplotlib.axes.Axes The axes on which to draw the figure."""
<|body_0|>
def plot_stam... | stack_v2_sparse_classes_10k_train_004406 | 5,463 | permissive | [
{
"docstring": "Plot a single stamp image. Parameters ---------- stamp : np.array The numpy array containing the stamp's pixel values. axes : matplotlib.axes.Axes The axes on which to draw the figure.",
"name": "plot_single_stamp",
"signature": "def plot_single_stamp(stamp, axes=None)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_val_000082 | Implement the Python class `ResultsVisualizer` described below.
Class description:
Implement the ResultsVisualizer class.
Method signatures and docstrings:
- def plot_single_stamp(stamp, axes=None): Plot a single stamp image. Parameters ---------- stamp : np.array The numpy array containing the stamp's pixel values. ... | Implement the Python class `ResultsVisualizer` described below.
Class description:
Implement the ResultsVisualizer class.
Method signatures and docstrings:
- def plot_single_stamp(stamp, axes=None): Plot a single stamp image. Parameters ---------- stamp : np.array The numpy array containing the stamp's pixel values. ... | 94cb6d75c139de8fbd03082e3b533e50cccefc0b | <|skeleton|>
class ResultsVisualizer:
def plot_single_stamp(stamp, axes=None):
"""Plot a single stamp image. Parameters ---------- stamp : np.array The numpy array containing the stamp's pixel values. axes : matplotlib.axes.Axes The axes on which to draw the figure."""
<|body_0|>
def plot_stam... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResultsVisualizer:
def plot_single_stamp(stamp, axes=None):
"""Plot a single stamp image. Parameters ---------- stamp : np.array The numpy array containing the stamp's pixel values. axes : matplotlib.axes.Axes The axes on which to draw the figure."""
if stamp is None or stamp.size == 0:
... | the_stack_v2_python_sparse | src/kbmod/analysis/plot_results.py | dirac-institute/kbmod | train | 27 | |
7fe24d2ed1d929c8c3df9105d04df17db423d3ea | [
"self.driver = None\nself.project = None\nself.project_info = None",
"support_browser_type = ['Phantomjs', 'Chrome', 'IE', 'Firefox', 'Chrome_headless']\nif browser_type not in support_browser_type:\n raise UnSupportBrowserTypeError('不支持的浏览器类型{0},目前仅支持{1}'.format(browser_type, support_browser_type))\nif browse... | <|body_start_0|>
self.driver = None
self.project = None
self.project_info = None
<|end_body_0|>
<|body_start_1|>
support_browser_type = ['Phantomjs', 'Chrome', 'IE', 'Firefox', 'Chrome_headless']
if browser_type not in support_browser_type:
raise UnSupportBrowserType... | 定义一个浏览器引擎类,根据browser_type的值去,控制启动不同的浏览器,这里主要是IE,Firefox, Chrome | Browser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Browser:
"""定义一个浏览器引擎类,根据browser_type的值去,控制启动不同的浏览器,这里主要是IE,Firefox, Chrome"""
def __init__(self):
"""初始化,判断浏览器类型是否可支持,设置driver为None"""
<|body_0|>
def lanuch(self, browser_type, url, implicitly_wait=20):
"""打开浏览器和网址,设置全局时延,最大化窗口 :param url: :param implicitly_wait... | stack_v2_sparse_classes_10k_train_004407 | 2,940 | no_license | [
{
"docstring": "初始化,判断浏览器类型是否可支持,设置driver为None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "打开浏览器和网址,设置全局时延,最大化窗口 :param url: :param implicitly_wait: :return:",
"name": "lanuch",
"signature": "def lanuch(self, browser_type, url, implicitly_wait=20)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002276 | Implement the Python class `Browser` described below.
Class description:
定义一个浏览器引擎类,根据browser_type的值去,控制启动不同的浏览器,这里主要是IE,Firefox, Chrome
Method signatures and docstrings:
- def __init__(self): 初始化,判断浏览器类型是否可支持,设置driver为None
- def lanuch(self, browser_type, url, implicitly_wait=20): 打开浏览器和网址,设置全局时延,最大化窗口 :param url: :... | Implement the Python class `Browser` described below.
Class description:
定义一个浏览器引擎类,根据browser_type的值去,控制启动不同的浏览器,这里主要是IE,Firefox, Chrome
Method signatures and docstrings:
- def __init__(self): 初始化,判断浏览器类型是否可支持,设置driver为None
- def lanuch(self, browser_type, url, implicitly_wait=20): 打开浏览器和网址,设置全局时延,最大化窗口 :param url: :... | c0b17c8a409dccfe73b0358a429b71a7e94c5e02 | <|skeleton|>
class Browser:
"""定义一个浏览器引擎类,根据browser_type的值去,控制启动不同的浏览器,这里主要是IE,Firefox, Chrome"""
def __init__(self):
"""初始化,判断浏览器类型是否可支持,设置driver为None"""
<|body_0|>
def lanuch(self, browser_type, url, implicitly_wait=20):
"""打开浏览器和网址,设置全局时延,最大化窗口 :param url: :param implicitly_wait... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Browser:
"""定义一个浏览器引擎类,根据browser_type的值去,控制启动不同的浏览器,这里主要是IE,Firefox, Chrome"""
def __init__(self):
"""初始化,判断浏览器类型是否可支持,设置driver为None"""
self.driver = None
self.project = None
self.project_info = None
def lanuch(self, browser_type, url, implicitly_wait=20):
"""... | the_stack_v2_python_sparse | WebAuto/common/browser.py | lqzk/AutoTest | train | 0 |
9361a03824c0138cb41ec7f82cabc2fc4137cdd2 | [
"if len(list) == 0:\n return None\nroot = TreeNode(list.pop(0))\nq = deque([root])\nwhile len(list) > 0:\n current_node = q.popleft()\n i = list.pop(0)\n if i:\n n = TreeNode(i)\n current_node.left = n\n q.append(n)\n if len(list) > 0:\n i = list.pop(0)\n if i:\n ... | <|body_start_0|>
if len(list) == 0:
return None
root = TreeNode(list.pop(0))
q = deque([root])
while len(list) > 0:
current_node = q.popleft()
i = list.pop(0)
if i:
n = TreeNode(i)
current_node.left = n
... | TestHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHelper:
def listToBinaryTree(self, list):
""":type list: List[int] :rtype: TreeNode"""
<|body_0|>
def binaryTreeToList(self, root):
""":type root: TreeNode :rtype: List"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(list) == 0:
... | stack_v2_sparse_classes_10k_train_004408 | 3,744 | no_license | [
{
"docstring": ":type list: List[int] :rtype: TreeNode",
"name": "listToBinaryTree",
"signature": "def listToBinaryTree(self, list)"
},
{
"docstring": ":type root: TreeNode :rtype: List",
"name": "binaryTreeToList",
"signature": "def binaryTreeToList(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000629 | Implement the Python class `TestHelper` described below.
Class description:
Implement the TestHelper class.
Method signatures and docstrings:
- def listToBinaryTree(self, list): :type list: List[int] :rtype: TreeNode
- def binaryTreeToList(self, root): :type root: TreeNode :rtype: List | Implement the Python class `TestHelper` described below.
Class description:
Implement the TestHelper class.
Method signatures and docstrings:
- def listToBinaryTree(self, list): :type list: List[int] :rtype: TreeNode
- def binaryTreeToList(self, root): :type root: TreeNode :rtype: List
<|skeleton|>
class TestHelper:... | a57282895fb213b68e5d81db301903721a92d80f | <|skeleton|>
class TestHelper:
def listToBinaryTree(self, list):
""":type list: List[int] :rtype: TreeNode"""
<|body_0|>
def binaryTreeToList(self, root):
""":type root: TreeNode :rtype: List"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestHelper:
def listToBinaryTree(self, list):
""":type list: List[int] :rtype: TreeNode"""
if len(list) == 0:
return None
root = TreeNode(list.pop(0))
q = deque([root])
while len(list) > 0:
current_node = q.popleft()
i = list.pop(0)
... | the_stack_v2_python_sparse | Python/helper.py | antonylu/leetcode2 | train | 0 | |
7e2642811b17392adf07f375f495fd57aeb24639 | [
"super().__init__()\nself.name: str = name\nself.params: dict = data",
"if self.params == {}:\n return {self.name: None}\nreturn {self.name: self.params}"
] | <|body_start_0|>
super().__init__()
self.name: str = name
self.params: dict = data
<|end_body_0|>
<|body_start_1|>
if self.params == {}:
return {self.name: None}
return {self.name: self.params}
<|end_body_1|>
| Configuration Dataset class. | Dataset | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Configuration Dataset class."""
def __init__(self, name: str, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataset class."""
<|body_0|>
def serialize(self, serialization_type: str='default') -> Dict[str, Any]:
"""Serialize Dataset cla... | stack_v2_sparse_classes_10k_train_004409 | 4,560 | permissive | [
{
"docstring": "Initialize Configuration Dataset class.",
"name": "__init__",
"signature": "def __init__(self, name: str, data: Dict[str, Any]={}) -> None"
},
{
"docstring": "Serialize Dataset class.",
"name": "serialize",
"signature": "def serialize(self, serialization_type: str='defaul... | 2 | stack_v2_sparse_classes_30k_train_007081 | Implement the Python class `Dataset` described below.
Class description:
Configuration Dataset class.
Method signatures and docstrings:
- def __init__(self, name: str, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataset class.
- def serialize(self, serialization_type: str='default') -> Dict[str, Any]: ... | Implement the Python class `Dataset` described below.
Class description:
Configuration Dataset class.
Method signatures and docstrings:
- def __init__(self, name: str, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataset class.
- def serialize(self, serialization_type: str='default') -> Dict[str, Any]: ... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class Dataset:
"""Configuration Dataset class."""
def __init__(self, name: str, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataset class."""
<|body_0|>
def serialize(self, serialization_type: str='default') -> Dict[str, Any]:
"""Serialize Dataset cla... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Configuration Dataset class."""
def __init__(self, name: str, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataset class."""
super().__init__()
self.name: str = name
self.params: dict = data
def serialize(self, serialization_type: str='def... | the_stack_v2_python_sparse | neural_compressor/ux/utils/workload/dataloader.py | Skp80/neural-compressor | train | 0 |
c2ce97ab822b5f9eb23902211ca40ce393b28ea9 | [
"post_data = dict(self.request.POST.lists())\nconsulta = Consulta.objects.get(id=int(self.kwargs['pk']))\nself.object = form.save(commit=False)\nself.object.texto_opcion = form.cleaned_data['texto_pregunta']\nself.object.tipo_pregunta = form.cleaned_data['tipo_pregunta']\nself.object.consulta = consulta\nself.objec... | <|body_start_0|>
post_data = dict(self.request.POST.lists())
consulta = Consulta.objects.get(id=int(self.kwargs['pk']))
self.object = form.save(commit=False)
self.object.texto_opcion = form.cleaned_data['texto_pregunta']
self.object.tipo_pregunta = form.cleaned_data['tipo_pregunt... | ! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 21-02-2017 @version 1.0.0 | PreguntaCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreguntaCreate:
"""! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 21-02-2017 @version 1.0.0"""
def form_valid(self, form):
"... | stack_v2_sparse_classes_10k_train_004410 | 22,004 | no_license | [
{
"docstring": "! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self <b>{object}</b> Objeto que instancia la clase @param form <b>{object}</b> Objeto que contiene el formulario de registro @return Retorna el formulario v... | 2 | stack_v2_sparse_classes_30k_train_001038 | Implement the Python class `PreguntaCreate` described below.
Class description:
! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 21-02-2017 @version 1.0.0
Metho... | Implement the Python class `PreguntaCreate` described below.
Class description:
! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 21-02-2017 @version 1.0.0
Metho... | 93cefc3c94c62e66b103510a2f668a419e5c5cae | <|skeleton|>
class PreguntaCreate:
"""! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 21-02-2017 @version 1.0.0"""
def form_valid(self, form):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PreguntaCreate:
"""! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 21-02-2017 @version 1.0.0"""
def form_valid(self, form):
"""! Metodo qu... | the_stack_v2_python_sparse | consulta/views.py | rudmanmrrod/gestor_consulta | train | 1 |
1bfadf42bf9e505926daf7448069c3f8083a688b | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('alanbur_jcaluag', 'alanbur_jcaluag')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/de08c6fe69c942509089e6db98c716a3_0.geojson'\nresponse = urllib.request.urlopen(url).read().decode('u... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('alanbur_jcaluag', 'alanbur_jcaluag')
url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/de08c6fe69c942509089e6db98c716a3_0.geojson'
... | extract traffic signal data from url | trafficSignal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class trafficSignal:
"""extract traffic signal data from url"""
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Creat... | stack_v2_sparse_classes_10k_train_004411 | 3,554 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_000675 | Implement the Python class `trafficSignal` described below.
Class description:
extract traffic signal data from url
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | Implement the Python class `trafficSignal` described below.
Class description:
extract traffic signal data from url
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class trafficSignal:
"""extract traffic signal data from url"""
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Creat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class trafficSignal:
"""extract traffic signal data from url"""
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.aut... | the_stack_v2_python_sparse | alanbur_jcaluag/trafficSignal.py | ROODAY/course-2017-fal-proj | train | 3 |
b193fabdd3da5642332a5e14485acaf24d7f40d4 | [
"super(MeanAggregator, self).__init__()\nself.features = features\nself.cuda = cuda\nself.gcn = gcn",
"_set = set\nif num_sample:\n _sample = random.sample\n samp_neighs = [_set(_sample(to_neigh, num_sample)) if len(to_neigh) >= num_sample else to_neigh for to_neigh in to_neighs]\nelse:\n samp_neighs = t... | <|body_start_0|>
super(MeanAggregator, self).__init__()
self.features = features
self.cuda = cuda
self.gcn = gcn
<|end_body_0|>
<|body_start_1|>
_set = set
if num_sample:
_sample = random.sample
samp_neighs = [_set(_sample(to_neigh, num_sample)) i... | Aggregates a node's embeddings using mean of neighbors' embeddings | MeanAggregator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanAggregator:
"""Aggregates a node's embeddings using mean of neighbors' embeddings"""
def __init__(self, features, cuda=False, gcn=False):
"""Initializes the aggregator for a specific graph. Parameters ---------- features : [type] function mapping LongTensor of node ids to FloatTe... | stack_v2_sparse_classes_10k_train_004412 | 14,546 | no_license | [
{
"docstring": "Initializes the aggregator for a specific graph. Parameters ---------- features : [type] function mapping LongTensor of node ids to FloatTensor of feature values. cuda : bool, optional whether to use GPU, by default False gcn : bool, optional whether to perform concatenation GraphSAGE-style, or ... | 2 | null | Implement the Python class `MeanAggregator` described below.
Class description:
Aggregates a node's embeddings using mean of neighbors' embeddings
Method signatures and docstrings:
- def __init__(self, features, cuda=False, gcn=False): Initializes the aggregator for a specific graph. Parameters ---------- features : ... | Implement the Python class `MeanAggregator` described below.
Class description:
Aggregates a node's embeddings using mean of neighbors' embeddings
Method signatures and docstrings:
- def __init__(self, features, cuda=False, gcn=False): Initializes the aggregator for a specific graph. Parameters ---------- features : ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MeanAggregator:
"""Aggregates a node's embeddings using mean of neighbors' embeddings"""
def __init__(self, features, cuda=False, gcn=False):
"""Initializes the aggregator for a specific graph. Parameters ---------- features : [type] function mapping LongTensor of node ids to FloatTe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MeanAggregator:
"""Aggregates a node's embeddings using mean of neighbors' embeddings"""
def __init__(self, features, cuda=False, gcn=False):
"""Initializes the aggregator for a specific graph. Parameters ---------- features : [type] function mapping LongTensor of node ids to FloatTensor of featu... | the_stack_v2_python_sparse | generated/test_dreamhomes_PyTorch_GNNs.py | jansel/pytorch-jit-paritybench | train | 35 |
5b6552326f394609dc964d7565ef0af170ff4018 | [
"name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()\ngetpindao(self.driver)\nfor i in range(1):\n BasePage.Base(self.driver).do_swipe(self.driver, 'up')\n try:\n self.assertTrue(VideoPage.Video(self.driver).find_video_cover())\n self.assertTrue(VideoPage.Video(self.drive... | <|body_start_0|>
name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()
getpindao(self.driver)
for i in range(1):
BasePage.Base(self.driver).do_swipe(self.driver, 'up')
try:
self.assertTrue(VideoPage.Video(self.driver).find_video_cover... | nologin_video | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
<|body_0|>
def test_02_invideos(self):
"""视频内页信息流UI测试"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()
getpind... | stack_v2_sparse_classes_10k_train_004413 | 2,158 | no_license | [
{
"docstring": "视频信息流UI测试",
"name": "test_01_video",
"signature": "def test_01_video(self)"
},
{
"docstring": "视频内页信息流UI测试",
"name": "test_02_invideos",
"signature": "def test_02_invideos(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005625 | Implement the Python class `nologin_video` described below.
Class description:
Implement the nologin_video class.
Method signatures and docstrings:
- def test_01_video(self): 视频信息流UI测试
- def test_02_invideos(self): 视频内页信息流UI测试 | Implement the Python class `nologin_video` described below.
Class description:
Implement the nologin_video class.
Method signatures and docstrings:
- def test_01_video(self): 视频信息流UI测试
- def test_02_invideos(self): 视频内页信息流UI测试
<|skeleton|>
class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
... | 7ce47cda6ac03b7eb707929dd2e0428132ff255f | <|skeleton|>
class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
<|body_0|>
def test_02_invideos(self):
"""视频内页信息流UI测试"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()
getpindao(self.driver)
for i in range(1):
BasePage.Base(self.driver).do_swipe(self.driver, 'up')
try:
self... | the_stack_v2_python_sparse | android_warning/android_warning/apptest/TestCase/nologin_testVideo.py | xiaominwanglast/uiautomator | train | 0 | |
1e1b37bdf82506f151aaa1701c1dea96b8c3b315 | [
"kwargs = self.dict()\nkwargs['data'] = fsr.load_result_df(self.path)\nreturn IntExperimentResult(**kwargs)",
"sess = check_sess(sess)\nsql_result = crud.create_experiment_result(self)\nself.uid = sql_result.id\nself.path = Path(sql_result.path)",
"kwargs = self.dict()\nkwargs['experimentGroups'] = self.experim... | <|body_start_0|>
kwargs = self.dict()
kwargs['data'] = fsr.load_result_df(self.path)
return IntExperimentResult(**kwargs)
<|end_body_0|>
<|body_start_1|>
sess = check_sess(sess)
sql_result = crud.create_experiment_result(self)
self.uid = sql_result.id
self.path =... | A class to handle database and file storage of ExperimentResults Attributes ---------- uid : int the objects unique identifier name : str the objects name hint : str brief description of the object description : str a detailed description of the experiment result experiment_group_id : int unique identifier of the assoc... | DbExperimentResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbExperimentResult:
"""A class to handle database and file storage of ExperimentResults Attributes ---------- uid : int the objects unique identifier name : str the objects name hint : str brief description of the object description : str a detailed description of the experiment result experiment... | stack_v2_sparse_classes_10k_train_004414 | 4,588 | permissive | [
{
"docstring": "Returns c_int.IntExperimentResult",
"name": "to_int_class",
"signature": "def to_int_class(self)"
},
{
"docstring": "Creates object in db. Path and id are generated and updated in object. Parameters: - sess(sqlalchemy.orm.Session): The database session to be used, if no session i... | 3 | stack_v2_sparse_classes_30k_train_000223 | Implement the Python class `DbExperimentResult` described below.
Class description:
A class to handle database and file storage of ExperimentResults Attributes ---------- uid : int the objects unique identifier name : str the objects name hint : str brief description of the object description : str a detailed descript... | Implement the Python class `DbExperimentResult` described below.
Class description:
A class to handle database and file storage of ExperimentResults Attributes ---------- uid : int the objects unique identifier name : str the objects name hint : str brief description of the object description : str a detailed descript... | 4bd9f45ad9e49f4178c0b8bb1a177d7db5349c34 | <|skeleton|>
class DbExperimentResult:
"""A class to handle database and file storage of ExperimentResults Attributes ---------- uid : int the objects unique identifier name : str the objects name hint : str brief description of the object description : str a detailed description of the experiment result experiment... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DbExperimentResult:
"""A class to handle database and file storage of ExperimentResults Attributes ---------- uid : int the objects unique identifier name : str the objects name hint : str brief description of the object description : str a detailed description of the experiment result experiment_group_id : i... | the_stack_v2_python_sparse | mistos-backend/src/app/api/classes/experiment_result.py | Maddonix/mistos_2 | train | 1 |
b8cb284d1143847643f4844c603cd9d7862bcfee | [
"if not tree.root:\n return\nqueue = [tree.root]\nresult = [tree.root.item]\nwhile len(queue) > 0:\n print(result)\n parent = queue.pop(0)\n if parent.lchild:\n queue.append(parent.lchild)\n result.append(parent.lchild.item)\n if parent.rchild:\n queue.append(parent.rchild)\n ... | <|body_start_0|>
if not tree.root:
return
queue = [tree.root]
result = [tree.root.item]
while len(queue) > 0:
print(result)
parent = queue.pop(0)
if parent.lchild:
queue.append(parent.lchild)
result.append(pa... | Display | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Display:
def traverse(self, tree):
"""层序遍历 :param tree: :return: None"""
<|body_0|>
def preorder(self, root, result):
"""先序遍历 :param tree: :return:"""
<|body_1|>
def inorder(self, root, result):
"""中序遍历 :param tree: :return:"""
<|body_2|>... | stack_v2_sparse_classes_10k_train_004415 | 1,877 | no_license | [
{
"docstring": "层序遍历 :param tree: :return: None",
"name": "traverse",
"signature": "def traverse(self, tree)"
},
{
"docstring": "先序遍历 :param tree: :return:",
"name": "preorder",
"signature": "def preorder(self, root, result)"
},
{
"docstring": "中序遍历 :param tree: :return:",
"n... | 4 | stack_v2_sparse_classes_30k_test_000002 | Implement the Python class `Display` described below.
Class description:
Implement the Display class.
Method signatures and docstrings:
- def traverse(self, tree): 层序遍历 :param tree: :return: None
- def preorder(self, root, result): 先序遍历 :param tree: :return:
- def inorder(self, root, result): 中序遍历 :param tree: :retur... | Implement the Python class `Display` described below.
Class description:
Implement the Display class.
Method signatures and docstrings:
- def traverse(self, tree): 层序遍历 :param tree: :return: None
- def preorder(self, root, result): 先序遍历 :param tree: :return:
- def inorder(self, root, result): 中序遍历 :param tree: :retur... | dca66459b4dd0bb1afe3ff73f4cd92430c35be41 | <|skeleton|>
class Display:
def traverse(self, tree):
"""层序遍历 :param tree: :return: None"""
<|body_0|>
def preorder(self, root, result):
"""先序遍历 :param tree: :return:"""
<|body_1|>
def inorder(self, root, result):
"""中序遍历 :param tree: :return:"""
<|body_2|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Display:
def traverse(self, tree):
"""层序遍历 :param tree: :return: None"""
if not tree.root:
return
queue = [tree.root]
result = [tree.root.item]
while len(queue) > 0:
print(result)
parent = queue.pop(0)
if parent.lchild:
... | the_stack_v2_python_sparse | binary_tree/tree_display.py | bobowang2017/python_study | train | 0 | |
4c23b1be8795ddcf1fa3ff07f86023bc149f0b48 | [
"c = collections.Counter(arr)\nfor i in c:\n if c[i] * 4 > len(arr):\n return i",
"n = len(arr)\nspan = n // 4 + 1\nfor i in range(0, n, span):\n iter_l = bisect.bisect_left(arr, arr[i])\n iter_r = bisect.bisect_right(arr, arr[i])\n if iter_r - iter_l >= span:\n return arr[i]"
] | <|body_start_0|>
c = collections.Counter(arr)
for i in c:
if c[i] * 4 > len(arr):
return i
<|end_body_0|>
<|body_start_1|>
n = len(arr)
span = n // 4 + 1
for i in range(0, n, span):
iter_l = bisect.bisect_left(arr, arr[i])
iter... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSpecialInteger(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def findSpecialInteger(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
c = collections.Counter(arr)
... | stack_v2_sparse_classes_10k_train_004416 | 855 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "findSpecialInteger",
"signature": "def findSpecialInteger(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "findSpecialInteger",
"signature": "def findSpecialInteger(self, arr)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSpecialInteger(self, arr): :type arr: List[int] :rtype: int
- def findSpecialInteger(self, arr): :type arr: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSpecialInteger(self, arr): :type arr: List[int] :rtype: int
- def findSpecialInteger(self, arr): :type arr: List[int] :rtype: int
<|skeleton|>
class Solution:
def f... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findSpecialInteger(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def findSpecialInteger(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findSpecialInteger(self, arr):
""":type arr: List[int] :rtype: int"""
c = collections.Counter(arr)
for i in c:
if c[i] * 4 > len(arr):
return i
def findSpecialInteger(self, arr):
""":type arr: List[int] :rtype: int"""
n = l... | the_stack_v2_python_sparse | 1287_Element_Appearing_More_Than_25%_In_Sorted_Array.py | bingli8802/leetcode | train | 0 | |
264030f531868fca69de0d639290b7cdd98302ac | [
"json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = jso... | 修改和删除地址 | UpdateDestroyAddressView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dict = json.loads(request.body.decode())
... | stack_v2_sparse_classes_10k_train_004417 | 18,106 | no_license | [
{
"docstring": "修改地址",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "删除地址",
"name": "delete",
"signature": "def delete(self, request, address_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001385 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址
<|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, addre... | 41ab7838dd5b1e5616febd9d6d299a9cf60d3f5d | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | xzlee2020/- | train | 0 |
e2b6fcdb10f659aba4f0941d17d3d9500875dff9 | [
"g.sort()\ns.sort()\ng_length = len(g) - 1\ngave_cookies = 0\nfor select_cookie in s:\n if gave_cookies > g_length:\n break\n elif g[gave_cookies] <= select_cookie:\n gave_cookies += 1\nreturn gave_cookies",
"g.sort()\ns.sort()\nchild = 0\ncookie = 0\nwhile child < len(g) and cookie < len(s):\... | <|body_start_0|>
g.sort()
s.sort()
g_length = len(g) - 1
gave_cookies = 0
for select_cookie in s:
if gave_cookies > g_length:
break
elif g[gave_cookies] <= select_cookie:
gave_cookies += 1
return gave_cookies
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findContentChildren(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_0|>
def findContentChildren2(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004418 | 1,966 | no_license | [
{
"docstring": ":type g: List[int] :type s: List[int] :rtype: int",
"name": "findContentChildren",
"signature": "def findContentChildren(self, g, s)"
},
{
"docstring": ":type g: List[int] :type s: List[int] :rtype: int",
"name": "findContentChildren2",
"signature": "def findContentChildr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContentChildren(self, g, s): :type g: List[int] :type s: List[int] :rtype: int
- def findContentChildren2(self, g, s): :type g: List[int] :type s: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContentChildren(self, g, s): :type g: List[int] :type s: List[int] :rtype: int
- def findContentChildren2(self, g, s): :type g: List[int] :type s: List[int] :rtype: int
... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def findContentChildren(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_0|>
def findContentChildren2(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findContentChildren(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
g.sort()
s.sort()
g_length = len(g) - 1
gave_cookies = 0
for select_cookie in s:
if gave_cookies > g_length:
break
elif... | the_stack_v2_python_sparse | Problems/0400_0499/0455_Assign_Cookies/Project_Python3/Assign_Cookies.py | NobuyukiInoue/LeetCode | train | 0 | |
fd300559c4bb90d17d90439b84f2bd8ddff1f339 | [
"self.ch1_list = natsort.natsorted(ch1_list)\nself.label = label\nself.channels = channels",
"files = [f for f in self.ch1_list if f.lower().endswith('ch' + str(self.channels[0]) + '.tif')]\ntiff_files = [TiffFile(tiffFile, self.channels, self.label) for tiffFile in files]\nreturn tiff_files"
] | <|body_start_0|>
self.ch1_list = natsort.natsorted(ch1_list)
self.label = label
self.channels = channels
<|end_body_0|>
<|body_start_1|>
files = [f for f in self.ch1_list if f.lower().endswith('ch' + str(self.channels[0]) + '.tif')]
tiff_files = [TiffFile(tiffFile, self.channels... | This class represents list of tiff files. These tiff files are the output from the cell extractor plugin and are used as training and classification data. | TiffList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TiffList:
"""This class represents list of tiff files. These tiff files are the output from the cell extractor plugin and are used as training and classification data."""
def __init__(self, ch1_list, channels, label=None):
"""A list of tiff files output by the cell extractor plugin t... | stack_v2_sparse_classes_10k_train_004419 | 2,889 | permissive | [
{
"docstring": "A list of tiff files output by the cell extractor plugin to be used in machine learning. Expects file names to end with \"ch[ch].tif\", where [ch] is the non-zero-padded channel index. Given a list of tiff files for the first channel, it will find the corresponding files for the channels passed ... | 2 | stack_v2_sparse_classes_30k_train_004540 | Implement the Python class `TiffList` described below.
Class description:
This class represents list of tiff files. These tiff files are the output from the cell extractor plugin and are used as training and classification data.
Method signatures and docstrings:
- def __init__(self, ch1_list, channels, label=None): A... | Implement the Python class `TiffList` described below.
Class description:
This class represents list of tiff files. These tiff files are the output from the cell extractor plugin and are used as training and classification data.
Method signatures and docstrings:
- def __init__(self, ch1_list, channels, label=None): A... | a4cbdb0976a46deeb84105281e2a332f95fee1d7 | <|skeleton|>
class TiffList:
"""This class represents list of tiff files. These tiff files are the output from the cell extractor plugin and are used as training and classification data."""
def __init__(self, ch1_list, channels, label=None):
"""A list of tiff files output by the cell extractor plugin t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TiffList:
"""This class represents list of tiff files. These tiff files are the output from the cell extractor plugin and are used as training and classification data."""
def __init__(self, ch1_list, channels, label=None):
"""A list of tiff files output by the cell extractor plugin to be used in ... | the_stack_v2_python_sparse | cellfinder/tools/tiff.py | adamltyson/cellfinder | train | 0 |
6418721c19ed2fbed5bacacf0555ad2ddfd5ce07 | [
"self.S = S\nscore = 0\ni = 0\nwhile i < len(S):\n subscore, i = self._get_score(i)\n score += subscore\nreturn score",
"if i_start >= len(self.S):\n return [0, len(self.S)]\nscore = 0\ni = i_start + 1\nwhile i < len(self.S) and self.S[i] != ')':\n sub_score, i = self._get_score(i)\n score += sub_s... | <|body_start_0|>
self.S = S
score = 0
i = 0
while i < len(S):
subscore, i = self._get_score(i)
score += subscore
return score
<|end_body_0|>
<|body_start_1|>
if i_start >= len(self.S):
return [0, len(self.S)]
score = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory."""
<|body_0|>
def _get_score(self,... | stack_v2_sparse_classes_10k_train_004420 | 2,047 | no_license | [
{
"docstring": "Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory.",
"name": "scoreOfParentheses",
"signature": "def scoreOfParentheses(self, S: str) -> int"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_002133 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S: str) -> int: Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without st... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S: str) -> int: Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without st... | ee8237b66975fb5584a3d68b311e762c0462c8aa | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory."""
<|body_0|>
def _get_score(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""Time complexity. Each symbol is read once and processed in O(1) manner, so total complexity is O(n) Space complexity: O(1) without stacking memory, O(max depth) with stacking memory."""
self.S = S
score = 0
i = 0
... | the_stack_v2_python_sparse | LC856-Score-of-Parentheses.py | kate-melnykova/LeetCode-solutions | train | 2 | |
cf84c3d572c10e281bac5f75e61ed3f432e71777 | [
"super().__init__()\nkwargs = {'growth': growth, 'interval_width': threshold, 'holidays': holidays, 'holidays_prior_scale': holidays_prior_scale, 'changepoint_prior_scale': changepoint_prior_scale, 'changepoint_range': changepoint_range, 'seasonality_mode': seasonality_mode, 'daily_seasonality': daily_seasonality, ... | <|body_start_0|>
super().__init__()
kwargs = {'growth': growth, 'interval_width': threshold, 'holidays': holidays, 'holidays_prior_scale': holidays_prior_scale, 'changepoint_prior_scale': changepoint_prior_scale, 'changepoint_range': changepoint_range, 'seasonality_mode': seasonality_mode, 'daily_season... | OutlierProphet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_se... | stack_v2_sparse_classes_10k_train_004421 | 8,498 | permissive | [
{
"docstring": "Outlier detector for time series data using fbprophet. See https://facebook.github.io/prophet/ for more details. Parameters ---------- threshold Width of the uncertainty intervals of the forecast, used as outlier threshold. Equivalent to `interval_width`. If the instance lies outside of the unce... | 4 | stack_v2_sparse_classes_30k_train_002490 | Implement the Python class `OutlierProphet` described below.
Class description:
Implement the OutlierProphet class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=N... | Implement the Python class `OutlierProphet` described below.
Class description:
Implement the OutlierProphet class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=N... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_seasonality: Uni... | the_stack_v2_python_sparse | alibi_detect/od/prophet.py | SeldonIO/alibi-detect | train | 1,922 | |
b7bbeaae4b6a0ba882a463695a6064b1e4755a57 | [
"if not self.formset:\n raise ImproperlyConfigured(\"You must specify formset in '{class_name}' to configure '{mixin_name}'\".format(class_name=self.__class__, mixin_name=__class__.__name__))\ncontext_data = super().get_context_data(*args, **kwargs)\nqueryset = self.formset.model.objects.filter(**{self.formset.f... | <|body_start_0|>
if not self.formset:
raise ImproperlyConfigured("You must specify formset in '{class_name}' to configure '{mixin_name}'".format(class_name=self.__class__, mixin_name=__class__.__name__))
context_data = super().get_context_data(*args, **kwargs)
queryset = self.formset... | Добавляет formset в контекст формы. | SingleFormSetMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleFormSetMixin:
"""Добавляет formset в контекст формы."""
def get_context_data(self, *args, **kwargs):
"""Добавляет formset в контекст."""
<|body_0|>
def form_valid(self, form):
"""Сохраняет formset."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004422 | 8,263 | permissive | [
{
"docstring": "Добавляет formset в контекст.",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstring": "Сохраняет formset.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000016 | Implement the Python class `SingleFormSetMixin` described below.
Class description:
Добавляет formset в контекст формы.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Добавляет formset в контекст.
- def form_valid(self, form): Сохраняет formset. | Implement the Python class `SingleFormSetMixin` described below.
Class description:
Добавляет formset в контекст формы.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Добавляет formset в контекст.
- def form_valid(self, form): Сохраняет formset.
<|skeleton|>
class SingleFormSetMixin... | 7246b4f524d138d48aadf4866e0b218bb924f69c | <|skeleton|>
class SingleFormSetMixin:
"""Добавляет formset в контекст формы."""
def get_context_data(self, *args, **kwargs):
"""Добавляет formset в контекст."""
<|body_0|>
def form_valid(self, form):
"""Сохраняет formset."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SingleFormSetMixin:
"""Добавляет formset в контекст формы."""
def get_context_data(self, *args, **kwargs):
"""Добавляет formset в контекст."""
if not self.formset:
raise ImproperlyConfigured("You must specify formset in '{class_name}' to configure '{mixin_name}'".format(class_... | the_stack_v2_python_sparse | locker/core/views.py | crowmurk/locker | train | 0 |
26676263d1d19864965dc6baff05ea892c764f62 | [
"self.logger = logging.getLogger(__name__)\nself.hdr_path = header_path\nif path is not None:\n self.path = path\nelse:\n self.path = os.path.splitext(header_path)[0]\nself.unpack_fmt = unpack_fmt\nself.hdr = self.process_hdr()\nif 'pixperline' not in self.hdr:\n self.calc_from_xy()",
"try:\n num_byte... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.hdr_path = header_path
if path is not None:
self.path = path
else:
self.path = os.path.splitext(header_path)[0]
self.unpack_fmt = unpack_fmt
self.hdr = self.process_hdr()
if 'p... | Superclass for BilFile and BsqFile. Contains generic read() method that subclasses use to unpack binary data in the correct order. | EnviFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnviFile:
"""Superclass for BilFile and BsqFile. Contains generic read() method that subclasses use to unpack binary data in the correct order."""
def __init__(self, header_path, path=None, unpack_fmt='<d'):
""":param str header_path: Path to header file. :param str path: Path to fil... | stack_v2_sparse_classes_10k_train_004423 | 7,393 | permissive | [
{
"docstring": ":param str header_path: Path to header file. :param str path: Path to file. Guessed from header if not provided. :param str unpack_fmt: Format string describing structure of data. Default: \"<d\" - little-endian, double precision",
"name": "__init__",
"signature": "def __init__(self, hea... | 6 | stack_v2_sparse_classes_30k_train_006803 | Implement the Python class `EnviFile` described below.
Class description:
Superclass for BilFile and BsqFile. Contains generic read() method that subclasses use to unpack binary data in the correct order.
Method signatures and docstrings:
- def __init__(self, header_path, path=None, unpack_fmt='<d'): :param str heade... | Implement the Python class `EnviFile` described below.
Class description:
Superclass for BilFile and BsqFile. Contains generic read() method that subclasses use to unpack binary data in the correct order.
Method signatures and docstrings:
- def __init__(self, header_path, path=None, unpack_fmt='<d'): :param str heade... | 5d7e21f28ead02d226c19f2831bc261897300b0f | <|skeleton|>
class EnviFile:
"""Superclass for BilFile and BsqFile. Contains generic read() method that subclasses use to unpack binary data in the correct order."""
def __init__(self, header_path, path=None, unpack_fmt='<d'):
""":param str header_path: Path to header file. :param str path: Path to fil... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnviFile:
"""Superclass for BilFile and BsqFile. Contains generic read() method that subclasses use to unpack binary data in the correct order."""
def __init__(self, header_path, path=None, unpack_fmt='<d'):
""":param str header_path: Path to header file. :param str path: Path to file. Guessed fr... | the_stack_v2_python_sparse | python/src/ceda_di/filetypes/file_io/envi_io.py | cedadev/ceda-di | train | 5 |
6c7b92d711a3149db2cf5a313b492ffda70a088a | [
"super().__init__(**kwargs)\nself.prediction_length = prediction_length\nself.context_length = context_length\nself.cardinality = cardinality\nself.kernel_output = kernel_output\nself.params_scaling = params_scaling\nself.float_type = float_type\nself.max_iter_jitter = max_iter_jitter\nself.jitter_method = jitter_m... | <|body_start_0|>
super().__init__(**kwargs)
self.prediction_length = prediction_length
self.context_length = context_length
self.cardinality = cardinality
self.kernel_output = kernel_output
self.params_scaling = params_scaling
self.float_type = float_type
... | Defines a Gluon block used for GP training and predictions. | GaussianProcessNetworkBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcessNetworkBase:
"""Defines a Gluon block used for GP training and predictions."""
def __init__(self, prediction_length: int, context_length: int, cardinality: int, kernel_output: KernelOutputDict, params_scaling: bool, float_type: DType, max_iter_jitter: int, jitter_method: str, ... | stack_v2_sparse_classes_10k_train_004424 | 9,486 | permissive | [
{
"docstring": "Parameters ---------- prediction_length Prediction length. context_length Training length. cardinality Number of time series. kernel_output KernelOutput instance to determine which kernel subclass to be instantiated. params_scaling Determines whether or not to scale the model parameters. float_t... | 2 | null | Implement the Python class `GaussianProcessNetworkBase` described below.
Class description:
Defines a Gluon block used for GP training and predictions.
Method signatures and docstrings:
- def __init__(self, prediction_length: int, context_length: int, cardinality: int, kernel_output: KernelOutputDict, params_scaling:... | Implement the Python class `GaussianProcessNetworkBase` described below.
Class description:
Defines a Gluon block used for GP training and predictions.
Method signatures and docstrings:
- def __init__(self, prediction_length: int, context_length: int, cardinality: int, kernel_output: KernelOutputDict, params_scaling:... | df4256b0e67120db555c109a1bf6cfa2b3bd3cd8 | <|skeleton|>
class GaussianProcessNetworkBase:
"""Defines a Gluon block used for GP training and predictions."""
def __init__(self, prediction_length: int, context_length: int, cardinality: int, kernel_output: KernelOutputDict, params_scaling: bool, float_type: DType, max_iter_jitter: int, jitter_method: str, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GaussianProcessNetworkBase:
"""Defines a Gluon block used for GP training and predictions."""
def __init__(self, prediction_length: int, context_length: int, cardinality: int, kernel_output: KernelOutputDict, params_scaling: bool, float_type: DType, max_iter_jitter: int, jitter_method: str, **kwargs) -> ... | the_stack_v2_python_sparse | src/gluonts/model/gp_forecaster/_network.py | mbohlkeschneider/gluon-ts | train | 54 |
5b63c1cb7b69510c4b09b8a9989104dc059425f2 | [
"bad = np.zeros(len(self.times), dtype=bool)\nfor pcad_mode, max_delta_val in self.max_delta_vals.items():\n mask = self.states_at_times['pcad_mode'] == pcad_mode\n bad |= (np.abs(self.tlm_vals - self.state_vals) > max_delta_val) & mask\nreturn bad",
"super().add_exclude_intervals()\nself.exclude_ofp_interv... | <|body_start_0|>
bad = np.zeros(len(self.times), dtype=bool)
for pcad_mode, max_delta_val in self.max_delta_vals.items():
mask = self.states_at_times['pcad_mode'] == pcad_mode
bad |= (np.abs(self.tlm_vals - self.state_vals) > max_delta_val) & mask
return bad
<|end_body_0|... | ValidatePitchRollBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidatePitchRollBase:
def get_violations_mask(self):
"""Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings."""
<|body_0|>
def add_exclude... | stack_v2_sparse_classes_10k_train_004425 | 27,851 | permissive | [
{
"docstring": "Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings.",
"name": "get_violations_mask",
"signature": "def get_violations_mask(self)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_002413 | Implement the Python class `ValidatePitchRollBase` described below.
Class description:
Implement the ValidatePitchRollBase class.
Method signatures and docstrings:
- def get_violations_mask(self): Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Ta... | Implement the Python class `ValidatePitchRollBase` described below.
Class description:
Implement the ValidatePitchRollBase class.
Method signatures and docstrings:
- def get_violations_mask(self): Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Ta... | eb58686d91b6668af55ae51959a1f8f6eccb7d7d | <|skeleton|>
class ValidatePitchRollBase:
def get_violations_mask(self):
"""Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings."""
<|body_0|>
def add_exclude... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValidatePitchRollBase:
def get_violations_mask(self):
"""Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings."""
bad = np.zeros(len(self.times), dtype=bool)
... | the_stack_v2_python_sparse | kadi/commands/validate.py | sot/kadi | train | 3 | |
726ca9d290e827e770b872e0d7ebd50aefe8cc21 | [
"population_size = 4\nnumber_universe = 1\nfactory = Factory_SimGAN_ECG\nmpi = False\ngenome_seeds = [['misc/IndivSeed_SimGAN_Seed0/RefinerBlock_lisp.txt', 'misc/IndivSeed_SimGAN_Seed0/DiscriminatorBlock_lisp.txt', 'misc/IndivSeed_SimGAN_ECG_Seed0/ConfigBlock_lisp.txt']] * population_size\nhall_of_fame_flag = True\... | <|body_start_0|>
population_size = 4
number_universe = 1
factory = Factory_SimGAN_ECG
mpi = False
genome_seeds = [['misc/IndivSeed_SimGAN_Seed0/RefinerBlock_lisp.txt', 'misc/IndivSeed_SimGAN_Seed0/DiscriminatorBlock_lisp.txt', 'misc/IndivSeed_SimGAN_ECG_Seed0/ConfigBlock_lisp.txt... | Problem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem:
def __init__(self):
"""not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different"""
<|body_0|>
def construct_dataset(self):
"""Constructs a train and validation 1D signal datasets"""
<|body_1|>
def ch... | stack_v2_sparse_classes_10k_train_004426 | 6,254 | permissive | [
{
"docstring": "not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Constructs a train and validation 1D signal datasets",
"name": "construct_dataset",
"signature... | 3 | stack_v2_sparse_classes_30k_train_002891 | Implement the Python class `Problem` described below.
Class description:
Implement the Problem class.
Method signatures and docstrings:
- def __init__(self): not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different
- def construct_dataset(self): Constructs a train and val... | Implement the Python class `Problem` described below.
Class description:
Implement the Problem class.
Method signatures and docstrings:
- def __init__(self): not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different
- def construct_dataset(self): Constructs a train and val... | a93df7ae91fd5905df368661b86ae653c3d08869 | <|skeleton|>
class Problem:
def __init__(self):
"""not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different"""
<|body_0|>
def construct_dataset(self):
"""Constructs a train and validation 1D signal datasets"""
<|body_1|>
def ch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Problem:
def __init__(self):
"""not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different"""
population_size = 4
number_universe = 1
factory = Factory_SimGAN_ECG
mpi = False
genome_seeds = [['misc/IndivSeed_SimGAN_See... | the_stack_v2_python_sparse | problems/problem_simgan_ecg.py | ezCGP/ezCGP | train | 6 | |
62faaccf74199d4800fa9dd50b65ab42be2e855f | [
"self.num_parallel_calls = tf.convert_to_tensor(num_parallel_calls, tf.int32)\nif times.dtype is not float_type:\n times = tf.cast(times, float_type)\nself.times = times\nself.slice_size = index_feed.step\nself.Nt = tf.shape(self.times)[0]\nself.index_feed = index_feed\nself.time_feed = index_feed.feed.map(self.... | <|body_start_0|>
self.num_parallel_calls = tf.convert_to_tensor(num_parallel_calls, tf.int32)
if times.dtype is not float_type:
times = tf.cast(times, float_type)
self.times = times
self.slice_size = index_feed.step
self.Nt = tf.shape(self.times)[0]
self.index... | TimeFeed | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeFeed:
def __init__(self, index_feed: IndexFeed, times, num_parallel_calls=10):
"""Create a time feed :param index_feed: IndexFeed Pulse of this feed :param times: float_type, Tensor, [Nt, 1] Times to slice :param num_parallel_calls:"""
<|body_0|>
def get_times_slice(self... | stack_v2_sparse_classes_10k_train_004427 | 18,860 | permissive | [
{
"docstring": "Create a time feed :param index_feed: IndexFeed Pulse of this feed :param times: float_type, Tensor, [Nt, 1] Times to slice :param num_parallel_calls:",
"name": "__init__",
"signature": "def __init__(self, index_feed: IndexFeed, times, num_parallel_calls=10)"
},
{
"docstring": "G... | 2 | stack_v2_sparse_classes_30k_train_003448 | Implement the Python class `TimeFeed` described below.
Class description:
Implement the TimeFeed class.
Method signatures and docstrings:
- def __init__(self, index_feed: IndexFeed, times, num_parallel_calls=10): Create a time feed :param index_feed: IndexFeed Pulse of this feed :param times: float_type, Tensor, [Nt,... | Implement the Python class `TimeFeed` described below.
Class description:
Implement the TimeFeed class.
Method signatures and docstrings:
- def __init__(self, index_feed: IndexFeed, times, num_parallel_calls=10): Create a time feed :param index_feed: IndexFeed Pulse of this feed :param times: float_type, Tensor, [Nt,... | 2997d60d8cf07f875e42c0b5f07944e9ab7e9d33 | <|skeleton|>
class TimeFeed:
def __init__(self, index_feed: IndexFeed, times, num_parallel_calls=10):
"""Create a time feed :param index_feed: IndexFeed Pulse of this feed :param times: float_type, Tensor, [Nt, 1] Times to slice :param num_parallel_calls:"""
<|body_0|>
def get_times_slice(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TimeFeed:
def __init__(self, index_feed: IndexFeed, times, num_parallel_calls=10):
"""Create a time feed :param index_feed: IndexFeed Pulse of this feed :param times: float_type, Tensor, [Nt, 1] Times to slice :param num_parallel_calls:"""
self.num_parallel_calls = tf.convert_to_tensor(num_par... | the_stack_v2_python_sparse | bayes_filter/feeds.py | Joshuaalbert/bayes_filter | train | 0 | |
2fb96cca7f489ffaae3de606d587648b62c70f0d | [
"extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + NAMES['extent'] + ' <', None, 'clean.task.maxextent', '.3F')\ntitles = [NAMES['population'] + ' <i>Lower Limit</i>', NAMES['saturation'] + ' <i>Upper Limit</i>']\nreturn f\"\\n {extents}\\n {current.table(titles[0]... | <|body_start_0|>
extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + NAMES['extent'] + ' <', None, 'clean.task.maxextent', '.3F')
titles = [NAMES['population'] + ' <i>Lower Limit</i>', NAMES['saturation'] + ' <i>Upper Limit</i>']
return f"\n {extents}\n ... | _CleanStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CleanStore:
def tabs(current) -> str:
"""return the tabs"""
<|body_0|>
def _diff(self, _, changed):
"""yield the changes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + ... | stack_v2_sparse_classes_10k_train_004428 | 15,492 | no_license | [
{
"docstring": "return the tabs",
"name": "tabs",
"signature": "def tabs(current) -> str"
},
{
"docstring": "yield the changes",
"name": "_diff",
"signature": "def _diff(self, _, changed)"
}
] | 2 | null | Implement the Python class `_CleanStore` described below.
Class description:
Implement the _CleanStore class.
Method signatures and docstrings:
- def tabs(current) -> str: return the tabs
- def _diff(self, _, changed): yield the changes | Implement the Python class `_CleanStore` described below.
Class description:
Implement the _CleanStore class.
Method signatures and docstrings:
- def tabs(current) -> str: return the tabs
- def _diff(self, _, changed): yield the changes
<|skeleton|>
class _CleanStore:
def tabs(current) -> str:
"""return... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class _CleanStore:
def tabs(current) -> str:
"""return the tabs"""
<|body_0|>
def _diff(self, _, changed):
"""yield the changes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _CleanStore:
def tabs(current) -> str:
"""return the tabs"""
extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + NAMES['extent'] + ' <', None, 'clean.task.maxextent', '.3F')
titles = [NAMES['population'] + ' <i>Lower Limit</i>', NAMES['saturation'] + ' <i>Upp... | the_stack_v2_python_sparse | src/peakcalling/view/_widgets/_tasks.py | depixusgenome/trackanalysis | train | 0 | |
26b210209b29dc797696bde6730d17bf5cd76a3b | [
"self.head = head\nself.size = 0\nwhile head:\n self.size += 1\n head = head.next",
"k = random.randrange(self.size)\ni = 0\nhead = self.head\nwhile i < k:\n head = head.next\n i += 1\nreturn head.val"
] | <|body_start_0|>
self.head = head
self.size = 0
while head:
self.size += 1
head = head.next
<|end_body_0|>
<|body_start_1|>
k = random.randrange(self.size)
i = 0
head = self.head
while i < k:
head = head.next
i += 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_004429 | 1,057 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | 4f5f5124534bd4423356a5f5572b8a39b7828d80 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
self.head = head
self.size = 0
while head:
self.size += 1
head = head.next
def... | the_stack_v2_python_sparse | leetcode/linked-list-random-node/285257658.py | ausaki/data_structures_and_algorithms | train | 1 | |
22b2b45144d5e1b5cc0a3dbb1d55016e3ff51688 | [
"self.applications = applications\nself.entity_permission_info = entity_permission_info\nself.logical_size_bytes = logical_size_bytes\nself.registration_info = registration_info\nself.root_node = root_node\nself.stats = stats\nself.stats_by_env = stats_by_env\nself.total_downtiered_size_in_bytes = total_downtiered_... | <|body_start_0|>
self.applications = applications
self.entity_permission_info = entity_permission_info
self.logical_size_bytes = logical_size_bytes
self.registration_info = registration_info
self.root_node = root_node
self.stats = stats
self.stats_by_env = stats_b... | Implementation of the 'ProtectionSourceTreeInfo' model. Specifies the registration and protection information of a registered Protection Source Tree on the Cohesity Cluster. Many different Protection Source trees are supported such as 'kVMware', 'kAcropolis', 'kPhysical' etc., Attributes: applications (list of Applicat... | ProtectionSourceTreeInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionSourceTreeInfo:
"""Implementation of the 'ProtectionSourceTreeInfo' model. Specifies the registration and protection information of a registered Protection Source Tree on the Cohesity Cluster. Many different Protection Source trees are supported such as 'kVMware', 'kAcropolis', 'kPhysic... | stack_v2_sparse_classes_10k_train_004430 | 6,386 | permissive | [
{
"docstring": "Constructor for the ProtectionSourceTreeInfo class",
"name": "__init__",
"signature": "def __init__(self, applications=None, entity_permission_info=None, logical_size_bytes=None, registration_info=None, root_node=None, stats=None, stats_by_env=None, total_downtiered_size_in_bytes=None, t... | 2 | null | Implement the Python class `ProtectionSourceTreeInfo` described below.
Class description:
Implementation of the 'ProtectionSourceTreeInfo' model. Specifies the registration and protection information of a registered Protection Source Tree on the Cohesity Cluster. Many different Protection Source trees are supported su... | Implement the Python class `ProtectionSourceTreeInfo` described below.
Class description:
Implementation of the 'ProtectionSourceTreeInfo' model. Specifies the registration and protection information of a registered Protection Source Tree on the Cohesity Cluster. Many different Protection Source trees are supported su... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionSourceTreeInfo:
"""Implementation of the 'ProtectionSourceTreeInfo' model. Specifies the registration and protection information of a registered Protection Source Tree on the Cohesity Cluster. Many different Protection Source trees are supported such as 'kVMware', 'kAcropolis', 'kPhysic... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProtectionSourceTreeInfo:
"""Implementation of the 'ProtectionSourceTreeInfo' model. Specifies the registration and protection information of a registered Protection Source Tree on the Cohesity Cluster. Many different Protection Source trees are supported such as 'kVMware', 'kAcropolis', 'kPhysical' etc., Att... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_source_tree_info.py | cohesity/management-sdk-python | train | 24 |
f1bc5d26f3ffecb5a68d1b8af313a27eb5cb1798 | [
"self.date1 = datetime.date(2011, 1, 1)\nself.date2 = datetime.date(2011, 1, 2)\nself.date3 = datetime.date(2011, 1, 3)\nself.test_user = create_test_user()\nself.boiler_obj = create_test_boiler(self.test_user)\nself.fuel_info1 = FuelInfo.objects.create(boiler=self.boiler_obj, creator=self.test_user, type='Coal')\n... | <|body_start_0|>
self.date1 = datetime.date(2011, 1, 1)
self.date2 = datetime.date(2011, 1, 2)
self.date3 = datetime.date(2011, 1, 3)
self.test_user = create_test_user()
self.boiler_obj = create_test_boiler(self.test_user)
self.fuel_info1 = FuelInfo.objects.create(boiler=... | FuelRemainsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuelRemainsTest:
def setUp(self):
"""Pre-execution"""
<|body_0|>
def tearDown(self):
"""Post-execution"""
<|body_1|>
def test_creation(self):
"""1. Создаем объект остатоков на первый день месяца (остатки топлива на 1е число месяца = 10.5) 2. Созд... | stack_v2_sparse_classes_10k_train_004431 | 14,802 | no_license | [
{
"docstring": "Pre-execution",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Post-execution",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "1. Создаем объект остатоков на первый день месяца (остатки топлива на 1е число месяца = 10.... | 4 | stack_v2_sparse_classes_30k_train_007160 | Implement the Python class `FuelRemainsTest` described below.
Class description:
Implement the FuelRemainsTest class.
Method signatures and docstrings:
- def setUp(self): Pre-execution
- def tearDown(self): Post-execution
- def test_creation(self): 1. Создаем объект остатоков на первый день месяца (остатки топлива на... | Implement the Python class `FuelRemainsTest` described below.
Class description:
Implement the FuelRemainsTest class.
Method signatures and docstrings:
- def setUp(self): Pre-execution
- def tearDown(self): Post-execution
- def test_creation(self): 1. Создаем объект остатоков на первый день месяца (остатки топлива на... | 016c3e5ad4099d6e1dbff42fd414f5fedd4d8530 | <|skeleton|>
class FuelRemainsTest:
def setUp(self):
"""Pre-execution"""
<|body_0|>
def tearDown(self):
"""Post-execution"""
<|body_1|>
def test_creation(self):
"""1. Создаем объект остатоков на первый день месяца (остатки топлива на 1е число месяца = 10.5) 2. Созд... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FuelRemainsTest:
def setUp(self):
"""Pre-execution"""
self.date1 = datetime.date(2011, 1, 1)
self.date2 = datetime.date(2011, 1, 2)
self.date3 = datetime.date(2011, 1, 3)
self.test_user = create_test_user()
self.boiler_obj = create_test_boiler(self.test_user)
... | the_stack_v2_python_sparse | src/dailyreport/fuel/tests.py | johnsky/dailyreport-server | train | 0 | |
9900dc120c93a8f245c2be866bca42c710bb7cd4 | [
"self.skew_detection_config = skew_detection_config\nself.drift_detection_config = drift_detection_config\nself.explanation_config = explanation_config\nself._config_for_bp = False",
"training_dataset = None\nif self.skew_detection_config is not None:\n training_dataset = gca_model_monitoring.ModelMonitoringOb... | <|body_start_0|>
self.skew_detection_config = skew_detection_config
self.drift_detection_config = drift_detection_config
self.explanation_config = explanation_config
self._config_for_bp = False
<|end_body_0|>
<|body_start_1|>
training_dataset = None
if self.skew_detectio... | _ObjectiveConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ObjectiveConfig:
def __init__(self, skew_detection_config: Optional['gca_model_monitoring._SkewDetectionConfig']=None, drift_detection_config: Optional['gca_model_monitoring._DriftDetectionConfig']=None, explanation_config: Optional['gca_model_monitoring._ExplanationConfig']=None):
"""B... | stack_v2_sparse_classes_10k_train_004432 | 17,467 | permissive | [
{
"docstring": "Base class for ObjectiveConfig. Args: skew_detection_config (_SkewDetectionConfig): Optional. An instance of _SkewDetectionConfig. drift_detection_config (_DriftDetectionConfig): Optional. An instance of _DriftDetectionConfig. explanation_config (_ExplanationConfig): Optional. An instance of _Ex... | 2 | stack_v2_sparse_classes_30k_train_004998 | Implement the Python class `_ObjectiveConfig` described below.
Class description:
Implement the _ObjectiveConfig class.
Method signatures and docstrings:
- def __init__(self, skew_detection_config: Optional['gca_model_monitoring._SkewDetectionConfig']=None, drift_detection_config: Optional['gca_model_monitoring._Drif... | Implement the Python class `_ObjectiveConfig` described below.
Class description:
Implement the _ObjectiveConfig class.
Method signatures and docstrings:
- def __init__(self, skew_detection_config: Optional['gca_model_monitoring._SkewDetectionConfig']=None, drift_detection_config: Optional['gca_model_monitoring._Drif... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class _ObjectiveConfig:
def __init__(self, skew_detection_config: Optional['gca_model_monitoring._SkewDetectionConfig']=None, drift_detection_config: Optional['gca_model_monitoring._DriftDetectionConfig']=None, explanation_config: Optional['gca_model_monitoring._ExplanationConfig']=None):
"""B... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _ObjectiveConfig:
def __init__(self, skew_detection_config: Optional['gca_model_monitoring._SkewDetectionConfig']=None, drift_detection_config: Optional['gca_model_monitoring._DriftDetectionConfig']=None, explanation_config: Optional['gca_model_monitoring._ExplanationConfig']=None):
"""Base class for ... | the_stack_v2_python_sparse | google/cloud/aiplatform/model_monitoring/objective.py | googleapis/python-aiplatform | train | 418 | |
19010bc22c79b4716d5467797d05bf2d7327b74e | [
"if db_dir is None:\n db_dir = OnChainSQLite3.DEFAULT_PAYMENT_DB_DIR\nif db is None:\n db = OnChainSQLite3.DEFAULT_PAYMENT_DB_PATH\nif db_dir and (not os.path.exists(db_dir)):\n os.makedirs(db_dir)\nself.connection = sqlite3.connect(os.path.join(db_dir, db), check_same_thread=False)\nself.c = self.connecti... | <|body_start_0|>
if db_dir is None:
db_dir = OnChainSQLite3.DEFAULT_PAYMENT_DB_DIR
if db is None:
db = OnChainSQLite3.DEFAULT_PAYMENT_DB_PATH
if db_dir and (not os.path.exists(db_dir)):
os.makedirs(db_dir)
self.connection = sqlite3.connect(os.path.join... | SQLite3 binding for the on-chain transaction model. | OnChainSQLite3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnChainSQLite3:
"""SQLite3 binding for the on-chain transaction model."""
def __init__(self, db=None, db_dir=None):
"""Instantiate SQLite3 for storing on chain transaction data."""
<|body_0|>
def create(self, txid, amount):
"""Create a transaction entry."""
... | stack_v2_sparse_classes_10k_train_004433 | 16,798 | permissive | [
{
"docstring": "Instantiate SQLite3 for storing on chain transaction data.",
"name": "__init__",
"signature": "def __init__(self, db=None, db_dir=None)"
},
{
"docstring": "Create a transaction entry.",
"name": "create",
"signature": "def create(self, txid, amount)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_000088 | Implement the Python class `OnChainSQLite3` described below.
Class description:
SQLite3 binding for the on-chain transaction model.
Method signatures and docstrings:
- def __init__(self, db=None, db_dir=None): Instantiate SQLite3 for storing on chain transaction data.
- def create(self, txid, amount): Create a transa... | Implement the Python class `OnChainSQLite3` described below.
Class description:
SQLite3 binding for the on-chain transaction model.
Method signatures and docstrings:
- def __init__(self, db=None, db_dir=None): Instantiate SQLite3 for storing on chain transaction data.
- def create(self, txid, amount): Create a transa... | a5e99fccf11ed75420775ae3e924c9ce94f2e86d | <|skeleton|>
class OnChainSQLite3:
"""SQLite3 binding for the on-chain transaction model."""
def __init__(self, db=None, db_dir=None):
"""Instantiate SQLite3 for storing on chain transaction data."""
<|body_0|>
def create(self, txid, amount):
"""Create a transaction entry."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OnChainSQLite3:
"""SQLite3 binding for the on-chain transaction model."""
def __init__(self, db=None, db_dir=None):
"""Instantiate SQLite3 for storing on chain transaction data."""
if db_dir is None:
db_dir = OnChainSQLite3.DEFAULT_PAYMENT_DB_DIR
if db is None:
... | the_stack_v2_python_sparse | two1/bitserv/models.py | shayanb/two1 | train | 4 |
28cfe63e21c3b9c788d853e633271f2b80d35eea | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AutomaticRepliesMailTips()",
"from .date_time_time_zone import DateTimeTimeZone\nfrom .locale_info import LocaleInfo\nfrom .date_time_time_zone import DateTimeTimeZone\nfrom .locale_info import LocaleInfo\nfields: Dict[str, Callable[[A... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AutomaticRepliesMailTips()
<|end_body_0|>
<|body_start_1|>
from .date_time_time_zone import DateTimeTimeZone
from .locale_info import LocaleInfo
from .date_time_time_zone import ... | AutomaticRepliesMailTips | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutomaticRepliesMailTips:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips:
"""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 cre... | stack_v2_sparse_classes_10k_train_004434 | 3,738 | 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: AutomaticRepliesMailTips",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimi... | 3 | null | Implement the Python class `AutomaticRepliesMailTips` described below.
Class description:
Implement the AutomaticRepliesMailTips class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips: Creates a new instance of the appropriate c... | Implement the Python class `AutomaticRepliesMailTips` described below.
Class description:
Implement the AutomaticRepliesMailTips class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AutomaticRepliesMailTips:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips:
"""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 cre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AutomaticRepliesMailTips:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/automatic_replies_mail_tips.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
080f763229dc6df2d2a54807ffab2b120f726c4e | [
"self.config = config\nprint(config)\nself.model = TiSASRec(config['model'])\nself.num_batch = config['model']['n_users'] // config['model']['batch_size']\nself.bce_criterion = torch.nn.BCEWithLogitsLoss()\nsuper(TiSASRecEngine, self).__init__(config)",
"assert hasattr(self, 'model'), 'Please specify the exact mo... | <|body_start_0|>
self.config = config
print(config)
self.model = TiSASRec(config['model'])
self.num_batch = config['model']['n_users'] // config['model']['batch_size']
self.bce_criterion = torch.nn.BCEWithLogitsLoss()
super(TiSASRecEngine, self).__init__(config)
<|end_bod... | Engine for training & evaluating TiSASRec model. | TiSASRecEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TiSASRecEngine:
"""Engine for training & evaluating TiSASRec model."""
def __init__(self, config):
"""Initialize TiSASRecEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train the model in a single batch."""
<|body_1|... | stack_v2_sparse_classes_10k_train_004435 | 15,823 | permissive | [
{
"docstring": "Initialize TiSASRecEngine Class.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train the model in a single batch.",
"name": "train_single_batch",
"signature": "def train_single_batch(self, batch_data, ratings=None)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_005723 | Implement the Python class `TiSASRecEngine` described below.
Class description:
Engine for training & evaluating TiSASRec model.
Method signatures and docstrings:
- def __init__(self, config): Initialize TiSASRecEngine Class.
- def train_single_batch(self, batch_data, ratings=None): Train the model in a single batch.... | Implement the Python class `TiSASRecEngine` described below.
Class description:
Engine for training & evaluating TiSASRec model.
Method signatures and docstrings:
- def __init__(self, config): Initialize TiSASRecEngine Class.
- def train_single_batch(self, batch_data, ratings=None): Train the model in a single batch.... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class TiSASRecEngine:
"""Engine for training & evaluating TiSASRec model."""
def __init__(self, config):
"""Initialize TiSASRecEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train the model in a single batch."""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TiSASRecEngine:
"""Engine for training & evaluating TiSASRec model."""
def __init__(self, config):
"""Initialize TiSASRecEngine Class."""
self.config = config
print(config)
self.model = TiSASRec(config['model'])
self.num_batch = config['model']['n_users'] // config... | the_stack_v2_python_sparse | beta_rec/models/tisasrec.py | beta-team/beta-recsys | train | 156 |
0d4f7d61f4a35c62f973ef175267e9b3999931d0 | [
"self.kafo = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.bakery = Company.objects.create(name='bakery', caffe=self.kaf... | <|body_start_0|>
self.kafo = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')
self.bakery = Company.objects.cr... | FullExpense model tests. | FullExpenseModelTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullExpenseModelTest:
"""FullExpense model tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_full_expense_validation(self):
"""Check if name is unique across one caffe."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.kaf... | stack_v2_sparse_classes_10k_train_004436 | 8,665 | permissive | [
{
"docstring": "Test data setup.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check if name is unique across one caffe.",
"name": "test_full_expense_validation",
"signature": "def test_full_expense_validation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000432 | Implement the Python class `FullExpenseModelTest` described below.
Class description:
FullExpense model tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_full_expense_validation(self): Check if name is unique across one caffe. | Implement the Python class `FullExpenseModelTest` described below.
Class description:
FullExpense model tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_full_expense_validation(self): Check if name is unique across one caffe.
<|skeleton|>
class FullExpenseModelTest:
"""Full... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class FullExpenseModelTest:
"""FullExpense model tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_full_expense_validation(self):
"""Check if name is unique across one caffe."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FullExpenseModelTest:
"""FullExpense model tests."""
def setUp(self):
"""Test data setup."""
self.kafo = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa'... | the_stack_v2_python_sparse | caffe/cash/test_models.py | VirrageS/io-kawiarnie | train | 3 |
51c6e2082128fc69365c5a1b73acbcd1629bfcca | [
"sign = 1 if x >= 0 else -1\nx *= sign\noutput = 0\nwhile x:\n output = output * 10 + x % 10\n x = x // 10\nif output > 2 ** 31 - 1:\n return 0\nelse:\n return output * sign",
"if not x:\n return x\nsign = 1 if x >= 0 else -1\ndigits = str(x * sign)[::-1]\nindex_zeros = -1\nfor i, d in enumerate(di... | <|body_start_0|>
sign = 1 if x >= 0 else -1
x *= sign
output = 0
while x:
output = output * 10 + x % 10
x = x // 10
if output > 2 ** 31 - 1:
return 0
else:
return output * sign
<|end_body_0|>
<|body_start_1|>
if not... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_naive(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sign = 1 if x >= 0 else -1
x *= sign
output = 0
... | stack_v2_sparse_classes_10k_train_004437 | 1,783 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse_naive",
"signature": "def reverse_naive(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004619 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_naive(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_naive(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x:... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_naive(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
sign = 1 if x >= 0 else -1
x *= sign
output = 0
while x:
output = output * 10 + x % 10
x = x // 10
if output > 2 ** 31 - 1:
return 0
else:
retu... | the_stack_v2_python_sparse | src/lt_7.py | oxhead/CodingYourWay | train | 0 | |
593463b05855cb3ebffac5c7ec4c9ca85eaba891 | [
"super().__init__()\nself._name = name\nself._queue = queue\nself.data_incoming = True",
"while self.data_incoming or len(self._queue):\n if not self._queue:\n logging.info('Consumer %d is sleeping since queue is empty', self._name)\n time.sleep(0.75)\n print(self._queue.get())\n time.sleep... | <|body_start_0|>
super().__init__()
self._name = name
self._queue = queue
self.data_incoming = True
<|end_body_0|>
<|body_start_1|>
while self.data_incoming or len(self._queue):
if not self._queue:
logging.info('Consumer %d is sleeping since queue is ... | The ConsumerThread is responsible for consuming data from the queue and printing it out to the console. | ConsumerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerThread:
"""The ConsumerThread is responsible for consuming data from the queue and printing it out to the console."""
def __init__(self, queue: CityOverheadTimeQueue, name: int):
"""Initializes the ConsumerThread with the same queue as the one the producer has. It also implem... | stack_v2_sparse_classes_10k_train_004438 | 5,647 | no_license | [
{
"docstring": "Initializes the ConsumerThread with the same queue as the one the producer has. It also implements a data_incoming boolean attribute that is set to True. This attribute should change to False after the producer thread has joined the main thread and finished processing all the cities. :param queu... | 2 | stack_v2_sparse_classes_30k_train_005778 | Implement the Python class `ConsumerThread` described below.
Class description:
The ConsumerThread is responsible for consuming data from the queue and printing it out to the console.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue, name: int): Initializes the ConsumerThread with t... | Implement the Python class `ConsumerThread` described below.
Class description:
The ConsumerThread is responsible for consuming data from the queue and printing it out to the console.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue, name: int): Initializes the ConsumerThread with t... | 5fbc92a7ddd9103076a7095124b5ae108b002f03 | <|skeleton|>
class ConsumerThread:
"""The ConsumerThread is responsible for consuming data from the queue and printing it out to the console."""
def __init__(self, queue: CityOverheadTimeQueue, name: int):
"""Initializes the ConsumerThread with the same queue as the one the producer has. It also implem... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConsumerThread:
"""The ConsumerThread is responsible for consuming data from the queue and printing it out to the console."""
def __init__(self, queue: CityOverheadTimeQueue, name: int):
"""Initializes the ConsumerThread with the same queue as the one the producer has. It also implements a data_i... | the_stack_v2_python_sparse | Labs/Lab10/producer_consumer.py | pyopoly/3522_A00699267 | train | 0 |
c2e08ad7a9b011d8d75b037d09501879b2bbb829 | [
"dict.__init__(self)\nself.context = context\nself[GTPL_CONDITION] = {}\nself.trace_id = (0, 'templates')\nreturn",
"self.trace_id = trace_dict[xml_templates_element]\nfor template_entry in xml_templates_element:\n template_type = template_entry.tag.split('}')[-1]\n if template_type != GTPL_CONDITION:\n ... | <|body_start_0|>
dict.__init__(self)
self.context = context
self[GTPL_CONDITION] = {}
self.trace_id = (0, 'templates')
return
<|end_body_0|>
<|body_start_1|>
self.trace_id = trace_dict[xml_templates_element]
for template_entry in xml_templates_element:
... | Dictionary of GEAR templates by type | GearTemplates | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GearTemplates:
"""Dictionary of GEAR templates by type"""
def __init__(self, context):
"""Create the dictionary of GEAR templates Only condition templates are supported at this point"""
<|body_0|>
def read_from_xml(self, xml_templates_element, trace_dict):
"""Add... | stack_v2_sparse_classes_10k_train_004439 | 3,618 | no_license | [
{
"docstring": "Create the dictionary of GEAR templates Only condition templates are supported at this point",
"name": "__init__",
"signature": "def __init__(self, context)"
},
{
"docstring": "Add template info defined in an XML templates element",
"name": "read_from_xml",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_000639 | Implement the Python class `GearTemplates` described below.
Class description:
Dictionary of GEAR templates by type
Method signatures and docstrings:
- def __init__(self, context): Create the dictionary of GEAR templates Only condition templates are supported at this point
- def read_from_xml(self, xml_templates_elem... | Implement the Python class `GearTemplates` described below.
Class description:
Dictionary of GEAR templates by type
Method signatures and docstrings:
- def __init__(self, context): Create the dictionary of GEAR templates Only condition templates are supported at this point
- def read_from_xml(self, xml_templates_elem... | eba6c1489b503fdcf040a126942643b355867bcd | <|skeleton|>
class GearTemplates:
"""Dictionary of GEAR templates by type"""
def __init__(self, context):
"""Create the dictionary of GEAR templates Only condition templates are supported at this point"""
<|body_0|>
def read_from_xml(self, xml_templates_element, trace_dict):
"""Add... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GearTemplates:
"""Dictionary of GEAR templates by type"""
def __init__(self, context):
"""Create the dictionary of GEAR templates Only condition templates are supported at this point"""
dict.__init__(self)
self.context = context
self[GTPL_CONDITION] = {}
self.trace... | the_stack_v2_python_sparse | src/ibm/teal/analyzer/gear/templates.py | ppjsand/pyteal | train | 1 |
4a10c9acd1e120037f209fc0b785774b4e0004b5 | [
"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... | TimeSeriesStreamingServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSeriesStreamingServicer:
def MetaDataCoordination(self, request, context):
"""Back-and-forth needed to coordinate server with client"""
<|body_0|>
def RealTimeSeries(self, request, context):
"""Signal consisting of a stream of real-valued samples"""
<|bod... | stack_v2_sparse_classes_10k_train_004440 | 3,225 | no_license | [
{
"docstring": "Back-and-forth needed to coordinate server with client",
"name": "MetaDataCoordination",
"signature": "def MetaDataCoordination(self, request, context)"
},
{
"docstring": "Signal consisting of a stream of real-valued samples",
"name": "RealTimeSeries",
"signature": "def R... | 3 | stack_v2_sparse_classes_30k_train_003870 | Implement the Python class `TimeSeriesStreamingServicer` described below.
Class description:
Implement the TimeSeriesStreamingServicer class.
Method signatures and docstrings:
- def MetaDataCoordination(self, request, context): Back-and-forth needed to coordinate server with client
- def RealTimeSeries(self, request,... | Implement the Python class `TimeSeriesStreamingServicer` described below.
Class description:
Implement the TimeSeriesStreamingServicer class.
Method signatures and docstrings:
- def MetaDataCoordination(self, request, context): Back-and-forth needed to coordinate server with client
- def RealTimeSeries(self, request,... | 7760c23893968aed84d9659b082932c97c20460e | <|skeleton|>
class TimeSeriesStreamingServicer:
def MetaDataCoordination(self, request, context):
"""Back-and-forth needed to coordinate server with client"""
<|body_0|>
def RealTimeSeries(self, request, context):
"""Signal consisting of a stream of real-valued samples"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TimeSeriesStreamingServicer:
def MetaDataCoordination(self, request, context):
"""Back-and-forth needed to coordinate server with client"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not imple... | the_stack_v2_python_sparse | signal_server_to_client/time_series_streaming_pb2_grpc.py | iansmorrison/gRPC_Python_API | train | 0 | |
8fd7353e4769d95986a91f882e3ec7dab72f94ff | [
"self.patience = patience\nself.verbose = verbose\nself.counter = 0\nself.best_score = None\nself.early_stop = False\nself.val_loss_min = np.Inf\nself.folder_path = folder_path",
"score = val_loss\nif self.best_score is None:\n self.best_score = score\n self.save_checkpoint(epoch, train_loss, val_loss, mode... | <|body_start_0|>
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_score = None
self.early_stop = False
self.val_loss_min = np.Inf
self.folder_path = folder_path
<|end_body_0|>
<|body_start_1|>
score = val_loss
if self.bes... | Early stops the training if validation loss doesn't improve after a given patience. | EarlyStopping | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, folder_path, patience=7, verbose=False):
"""Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True,... | stack_v2_sparse_classes_10k_train_004441 | 2,522 | no_license | [
{
"docstring": "Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True, prints a message for each validation loss improvement. Default: False path (str): path to folder where tp save the state dict.",
"name": "__init__",
"signature": "def __in... | 3 | stack_v2_sparse_classes_30k_train_002008 | Implement the Python class `EarlyStopping` described below.
Class description:
Early stops the training if validation loss doesn't improve after a given patience.
Method signatures and docstrings:
- def __init__(self, folder_path, patience=7, verbose=False): Args: patience (int): How long to wait after last time vali... | Implement the Python class `EarlyStopping` described below.
Class description:
Early stops the training if validation loss doesn't improve after a given patience.
Method signatures and docstrings:
- def __init__(self, folder_path, patience=7, verbose=False): Args: patience (int): How long to wait after last time vali... | 6311e012ceb4e6a1a45fdd5237a3b629c5319f8c | <|skeleton|>
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, folder_path, patience=7, verbose=False):
"""Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, folder_path, patience=7, verbose=False):
"""Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True, prints a mes... | the_stack_v2_python_sparse | point_cloud_input/early_stopping.py | jtpils/master_thesis | train | 2 |
1451ccf5ff0951b9c8a222db4384a22ec0166fec | [
"super(FeedForwardModule, self).__init__()\nself.layer_norm = LayerNorm(input_feat)\nself.w_1 = torch.nn.Linear(input_feat, hidden_units, bias=bias)\nself.w_2 = torch.nn.Linear(hidden_units, input_feat, bias=bias)\nself.dropout1 = torch.nn.Dropout(dropout1)\nself.dropout2 = torch.nn.Dropout(dropout2)\nself.activati... | <|body_start_0|>
super(FeedForwardModule, self).__init__()
self.layer_norm = LayerNorm(input_feat)
self.w_1 = torch.nn.Linear(input_feat, hidden_units, bias=bias)
self.w_2 = torch.nn.Linear(hidden_units, input_feat, bias=bias)
self.dropout1 = torch.nn.Dropout(dropout1)
se... | Positionwise feed forward layer used in conformer | FeedForwardModule | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedForwardModule:
"""Positionwise feed forward layer used in conformer"""
def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True):
"""Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for ... | stack_v2_sparse_classes_10k_train_004442 | 9,087 | permissive | [
{
"docstring": "Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for layer1 dropout2: dropout value for layer2 activation_fn: Name of activation function bias: If linear layers should have bias",
"name": "__init__",
"signature": "def __init__(self, in... | 2 | null | Implement the Python class `FeedForwardModule` described below.
Class description:
Positionwise feed forward layer used in conformer
Method signatures and docstrings:
- def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True): Args: input_feat: Input feature dimension hidden_... | Implement the Python class `FeedForwardModule` described below.
Class description:
Positionwise feed forward layer used in conformer
Method signatures and docstrings:
- def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True): Args: input_feat: Input feature dimension hidden_... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class FeedForwardModule:
"""Positionwise feed forward layer used in conformer"""
def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True):
"""Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeedForwardModule:
"""Positionwise feed forward layer used in conformer"""
def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True):
"""Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for layer1 dropou... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/conformer_layer.py | microsoft/unilm | train | 15,313 |
e9ad7b3c2636fb38e377a562443f6c87e2f8255b | [
"self.X_mn = self.load_base_connectome(base_filename)\nr_state = np.random.RandomState(signature_seed)\nself.sigs = self.generate_injury_signatures(self.X_mn, n_injuries, r_state)",
"X, Y = self.sample_injury_strengths(n_samples, self.X_mn, self.sigs[0], self.sigs[1], noise_weight)\nassert X.shape[0] == n_samples... | <|body_start_0|>
self.X_mn = self.load_base_connectome(base_filename)
r_state = np.random.RandomState(signature_seed)
self.sigs = self.generate_injury_signatures(self.X_mn, n_injuries, r_state)
<|end_body_0|>
<|body_start_1|>
X, Y = self.sample_injury_strengths(n_samples, self.X_mn, sel... | ConnectomeInjury | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectomeInjury:
def __init__(self, base_filename, n_injuries=2, signature_seed=333):
"""Use to create synthetic injury data."""
<|body_0|>
def generate_injury(self, n_samples=100, noise_weight=0.125):
"""Return n_samples of synthetic injury data and corresponding i... | stack_v2_sparse_classes_10k_train_004443 | 8,625 | permissive | [
{
"docstring": "Use to create synthetic injury data.",
"name": "__init__",
"signature": "def __init__(self, base_filename, n_injuries=2, signature_seed=333)"
},
{
"docstring": "Return n_samples of synthetic injury data and corresponding injury strength.",
"name": "generate_injury",
"sign... | 5 | stack_v2_sparse_classes_30k_val_000356 | Implement the Python class `ConnectomeInjury` described below.
Class description:
Implement the ConnectomeInjury class.
Method signatures and docstrings:
- def __init__(self, base_filename, n_injuries=2, signature_seed=333): Use to create synthetic injury data.
- def generate_injury(self, n_samples=100, noise_weight=... | Implement the Python class `ConnectomeInjury` described below.
Class description:
Implement the ConnectomeInjury class.
Method signatures and docstrings:
- def __init__(self, base_filename, n_injuries=2, signature_seed=333): Use to create synthetic injury data.
- def generate_injury(self, n_samples=100, noise_weight=... | 7a807ed690929563ce36086eaf0998d0e8856aea | <|skeleton|>
class ConnectomeInjury:
def __init__(self, base_filename, n_injuries=2, signature_seed=333):
"""Use to create synthetic injury data."""
<|body_0|>
def generate_injury(self, n_samples=100, noise_weight=0.125):
"""Return n_samples of synthetic injury data and corresponding i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConnectomeInjury:
def __init__(self, base_filename, n_injuries=2, signature_seed=333):
"""Use to create synthetic injury data."""
self.X_mn = self.load_base_connectome(base_filename)
r_state = np.random.RandomState(signature_seed)
self.sigs = self.generate_injury_signatures(sel... | the_stack_v2_python_sparse | pynet/datasets/connectome.py | Duplums/pynet | train | 0 | |
caf083eb67f04310670b050b0707ef54be1b9537 | [
"n = len(nums)\ndp = [0] * n\ndp[-1] = 1\nfor i in range(n - 2, -1, -1):\n for j in range(i + 1, n):\n if dp[j] == 1 and nums[i] >= j - i:\n dp[i] = 1\n break\nreturn dp[0]",
"n = len(nums)\ndp = [False] * n\ndp[-1] = True\nindex = n - 1\nfor i in range(n - 2, -1, -1):\n if inde... | <|body_start_0|>
n = len(nums)
dp = [0] * n
dp[-1] = 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if dp[j] == 1 and nums[i] >= j - i:
dp[i] = 1
break
return dp[0]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_2... | stack_v2_sparse_classes_10k_train_004444 | 1,572 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",... | 4 | stack_v2_sparse_classes_30k_train_000640 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype:... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_2... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
n = len(nums)
dp = [0] * n
dp[-1] = 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if dp[j] == 1 and nums[i] >= j - i:
dp[i] = 1
... | the_stack_v2_python_sparse | 0055_Jump_Game.py | bingli8802/leetcode | train | 0 | |
b5e97b34b7b58e6f7e5e008d440401792011b40b | [
"if reference is not None and query is not None:\n raise ValueError('Both reference and query params provided')\nif reference is not None:\n sieve = ItemImplicitSieve(data, reference)\nif query is not None:\n sieve = ItemExplicitSieve(data, query)\nreturn sieve",
"if isinstance(reference_query_sieve, (li... | <|body_start_0|>
if reference is not None and query is not None:
raise ValueError('Both reference and query params provided')
if reference is not None:
sieve = ItemImplicitSieve(data, reference)
if query is not None:
sieve = ItemExplicitSieve(data, query)
... | ItemSievesFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemSievesFactory:
def from_ref_and_query(data, reference=None, query=None):
"""Both reference and query must not be provided at the same time :param data: DataSet of the sieve :param reference: A list of item keys :param query: An explicit query"""
<|body_0|>
def from_rqs(d... | stack_v2_sparse_classes_10k_train_004445 | 12,842 | no_license | [
{
"docstring": "Both reference and query must not be provided at the same time :param data: DataSet of the sieve :param reference: A list of item keys :param query: An explicit query",
"name": "from_ref_and_query",
"signature": "def from_ref_and_query(data, reference=None, query=None)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_006583 | Implement the Python class `ItemSievesFactory` described below.
Class description:
Implement the ItemSievesFactory class.
Method signatures and docstrings:
- def from_ref_and_query(data, reference=None, query=None): Both reference and query must not be provided at the same time :param data: DataSet of the sieve :para... | Implement the Python class `ItemSievesFactory` described below.
Class description:
Implement the ItemSievesFactory class.
Method signatures and docstrings:
- def from_ref_and_query(data, reference=None, query=None): Both reference and query must not be provided at the same time :param data: DataSet of the sieve :para... | 76761cf513a438a7bc24f6ffa748c9ccacb6e4b4 | <|skeleton|>
class ItemSievesFactory:
def from_ref_and_query(data, reference=None, query=None):
"""Both reference and query must not be provided at the same time :param data: DataSet of the sieve :param reference: A list of item keys :param query: An explicit query"""
<|body_0|>
def from_rqs(d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ItemSievesFactory:
def from_ref_and_query(data, reference=None, query=None):
"""Both reference and query must not be provided at the same time :param data: DataSet of the sieve :param reference: A list of item keys :param query: An explicit query"""
if reference is not None and query is not No... | the_stack_v2_python_sparse | indyva/dynamics/sieve.py | crispamares/indyva | train | 1 | |
2ca8b52e3f9e8f2192f8b33935f2d363cd13fc38 | [
"connection = pymysql.connect(host='31.31.196.245', user='u0981115', password='qwert5656', database='u0981115_itsunrise', charset='utf8mb4')\ncursor = connection.cursor()\ncursor.execute(self)\nOTV = cursor.fetchall()\nreturn OTV",
"connection = pymysql.connect(host='31.31.196.245', user='u0981115', password='qwe... | <|body_start_0|>
connection = pymysql.connect(host='31.31.196.245', user='u0981115', password='qwert5656', database='u0981115_itsunrise', charset='utf8mb4')
cursor = connection.cursor()
cursor.execute(self)
OTV = cursor.fetchall()
return OTV
<|end_body_0|>
<|body_start_1|>
... | Работа с Базой данных получить данные:: DB.GET('Текст запроса SQL') отправить данные:: DB.POST('Текст запроса SQL') | DB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DB:
"""Работа с Базой данных получить данные:: DB.GET('Текст запроса SQL') отправить данные:: DB.POST('Текст запроса SQL')"""
def GET(self):
"""Получает данные с Базы данных"""
<|body_0|>
def POST(self):
"""Отправляет данные в Базу данных"""
<|body_1|>
<... | stack_v2_sparse_classes_10k_train_004446 | 8,580 | no_license | [
{
"docstring": "Получает данные с Базы данных",
"name": "GET",
"signature": "def GET(self)"
},
{
"docstring": "Отправляет данные в Базу данных",
"name": "POST",
"signature": "def POST(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004787 | Implement the Python class `DB` described below.
Class description:
Работа с Базой данных получить данные:: DB.GET('Текст запроса SQL') отправить данные:: DB.POST('Текст запроса SQL')
Method signatures and docstrings:
- def GET(self): Получает данные с Базы данных
- def POST(self): Отправляет данные в Базу данных | Implement the Python class `DB` described below.
Class description:
Работа с Базой данных получить данные:: DB.GET('Текст запроса SQL') отправить данные:: DB.POST('Текст запроса SQL')
Method signatures and docstrings:
- def GET(self): Получает данные с Базы данных
- def POST(self): Отправляет данные в Базу данных
<|... | 0b9727d2c7ef8b76d4ed5a3344f17bfb215f9c73 | <|skeleton|>
class DB:
"""Работа с Базой данных получить данные:: DB.GET('Текст запроса SQL') отправить данные:: DB.POST('Текст запроса SQL')"""
def GET(self):
"""Получает данные с Базы данных"""
<|body_0|>
def POST(self):
"""Отправляет данные в Базу данных"""
<|body_1|>
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DB:
"""Работа с Базой данных получить данные:: DB.GET('Текст запроса SQL') отправить данные:: DB.POST('Текст запроса SQL')"""
def GET(self):
"""Получает данные с Базы данных"""
connection = pymysql.connect(host='31.31.196.245', user='u0981115', password='qwert5656', database='u0981115_its... | the_stack_v2_python_sparse | site/site.py | WTTeneger/ITSunrise_MCH | train | 0 |
e405d7988a62c1d40b8c40719db965e35556ad29 | [
"super(VGG16Classfier, self).__init__()\nself.flatten = P.Flatten()\nself.relu = nn.ReLU()\nself.fc1 = _fc(in_channels=7 * 7 * 512, out_channels=4096)\nself.fc2 = _fc(in_channels=4096, out_channels=4096)\nself.reshape = P.Reshape()\nself.dropout = nn.Dropout(p=0.5)",
"x = self.reshape(x, (-1, 7 * 7 * 512))\nx = s... | <|body_start_0|>
super(VGG16Classfier, self).__init__()
self.flatten = P.Flatten()
self.relu = nn.ReLU()
self.fc1 = _fc(in_channels=7 * 7 * 512, out_channels=4096)
self.fc2 = _fc(in_channels=4096, out_channels=4096)
self.reshape = P.Reshape()
self.dropout = nn.Dro... | VGG16Classfier | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG16Classfier:
def __init__(self):
"""VGG16 classfier structure"""
<|body_0|>
def construct(self, x):
""":param x: shape=(B, 512, 7, 7) :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(VGG16Classfier, self).__init__()
self.fla... | stack_v2_sparse_classes_10k_train_004447 | 5,998 | permissive | [
{
"docstring": "VGG16 classfier structure",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param x: shape=(B, 512, 7, 7) :return:",
"name": "construct",
"signature": "def construct(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002289 | Implement the Python class `VGG16Classfier` described below.
Class description:
Implement the VGG16Classfier class.
Method signatures and docstrings:
- def __init__(self): VGG16 classfier structure
- def construct(self, x): :param x: shape=(B, 512, 7, 7) :return: | Implement the Python class `VGG16Classfier` described below.
Class description:
Implement the VGG16Classfier class.
Method signatures and docstrings:
- def __init__(self): VGG16 classfier structure
- def construct(self, x): :param x: shape=(B, 512, 7, 7) :return:
<|skeleton|>
class VGG16Classfier:
def __init__(... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class VGG16Classfier:
def __init__(self):
"""VGG16 classfier structure"""
<|body_0|>
def construct(self, x):
""":param x: shape=(B, 512, 7, 7) :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VGG16Classfier:
def __init__(self):
"""VGG16 classfier structure"""
super(VGG16Classfier, self).__init__()
self.flatten = P.Flatten()
self.relu = nn.ReLU()
self.fc1 = _fc(in_channels=7 * 7 * 512, out_channels=4096)
self.fc2 = _fc(in_channels=4096, out_channels=4... | the_stack_v2_python_sparse | official/cv/CTPN/src/CTPN/vgg16.py | mindspore-ai/models | train | 301 | |
d6e7fa50785ceaf02442276608ad24910e38d016 | [
"published = super(PageManager, self).published(for_user=for_user)\nunauthenticated = for_user and (not is_authenticated(for_user))\nif unauthenticated and (not include_login_required) and (not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED):\n published = published.exclude(login_required=True)\nreturn publishe... | <|body_start_0|>
published = super(PageManager, self).published(for_user=for_user)
unauthenticated = for_user and (not is_authenticated(for_user))
if unauthenticated and (not include_login_required) and (not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED):
published = published.excl... | PageManager | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageManager:
def published(self, for_user=None, include_login_required=False):
"""Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. Th... | stack_v2_sparse_classes_10k_train_004448 | 4,052 | permissive | [
{
"docstring": "Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. The extra ``include_login_required`` arg allows callers to override the ``PAGES_PUBLISHED_IN... | 2 | stack_v2_sparse_classes_30k_test_000239 | Implement the Python class `PageManager` described below.
Class description:
Implement the PageManager class.
Method signatures and docstrings:
- def published(self, for_user=None, include_login_required=False): Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the... | Implement the Python class `PageManager` described below.
Class description:
Implement the PageManager class.
Method signatures and docstrings:
- def published(self, for_user=None, include_login_required=False): Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the... | 29203de1d111a6d94d576a89430b37edd24cef55 | <|skeleton|>
class PageManager:
def published(self, for_user=None, include_login_required=False):
"""Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PageManager:
def published(self, for_user=None, include_login_required=False):
"""Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. The extra ``incl... | the_stack_v2_python_sparse | mezzanine/pages/managers.py | fermorltd/mezzanine | train | 6 | |
abce315d17b908297a366f0c835a9c58aff88735 | [
"self._remove_spcPts()\nspcPct = self.get_or_add_spcPct()\nspcPct.val = value",
"self._remove_spcPct()\nspcPts = self.get_or_add_spcPts()\nspcPts.val = value"
] | <|body_start_0|>
self._remove_spcPts()
spcPct = self.get_or_add_spcPct()
spcPct.val = value
<|end_body_0|>
<|body_start_1|>
self._remove_spcPct()
spcPts = self.get_or_add_spcPts()
spcPts.val = value
<|end_body_1|>
| Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements. | CT_TextSpacing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_TextSpacing:
"""Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements."""
def set_spcPct(self, value):
"""Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present."""
<|body_0|>
def set_spcPts(self, value):
"""Set spacing to *v... | stack_v2_sparse_classes_10k_train_004449 | 15,294 | permissive | [
{
"docstring": "Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present.",
"name": "set_spcPct",
"signature": "def set_spcPct(self, value)"
},
{
"docstring": "Set spacing to *value* points. A ./a:spcPct child is removed if present.",
"name": "set_spcPts",
... | 2 | null | Implement the Python class `CT_TextSpacing` described below.
Class description:
Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements.
Method signatures and docstrings:
- def set_spcPct(self, value): Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present.
- def set_spcPts(self, valu... | Implement the Python class `CT_TextSpacing` described below.
Class description:
Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements.
Method signatures and docstrings:
- def set_spcPct(self, value): Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present.
- def set_spcPts(self, valu... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_TextSpacing:
"""Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements."""
def set_spcPct(self, value):
"""Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present."""
<|body_0|>
def set_spcPts(self, value):
"""Set spacing to *v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CT_TextSpacing:
"""Used for <a:lnSpc>, <a:spcBef>, and <a:spcAft> elements."""
def set_spcPct(self, value):
"""Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is removed if present."""
self._remove_spcPts()
spcPct = self.get_or_add_spcPct()
spcPct.val = v... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/text.py | ryfeus/lambda-packs | train | 1,283 |
a8a1415f5b14701c989bebce54ad0ede4fbf9a4c | [
"super(Critic, self).__init__()\ninput_shape = (state_size + action_size) * 2\nself.seed = torch.manual_seed(seed)\nself.fc1 = nn.Linear(input_shape, layer_in_out[0])\nself.fc2 = nn.Linear(layer_in_out[0], layer_in_out[1])\nself.fc3 = nn.Linear(layer_in_out[1], 1)\nself.bn1 = nn.BatchNorm1d(layer_in_out[0])\nself.r... | <|body_start_0|>
super(Critic, self).__init__()
input_shape = (state_size + action_size) * 2
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(input_shape, layer_in_out[0])
self.fc2 = nn.Linear(layer_in_out[0], layer_in_out[1])
self.fc3 = nn.Linear(layer_in_out[1],... | Critic (Value) Model. | Critic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Critic (Value) Model."""
def __init__(self, state_size, action_size, layer_in_out, seed):
"""Initialize parameters and build model. Params ====== input_size (int): number of dimensions for input layer seed (int): random seed fc1_units (int): number of nodes in the first hi... | stack_v2_sparse_classes_10k_train_004450 | 2,775 | no_license | [
{
"docstring": "Initialize parameters and build model. Params ====== input_size (int): number of dimensions for input layer seed (int): random seed fc1_units (int): number of nodes in the first hidden layer fc2_units (int): number of nodes in the second hidden layer",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_006416 | Implement the Python class `Critic` described below.
Class description:
Critic (Value) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, layer_in_out, seed): Initialize parameters and build model. Params ====== input_size (int): number of dimensions for input layer seed (int): ran... | Implement the Python class `Critic` described below.
Class description:
Critic (Value) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, layer_in_out, seed): Initialize parameters and build model. Params ====== input_size (int): number of dimensions for input layer seed (int): ran... | 31e9aca1a97e83d323eea46287048bc6a3a0fb5f | <|skeleton|>
class Critic:
"""Critic (Value) Model."""
def __init__(self, state_size, action_size, layer_in_out, seed):
"""Initialize parameters and build model. Params ====== input_size (int): number of dimensions for input layer seed (int): random seed fc1_units (int): number of nodes in the first hi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Critic:
"""Critic (Value) Model."""
def __init__(self, state_size, action_size, layer_in_out, seed):
"""Initialize parameters and build model. Params ====== input_size (int): number of dimensions for input layer seed (int): random seed fc1_units (int): number of nodes in the first hidden layer fc... | the_stack_v2_python_sparse | src/collab_compete/model.py | Sardhendu/DeepRL | train | 3 |
24279632f980c7ee174612d490f01a5ec4b5317f | [
"self.cap = capacity\nself.cnt = collections.defaultdict(int)\nself.cache = {}\nself.visited = collections.deque()",
"if key in self.cache:\n self.visited.append(key)\n self.cnt[key] += 1\n return self.cache[key]\nreturn -1",
"if key not in self.cache and len(self.cache) >= self.cap:\n while self.vi... | <|body_start_0|>
self.cap = capacity
self.cnt = collections.defaultdict(int)
self.cache = {}
self.visited = collections.deque()
<|end_body_0|>
<|body_start_1|>
if key in self.cache:
self.visited.append(key)
self.cnt[key] += 1
return self.cache... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_004451 | 2,031 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_004752 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 28d47c9488d47921769f40383ea9ffe2c56f3597 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.cnt = collections.defaultdict(int)
self.cache = {}
self.visited = collections.deque()
def get(self, key):
""":type key: int :rtype: int"""
if key in self.cach... | the_stack_v2_python_sparse | 146. LRU Cache.py | liangliannie/LeetCode | train | 0 | |
bb0e4a9572b41f66038410fbc7dfa6c7f2c1a779 | [
"super(LikelihoodWeighting, self).__init__()\nself.model = LWCopoutine(model)\nself.current_score = 0.0\nself.samples = []",
"samples = []\nfor i in range(num_samples):\n rv = self.model(*args, **kwargs)\n samples.append([i, rv, self.model.current_score])\nreturn samples"
] | <|body_start_0|>
super(LikelihoodWeighting, self).__init__()
self.model = LWCopoutine(model)
self.current_score = 0.0
self.samples = []
<|end_body_0|>
<|body_start_1|>
samples = []
for i in range(num_samples):
rv = self.model(*args, **kwargs)
samp... | LikelihoodWeighting | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikelihoodWeighting:
def __init__(self, model, *args, **kwargs):
"""Call parent class initially, then setup the couroutines to run"""
<|body_0|>
def runner(self, num_samples, *args, **kwargs):
"""Main function of an Infer object, automatically switches context with c... | stack_v2_sparse_classes_10k_train_004452 | 2,758 | permissive | [
{
"docstring": "Call parent class initially, then setup the couroutines to run",
"name": "__init__",
"signature": "def __init__(self, model, *args, **kwargs)"
},
{
"docstring": "Main function of an Infer object, automatically switches context with copoutine",
"name": "runner",
"signature... | 2 | stack_v2_sparse_classes_30k_train_006238 | Implement the Python class `LikelihoodWeighting` described below.
Class description:
Implement the LikelihoodWeighting class.
Method signatures and docstrings:
- def __init__(self, model, *args, **kwargs): Call parent class initially, then setup the couroutines to run
- def runner(self, num_samples, *args, **kwargs):... | Implement the Python class `LikelihoodWeighting` described below.
Class description:
Implement the LikelihoodWeighting class.
Method signatures and docstrings:
- def __init__(self, model, *args, **kwargs): Call parent class initially, then setup the couroutines to run
- def runner(self, num_samples, *args, **kwargs):... | 35b26902d30cb642cf9048c6a997ed741d951879 | <|skeleton|>
class LikelihoodWeighting:
def __init__(self, model, *args, **kwargs):
"""Call parent class initially, then setup the couroutines to run"""
<|body_0|>
def runner(self, num_samples, *args, **kwargs):
"""Main function of an Infer object, automatically switches context with c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LikelihoodWeighting:
def __init__(self, model, *args, **kwargs):
"""Call parent class initially, then setup the couroutines to run"""
super(LikelihoodWeighting, self).__init__()
self.model = LWCopoutine(model)
self.current_score = 0.0
self.samples = []
def runner(s... | the_stack_v2_python_sparse | pyro/infer/abstract_infer.py | hoangcuong2011/pyro | train | 0 | |
9341805455df3fb6100971394d95e09b4c1e1c64 | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\nreturn [-1, -1]",
"d = {}\nfor idx, n in enumerate(nums):\n if target - n in d.keys():\n return [d[target - n], idx]\n else:\n d[n] = idx\nreturn [-1, -1]",
... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return [-1, -1]
<|end_body_0|>
<|body_start_1|>
d = {}
for idx, n in enumerate(nums):
if target - n in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum_3(self, nums, t... | stack_v2_sparse_classes_10k_train_004453 | 1,617 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_2",
"signature": "def twoSum_2(self, nums, target... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_2(self, nums, target): :type nums: List[int] :type target: int :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_2(self, nums, target): :type nums: List[int] :type target: int :rtype: Li... | 8cdb97bc7588b96b91b1c550afd84e976c1926e0 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum_3(self, nums, t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return [-1, -1]
de... | the_stack_v2_python_sparse | Array/2Sum.py | ZhengLiangliang1996/Leetcode_ML_Daily | train | 1 | |
816b1945f37628be0ff9e92dc52a970ad6ce9c3f | [
"super().__init__(**kwargs)\nself.func = func\nself.args = args or {}",
"response = self.func(**self.args)\nif response.status_code > 0 and self.skippable:\n response.warning = True\n response.status_code = 0\nreturn response"
] | <|body_start_0|>
super().__init__(**kwargs)
self.func = func
self.args = args or {}
<|end_body_0|>
<|body_start_1|>
response = self.func(**self.args)
if response.status_code > 0 and self.skippable:
response.warning = True
response.status_code = 0
... | A step which execution is a function call. Is composed of a function, arguments, and a message (feedback). | FunctionStep | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionStep:
"""A step which execution is a function call. Is composed of a function, arguments, and a message (feedback)."""
def __init__(self, func, args=None, **kwargs):
"""Constructor."""
<|body_0|>
def execute(self):
"""Execute the function with the given a... | stack_v2_sparse_classes_10k_train_004454 | 1,815 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, func, args=None, **kwargs)"
},
{
"docstring": "Execute the function with the given arguments.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003958 | Implement the Python class `FunctionStep` described below.
Class description:
A step which execution is a function call. Is composed of a function, arguments, and a message (feedback).
Method signatures and docstrings:
- def __init__(self, func, args=None, **kwargs): Constructor.
- def execute(self): Execute the func... | Implement the Python class `FunctionStep` described below.
Class description:
A step which execution is a function call. Is composed of a function, arguments, and a message (feedback).
Method signatures and docstrings:
- def __init__(self, func, args=None, **kwargs): Constructor.
- def execute(self): Execute the func... | 40573024e8ad81430afdda8fc8ceb2acbd55d7d2 | <|skeleton|>
class FunctionStep:
"""A step which execution is a function call. Is composed of a function, arguments, and a message (feedback)."""
def __init__(self, func, args=None, **kwargs):
"""Constructor."""
<|body_0|>
def execute(self):
"""Execute the function with the given a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FunctionStep:
"""A step which execution is a function call. Is composed of a function, arguments, and a message (feedback)."""
def __init__(self, func, args=None, **kwargs):
"""Constructor."""
super().__init__(**kwargs)
self.func = func
self.args = args or {}
def exec... | the_stack_v2_python_sparse | invenio_cli/commands/steps.py | inveniosoftware/invenio-cli | train | 8 |
c1ce0248beb8436e7a53924ce5884e5c28f299f9 | [
"wb = load_workbook(file, read_only=True, data_only=True)\nlogger.debug('In parse(). workbook has %d sheets' % len(wb.worksheets))\nif len(wb.worksheets) > 1:\n reporting.warnings(self.import_uuid, exceptions.IgnoredWorksheetWarning(processed_title=wb.sheetnames[0], ignored_sheet_count=len(wb.worksheets) - 1))\n... | <|body_start_0|>
wb = load_workbook(file, read_only=True, data_only=True)
logger.debug('In parse(). workbook has %d sheets' % len(wb.worksheets))
if len(wb.worksheets) > 1:
reporting.warnings(self.import_uuid, exceptions.IgnoredWorksheetWarning(processed_title=wb.sheetnames[0], ignor... | ExcelParserMixin | [
"BSD-3-Clause",
"BSD-3-Clause-LBNL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelParserMixin:
def parse(self, file):
"""Parses the input as an Excel workbook. :param file: a file-like object :return: the ParseResult read from file, otherwise None :raises OSError: if the file can't be opened :raises EDDImportError: if the file format or content is bad"""
... | stack_v2_sparse_classes_10k_train_004455 | 28,563 | permissive | [
{
"docstring": "Parses the input as an Excel workbook. :param file: a file-like object :return: the ParseResult read from file, otherwise None :raises OSError: if the file can't be opened :raises EDDImportError: if the file format or content is bad",
"name": "parse",
"signature": "def parse(self, file)"... | 2 | null | Implement the Python class `ExcelParserMixin` described below.
Class description:
Implement the ExcelParserMixin class.
Method signatures and docstrings:
- def parse(self, file): Parses the input as an Excel workbook. :param file: a file-like object :return: the ParseResult read from file, otherwise None :raises OSEr... | Implement the Python class `ExcelParserMixin` described below.
Class description:
Implement the ExcelParserMixin class.
Method signatures and docstrings:
- def parse(self, file): Parses the input as an Excel workbook. :param file: a file-like object :return: the ParseResult read from file, otherwise None :raises OSEr... | 271a7041c90572d5d197fba01effde164bc96ca7 | <|skeleton|>
class ExcelParserMixin:
def parse(self, file):
"""Parses the input as an Excel workbook. :param file: a file-like object :return: the ParseResult read from file, otherwise None :raises OSError: if the file can't be opened :raises EDDImportError: if the file format or content is bad"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExcelParserMixin:
def parse(self, file):
"""Parses the input as an Excel workbook. :param file: a file-like object :return: the ParseResult read from file, otherwise None :raises OSError: if the file can't be opened :raises EDDImportError: if the file format or content is bad"""
wb = load_work... | the_stack_v2_python_sparse | server/edd/load/parsers/core.py | JBEI/edd | train | 13 | |
29e45e41330a187e501662ae57fd30b54002cbdf | [
"super(EncoderDecoderReconstructor, self).__init__(conf, output_dim, name)\nself.encoder = encoder_factory.factory(conf)\nself.decoder = asr_decoder_factory.factory(conf, self.output_dim[0])\nself.reconstructor = reconstructor_factory.factory(conf, self.output_dim[1])",
"std_input_noise = float(self.conf['std_inp... | <|body_start_0|>
super(EncoderDecoderReconstructor, self).__init__(conf, output_dim, name)
self.encoder = encoder_factory.factory(conf)
self.decoder = asr_decoder_factory.factory(conf, self.output_dim[0])
self.reconstructor = reconstructor_factory.factory(conf, self.output_dim[1])
<|end_... | a general class for an encoder decoder reconstructor system | EncoderDecoderReconstructor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderDecoderReconstructor:
"""a general class for an encoder decoder reconstructor system"""
def __init__(self, conf, output_dim, name=None):
"""Constructor for this kind of object Args: conf: The classifier configuration output_dim: the classifier output dimension as a tuple of th... | stack_v2_sparse_classes_10k_train_004456 | 4,738 | permissive | [
{
"docstring": "Constructor for this kind of object Args: conf: The classifier configuration output_dim: the classifier output dimension as a tuple of the dimension of the actual outputs and the dimension of the quantized reconstructed audio samples name: the classifier name",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_005527 | Implement the Python class `EncoderDecoderReconstructor` described below.
Class description:
a general class for an encoder decoder reconstructor system
Method signatures and docstrings:
- def __init__(self, conf, output_dim, name=None): Constructor for this kind of object Args: conf: The classifier configuration out... | Implement the Python class `EncoderDecoderReconstructor` described below.
Class description:
a general class for an encoder decoder reconstructor system
Method signatures and docstrings:
- def __init__(self, conf, output_dim, name=None): Constructor for this kind of object Args: conf: The classifier configuration out... | 09586e57bf4c6d29a6679e9bb3a488e09451f08e | <|skeleton|>
class EncoderDecoderReconstructor:
"""a general class for an encoder decoder reconstructor system"""
def __init__(self, conf, output_dim, name=None):
"""Constructor for this kind of object Args: conf: The classifier configuration output_dim: the classifier output dimension as a tuple of th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncoderDecoderReconstructor:
"""a general class for an encoder decoder reconstructor system"""
def __init__(self, conf, output_dim, name=None):
"""Constructor for this kind of object Args: conf: The classifier configuration output_dim: the classifier output dimension as a tuple of the dimension o... | the_stack_v2_python_sparse | nabu/neuralnetworks/classifiers/asr/encoder_decoder_reconstructor.py | chenxinglili/nabu | train | 0 |
894afbec7420c31c65df42d3e367218c3ff39e16 | [
"if fused in (True, None):\n raise ValueError('The TPU version of BatchNormalization does not support fused=True.')\nself.max_shards_for_local = max_shards_for_local\nsuper(BatchNormalization, self).__init__(fused=fused, **kwargs)",
"num_shards = tpu_function.get_tpu_context().number_of_shards\ngroup_assignmen... | <|body_start_0|>
if fused in (True, None):
raise ValueError('The TPU version of BatchNormalization does not support fused=True.')
self.max_shards_for_local = max_shards_for_local
super(BatchNormalization, self).__init__(fused=fused, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | Batch Normalization layer that supports cross replica computation on TPU. This class extends the keras.BatchNormalization implementation by supporting cross replica means and variances. The base class implementation only computes moments based on mini-batch per replica (TPU core). For detailed information of arguments ... | BatchNormalization | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchNormalization:
"""Batch Normalization layer that supports cross replica computation on TPU. This class extends the keras.BatchNormalization implementation by supporting cross replica means and variances. The base class implementation only computes moments based on mini-batch per replica (TPU... | stack_v2_sparse_classes_10k_train_004457 | 26,918 | permissive | [
{
"docstring": "Builds the batch normalization layer. Arguments: fused: If `False`, use the system recommended implementation. Only support `False` in the current implementation. max_shards_for_local: The maximum number of TPU shards that should use local Batch Normalization. Any larger number of shards will us... | 3 | null | Implement the Python class `BatchNormalization` described below.
Class description:
Batch Normalization layer that supports cross replica computation on TPU. This class extends the keras.BatchNormalization implementation by supporting cross replica means and variances. The base class implementation only computes momen... | Implement the Python class `BatchNormalization` described below.
Class description:
Batch Normalization layer that supports cross replica computation on TPU. This class extends the keras.BatchNormalization implementation by supporting cross replica means and variances. The base class implementation only computes momen... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class BatchNormalization:
"""Batch Normalization layer that supports cross replica computation on TPU. This class extends the keras.BatchNormalization implementation by supporting cross replica means and variances. The base class implementation only computes moments based on mini-batch per replica (TPU... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchNormalization:
"""Batch Normalization layer that supports cross replica computation on TPU. This class extends the keras.BatchNormalization implementation by supporting cross replica means and variances. The base class implementation only computes moments based on mini-batch per replica (TPU core). For d... | the_stack_v2_python_sparse | models/official/detection/modeling/architecture/nn_ops.py | tensorflow/tpu | train | 5,627 |
52918d175d5bb55d37edbc3a91a9ec1a61768dc1 | [
"if not isinstance(menu, SpyderMenu):\n raise SpyderAPIError('Menu must be an instance of SpyderMenu!')\nmenu.add_action(action_or_menu, section=section, before=before)",
"from spyder.api.widgets.menus import SpyderMenu\nmenu = SpyderMenu(parent=self, title=text)\nif icon is not None:\n menu.menuAction().se... | <|body_start_0|>
if not isinstance(menu, SpyderMenu):
raise SpyderAPIError('Menu must be an instance of SpyderMenu!')
menu.add_action(action_or_menu, section=section, before=before)
<|end_body_0|>
<|body_start_1|>
from spyder.api.widgets.menus import SpyderMenu
menu = Spyder... | Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way. | SpyderMenuMixin | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LGPL-3.0-only",
"LicenseRef-scancode-free-unknown",
"LGPL-3.0-or-later",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-or-later",
"CC-BY-2.5",
"CC-BY-4.0",
"MIT",
"LGPL-2.1-only",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"OF... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpyderMenuMixin:
"""Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way."""
def add_item_to_menu(self, action_or_menu, menu, section=None, before=None):
"""Add a SpyderAction or a QWidget to the m... | stack_v2_sparse_classes_10k_train_004458 | 20,997 | permissive | [
{
"docstring": "Add a SpyderAction or a QWidget to the menu.",
"name": "add_item_to_menu",
"signature": "def add_item_to_menu(self, action_or_menu, menu, section=None, before=None)"
},
{
"docstring": "Create a menu. Parameters ---------- name: str Unique str identifier. text: str or None Localiz... | 4 | stack_v2_sparse_classes_30k_test_000294 | Implement the Python class `SpyderMenuMixin` described below.
Class description:
Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way.
Method signatures and docstrings:
- def add_item_to_menu(self, action_or_menu, menu, section=Non... | Implement the Python class `SpyderMenuMixin` described below.
Class description:
Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way.
Method signatures and docstrings:
- def add_item_to_menu(self, action_or_menu, menu, section=Non... | 0b4929cef420ba6c625566e52200e959f3566f33 | <|skeleton|>
class SpyderMenuMixin:
"""Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way."""
def add_item_to_menu(self, action_or_menu, menu, section=None, before=None):
"""Add a SpyderAction or a QWidget to the m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpyderMenuMixin:
"""Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way."""
def add_item_to_menu(self, action_or_menu, menu, section=None, before=None):
"""Add a SpyderAction or a QWidget to the menu."""
... | the_stack_v2_python_sparse | spyder/api/widgets/mixins.py | juanis2112/spyder | train | 1 |
70fe5cb34093e5a9dc70f344c3fe4eae9bde64a6 | [
"url = 'testurl.com'\noutput = split_url_for_query(url)\nself.assertEqual(output, ('com.testurl.%', '%'))",
"url = 'testurl.com/test'\noutput = split_url_for_query(url)\nself.assertEqual(output, ('com.testurl.%', '%./test%'))",
"url = '*.testurl.com/test'\noutput = split_url_for_query(url)\nself.assertEqual(out... | <|body_start_0|>
url = 'testurl.com'
output = split_url_for_query(url)
self.assertEqual(output, ('com.testurl.%', '%'))
<|end_body_0|>
<|body_start_1|>
url = 'testurl.com/test'
output = split_url_for_query(url)
self.assertEqual(output, ('com.testurl.%', '%./test%'))
<|en... | LinksHelpersTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinksHelpersTest:
def test_split_url_for_query_1(self):
"""Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases"""
<|body_0|>
def test_split_url_for_query_2(self):
"""Given a URL pattern with a path, e... | stack_v2_sparse_classes_10k_train_004459 | 20,276 | permissive | [
{
"docstring": "Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases",
"name": "test_split_url_for_query_1",
"signature": "def test_split_url_for_query_1(self)"
},
{
"docstring": "Given a URL pattern with a path, ensure that our h... | 4 | stack_v2_sparse_classes_30k_train_005563 | Implement the Python class `LinksHelpersTest` described below.
Class description:
Implement the LinksHelpersTest class.
Method signatures and docstrings:
- def test_split_url_for_query_1(self): Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases
- def... | Implement the Python class `LinksHelpersTest` described below.
Class description:
Implement the LinksHelpersTest class.
Method signatures and docstrings:
- def test_split_url_for_query_1(self): Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases
- def... | e536b510482b522e0a804ba9424b58f56b113846 | <|skeleton|>
class LinksHelpersTest:
def test_split_url_for_query_1(self):
"""Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases"""
<|body_0|>
def test_split_url_for_query_2(self):
"""Given a URL pattern with a path, e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinksHelpersTest:
def test_split_url_for_query_1(self):
"""Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases"""
url = 'testurl.com'
output = split_url_for_query(url)
self.assertEqual(output, ('com.testurl.%', ... | the_stack_v2_python_sparse | extlinks/links/tests.py | WikipediaLibrary/externallinks | train | 6 | |
de8e2c61ef548c7b2dc0f74fff9bdc1df469d1d6 | [
"if AuthenticationCode.objects.filter(phone_num=phone, is_active=True).exists():\n record = AuthenticationCode.objects.filter(phone_num=phone, is_active=True).first()\n if (timezone.now() - record.created_at).total_seconds() > seconds:\n AuthenticationCode.objects.filter(phone_num=phone).update(is_acti... | <|body_start_0|>
if AuthenticationCode.objects.filter(phone_num=phone, is_active=True).exists():
record = AuthenticationCode.objects.filter(phone_num=phone, is_active=True).first()
if (timezone.now() - record.created_at).total_seconds() > seconds:
AuthenticationCode.objec... | AuthenticationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationManager:
def already_sent(self, phone, seconds=60):
"""Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold"""
<|body_0|>
def check_code(self, code, phone, seconds=6... | stack_v2_sparse_classes_10k_train_004460 | 7,061 | no_license | [
{
"docstring": "Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold",
"name": "already_sent",
"signature": "def already_sent(self, phone, seconds=60)"
},
{
"docstring": "Check the code :param code au... | 3 | stack_v2_sparse_classes_30k_train_005199 | Implement the Python class `AuthenticationManager` described below.
Class description:
Implement the AuthenticationManager class.
Method signatures and docstrings:
- def already_sent(self, phone, seconds=60): Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone pho... | Implement the Python class `AuthenticationManager` described below.
Class description:
Implement the AuthenticationManager class.
Method signatures and docstrings:
- def already_sent(self, phone, seconds=60): Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone pho... | e3cd0b466393b3e9822a752d27082c063ee79ff6 | <|skeleton|>
class AuthenticationManager:
def already_sent(self, phone, seconds=60):
"""Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold"""
<|body_0|>
def check_code(self, code, phone, seconds=6... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AuthenticationManager:
def already_sent(self, phone, seconds=60):
"""Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold"""
if AuthenticationCode.objects.filter(phone_num=phone, is_active=True).exi... | the_stack_v2_python_sparse | User/models.py | huangy10/SingingVoice | train | 0 | |
9f7529dbf26c0310e72fb4bc06a97a7131da365d | [
"_keys = [0] * val_range\nfor inx in range(0, length):\n key = _array[inx] - 1\n _keys[key] = _keys[key] + 1\nless = 0\nfor inx in range(0, val_range):\n _keys[inx] = less + _keys[inx]\n less = _keys[inx]\nreturn _keys",
"result = [0] * length\nfor inx in range(0, length):\n key = _array[inx]\n ... | <|body_start_0|>
_keys = [0] * val_range
for inx in range(0, length):
key = _array[inx] - 1
_keys[key] = _keys[key] + 1
less = 0
for inx in range(0, val_range):
_keys[inx] = less + _keys[inx]
less = _keys[inx]
return _keys
<|end_bod... | Implementation of Counting Sort Thomas H. Cormen Algorithms Unlocked (2013) page 67 | CountingSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountingSort:
"""Implementation of Counting Sort Thomas H. Cormen Algorithms Unlocked (2013) page 67"""
def count_keys_equal_or_less(_array, length, val_range):
"""computing how many elements have sort keys equal or less to that value :parameters: _array: *list* - array of elements l... | stack_v2_sparse_classes_10k_train_004461 | 2,657 | no_license | [
{
"docstring": "computing how many elements have sort keys equal or less to that value :parameters: _array: *list* - array of elements length: *Number* - length of sorting array valRange: *Number* - max value in sorting array :returns: *list* - An array equal_or_less[0..valRange-1] such that equal_or_less[j] co... | 3 | stack_v2_sparse_classes_30k_train_001939 | Implement the Python class `CountingSort` described below.
Class description:
Implementation of Counting Sort Thomas H. Cormen Algorithms Unlocked (2013) page 67
Method signatures and docstrings:
- def count_keys_equal_or_less(_array, length, val_range): computing how many elements have sort keys equal or less to tha... | Implement the Python class `CountingSort` described below.
Class description:
Implementation of Counting Sort Thomas H. Cormen Algorithms Unlocked (2013) page 67
Method signatures and docstrings:
- def count_keys_equal_or_less(_array, length, val_range): computing how many elements have sort keys equal or less to tha... | 8b3b1f146b7eac5dc15b16aaf837441069cf5989 | <|skeleton|>
class CountingSort:
"""Implementation of Counting Sort Thomas H. Cormen Algorithms Unlocked (2013) page 67"""
def count_keys_equal_or_less(_array, length, val_range):
"""computing how many elements have sort keys equal or less to that value :parameters: _array: *list* - array of elements l... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CountingSort:
"""Implementation of Counting Sort Thomas H. Cormen Algorithms Unlocked (2013) page 67"""
def count_keys_equal_or_less(_array, length, val_range):
"""computing how many elements have sort keys equal or less to that value :parameters: _array: *list* - array of elements length: *Numbe... | the_stack_v2_python_sparse | sort/counting.py | shuvava/python_algorithms | train | 2 |
04df25279e921b7364b345e089441379c0573d05 | [
"if not s:\n return 0\nstr_list = s.split()\nwhile str_list:\n if str_list[-1]:\n return len(str_list[-1])\n else:\n str_list.pop()\nelse:\n return 0",
"if not s:\n return 0\ni = len(s) - 1\nwhile i >= 0:\n if s[i] == ' ':\n i -= 1\n else:\n sub_len = 1\n wh... | <|body_start_0|>
if not s:
return 0
str_list = s.split()
while str_list:
if str_list[-1]:
return len(str_list[-1])
else:
str_list.pop()
else:
return 0
<|end_body_0|>
<|body_start_1|>
if not s:
... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLastWord1(self, s):
"""split string first"""
<|body_0|>
def lengthOfLastWord2(self, s):
"""two pointers (reverse)"""
<|body_1|>
def lengthOfLastWord3(self, s):
"""use str.rstrip"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_004462 | 1,427 | permissive | [
{
"docstring": "split string first",
"name": "lengthOfLastWord1",
"signature": "def lengthOfLastWord1(self, s)"
},
{
"docstring": "two pointers (reverse)",
"name": "lengthOfLastWord2",
"signature": "def lengthOfLastWord2(self, s)"
},
{
"docstring": "use str.rstrip",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_004080 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLastWord1(self, s): split string first
- def lengthOfLastWord2(self, s): two pointers (reverse)
- def lengthOfLastWord3(self, s): use str.rstrip | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLastWord1(self, s): split string first
- def lengthOfLastWord2(self, s): two pointers (reverse)
- def lengthOfLastWord3(self, s): use str.rstrip
<|skeleton|>
class S... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def lengthOfLastWord1(self, s):
"""split string first"""
<|body_0|>
def lengthOfLastWord2(self, s):
"""two pointers (reverse)"""
<|body_1|>
def lengthOfLastWord3(self, s):
"""use str.rstrip"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLastWord1(self, s):
"""split string first"""
if not s:
return 0
str_list = s.split()
while str_list:
if str_list[-1]:
return len(str_list[-1])
else:
str_list.pop()
else:
... | the_stack_v2_python_sparse | leetcode/0058_length_of_last_word.py | chaosWsF/Python-Practice | train | 1 | |
9a0a0d3ec27905246514210f4a7ab9d6fc043992 | [
"if not callable(condition):\n bad_type = type(condition)\n msg = f'Expected callable function for condition, got {bad_type}'\n raise TypeError(msg)\nself.condition = condition\nself.workflow = Workflow(workflow)",
"old_circuit = circuit.copy()\nold_data = data.copy()\nawait self.workflow.run(circuit, da... | <|body_start_0|>
if not callable(condition):
bad_type = type(condition)
msg = f'Expected callable function for condition, got {bad_type}'
raise TypeError(msg)
self.condition = condition
self.workflow = Workflow(workflow)
<|end_body_0|>
<|body_start_1|>
... | The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state. | DoThenDecide | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoThenDecide:
"""The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state."""
def __init__(self, condition: Callable[[Circuit, Circuit], bool], workflow: WorkflowLike) -> None:
"""Con... | stack_v2_sparse_classes_10k_train_004463 | 2,346 | permissive | [
{
"docstring": "Construct a DoThenDecide. Args: condition (Callable[[Circuit, Circuit], bool]): The condition function that determines if the new circuit (second parameter) after running `workflow` should replace the original circuit (first parameter). If the condition returns True, then replace the original ci... | 2 | stack_v2_sparse_classes_30k_train_006949 | Implement the Python class `DoThenDecide` described below.
Class description:
The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state.
Method signatures and docstrings:
- def __init__(self, condition: Callable[[Circu... | Implement the Python class `DoThenDecide` described below.
Class description:
The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state.
Method signatures and docstrings:
- def __init__(self, condition: Callable[[Circu... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class DoThenDecide:
"""The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state."""
def __init__(self, condition: Callable[[Circuit, Circuit], bool], workflow: WorkflowLike) -> None:
"""Con... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DoThenDecide:
"""The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state."""
def __init__(self, condition: Callable[[Circuit, Circuit], bool], workflow: WorkflowLike) -> None:
"""Construct a DoTh... | the_stack_v2_python_sparse | bqskit/passes/control/dothendecide.py | BQSKit/bqskit | train | 54 |
1d4f4e6f207fad81c4bca588960f3a2c7664535d | [
"if self.request.method in permissions.SAFE_METHODS:\n return (permissions.IsAuthenticated(),)\nreturn (permissions.IsAuthenticated(), IsAdminOfTeam())",
"serializer = self.serializer_class(data=request.data)\nif serializer.is_valid():\n team = get_object_or_404(Team.objects.all(), name=serializer.validated... | <|body_start_0|>
if self.request.method in permissions.SAFE_METHODS:
return (permissions.IsAuthenticated(),)
return (permissions.IsAuthenticated(), IsAdminOfTeam())
<|end_body_0|>
<|body_start_1|>
serializer = self.serializer_class(data=request.data)
if serializer.is_valid()... | MemberInTeamViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberInTeamViewSet:
def get_permissions(self):
"""If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated."""
<|b... | stack_v2_sparse_classes_10k_train_004464 | 14,739 | no_license | [
{
"docstring": "If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated.",
"name": "get_permissions",
"signature": "def get_permissions(se... | 4 | stack_v2_sparse_classes_30k_train_003479 | Implement the Python class `MemberInTeamViewSet` described below.
Class description:
Implement the MemberInTeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the tea... | Implement the Python class `MemberInTeamViewSet` described below.
Class description:
Implement the MemberInTeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the tea... | 8f296850eeab1df4c52bb7b9df0681884449e761 | <|skeleton|>
class MemberInTeamViewSet:
def get_permissions(self):
"""If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MemberInTeamViewSet:
def get_permissions(self):
"""If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated."""
if self.request.m... | the_stack_v2_python_sparse | src/web/teams/views.py | CiberRato/pei2015-ciberrato | train | 0 | |
9ecaa0bd85b98ad2aabfacbb1fe22be23e5b3fde | [
"EasyFrame.__init__(self, title='Bouncy')\nself.addLabel(text='Initial Height', row=0, column=0)\nself.heightField = self.addFloatField(value=0.0, row=0, column=1)\nself.addLabel(text='Bounciness Index', row=1, column=0)\nself.indexField = self.addFloatField(value=0.0, row=1, column=1)\nself.addLabel(text='Number o... | <|body_start_0|>
EasyFrame.__init__(self, title='Bouncy')
self.addLabel(text='Initial Height', row=0, column=0)
self.heightField = self.addFloatField(value=0.0, row=0, column=1)
self.addLabel(text='Bounciness Index', row=1, column=0)
self.indexField = self.addFloatField(value=0.0... | BouncyGUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BouncyGUI:
def __init__(self):
"""Set up the window and widgets."""
<|body_0|>
def computeDistance(self):
"""Event handler for the Compute button and set the distanceField."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
EasyFrame.__init__(self, tit... | stack_v2_sparse_classes_10k_train_004465 | 2,472 | no_license | [
{
"docstring": "Set up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Event handler for the Compute button and set the distanceField.",
"name": "computeDistance",
"signature": "def computeDistance(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001522 | Implement the Python class `BouncyGUI` described below.
Class description:
Implement the BouncyGUI class.
Method signatures and docstrings:
- def __init__(self): Set up the window and widgets.
- def computeDistance(self): Event handler for the Compute button and set the distanceField. | Implement the Python class `BouncyGUI` described below.
Class description:
Implement the BouncyGUI class.
Method signatures and docstrings:
- def __init__(self): Set up the window and widgets.
- def computeDistance(self): Event handler for the Compute button and set the distanceField.
<|skeleton|>
class BouncyGUI:
... | 30375264cf0103e3455fdf92c35a2c5c15b5d7ef | <|skeleton|>
class BouncyGUI:
def __init__(self):
"""Set up the window and widgets."""
<|body_0|>
def computeDistance(self):
"""Event handler for the Compute button and set the distanceField."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BouncyGUI:
def __init__(self):
"""Set up the window and widgets."""
EasyFrame.__init__(self, title='Bouncy')
self.addLabel(text='Initial Height', row=0, column=0)
self.heightField = self.addFloatField(value=0.0, row=0, column=1)
self.addLabel(text='Bounciness Index', ro... | the_stack_v2_python_sparse | Ch8 exercises/bouncywithgui.py | davelpat/Fundamentals_of_Python | train | 1 | |
dd511a79c49f7b0e1dc953e36b6bd7b1d2c96be4 | [
"if n in [0, 1]:\n return []\nif n in [2, 3]:\n return [n]\nresult = [2, 3]\nfor each in range(4, n, 1):\n prime = True\n for i in range(2, each - 1):\n if each % i == 0:\n prime = False\n break\n if prime:\n result.append(each)\nreturn result",
"if n in [0, 1]:\... | <|body_start_0|>
if n in [0, 1]:
return []
if n in [2, 3]:
return [n]
result = [2, 3]
for each in range(4, n, 1):
prime = True
for i in range(2, each - 1):
if each % i == 0:
prime = False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def enumeratePrimes(self, n):
""":type n: int :rtype: list of int"""
<|body_0|>
def enumeratePrimes_1(self, n):
""":type n: int :rtype: list of int"""
<|body_1|>
def enumeratePrimes_2(self, n):
""":type n: int :rtype: list of int"""
... | stack_v2_sparse_classes_10k_train_004466 | 2,243 | no_license | [
{
"docstring": ":type n: int :rtype: list of int",
"name": "enumeratePrimes",
"signature": "def enumeratePrimes(self, n)"
},
{
"docstring": ":type n: int :rtype: list of int",
"name": "enumeratePrimes_1",
"signature": "def enumeratePrimes_1(self, n)"
},
{
"docstring": ":type n: i... | 3 | stack_v2_sparse_classes_30k_train_001849 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def enumeratePrimes(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_1(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_2(self, n): :type n: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def enumeratePrimes(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_1(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_2(self, n): :type n: int :... | ec48cbde4356208afac226d41752daffe674be2c | <|skeleton|>
class Solution:
def enumeratePrimes(self, n):
""":type n: int :rtype: list of int"""
<|body_0|>
def enumeratePrimes_1(self, n):
""":type n: int :rtype: list of int"""
<|body_1|>
def enumeratePrimes_2(self, n):
""":type n: int :rtype: list of int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def enumeratePrimes(self, n):
""":type n: int :rtype: list of int"""
if n in [0, 1]:
return []
if n in [2, 3]:
return [n]
result = [2, 3]
for each in range(4, n, 1):
prime = True
for i in range(2, each - 1):
... | the_stack_v2_python_sparse | B2BSWE/Arrays/all_primes_to_n.py | librar127/PythonDS | train | 0 | |
5ee3d66b1c3a1e5b4b3212ab374b0639c7a79cdf | [
"vulnerability = PsirtResult()\nvulnerability.id = data.get('id')\nvulnerability.title = data.get('title')\nvulnerability.bugs = data.get('bugs')\nvulnerability.cves = data.get('cves')\nvulnerability.cvrf = data.get('cvrf')\nvulnerability.oval = data.get('oval')\nvulnerability.cvss = data.get('cvss')\nvulnerability... | <|body_start_0|>
vulnerability = PsirtResult()
vulnerability.id = data.get('id')
vulnerability.title = data.get('title')
vulnerability.bugs = data.get('bugs')
vulnerability.cves = data.get('cves')
vulnerability.cvrf = data.get('cvrf')
vulnerability.oval = data.get... | Ciscoapi PSIRT output parser. Supports both text and json (default) outputs. | PsirtParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PsirtParser:
"""Ciscoapi PSIRT output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data: dict) -> PsirtResult:
"""Convert ciscoapis result dict to PsirtResult object"""
<|body_0|>
def dict_to_results(cls, data: list) -> PsirtResults:
... | stack_v2_sparse_classes_10k_train_004467 | 1,441 | permissive | [
{
"docstring": "Convert ciscoapis result dict to PsirtResult object",
"name": "dict_to_result",
"signature": "def dict_to_result(cls, data: dict) -> PsirtResult"
},
{
"docstring": "Convert list of ciscoapis result dicts to PsirtResults",
"name": "dict_to_results",
"signature": "def dict_... | 2 | stack_v2_sparse_classes_30k_val_000234 | Implement the Python class `PsirtParser` described below.
Class description:
Ciscoapi PSIRT output parser. Supports both text and json (default) outputs.
Method signatures and docstrings:
- def dict_to_result(cls, data: dict) -> PsirtResult: Convert ciscoapis result dict to PsirtResult object
- def dict_to_results(cl... | Implement the Python class `PsirtParser` described below.
Class description:
Ciscoapi PSIRT output parser. Supports both text and json (default) outputs.
Method signatures and docstrings:
- def dict_to_result(cls, data: dict) -> PsirtResult: Convert ciscoapis result dict to PsirtResult object
- def dict_to_results(cl... | bb21ff02965ed0cca5a55ee559eae77856d9866c | <|skeleton|>
class PsirtParser:
"""Ciscoapi PSIRT output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data: dict) -> PsirtResult:
"""Convert ciscoapis result dict to PsirtResult object"""
<|body_0|>
def dict_to_results(cls, data: list) -> PsirtResults:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PsirtParser:
"""Ciscoapi PSIRT output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data: dict) -> PsirtResult:
"""Convert ciscoapis result dict to PsirtResult object"""
vulnerability = PsirtResult()
vulnerability.id = data.get('id')
vul... | the_stack_v2_python_sparse | tools/ciscoapis/parsers.py | collectivesense/aucote | train | 0 |
99ee40f2bb8769328c9ee7f6026f46e1d68681dd | [
"product = ProductFactory(stock_amount=10)\nself.assertEqual(product.left_in_stock, 10)\nself.assertTrue(product.is_available())",
"product = ProductFactory(stock_amount=2)\nOrderProductRelationFactory(product=product, order__open=None)\nopr = OrderProductRelationFactory(product=product, order__open=None)\nself.a... | <|body_start_0|>
product = ProductFactory(stock_amount=10)
self.assertEqual(product.left_in_stock, 10)
self.assertTrue(product.is_available())
<|end_body_0|>
<|body_start_1|>
product = ProductFactory(stock_amount=2)
OrderProductRelationFactory(product=product, order__open=None)
... | Test logic about availability of products. | ProductAvailabilityTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
<|body_0|>
def test_product_not_available_by_stock(self):
"""If max orders have... | stack_v2_sparse_classes_10k_train_004468 | 26,437 | permissive | [
{
"docstring": "If no orders have been made, the product is still available.",
"name": "test_product_available_by_stock",
"signature": "def test_product_available_by_stock(self)"
},
{
"docstring": "If max orders have been made, the product is NOT available.",
"name": "test_product_not_availa... | 6 | null | Implement the Python class `ProductAvailabilityTest` described below.
Class description:
Test logic about availability of products.
Method signatures and docstrings:
- def test_product_available_by_stock(self): If no orders have been made, the product is still available.
- def test_product_not_available_by_stock(self... | Implement the Python class `ProductAvailabilityTest` described below.
Class description:
Test logic about availability of products.
Method signatures and docstrings:
- def test_product_available_by_stock(self): If no orders have been made, the product is still available.
- def test_product_not_available_by_stock(self... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
<|body_0|>
def test_product_not_available_by_stock(self):
"""If max orders have... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
product = ProductFactory(stock_amount=10)
self.assertEqual(product.left_in_stock, 10)
sel... | the_stack_v2_python_sparse | src/shop/tests.py | bornhack/bornhack-website | train | 9 |
dff3540d647350e1afdfacf321ff916dc2db23dc | [
"if n in [0, 1]:\n return 1\nreturn self.climbStairs(n - 1) + self.climbStairs(n - 2)",
"mem = {0: 1, 1: 1}\nfor i in range(n + 1):\n if i not in mem:\n mem[i] = mem[i - 1] + mem[i - 2]\nreturn mem[n]"
] | <|body_start_0|>
if n in [0, 1]:
return 1
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
<|end_body_0|>
<|body_start_1|>
mem = {0: 1, 1: 1}
for i in range(n + 1):
if i not in mem:
mem[i] = mem[i - 1] + mem[i - 2]
return mem[n]
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs1(self, n):
""":type: n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n in [0, 1]:
return 1
return self.climbStair... | stack_v2_sparse_classes_10k_train_004469 | 664 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": ":type: n: int :rtype: int",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs1(self, n): :type: n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs1(self, n): :type: n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs(self, n):
"""... | 857b8c7fccfe8216da59228c1cf3675444855673 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs1(self, n):
""":type: n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
if n in [0, 1]:
return 1
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
def climbStairs1(self, n):
""":type: n: int :rtype: int"""
mem = {0: 1, 1: 1}
for i in range(n +... | the_stack_v2_python_sparse | algorithm/Climbing-Stairs.py | atashi/LLL | train | 0 | |
d7b106f05df134d2fa2d3bfd997385fdd56236ec | [
"requestor = Requestor(local_api_key=api_key)\nurl = cls.class_url()\nwrapped_params = {cls.snakecase_name(): params}\nresponse, api_key = requestor.request(method=RequestMethod.POST, url=url, params=wrapped_params)\nreturn convert_to_easypost_object(response=response, api_key=api_key)",
"if not easypost_id:\n ... | <|body_start_0|>
requestor = Requestor(local_api_key=api_key)
url = cls.class_url()
wrapped_params = {cls.snakecase_name(): params}
response, api_key = requestor.request(method=RequestMethod.POST, url=url, params=wrapped_params)
return convert_to_easypost_object(response=response... | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def create(cls, api_key: Optional[str]=None, **params) -> 'User':
"""Create a child user."""
<|body_0|>
def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'User':
"""Retrieve a user."""
<|body_1|>
def retri... | stack_v2_sparse_classes_10k_train_004470 | 3,246 | permissive | [
{
"docstring": "Create a child user.",
"name": "create",
"signature": "def create(cls, api_key: Optional[str]=None, **params) -> 'User'"
},
{
"docstring": "Retrieve a user.",
"name": "retrieve",
"signature": "def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None,... | 6 | stack_v2_sparse_classes_30k_train_003474 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def create(cls, api_key: Optional[str]=None, **params) -> 'User': Create a child user.
- def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'Use... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def create(cls, api_key: Optional[str]=None, **params) -> 'User': Create a child user.
- def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'Use... | c8f7a3f2472ae5fea13a5b596b4618bd55f3be0c | <|skeleton|>
class User:
def create(cls, api_key: Optional[str]=None, **params) -> 'User':
"""Create a child user."""
<|body_0|>
def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'User':
"""Retrieve a user."""
<|body_1|>
def retri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class User:
def create(cls, api_key: Optional[str]=None, **params) -> 'User':
"""Create a child user."""
requestor = Requestor(local_api_key=api_key)
url = cls.class_url()
wrapped_params = {cls.snakecase_name(): params}
response, api_key = requestor.request(method=RequestMeth... | the_stack_v2_python_sparse | easypost/user.py | dsanders11/easypost-python | train | 0 | |
c63023019111cd51fc6ecaf5602af33e842a6462 | [
"m = len(prices)\nbuy = float('inf')\nres = 0\nfor i in range(m):\n if prices[i] > buy:\n res = max(res, prices[i] - buy)\n else:\n buy = prices[i]\nreturn res",
"stack = []\nres = 0\nfor i in prices:\n flag = 0\n while stack and stack[-1] > i:\n if flag == 0:\n res = m... | <|body_start_0|>
m = len(prices)
buy = float('inf')
res = 0
for i in range(m):
if prices[i] > buy:
res = max(res, prices[i] - buy)
else:
buy = prices[i]
return res
<|end_body_0|>
<|body_start_1|>
stack = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit1(self, prices):
"""[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化"""
<|body_0|>
def maxProfit(self, prices):
"""单调栈: [7,1_最短回文串.py,5,3,6,4] stack = [1_最短回文串.py,2,3] #单调递减栈 出... | stack_v2_sparse_classes_10k_train_004471 | 1,225 | no_license | [
{
"docstring": "[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices)"
},
{
"docstring": "单调栈: [7,1_最短回文串.py,5,3,6,4] stack = [1_最短回文串.py,2,3] #单调递减栈 出栈产生利润",
"na... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices): [7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化
- def maxProfit(self, prices): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices): [7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化
- def maxProfit(self, prices): ... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def maxProfit1(self, prices):
"""[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化"""
<|body_0|>
def maxProfit(self, prices):
"""单调栈: [7,1_最短回文串.py,5,3,6,4] stack = [1_最短回文串.py,2,3] #单调递减栈 出... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit1(self, prices):
"""[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化"""
m = len(prices)
buy = float('inf')
res = 0
for i in range(m):
if prices[i] > buy:
... | the_stack_v2_python_sparse | 3_Offer2nd-HandWriting/6_DP/8_股票的最大利润.py | fzingithub/SwordRefers2Offer | train | 1 | |
6c3761492949c5e01b9ffc33892575fdc908336f | [
"if SeedForumsTasks._large_thread is None:\n return\ndiscussion_id, thread_id = SeedForumsTasks._large_thread\nresponse_id = super(SeedForumsTasks, self).create_response(thread_id)\nif not SeedForumsTasks._large_thread_response_ids or random.randint(1, len(SeedForumsTasks._large_thread_response_ids)) <= 1:\n ... | <|body_start_0|>
if SeedForumsTasks._large_thread is None:
return
discussion_id, thread_id = SeedForumsTasks._large_thread
response_id = super(SeedForumsTasks, self).create_response(thread_id)
if not SeedForumsTasks._large_thread_response_ids or random.randint(1, len(SeedForu... | Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed. * LARGE_THREAD_ID: Thread id for the larg... | SeedForumsTasks | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeedForumsTasks:
"""Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed... | stack_v2_sparse_classes_10k_train_004472 | 14,154 | permissive | [
{
"docstring": "Post a response to an existing thread.",
"name": "create_response",
"signature": "def create_response(self)"
},
{
"docstring": "Post a response to an existing thread.",
"name": "create_comment",
"signature": "def create_comment(self)"
},
{
"docstring": "This on_st... | 3 | stack_v2_sparse_classes_30k_train_006911 | Implement the Python class `SeedForumsTasks` described below.
Class description:
Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be c... | Implement the Python class `SeedForumsTasks` described below.
Class description:
Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be c... | 1a6dc891d2fb72575f354521988a531489f30032 | <|skeleton|>
class SeedForumsTasks:
"""Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeedForumsTasks:
"""Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed. * LARGE_THR... | the_stack_v2_python_sparse | loadtests/lms/forums.py | kavithachandra/edx-load-tests | train | 0 |
5e14428d64985553340d17bbd8968272164cf654 | [
"successor = None\nwhile root:\n if p.val < root.val:\n successor = root\n root = root.left\n else:\n root = root.right\nreturn successor",
"if not root:\n return None\nif root == p:\n node = root.right\n while node and node.left:\n node = node.left\n return node\neli... | <|body_start_0|>
successor = None
while root:
if p.val < root.val:
successor = root
root = root.left
else:
root = root.right
return successor
<|end_body_0|>
<|body_start_1|>
if not root:
return None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderSuccessor(self, root, p):
""":type root: TreeNode :type p: TreeNode :rtype: TreeNode"""
<|body_0|>
def inorderSuccessor_recursive(self, root, p):
""":type root: TreeNode :type p: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_004473 | 2,142 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :rtype: TreeNode",
"name": "inorderSuccessor",
"signature": "def inorderSuccessor(self, root, p)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :rtype: TreeNode",
"name": "inorderSuccessor_recursive",
"signature": "def in... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderSuccessor(self, root, p): :type root: TreeNode :type p: TreeNode :rtype: TreeNode
- def inorderSuccessor_recursive(self, root, p): :type root: TreeNode :type p: TreeNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderSuccessor(self, root, p): :type root: TreeNode :type p: TreeNode :rtype: TreeNode
- def inorderSuccessor_recursive(self, root, p): :type root: TreeNode :type p: TreeNo... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def inorderSuccessor(self, root, p):
""":type root: TreeNode :type p: TreeNode :rtype: TreeNode"""
<|body_0|>
def inorderSuccessor_recursive(self, root, p):
""":type root: TreeNode :type p: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderSuccessor(self, root, p):
""":type root: TreeNode :type p: TreeNode :rtype: TreeNode"""
successor = None
while root:
if p.val < root.val:
successor = root
root = root.left
else:
root = root.rig... | the_stack_v2_python_sparse | src/lt_285.py | oxhead/CodingYourWay | train | 0 | |
79acc4c1457c3c68a88850b7946cb2970491229b | [
"self.repository = repository\nself.key = key\nself.img_bytes_io = None\nsuper(LoadImage, self).__init__(prefix='LI', phase_name='Load image', invocation_id=invocation_id)",
"if not self.__load_image():\n return False\nreturn True",
"status, response, img_bytes_io = self.repository.load_file_as_bytes_io(self... | <|body_start_0|>
self.repository = repository
self.key = key
self.img_bytes_io = None
super(LoadImage, self).__init__(prefix='LI', phase_name='Load image', invocation_id=invocation_id)
<|end_body_0|>
<|body_start_1|>
if not self.__load_image():
return False
r... | Image loading object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response. | LoadImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadImage:
"""Image loading object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response."""
def __init__(self, repository, key: str, invocation_id: str):
"""Constructor of the load image object, stores provided and locally... | stack_v2_sparse_classes_10k_train_004474 | 2,233 | no_license | [
{
"docstring": "Constructor of the load image object, stores provided and locally generated data, runs main object procedure. :param repository: selected repository to work upon. :param key: string containing stored image name. :param invocation_id: string containing id of current cloud function invocation to b... | 3 | stack_v2_sparse_classes_30k_train_003487 | Implement the Python class `LoadImage` described below.
Class description:
Image loading object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response.
Method signatures and docstrings:
- def __init__(self, repository, key: str, invocation_id: str): Construc... | Implement the Python class `LoadImage` described below.
Class description:
Image loading object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response.
Method signatures and docstrings:
- def __init__(self, repository, key: str, invocation_id: str): Construc... | 8f1b94518303c4e0a38df1ff6caa0e7326451d67 | <|skeleton|>
class LoadImage:
"""Image loading object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response."""
def __init__(self, repository, key: str, invocation_id: str):
"""Constructor of the load image object, stores provided and locally... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoadImage:
"""Image loading object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response."""
def __init__(self, repository, key: str, invocation_id: str):
"""Constructor of the load image object, stores provided and locally generated da... | the_stack_v2_python_sparse | Serverless/handlers/s3_generate_thumbnail/load_image.py | RogerVFbr/MyCelebs | train | 0 |
1cc5c99926c620117b5ad2a6171dfbec7027136d | [
"super().__init__()\nself._c_prob, self._d_prob = (c_prob, d_prob)\nself._init_c_prob, self._init_d_prob = (c_prob, d_prob)\nself._aspiration_level = abs(max(self.match_attributes['game'].RPST()) / aspiration_level_divider)\nself._stimulus = 0.0\nself._learning_rate = learning_rate",
"game = self.match_attributes... | <|body_start_0|>
super().__init__()
self._c_prob, self._d_prob = (c_prob, d_prob)
self._init_c_prob, self._init_d_prob = (c_prob, d_prob)
self._aspiration_level = abs(max(self.match_attributes['game'].RPST()) / aspiration_level_divider)
self._stimulus = 0.0
self._learning... | A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous play's payoff in the specified probability. ... | BushMosteller | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BushMosteller:
"""A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous pla... | stack_v2_sparse_classes_10k_train_004475 | 4,480 | permissive | [
{
"docstring": "Parameters c_prob: float, 0.5 Probability to play C , is modified during the match d_prob: float, 0.5 Probability to play D , is modified during the match aspiration_level_divider: float, 3.0 Value that regulates the aspiration level, isn't modified during match learning rate [0 , 1] Percentage ... | 3 | stack_v2_sparse_classes_30k_train_003735 | Implement the Python class `BushMosteller` described below.
Class description:
A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a ... | Implement the Python class `BushMosteller` described below.
Class description:
A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a ... | fa748627cd4f0333bb2dbfcb1454372a78a9098a | <|skeleton|>
class BushMosteller:
"""A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous pla... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BushMosteller:
"""A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous play's payoff in... | the_stack_v2_python_sparse | axelrod/strategies/bush_mosteller.py | Axelrod-Python/Axelrod | train | 673 |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\ntypeID = read_length_and_key(fp)\nenum = read_length_and_key(fp)\nreturn cls(name, classID, typeID, enum)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_length_and_key(fp, sel... | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
typeID = read_length_and_key(fp)
enum = read_length_and_key(fp)
return cls(name, classID, typeID, enum)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
... | Enumerated reference structure. .. py:attribute:: value | EnumeratedReference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumeratedReference:
"""Enumerated reference structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp... | stack_v2_sparse_classes_10k_train_004476 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003406 | Implement the Python class `EnumeratedReference` described below.
Class description:
Enumerated reference structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-l... | Implement the Python class `EnumeratedReference` described below.
Class description:
Enumerated reference structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-l... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class EnumeratedReference:
"""Enumerated reference structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnumeratedReference:
"""Enumerated reference structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
typeID = read_length_and_key(f... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
fc5098e903f2c888d6eadfb11a5210f594600dce | [
"tempDictionary = {}\ntempDictionary['total_price'] = 0\nfor product in products:\n if not product['name'] in self.products_data:\n new_product = super(Purchase, self).__init__(product['name'], product['type'], 0, product['price'])\n product_price = product['quantity'] * product['price']\n tax = pro... | <|body_start_0|>
tempDictionary = {}
tempDictionary['total_price'] = 0
for product in products:
if not product['name'] in self.products_data:
new_product = super(Purchase, self).__init__(product['name'], product['type'], 0, product['price'])
product_price ... | This class used to store purchase of products | Purchase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Purchase:
"""This class used to store purchase of products"""
def create_purchase_order(self, products, vendor_name):
"""func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if ... | stack_v2_sparse_classes_10k_train_004477 | 2,497 | no_license | [
{
"docstring": "func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if more than purchase price else purchase number",
"name": "create_purchase_order",
"signature": "def create_purchase_order(self... | 2 | stack_v2_sparse_classes_30k_train_006611 | Implement the Python class `Purchase` described below.
Class description:
This class used to store purchase of products
Method signatures and docstrings:
- def create_purchase_order(self, products, vendor_name): func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionar... | Implement the Python class `Purchase` described below.
Class description:
This class used to store purchase of products
Method signatures and docstrings:
- def create_purchase_order(self, products, vendor_name): func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionar... | 08668c834bdb4aee3abafdedc9126bba7aa041b8 | <|skeleton|>
class Purchase:
"""This class used to store purchase of products"""
def create_purchase_order(self, products, vendor_name):
"""func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Purchase:
"""This class used to store purchase of products"""
def create_purchase_order(self, products, vendor_name):
"""func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if more than pur... | the_stack_v2_python_sparse | Test1/purchase.py | maulikb-emipro/Python-Training | train | 0 |
f06c073330ee853587217d023a191b8e2de1ab7d | [
"self.prefixes = collections.defaultdict(set)\nself.suffixes = collections.defaultdict(set)\nself.weights = {}\nfor i, word in enumerate(words):\n prefix, suffix = ('', '')\n for char in [''] + list(word):\n prefix += char\n self.prefixes[prefix].add(word)\n for char in [''] + list(word[::-1]... | <|body_start_0|>
self.prefixes = collections.defaultdict(set)
self.suffixes = collections.defaultdict(set)
self.weights = {}
for i, word in enumerate(words):
prefix, suffix = ('', '')
for char in [''] + list(word):
prefix += char
se... | WordFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefixes = collections.defaultdict(se... | stack_v2_sparse_classes_10k_train_004478 | 1,094 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type prefix: str :type suffix: str :rtype: int",
"name": "f",
"signature": "def f(self, prefix, suffix)"
}
] | 2 | null | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
<|skeleton|>
class WordFilter:
def __in... | 26c6ee936cdc1914dc3598c5dc74df64fa7960a1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
self.prefixes = collections.defaultdict(set)
self.suffixes = collections.defaultdict(set)
self.weights = {}
for i, word in enumerate(words):
prefix, suffix = ('', '')
for char in... | the_stack_v2_python_sparse | 745-Prefix and Suffix Search.py | JinnieJJ/leetcode | train | 3 | |
73db89ba05ccf582a567cb06a8a8fbee1183aad6 | [
"response_message = ResponseMessage()\nresponse_message.callback_url = request_message.callback_url\nresponse_message.job_id = request_message.job_id\nresponse_message.username = request_message.username\nreturn response_message",
"message = yaml.load(message_yaml)\nassert isinstance(message, ResponseMessage)\nre... | <|body_start_0|>
response_message = ResponseMessage()
response_message.callback_url = request_message.callback_url
response_message.job_id = request_message.job_id
response_message.username = request_message.username
return response_message
<|end_body_0|>
<|body_start_1|>
... | Class for response messages. | ResponseMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseMessage:
"""Class for response messages."""
def from_request_message(request_message):
"""Builds a response object from a request object."""
<|body_0|>
def load(message_yaml):
"""Loads the response message from yaml asserting it deserialized properly."""
... | stack_v2_sparse_classes_10k_train_004479 | 4,974 | no_license | [
{
"docstring": "Builds a response object from a request object.",
"name": "from_request_message",
"signature": "def from_request_message(request_message)"
},
{
"docstring": "Loads the response message from yaml asserting it deserialized properly.",
"name": "load",
"signature": "def load(... | 2 | stack_v2_sparse_classes_30k_val_000136 | Implement the Python class `ResponseMessage` described below.
Class description:
Class for response messages.
Method signatures and docstrings:
- def from_request_message(request_message): Builds a response object from a request object.
- def load(message_yaml): Loads the response message from yaml asserting it deser... | Implement the Python class `ResponseMessage` described below.
Class description:
Class for response messages.
Method signatures and docstrings:
- def from_request_message(request_message): Builds a response object from a request object.
- def load(message_yaml): Loads the response message from yaml asserting it deser... | 0051a4b09a0c5d5f0de8bd923b928d75516d3186 | <|skeleton|>
class ResponseMessage:
"""Class for response messages."""
def from_request_message(request_message):
"""Builds a response object from a request object."""
<|body_0|>
def load(message_yaml):
"""Loads the response message from yaml asserting it deserialized properly."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResponseMessage:
"""Class for response messages."""
def from_request_message(request_message):
"""Builds a response object from a request object."""
response_message = ResponseMessage()
response_message.callback_url = request_message.callback_url
response_message.job_id = ... | the_stack_v2_python_sparse | daedalus/queueing/messages.py | Millz0r/daedalus | train | 0 |
937764634aea8e414b00d1cf39c0d92a8b1fa877 | [
"if id is None:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\nelse:\n self.id = id",
"if list_dictionaries is None or list_dictionaries is []:\n return '[]'\nreturn json.dumps(list_dictionaries)",
"mtlist = []\nmtfile = cls.__name__ + '.json'\nif list_objs:\n for increment in list_objs:... | <|body_start_0|>
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
self.id = id
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or list_dictionaries is []:
return '[]'
return json.dumps(list_dictionaries)... | Fragile. Don't drop | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Fragile. Don't drop"""
def __init__(self, id=None):
"""Base constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""return json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""Save list_objs to json string"""
... | stack_v2_sparse_classes_10k_train_004480 | 1,767 | no_license | [
{
"docstring": "Base constructor",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "return json string",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "Save list_objs to json string",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_003577 | Implement the Python class `Base` described below.
Class description:
Fragile. Don't drop
Method signatures and docstrings:
- def __init__(self, id=None): Base constructor
- def to_json_string(list_dictionaries): return json string
- def save_to_file(cls, list_objs): Save list_objs to json string
- def from_json_stri... | Implement the Python class `Base` described below.
Class description:
Fragile. Don't drop
Method signatures and docstrings:
- def __init__(self, id=None): Base constructor
- def to_json_string(list_dictionaries): return json string
- def save_to_file(cls, list_objs): Save list_objs to json string
- def from_json_stri... | dcad3daba72465b20fa1d1dee7c728981b5e33b1 | <|skeleton|>
class Base:
"""Fragile. Don't drop"""
def __init__(self, id=None):
"""Base constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""return json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""Save list_objs to json string"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Base:
"""Fragile. Don't drop"""
def __init__(self, id=None):
"""Base constructor"""
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
self.id = id
def to_json_string(list_dictionaries):
"""return json string"""... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | Christopher-Caswell/holbertonschool-higher_level_programming | train | 0 |
35b49584f8a19b9e20cf08851191c465a7ebc6b6 | [
"self.front = front\nself.end = end_next = self.front\nwhile end_next:\n if isinstance(end_next, Node):\n self.end = end_next\n end_next = end_next.next",
"new_node = Node(value)\nif self.is_empty():\n self.front = self.end = new_node\nelse:\n self.end.next = self.end = new_node",
"if sel... | <|body_start_0|>
self.front = front
self.end = end_next = self.front
while end_next:
if isinstance(end_next, Node):
self.end = end_next
end_next = end_next.next
<|end_body_0|>
<|body_start_1|>
new_node = Node(value)
if self.is_empty():... | Queue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queue:
def __init__(self, front=None):
"""A constructor function that allows the user to input a another LL to create a new Queue. In: None or Linked List Exception: None Out: None"""
<|body_0|>
def enqueue(self, value):
"""Takes in a value and adds it to the end of ... | stack_v2_sparse_classes_10k_train_004481 | 1,674 | permissive | [
{
"docstring": "A constructor function that allows the user to input a another LL to create a new Queue. In: None or Linked List Exception: None Out: None",
"name": "__init__",
"signature": "def __init__(self, front=None)"
},
{
"docstring": "Takes in a value and adds it to the end of the Queue. ... | 5 | stack_v2_sparse_classes_30k_train_006579 | Implement the Python class `Queue` described below.
Class description:
Implement the Queue class.
Method signatures and docstrings:
- def __init__(self, front=None): A constructor function that allows the user to input a another LL to create a new Queue. In: None or Linked List Exception: None Out: None
- def enqueue... | Implement the Python class `Queue` described below.
Class description:
Implement the Queue class.
Method signatures and docstrings:
- def __init__(self, front=None): A constructor function that allows the user to input a another LL to create a new Queue. In: None or Linked List Exception: None Out: None
- def enqueue... | 28a6c6bd75ed7feca8de237ce54d2ae823c95f24 | <|skeleton|>
class Queue:
def __init__(self, front=None):
"""A constructor function that allows the user to input a another LL to create a new Queue. In: None or Linked List Exception: None Out: None"""
<|body_0|>
def enqueue(self, value):
"""Takes in a value and adds it to the end of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Queue:
def __init__(self, front=None):
"""A constructor function that allows the user to input a another LL to create a new Queue. In: None or Linked List Exception: None Out: None"""
self.front = front
self.end = end_next = self.front
while end_next:
if isinstance(... | the_stack_v2_python_sparse | data_structures/stack-and-queue/queue.py | Stanels42/python-data-structures-and-algorithms | train | 1 | |
5ebf4579df60cb28b252bdd239314a217f9477df | [
"self.locations_hltv_starting_ = config[sC.BUCKET_LOCATIONS][sC.HLTV_STARTING]\nself.score_starting_ = config[sC.BUCKET_LOCATIONS][sC.SCORE_STARTING]\nself.logs_starting_ = config[sC.BUCKET_LOCATIONS][sC.LOGS_STARTING]\nself.temp = config[sC.FOLDER_LOCATIONS][sC.TEMP_APP_ENGINE_FOLDER]\nself.results_ = config[sC.FO... | <|body_start_0|>
self.locations_hltv_starting_ = config[sC.BUCKET_LOCATIONS][sC.HLTV_STARTING]
self.score_starting_ = config[sC.BUCKET_LOCATIONS][sC.SCORE_STARTING]
self.logs_starting_ = config[sC.BUCKET_LOCATIONS][sC.LOGS_STARTING]
self.temp = config[sC.FOLDER_LOCATIONS][sC.TEMP_APP_ENG... | FTPHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FTPHelper:
def __init__(self, config):
"""Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object"""
<|body_0|>
def get_hltv_demos_from_ftp(self, date, server_id, folder):
"""Download Match HLTV demos from instance :param date... | stack_v2_sparse_classes_10k_train_004482 | 3,170 | no_license | [
{
"docstring": "Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Download Match HLTV demos from instance :param date: date for which the demos will be downloaded :pa... | 3 | stack_v2_sparse_classes_30k_train_001179 | Implement the Python class `FTPHelper` described below.
Class description:
Implement the FTPHelper class.
Method signatures and docstrings:
- def __init__(self, config): Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object
- def get_hltv_demos_from_ftp(self, date, server_id... | Implement the Python class `FTPHelper` described below.
Class description:
Implement the FTPHelper class.
Method signatures and docstrings:
- def __init__(self, config): Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object
- def get_hltv_demos_from_ftp(self, date, server_id... | e282063def8f8424143fc5e1ae1d2e495ddb3313 | <|skeleton|>
class FTPHelper:
def __init__(self, config):
"""Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object"""
<|body_0|>
def get_hltv_demos_from_ftp(self, date, server_id, folder):
"""Download Match HLTV demos from instance :param date... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FTPHelper:
def __init__(self, config):
"""Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object"""
self.locations_hltv_starting_ = config[sC.BUCKET_LOCATIONS][sC.HLTV_STARTING]
self.score_starting_ = config[sC.BUCKET_LOCATIONS][sC.SCORE_STARTI... | the_stack_v2_python_sparse | helpers/FTPHelper.py | SanketRevankar/TournamentManagementPy | train | 1 | |
89f507bc0e205ae3fc33ab4b8d80c3be9424c360 | [
"super(DJFMidasNet, self).__init__()\nuse_pretrained = False if path else True\nself.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)\nself.scratch.refinenet4 = DJFFeatureFusionBlock(features)\nself.scratch.refinenet3 = DJFFeatureFusionBlock(features)\nself.scratch.refinenet2 = DJFFeatur... | <|body_start_0|>
super(DJFMidasNet, self).__init__()
use_pretrained = False if path else True
self.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)
self.scratch.refinenet4 = DJFFeatureFusionBlock(features)
self.scratch.refinenet3 = DJFFeatureFusionBloc... | Network for monocular depth estimation. | DJFMidasNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DJFMidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. b... | stack_v2_sparse_classes_10k_train_004483 | 13,019 | permissive | [
{
"docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50",
"name": "__init__",
"signature": "def __init__(self, path=None, features=... | 2 | null | Implement the Python class `DJFMidasNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. feature... | Implement the Python class `DJFMidasNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. feature... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class DJFMidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DJFMidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str,... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/midas_net.py | kcyu2014/nas-landmarkreg | train | 10 |
cf223f2937e86fe317e5b3706026fddc724017fd | [
"logging.Handler.__init__(self)\nif not isinstance(database, LogMaster) and (not isinstance(database, LogReadWrite)):\n raise TypeError('A LogMaster or LogReadWrite object must be specified. A {:} was specified instead'.format(type(database)))\nself.database_name = database.database_name\nself.write_log_buffer =... | <|body_start_0|>
logging.Handler.__init__(self)
if not isinstance(database, LogMaster) and (not isinstance(database, LogReadWrite)):
raise TypeError('A LogMaster or LogReadWrite object must be specified. A {:} was specified instead'.format(type(database)))
self.database_name = databa... | A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package. | MongoLogBufferHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoLogBufferHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster... | stack_v2_sparse_classes_10k_train_004484 | 47,472 | no_license | [
{
"docstring": "A LogMaster or LogReadWrite object must be specified. The resulting handler object will have a 'database_name' attribute that can be used to identify the handler's destination.",
"name": "__init__",
"signature": "def __init__(self, database)"
},
{
"docstring": "If a formatter is ... | 2 | stack_v2_sparse_classes_30k_train_000587 | Implement the Python class `MongoLogBufferHandler` described below.
Class description:
A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package.
Method signatures an... | Implement the Python class `MongoLogBufferHandler` described below.
Class description:
A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package.
Method signatures an... | aab8f9789cb6d9b824836ffa4613b4b17d7d4df6 | <|skeleton|>
class MongoLogBufferHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MongoLogBufferHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster or LogReadWr... | the_stack_v2_python_sparse | Drivers/Database/MongoDB.py | cdfredrick/AstroComb_HPF | train | 1 |
49b58f5e203aa1443ad7f6e1a283e782746d5881 | [
"if re.match('^[+-]?[0-9]*(\\\\.[0-9]*)?([eE][+-]?[0-9]+)?$', s):\n return True\nelse:\n return False",
"try:\n float(s)\nexcept:\n return False\nreturn True"
] | <|body_start_0|>
if re.match('^[+-]?[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]+)?$', s):
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
try:
float(s)
except:
return False
return True
<|end_body_1|>
| Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isNumeric(self, s):
"""正则表达式"""
<|body_0|>
def isNumeric2(self, s):
"""作弊法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if re.match('^[+-]?[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]+)?$', s):
return True
else:
... | stack_v2_sparse_classes_10k_train_004485 | 1,224 | permissive | [
{
"docstring": "正则表达式",
"name": "isNumeric",
"signature": "def isNumeric(self, s)"
},
{
"docstring": "作弊法",
"name": "isNumeric2",
"signature": "def isNumeric2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000085 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNumeric(self, s): 正则表达式
- def isNumeric2(self, s): 作弊法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNumeric(self, s): 正则表达式
- def isNumeric2(self, s): 作弊法
<|skeleton|>
class Solution:
def isNumeric(self, s):
"""正则表达式"""
<|body_0|>
def isNumeric2... | 889d8fa489f1f2719c5a0dafd3ae51df7b4bf978 | <|skeleton|>
class Solution:
def isNumeric(self, s):
"""正则表达式"""
<|body_0|>
def isNumeric2(self, s):
"""作弊法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isNumeric(self, s):
"""正则表达式"""
if re.match('^[+-]?[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]+)?$', s):
return True
else:
return False
def isNumeric2(self, s):
"""作弊法"""
try:
float(s)
except:
return False... | the_stack_v2_python_sparse | 剑指offer/20-表示数值的字符串/isNumeric.py | jinbooooom/coding-for-algorithms | train | 14 | |
72940c3351ed8d5acead4df7899c98379352d6c8 | [
"self.numsIter = iter(nums)\nself._hasNext = None\nself._nextVal = None",
"if self._hasNext is None:\n try:\n self._nextVal = next(self.numsIter)\n except StopIteration:\n self._hasNext = False\n else:\n self._hasNext = True\nreturn self._hasNext",
"if self._hasNext:\n result = ... | <|body_start_0|>
self.numsIter = iter(nums)
self._hasNext = None
self._nextVal = None
<|end_body_0|>
<|body_start_1|>
if self._hasNext is None:
try:
self._nextVal = next(self.numsIter)
except StopIteration:
self._hasNext = False
... | Iterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Iterator:
def __init__(self, nums):
"""Initializes an iterator object to the beginning of a list. :type nums: List[int]"""
<|body_0|>
def hasNext(self):
"""Returns true if the iteration has more elements. :rtype: bool"""
<|body_1|>
def next(self):
... | stack_v2_sparse_classes_10k_train_004486 | 6,268 | no_license | [
{
"docstring": "Initializes an iterator object to the beginning of a list. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "Returns true if the iteration has more elements. :rtype: bool",
"name": "hasNext",
"signature": "def hasNext(s... | 3 | null | Implement the Python class `Iterator` described below.
Class description:
Implement the Iterator class.
Method signatures and docstrings:
- def __init__(self, nums): Initializes an iterator object to the beginning of a list. :type nums: List[int]
- def hasNext(self): Returns true if the iteration has more elements. :... | Implement the Python class `Iterator` described below.
Class description:
Implement the Iterator class.
Method signatures and docstrings:
- def __init__(self, nums): Initializes an iterator object to the beginning of a list. :type nums: List[int]
- def hasNext(self): Returns true if the iteration has more elements. :... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Iterator:
def __init__(self, nums):
"""Initializes an iterator object to the beginning of a list. :type nums: List[int]"""
<|body_0|>
def hasNext(self):
"""Returns true if the iteration has more elements. :rtype: bool"""
<|body_1|>
def next(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Iterator:
def __init__(self, nums):
"""Initializes an iterator object to the beginning of a list. :type nums: List[int]"""
self.numsIter = iter(nums)
self._hasNext = None
self._nextVal = None
def hasNext(self):
"""Returns true if the iteration has more elements. :r... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00284.Peeking Iterator.py | roger6blog/LeetCode | train | 0 | |
16834b9bdca42b9ba29c235702527a5d2ad97465 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.bttn1 = Button(self, text='I do nothing!')\nself.bttn1.grid()\nself.bttn2 = Button(self)\nself.bttn2.grid()\nself.bttn2.configure(text='Me too')\nself.bttn3 = Button(self)\nself.bttn3.grid()\nself.bttn3['text'] = 'Same here!'"
... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.bttn1 = Button(self, text='I do nothing!')
self.bttn1.grid()
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.configure... | A GUI Application with three buttons | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""A GUI Application with three buttons"""
def __init__(self, master):
"""Initialise the frame"""
<|body_0|>
def create_widgets(self):
"""Create three buttons that do nothing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(App... | stack_v2_sparse_classes_10k_train_004487 | 1,388 | no_license | [
{
"docstring": "Initialise the frame",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create three buttons that do nothing",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001028 | Implement the Python class `Application` described below.
Class description:
A GUI Application with three buttons
Method signatures and docstrings:
- def __init__(self, master): Initialise the frame
- def create_widgets(self): Create three buttons that do nothing | Implement the Python class `Application` described below.
Class description:
A GUI Application with three buttons
Method signatures and docstrings:
- def __init__(self, master): Initialise the frame
- def create_widgets(self): Create three buttons that do nothing
<|skeleton|>
class Application:
"""A GUI Applicat... | 4dbb438ebea00c083194ffcd6d285dc43ebe554b | <|skeleton|>
class Application:
"""A GUI Application with three buttons"""
def __init__(self, master):
"""Initialise the frame"""
<|body_0|>
def create_widgets(self):
"""Create three buttons that do nothing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Application:
"""A GUI Application with three buttons"""
def __init__(self, master):
"""Initialise the frame"""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create three buttons that do nothing"""
... | the_stack_v2_python_sparse | Python 31 Programs/Ch 10/Lazy Buttons 2.py | kayyali18/Python | train | 0 |
69cd7a004977df6951dda67690458c86b1397761 | [
"if isinstance(expressions, tuple):\n expressions = [expressions]\nmasks = map(list, [comp(self.loc[(slice(None), method), :], thr).any(axis=1) for method, comp, thr in expressions])\nif len(masks) > 1:\n masks = numpy.logical_and(*masks)\nelse:\n masks = masks[0]\nidx = [f for f in masks for _ in xrange(l... | <|body_start_0|>
if isinstance(expressions, tuple):
expressions = [expressions]
masks = map(list, [comp(self.loc[(slice(None), method), :], thr).any(axis=1) for method, comp, thr in expressions])
if len(masks) > 1:
masks = numpy.logical_and(*masks)
else:
... | A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core.Peptide.Peptide`) and the second row ID the predic... | EpitopePredictionResult | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpitopePredictionResult:
"""A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core... | stack_v2_sparse_classes_10k_train_004488 | 14,645 | permissive | [
{
"docstring": "Filters a result data frame based on a specified expression consisting of a list of triple with (method_name, comparator, threshold). The expression is applied to each row. If any of the columns fulfill the criteria the row remains. :param list((str,comparator,float)) expressions: A list of trip... | 2 | null | Implement the Python class `EpitopePredictionResult` described below.
Class description:
A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of t... | Implement the Python class `EpitopePredictionResult` described below.
Class description:
A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of t... | b3e54c8c4ed12b780b61f74672e9667245a7bb78 | <|skeleton|>
class EpitopePredictionResult:
"""A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EpitopePredictionResult:
"""A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core.Peptide.Pept... | the_stack_v2_python_sparse | Fred2/Core/Result.py | FRED-2/Fred2 | train | 42 |
8928a33628fa4a8872e1c63cd2c9740c519eee47 | [
"with mock.patch('version.FetchValuesFromFile') as fetch_values_from_file_mock:\n fetch_values_from_file_mock.side_effect = lambda values, file: values.update(dict(_VersionTest._EXAMPLE_VERSION, **new_version_values))\n new_args = get_new_args(_VersionTest._EXAMPLE_ARGS)\n return version.BuildOutput(new_ar... | <|body_start_0|>
with mock.patch('version.FetchValuesFromFile') as fetch_values_from_file_mock:
fetch_values_from_file_mock.side_effect = lambda values, file: values.update(dict(_VersionTest._EXAMPLE_VERSION, **new_version_values))
new_args = get_new_args(_VersionTest._EXAMPLE_ARGS)
... | Unittests for the version module. | _VersionTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _VersionTest:
"""Unittests for the version module."""
def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args):
"""Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _E... | stack_v2_sparse_classes_10k_train_004489 | 6,236 | permissive | [
{
"docstring": "Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _EXAMPLE_VERSION get_new_args -- lambda for updating _EXAMPLE_ANDROID_ARGS",
"name": "_RunBuildOutput",
"signature": "def _RunBuildOutput(new_versi... | 6 | stack_v2_sparse_classes_30k_train_001263 | Implement the Python class `_VersionTest` described below.
Class description:
Unittests for the version module.
Method signatures and docstrings:
- def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args): Parameterized helper method for running the main testable method in version.py. Keywor... | Implement the Python class `_VersionTest` described below.
Class description:
Unittests for the version module.
Method signatures and docstrings:
- def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args): Parameterized helper method for running the main testable method in version.py. Keywor... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class _VersionTest:
"""Unittests for the version module."""
def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args):
"""Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _E... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _VersionTest:
"""Unittests for the version module."""
def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args):
"""Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _EXAMPLE_VERSIO... | the_stack_v2_python_sparse | build/util/version_test.py | chromium/chromium | train | 17,408 |
980de806b394bb46849606d7e27fdf360354e87e | [
"url = reverse('api-manufacturer-part-list')\nresponse = self.get(url)\nself.assertEqual(len(response.data), 3)\ndata = {'part': 1, 'manufacturer': 7, 'MPN': 'MPN_TEST'}\nresponse = self.client.post(url, data, format='json')\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nself.assertEqual(response... | <|body_start_0|>
url = reverse('api-manufacturer-part-list')
response = self.get(url)
self.assertEqual(len(response.data), 3)
data = {'part': 1, 'manufacturer': 7, 'MPN': 'MPN_TEST'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_co... | Series of tests for the Manufacturer DRF API. | ManufacturerTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManufacturerTest:
"""Series of tests for the Manufacturer DRF API."""
def test_manufacturer_part_list(self):
"""Test the ManufacturerPart API list functionality"""
<|body_0|>
def test_manufacturer_part_detail(self):
"""Tests for the ManufacturerPart detail endpoi... | stack_v2_sparse_classes_10k_train_004490 | 19,439 | permissive | [
{
"docstring": "Test the ManufacturerPart API list functionality",
"name": "test_manufacturer_part_list",
"signature": "def test_manufacturer_part_list(self)"
},
{
"docstring": "Tests for the ManufacturerPart detail endpoint.",
"name": "test_manufacturer_part_detail",
"signature": "def t... | 4 | stack_v2_sparse_classes_30k_train_003417 | Implement the Python class `ManufacturerTest` described below.
Class description:
Series of tests for the Manufacturer DRF API.
Method signatures and docstrings:
- def test_manufacturer_part_list(self): Test the ManufacturerPart API list functionality
- def test_manufacturer_part_detail(self): Tests for the Manufactu... | Implement the Python class `ManufacturerTest` described below.
Class description:
Series of tests for the Manufacturer DRF API.
Method signatures and docstrings:
- def test_manufacturer_part_list(self): Test the ManufacturerPart API list functionality
- def test_manufacturer_part_detail(self): Tests for the Manufactu... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class ManufacturerTest:
"""Series of tests for the Manufacturer DRF API."""
def test_manufacturer_part_list(self):
"""Test the ManufacturerPart API list functionality"""
<|body_0|>
def test_manufacturer_part_detail(self):
"""Tests for the ManufacturerPart detail endpoi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ManufacturerTest:
"""Series of tests for the Manufacturer DRF API."""
def test_manufacturer_part_list(self):
"""Test the ManufacturerPart API list functionality"""
url = reverse('api-manufacturer-part-list')
response = self.get(url)
self.assertEqual(len(response.data), 3)
... | the_stack_v2_python_sparse | InvenTree/company/test_api.py | inventree/InvenTree | train | 3,077 |
92c6a288f68ed99948e5a12a9ce9cb5786b92d8c | [
"self.num_objects_failed = num_objects_failed\nself.num_runs_failed = num_runs_failed\nself.num_runs_failed_sla = num_runs_failed_sla\nself.num_runs_met_sla = num_runs_met_sla\nself.stats_by_env = stats_by_env",
"if dictionary is None:\n return None\nnum_objects_failed = dictionary.get('numObjectsFailed')\nnum... | <|body_start_0|>
self.num_objects_failed = num_objects_failed
self.num_runs_failed = num_runs_failed
self.num_runs_failed_sla = num_runs_failed_sla
self.num_runs_met_sla = num_runs_met_sla
self.stats_by_env = stats_by_env
<|end_body_0|>
<|body_start_1|>
if dictionary is ... | Implementation of the 'LastProtectionRunStats' model. Specifies the stats of last Protection Run. Attributes: num_objects_failed (long|int): Specifies the number of objects that were failed in the last Run across all Protection Jobs. num_runs_failed (long|int): Specifies the number of Protection Jobs for which specifie... | LastProtectionRunStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LastProtectionRunStats:
"""Implementation of the 'LastProtectionRunStats' model. Specifies the stats of last Protection Run. Attributes: num_objects_failed (long|int): Specifies the number of objects that were failed in the last Run across all Protection Jobs. num_runs_failed (long|int): Specifie... | stack_v2_sparse_classes_10k_train_004491 | 3,250 | permissive | [
{
"docstring": "Constructor for the LastProtectionRunStats class",
"name": "__init__",
"signature": "def __init__(self, num_objects_failed=None, num_runs_failed=None, num_runs_failed_sla=None, num_runs_met_sla=None, stats_by_env=None)"
},
{
"docstring": "Creates an instance of this model from a ... | 2 | null | Implement the Python class `LastProtectionRunStats` described below.
Class description:
Implementation of the 'LastProtectionRunStats' model. Specifies the stats of last Protection Run. Attributes: num_objects_failed (long|int): Specifies the number of objects that were failed in the last Run across all Protection Job... | Implement the Python class `LastProtectionRunStats` described below.
Class description:
Implementation of the 'LastProtectionRunStats' model. Specifies the stats of last Protection Run. Attributes: num_objects_failed (long|int): Specifies the number of objects that were failed in the last Run across all Protection Job... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LastProtectionRunStats:
"""Implementation of the 'LastProtectionRunStats' model. Specifies the stats of last Protection Run. Attributes: num_objects_failed (long|int): Specifies the number of objects that were failed in the last Run across all Protection Jobs. num_runs_failed (long|int): Specifie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LastProtectionRunStats:
"""Implementation of the 'LastProtectionRunStats' model. Specifies the stats of last Protection Run. Attributes: num_objects_failed (long|int): Specifies the number of objects that were failed in the last Run across all Protection Jobs. num_runs_failed (long|int): Specifies the number ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/last_protection_run_stats.py | cohesity/management-sdk-python | train | 24 |
ee813d5978dcb68139f389fe049b37814792b4b6 | [
"cur, prev = (root, None)\nres = []\nwhile cur:\n if not cur.left:\n res.append(cur.val)\n cur = cur.right\n else:\n prev = cur.left\n while prev.right and prev.right != cur:\n prev = prev.right\n if not prev.right:\n prev.right = cur\n cur =... | <|body_start_0|>
cur, prev = (root, None)
res = []
while cur:
if not cur.left:
res.append(cur.val)
cur = cur.right
else:
prev = cur.left
while prev.right and prev.right != cur:
prev = prev... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_on(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur, prev = (root, Non... | stack_v2_sparse_classes_10k_train_004492 | 1,687 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_on",
"signature": "def inorderTraversal_on(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_on(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_on(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solutio... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_on(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
cur, prev = (root, None)
res = []
while cur:
if not cur.left:
res.append(cur.val)
cur = cur.right
else:
prev = cur.le... | the_stack_v2_python_sparse | 94-Binary-Tree-Inorder-Traversal/solution.py | Tanych/CodeTracking | train | 0 | |
716a49e260e69a61f581213e629fd5c4cc6b6470 | [
"delay = 0\nrow = []\nfor val in prev:\n row.append(val + delay)\n delay = val\nrow.append(delay)\nreturn row",
"self.tri = []\nif numRows >= 1:\n self.tri.append([1])\nif numRows >= 2:\n self.tri.append([1, 1])\ni = 3\nwhile i <= numRows:\n self.tri.append(self.nextRow(self.tri[-1]))\n i = i + ... | <|body_start_0|>
delay = 0
row = []
for val in prev:
row.append(val + delay)
delay = val
row.append(delay)
return row
<|end_body_0|>
<|body_start_1|>
self.tri = []
if numRows >= 1:
self.tri.append([1])
if numRows >= 2:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextRow(self, prev):
""":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)"""
<|body_0|>
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004493 | 1,004 | permissive | [
{
"docstring": ":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)",
"name": "nextRow",
"signature": "def nextRow(self, prev)"
},
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generate",
"signature": "def generate(self, numRows)"
}... | 2 | stack_v2_sparse_classes_30k_train_001541 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextRow(self, prev): :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)
- def generate(self, numRows): :type numRows: int :rtype: List[List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextRow(self, prev): :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)
- def generate(self, numRows): :type numRows: int :rtype: List[List[int... | 0521e27097a01a0a2ba2af30f3185d8bb5e3e227 | <|skeleton|>
class Solution:
def nextRow(self, prev):
""":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)"""
<|body_0|>
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def nextRow(self, prev):
""":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)"""
delay = 0
row = []
for val in prev:
row.append(val + delay)
delay = val
row.append(delay)
return row
def gener... | the_stack_v2_python_sparse | P118-PascalsTriangle/main.py | rlan/LeetCode | train | 0 | |
412f56d37953828168a990f05e663165e334e00e | [
"queryset = super().get_queryset()\nif self.action == 'retrieve':\n return queryset.with_rating()\nreturn queryset",
"first_user_id = request.user.id\nsecond_user = self.get_object()\nhas_users_dialog = Dialog.objects.exclude(meeting__isnull=False).filter(dialogmember__member_id=first_user_id).filter(dialogmem... | <|body_start_0|>
queryset = super().get_queryset()
if self.action == 'retrieve':
return queryset.with_rating()
return queryset
<|end_body_0|>
<|body_start_1|>
first_user_id = request.user.id
second_user = self.get_object()
has_users_dialog = Dialog.objects.ex... | ViewSet for viewing users, start dialog with user. | UserInfoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserInfoViewSet:
"""ViewSet for viewing users, start dialog with user."""
def get_queryset(self):
"""Return queryset of Users with rating for 'retrieve' requests."""
<|body_0|>
def join(self, request, *args, **kwargs):
"""Start dialog with user."""
<|body... | stack_v2_sparse_classes_10k_train_004494 | 3,759 | no_license | [
{
"docstring": "Return queryset of Users with rating for 'retrieve' requests.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Start dialog with user.",
"name": "join",
"signature": "def join(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `UserInfoViewSet` described below.
Class description:
ViewSet for viewing users, start dialog with user.
Method signatures and docstrings:
- def get_queryset(self): Return queryset of Users with rating for 'retrieve' requests.
- def join(self, request, *args, **kwargs): Start dialog with us... | Implement the Python class `UserInfoViewSet` described below.
Class description:
ViewSet for viewing users, start dialog with user.
Method signatures and docstrings:
- def get_queryset(self): Return queryset of Users with rating for 'retrieve' requests.
- def join(self, request, *args, **kwargs): Start dialog with us... | 0879ade24685b628624dce06698f8a0afd042000 | <|skeleton|>
class UserInfoViewSet:
"""ViewSet for viewing users, start dialog with user."""
def get_queryset(self):
"""Return queryset of Users with rating for 'retrieve' requests."""
<|body_0|>
def join(self, request, *args, **kwargs):
"""Start dialog with user."""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserInfoViewSet:
"""ViewSet for viewing users, start dialog with user."""
def get_queryset(self):
"""Return queryset of Users with rating for 'retrieve' requests."""
queryset = super().get_queryset()
if self.action == 'retrieve':
return queryset.with_rating()
r... | the_stack_v2_python_sparse | camp-python-2021-find-me-develop/apps/users/api/views.py | rhanmar/oi_projects_summer_2021 | train | 0 |
506d7a651b513b3474ac3b5cc718e0a9e9331929 | [
"length = 0\nhead_0 = head\nwhile head_0 is not None:\n head_0 = head_0.next\n length += 1\nidx_n = length - n\nif idx_n == 0:\n head = head.next\n return head\nhead_0, cur, idx = (head, head_0, 0)\nwhile idx < idx_n:\n cur, head_0 = (head_0, head_0.next)\n idx += 1\nif head_0 is None:\n cur.ne... | <|body_start_0|>
length = 0
head_0 = head
while head_0 is not None:
head_0 = head_0.next
length += 1
idx_n = length - n
if idx_n == 0:
head = head.next
return head
head_0, cur, idx = (head, head_0, 0)
while idx < idx... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd1(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004495 | 1,857 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd1",
"signature": "def removeNthFromEnd1(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(sel... | 2 | stack_v2_sparse_classes_30k_train_006609 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd1(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd1(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode... | 96e847591aa6ea7ea285dbcfc1c9bcfc32026de5 | <|skeleton|>
class Solution:
def removeNthFromEnd1(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd1(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
length = 0
head_0 = head
while head_0 is not None:
head_0 = head_0.next
length += 1
idx_n = length - n
if idx_n == 0:
hea... | the_stack_v2_python_sparse | LinkList/L19_remove-nth-node-from-end-of-list.py | lihujun101/LeetCode | train | 0 | |
325281d06c085bf0b3762cc427510df15d3966c4 | [
"flags.AddNamePositionalArg(parser)\nresource_printer.RegisterFormatter(integration_printer.INTEGRATION_PRINTER_FORMAT, integration_printer.IntegrationPrinter, hidden=True)\nparser.display_info.AddFormat(integration_printer.INTEGRATION_PRINTER_FORMAT)",
"release_track = self.ReleaseTrack()\nname = args.name\nconn... | <|body_start_0|>
flags.AddNamePositionalArg(parser)
resource_printer.RegisterFormatter(integration_printer.INTEGRATION_PRINTER_FORMAT, integration_printer.IntegrationPrinter, hidden=True)
parser.display_info.AddFormat(integration_printer.INTEGRATION_PRINTER_FORMAT)
<|end_body_0|>
<|body_start_1... | Describe a Cloud Run Integration. | Describe | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Describe:
"""Describe a Cloud Run Integration."""
def Args(cls, parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
<|body_0|>
def Run(self, args):
"""Describe an integration type."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_004496 | 2,991 | permissive | [
{
"docstring": "Set up arguments for this command. Args: parser: An argparse.ArgumentParser.",
"name": "Args",
"signature": "def Args(cls, parser)"
},
{
"docstring": "Describe an integration type.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | null | Implement the Python class `Describe` described below.
Class description:
Describe a Cloud Run Integration.
Method signatures and docstrings:
- def Args(cls, parser): Set up arguments for this command. Args: parser: An argparse.ArgumentParser.
- def Run(self, args): Describe an integration type. | Implement the Python class `Describe` described below.
Class description:
Describe a Cloud Run Integration.
Method signatures and docstrings:
- def Args(cls, parser): Set up arguments for this command. Args: parser: An argparse.ArgumentParser.
- def Run(self, args): Describe an integration type.
<|skeleton|>
class D... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Describe:
"""Describe a Cloud Run Integration."""
def Args(cls, parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
<|body_0|>
def Run(self, args):
"""Describe an integration type."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Describe:
"""Describe a Cloud Run Integration."""
def Args(cls, parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
flags.AddNamePositionalArg(parser)
resource_printer.RegisterFormatter(integration_printer.INTEGRATION_PRINTER_FORMAT, integra... | the_stack_v2_python_sparse | lib/surface/run/integrations/describe.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
c4c14ce7f685d3a09da2ae08d320c65c9aeb1d6a | [
"Frame.__init__(self, master)\nself.grid()\nself.create_widgets()",
"Label(self, text='Welcome to Order Up!').grid(row=0, column=0, columnspan=2, sticky=W)\nLabel(self, text='Please choose what you would like to eat.').grid(row=1, column=0, columnspan=2, sticky=W)\nLabel(self, text='******************************... | <|body_start_0|>
Frame.__init__(self, master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
Label(self, text='Welcome to Order Up!').grid(row=0, column=0, columnspan=2, sticky=W)
Label(self, text='Please choose what you would like to eat.').grid(row=1, column... | GUI application that creates a story based on user input. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI application that creates a story based on user input."""
def __init__(self, master):
"""Initialize Frame"""
<|body_0|>
def create_widgets(self):
"""Create widgets to create the menu"""
<|body_1|>
def food_eaten(self):
"""f... | stack_v2_sparse_classes_10k_train_004497 | 4,026 | no_license | [
{
"docstring": "Initialize Frame",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create widgets to create the menu",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "fill text box list of foods eaten and total... | 3 | stack_v2_sparse_classes_30k_train_007208 | Implement the Python class `Application` described below.
Class description:
GUI application that creates a story based on user input.
Method signatures and docstrings:
- def __init__(self, master): Initialize Frame
- def create_widgets(self): Create widgets to create the menu
- def food_eaten(self): fill text box li... | Implement the Python class `Application` described below.
Class description:
GUI application that creates a story based on user input.
Method signatures and docstrings:
- def __init__(self, master): Initialize Frame
- def create_widgets(self): Create widgets to create the menu
- def food_eaten(self): fill text box li... | 272683aa0bfb68889e7dc272797549217f318dda | <|skeleton|>
class Application:
"""GUI application that creates a story based on user input."""
def __init__(self, master):
"""Initialize Frame"""
<|body_0|>
def create_widgets(self):
"""Create widgets to create the menu"""
<|body_1|>
def food_eaten(self):
"""f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Application:
"""GUI application that creates a story based on user input."""
def __init__(self, master):
"""Initialize Frame"""
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create widgets to create the menu"""
... | the_stack_v2_python_sparse | CSC_217/CSC_217_470_Assignment2/CIS_217_470_ASSIGNMENT2b_MENU.py | denisetra/SCHOOL | train | 0 |
2c7435e8268949ff0043dbaa385c93202378089e | [
"@lru_cache(None)\ndef f(i, cur_sum):\n if i == len(nums):\n if target == cur_sum:\n return 1\n return 0\n return f(i + 1, cur_sum + nums[i]) + f(i + 1, cur_sum - nums[i])\nreturn f(0, 0)",
"if (sum(nums) + target) % 2 == 1:\n return 0\nt = (sum(nums) + target) // 2\ndp = [[0] * ... | <|body_start_0|>
@lru_cache(None)
def f(i, cur_sum):
if i == len(nums):
if target == cur_sum:
return 1
return 0
return f(i + 1, cur_sum + nums[i]) + f(i + 1, cur_sum - nums[i])
return f(0, 0)
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
"""method 1 recursion + memoize"""
<|body_0|>
def findTargetSumWays2(self, nums: List[int], target: int) -> int:
"""method 2 2D DP"""
<|body_1|>
def findTargetSumWays3(self, nums... | stack_v2_sparse_classes_10k_train_004498 | 2,087 | no_license | [
{
"docstring": "method 1 recursion + memoize",
"name": "findTargetSumWays",
"signature": "def findTargetSumWays(self, nums: List[int], target: int) -> int"
},
{
"docstring": "method 2 2D DP",
"name": "findTargetSumWays2",
"signature": "def findTargetSumWays2(self, nums: List[int], target... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums: List[int], target: int) -> int: method 1 recursion + memoize
- def findTargetSumWays2(self, nums: List[int], target: int) -> int: method 2 2D DP... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums: List[int], target: int) -> int: method 1 recursion + memoize
- def findTargetSumWays2(self, nums: List[int], target: int) -> int: method 2 2D DP... | 3a5649357e0f21cbbc5e238351300cd706d533b3 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
"""method 1 recursion + memoize"""
<|body_0|>
def findTargetSumWays2(self, nums: List[int], target: int) -> int:
"""method 2 2D DP"""
<|body_1|>
def findTargetSumWays3(self, nums... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
"""method 1 recursion + memoize"""
@lru_cache(None)
def f(i, cur_sum):
if i == len(nums):
if target == cur_sum:
return 1
return 0
retu... | the_stack_v2_python_sparse | leetcode-py/leetcode494.py | cicihou/LearningProject | train | 0 | |
fbe664acda29fa4f09813d4a03f0baa3fb8597d1 | [
"super().setup(*args, **kwargs)\nif hasattr(self.get_object(), 'events'):\n event_types = models.EventType.objects.filter(events__in=self.get_object().events.all()).distinct()\nelse:\n event_types = models.EventType.objects.filter(event_proposals__in=self.get_object().event_proposals.all()).distinct()\nself.m... | <|body_start_0|>
super().setup(*args, **kwargs)
if hasattr(self.get_object(), 'events'):
event_types = models.EventType.objects.filter(events__in=self.get_object().events.all()).distinct()
else:
event_types = models.EventType.objects.filter(event_proposals__in=self.get_ob... | Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice. | AvailabilityMatrixViewMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvailabilityMatrixViewMixin:
"""Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice."""
def setup(self, *args, **kwargs):
... | stack_v2_sparse_classes_10k_train_004499 | 7,691 | permissive | [
{
"docstring": "Get the availability matrix",
"name": "setup",
"signature": "def setup(self, *args, **kwargs)"
},
{
"docstring": "Add the matrix to form kwargs, only used if the view has a form",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_test_000080 | Implement the Python class `AvailabilityMatrixViewMixin` described below.
Class description:
Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice.
Met... | Implement the Python class `AvailabilityMatrixViewMixin` described below.
Class description:
Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice.
Met... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class AvailabilityMatrixViewMixin:
"""Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice."""
def setup(self, *args, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AvailabilityMatrixViewMixin:
"""Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice."""
def setup(self, *args, **kwargs):
"""Get... | the_stack_v2_python_sparse | src/program/mixins.py | bornhack/bornhack-website | train | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.