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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
146bdf8e2adb3efcd7e785903d1552757e82abba | [
"m = defaultdict(int)\nn = len(nums)\nres = 1\nfor i in range(n):\n for j in range(i):\n diff = nums[i] - nums[j]\n m[i, diff] = m[j, diff] + 1\n res = max(res, m[i, diff])\nreturn res + 1",
"n = len(nums)\ndp = [[0] * 2000 for _ in range(n)]\nres = 1\nfor i in range(n):\n for j in rang... | <|body_start_0|>
m = defaultdict(int)
n = len(nums)
res = 1
for i in range(n):
for j in range(i):
diff = nums[i] - nums[j]
m[i, diff] = m[j, diff] + 1
res = max(res, m[i, diff])
return res + 1
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestArithSeqLength(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestArithSeqLengthDP(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = defaultdict(int)
... | stack_v2_sparse_classes_10k_train_003100 | 2,814 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestArithSeqLength",
"signature": "def longestArithSeqLength(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestArithSeqLengthDP",
"signature": "def longestArithSeqLengthDP(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002703 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestArithSeqLength(self, nums): :type nums: List[int] :rtype: int
- def longestArithSeqLengthDP(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestArithSeqLength(self, nums): :type nums: List[int] :rtype: int
- def longestArithSeqLengthDP(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def longestArithSeqLength(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestArithSeqLengthDP(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestArithSeqLength(self, nums):
""":type nums: List[int] :rtype: int"""
m = defaultdict(int)
n = len(nums)
res = 1
for i in range(n):
for j in range(i):
diff = nums[i] - nums[j]
m[i, diff] = m[j, diff] + 1
... | the_stack_v2_python_sparse | L/LongestArithmeticSubsequence.py | bssrdf/pyleet | train | 2 | |
f0e00689b0b336d446f081adff6fe29f2df2d1e3 | [
"self.state.hist_count = 0\nself.state.history_paths = []\nif self.args.history_path:\n self.state.history_paths.append(self.args.history_path)\nelse:\n self.state.history_paths = self.GuessHistoryPaths(self.args.username)\n if not self.state.history_paths:\n raise flow_base.FlowError('Could not fin... | <|body_start_0|>
self.state.hist_count = 0
self.state.history_paths = []
if self.args.history_path:
self.state.history_paths.append(self.args.history_path)
else:
self.state.history_paths = self.GuessHistoryPaths(self.args.username)
if not self.state.hi... | Retrieve and analyze the Firefox history for a machine. Default directories as per: http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format Windows XP C:\\\\Documents and Settings\\\\<username>\\\\Application Data\\\\Mozilla\\\\ Firefox\\\\Profiles\\\\<profile folder>\\\\places.sqlite Windows Vista C:\\... | FirefoxHistory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirefoxHistory:
"""Retrieve and analyze the Firefox history for a machine. Default directories as per: http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format Windows XP C:\\\\Documents and Settings\\\\<username>\\\\Application Data\\\\Mozilla\\\\ Firefox\\\\Profiles\\\\<profile f... | stack_v2_sparse_classes_10k_train_003101 | 15,367 | permissive | [
{
"docstring": "Determine the Firefox history directory.",
"name": "Start",
"signature": "def Start(self)"
},
{
"docstring": "Take each file we retrieved and get the history from it.",
"name": "ParseFiles",
"signature": "def ParseFiles(self, responses)"
},
{
"docstring": "Take a ... | 3 | stack_v2_sparse_classes_30k_test_000052 | Implement the Python class `FirefoxHistory` described below.
Class description:
Retrieve and analyze the Firefox history for a machine. Default directories as per: http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format Windows XP C:\\\\Documents and Settings\\\\<username>\\\\Application Data\\\\Mozill... | Implement the Python class `FirefoxHistory` described below.
Class description:
Retrieve and analyze the Firefox history for a machine. Default directories as per: http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format Windows XP C:\\\\Documents and Settings\\\\<username>\\\\Application Data\\\\Mozill... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class FirefoxHistory:
"""Retrieve and analyze the Firefox history for a machine. Default directories as per: http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format Windows XP C:\\\\Documents and Settings\\\\<username>\\\\Application Data\\\\Mozilla\\\\ Firefox\\\\Profiles\\\\<profile f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FirefoxHistory:
"""Retrieve and analyze the Firefox history for a machine. Default directories as per: http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format Windows XP C:\\\\Documents and Settings\\\\<username>\\\\Application Data\\\\Mozilla\\\\ Firefox\\\\Profiles\\\\<profile folder>\\\\pla... | the_stack_v2_python_sparse | grr/server/grr_response_server/flows/general/webhistory.py | google/grr | train | 4,683 |
acea35c4fb28e27f494de01891132b2f5858156c | [
"self.config_path = None\nconfig_path = config_path or CONF.api_paste_config\nif not os.path.isabs(config_path):\n self.config_path = CONF.find_file(config_path)\nelif os.path.exists(config_path):\n self.config_path = config_path\nif not self.config_path:\n raise exception.ConfigNotFound(path=config_path)"... | <|body_start_0|>
self.config_path = None
config_path = config_path or CONF.api_paste_config
if not os.path.isabs(config_path):
self.config_path = CONF.find_file(config_path)
elif os.path.exists(config_path):
self.config_path = config_path
if not self.confi... | Used to load WSGI applications from paste configurations. 用于通过解析配置文件从paste文件中加载WSGI服务; | Loader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Loader:
"""Used to load WSGI applications from paste configurations. 用于通过解析配置文件从paste文件中加载WSGI服务;"""
def __init__(self, config_path=None):
"""Initialize the loader, and attempt to find the config."""
<|body_0|>
def load_app(self, name):
"""Return the paste URLMap... | stack_v2_sparse_classes_10k_train_003102 | 11,189 | no_license | [
{
"docstring": "Initialize the loader, and attempt to find the config.",
"name": "__init__",
"signature": "def __init__(self, config_path=None)"
},
{
"docstring": "Return the paste URLMap wrapped WSGI application.",
"name": "load_app",
"signature": "def load_app(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006597 | Implement the Python class `Loader` described below.
Class description:
Used to load WSGI applications from paste configurations. 用于通过解析配置文件从paste文件中加载WSGI服务;
Method signatures and docstrings:
- def __init__(self, config_path=None): Initialize the loader, and attempt to find the config.
- def load_app(self, name): Re... | Implement the Python class `Loader` described below.
Class description:
Used to load WSGI applications from paste configurations. 用于通过解析配置文件从paste文件中加载WSGI服务;
Method signatures and docstrings:
- def __init__(self, config_path=None): Initialize the loader, and attempt to find the config.
- def load_app(self, name): Re... | 7ed48fc4899036554af4fab9252490372a09503f | <|skeleton|>
class Loader:
"""Used to load WSGI applications from paste configurations. 用于通过解析配置文件从paste文件中加载WSGI服务;"""
def __init__(self, config_path=None):
"""Initialize the loader, and attempt to find the config."""
<|body_0|>
def load_app(self, name):
"""Return the paste URLMap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Loader:
"""Used to load WSGI applications from paste configurations. 用于通过解析配置文件从paste文件中加载WSGI服务;"""
def __init__(self, config_path=None):
"""Initialize the loader, and attempt to find the config."""
self.config_path = None
config_path = config_path or CONF.api_paste_config
... | the_stack_v2_python_sparse | xdrs/xdrs/wsgi.py | liucyao/XDRS | train | 0 |
a73de47b65448323d0a45d8b512bcd1f869e8882 | [
"user = request.user\ntry:\n video_client = user.video_client\n if timezone.now() > video_client.expires_at:\n video_client.delete()\n raise ValueError()\nexcept (AttributeError, ValueError):\n try:\n video_client = create_video_client(user)\n except (ValidationError, IntegrityError... | <|body_start_0|>
user = request.user
try:
video_client = user.video_client
if timezone.now() > video_client.expires_at:
video_client.delete()
raise ValueError()
except (AttributeError, ValueError):
try:
video_cli... | Shoutit Twilio API Resources. | ShoutitTwilioViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identit... | stack_v2_sparse_classes_10k_train_003103 | 7,701 | no_license | [
{
"docstring": "Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { \"token\": \"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE\", \"identity\": \"7c6ca4737db3447f936037374473e61f\" } </code></pre> ---",
"name": "video_auth",
"sign... | 4 | stack_v2_sparse_classes_30k_train_006546 | Implement the Python class `ShoutitTwilioViewSet` described below.
Class description:
Shoutit Twilio API Resources.
Method signatures and docstrings:
- def video_auth(self, request): Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAi... | Implement the Python class `ShoutitTwilioViewSet` described below.
Class description:
Shoutit Twilio API Resources.
Method signatures and docstrings:
- def video_auth(self, request): Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAi... | f3c95585ac639b45c28521712ed33a178ab36ea4 | <|skeleton|>
class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identity": "7c6ca473... | the_stack_v2_python_sparse | src/shoutit_twilio/views.py | shoutit/shoutit-api | train | 0 |
a850a8fa466cfcb539b0eabc41059e6a6cbc9a51 | [
"name = http.request.params.get('name', None)\nmodel = http.request.env['metro_park_base.location']\nreturn model.get_location_by_name(name)",
"placeholder = functools.partial(get_resource_path, 'metro_park_base', 'static', 'img')\nresponse = http.send_file(placeholder('logo.png'))\nreturn response",
"alias = h... | <|body_start_0|>
name = http.request.params.get('name', None)
model = http.request.env['metro_park_base.location']
return model.get_location_by_name(name)
<|end_body_0|>
<|body_start_1|>
placeholder = functools.partial(get_resource_path, 'metro_park_base', 'static', 'img')
respo... | 基础接口 | MetroParkBaseController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetroParkBaseController:
"""基础接口"""
def get_location_info_by_name(self, **kw):
"""根据名称取得位置信息 :param kw: :return:"""
<|body_0|>
def company_logo(self, dbname=None, **kw):
"""更改默认logo :param dbname: :param kw: :return:"""
<|body_1|>
def get_rail_state(... | stack_v2_sparse_classes_10k_train_003104 | 6,610 | no_license | [
{
"docstring": "根据名称取得位置信息 :param kw: :return:",
"name": "get_location_info_by_name",
"signature": "def get_location_info_by_name(self, **kw)"
},
{
"docstring": "更改默认logo :param dbname: :param kw: :return:",
"name": "company_logo",
"signature": "def company_logo(self, dbname=None, **kw)"... | 3 | stack_v2_sparse_classes_30k_train_000448 | Implement the Python class `MetroParkBaseController` described below.
Class description:
基础接口
Method signatures and docstrings:
- def get_location_info_by_name(self, **kw): 根据名称取得位置信息 :param kw: :return:
- def company_logo(self, dbname=None, **kw): 更改默认logo :param dbname: :param kw: :return:
- def get_rail_state(self... | Implement the Python class `MetroParkBaseController` described below.
Class description:
基础接口
Method signatures and docstrings:
- def get_location_info_by_name(self, **kw): 根据名称取得位置信息 :param kw: :return:
- def company_logo(self, dbname=None, **kw): 更改默认logo :param dbname: :param kw: :return:
- def get_rail_state(self... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class MetroParkBaseController:
"""基础接口"""
def get_location_info_by_name(self, **kw):
"""根据名称取得位置信息 :param kw: :return:"""
<|body_0|>
def company_logo(self, dbname=None, **kw):
"""更改默认logo :param dbname: :param kw: :return:"""
<|body_1|>
def get_rail_state(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MetroParkBaseController:
"""基础接口"""
def get_location_info_by_name(self, **kw):
"""根据名称取得位置信息 :param kw: :return:"""
name = http.request.params.get('name', None)
model = http.request.env['metro_park_base.location']
return model.get_location_by_name(name)
def company_lo... | the_stack_v2_python_sparse | mdias_addons/metro_park_base/controllers/controllers.py | rezaghanimi/main_mdias | train | 0 |
8c2a99816f180eb1522a6eb22c3de3b1f825ba6d | [
"super(DiskIO, self).__init__(host, port, community, version)\nself.disk = disk\nINDEXES['values'][disk] = None\nfor key, item in PERFDATA['data'].items():\n item['index_label'] = disk\nself.sleep = sleep\nself.io_key = '%s:check_disk_io:%s' % (self.host, self.disk)",
"exist, contains = self.cache.check_if_exi... | <|body_start_0|>
super(DiskIO, self).__init__(host, port, community, version)
self.disk = disk
INDEXES['values'][disk] = None
for key, item in PERFDATA['data'].items():
item['index_label'] = disk
self.sleep = sleep
self.io_key = '%s:check_disk_io:%s' % (self.h... | DiskIO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiskIO:
def __init__(self, host, port, community, version, disk, sleep):
"""Class Initialization :param host: hostname of the machine :param port: port number of SNMP in the machine :param community: SNMP community :param version: SNMP version (1, 2c, 3) :param disk: label of the disk in... | stack_v2_sparse_classes_10k_train_003105 | 6,438 | no_license | [
{
"docstring": "Class Initialization :param host: hostname of the machine :param port: port number of SNMP in the machine :param community: SNMP community :param version: SNMP version (1, 2c, 3) :param disk: label of the disk in the machine to monitor :param sleep: sleep time to get I/O differences if there are... | 4 | stack_v2_sparse_classes_30k_train_004570 | Implement the Python class `DiskIO` described below.
Class description:
Implement the DiskIO class.
Method signatures and docstrings:
- def __init__(self, host, port, community, version, disk, sleep): Class Initialization :param host: hostname of the machine :param port: port number of SNMP in the machine :param comm... | Implement the Python class `DiskIO` described below.
Class description:
Implement the DiskIO class.
Method signatures and docstrings:
- def __init__(self, host, port, community, version, disk, sleep): Class Initialization :param host: hostname of the machine :param port: port number of SNMP in the machine :param comm... | fc8c808c46f65696f7c6ac8fd6266c1091dbb14d | <|skeleton|>
class DiskIO:
def __init__(self, host, port, community, version, disk, sleep):
"""Class Initialization :param host: hostname of the machine :param port: port number of SNMP in the machine :param community: SNMP community :param version: SNMP version (1, 2c, 3) :param disk: label of the disk in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DiskIO:
def __init__(self, host, port, community, version, disk, sleep):
"""Class Initialization :param host: hostname of the machine :param port: port number of SNMP in the machine :param community: SNMP community :param version: SNMP version (1, 2c, 3) :param disk: label of the disk in the machine t... | the_stack_v2_python_sparse | old/check_disk_io.py | aurimukas/icinga2_plugins | train | 3 | |
82bc337156bf60f4be72d723d4fd2749e8e818f7 | [
"self.functions: List[Callable] = functions\nself.input_dict: Dict[str, any] = input_dict\nself.dispatch_table: Dict[Tuple[str], Callable] = self._generate_dispatch_table()",
"parameters_not_none, parameter_values_not_none = self._parse_input_dict(self.input_dict)\nif parameters_not_none not in self.dispatch_tabl... | <|body_start_0|>
self.functions: List[Callable] = functions
self.input_dict: Dict[str, any] = input_dict
self.dispatch_table: Dict[Tuple[str], Callable] = self._generate_dispatch_table()
<|end_body_0|>
<|body_start_1|>
parameters_not_none, parameter_values_not_none = self._parse_input_d... | Dispatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dispatcher:
def __init__(self, functions: List[Callable], input_dict: Dict[str, Any]):
"""Initialize the dispatcher with a list of functions and an input dict"""
<|body_0|>
def __call__(self):
"""Call the dispatcher with the input dict"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_003106 | 2,130 | no_license | [
{
"docstring": "Initialize the dispatcher with a list of functions and an input dict",
"name": "__init__",
"signature": "def __init__(self, functions: List[Callable], input_dict: Dict[str, Any])"
},
{
"docstring": "Call the dispatcher with the input dict",
"name": "__call__",
"signature"... | 4 | stack_v2_sparse_classes_30k_train_005966 | Implement the Python class `Dispatcher` described below.
Class description:
Implement the Dispatcher class.
Method signatures and docstrings:
- def __init__(self, functions: List[Callable], input_dict: Dict[str, Any]): Initialize the dispatcher with a list of functions and an input dict
- def __call__(self): Call the... | Implement the Python class `Dispatcher` described below.
Class description:
Implement the Dispatcher class.
Method signatures and docstrings:
- def __init__(self, functions: List[Callable], input_dict: Dict[str, Any]): Initialize the dispatcher with a list of functions and an input dict
- def __call__(self): Call the... | d2ec6d25b577dd6938bbf92317aeff1d6b3c5b08 | <|skeleton|>
class Dispatcher:
def __init__(self, functions: List[Callable], input_dict: Dict[str, Any]):
"""Initialize the dispatcher with a list of functions and an input dict"""
<|body_0|>
def __call__(self):
"""Call the dispatcher with the input dict"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dispatcher:
def __init__(self, functions: List[Callable], input_dict: Dict[str, Any]):
"""Initialize the dispatcher with a list of functions and an input dict"""
self.functions: List[Callable] = functions
self.input_dict: Dict[str, any] = input_dict
self.dispatch_table: Dict[Tu... | the_stack_v2_python_sparse | cg/utils/dispatcher.py | Clinical-Genomics/cg | train | 19 | |
2fc4f77ca82809f3878cb8bd5e1bd270e86c1ee1 | [
"name = 'hg'\nif os.name == 'nt':\n name += '.exe'\nbinary = self.find_binary(name)\nif binary and os.path.isdir(binary):\n full_path = os.path.join(binary, name)\n if os.path.exists(full_path):\n binary = full_path\nif not binary:\n show_error((u'Unable to find %s. Please set the hg_binary setti... | <|body_start_0|>
name = 'hg'
if os.name == 'nt':
name += '.exe'
binary = self.find_binary(name)
if binary and os.path.isdir(binary):
full_path = os.path.join(binary, name)
if os.path.exists(full_path):
binary = full_path
if not ... | Allows upgrading a local mercurial-repository-based package | HgUpgrader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HgUpgrader:
"""Allows upgrading a local mercurial-repository-based package"""
def retrieve_binary(self):
"""Returns the path to the hg executable :return: The string path to the executable or False on error"""
<|body_0|>
def run(self):
"""Updates the repository w... | stack_v2_sparse_classes_10k_train_003107 | 2,166 | permissive | [
{
"docstring": "Returns the path to the hg executable :return: The string path to the executable or False on error",
"name": "retrieve_binary",
"signature": "def retrieve_binary(self)"
},
{
"docstring": "Updates the repository with remote changes :return: False or error, or True on success",
... | 3 | null | Implement the Python class `HgUpgrader` described below.
Class description:
Allows upgrading a local mercurial-repository-based package
Method signatures and docstrings:
- def retrieve_binary(self): Returns the path to the hg executable :return: The string path to the executable or False on error
- def run(self): Upd... | Implement the Python class `HgUpgrader` described below.
Class description:
Allows upgrading a local mercurial-repository-based package
Method signatures and docstrings:
- def retrieve_binary(self): Returns the path to the hg executable :return: The string path to the executable or False on error
- def run(self): Upd... | 8c9833710577de6db6e8b1db5d9196e19e19d117 | <|skeleton|>
class HgUpgrader:
"""Allows upgrading a local mercurial-repository-based package"""
def retrieve_binary(self):
"""Returns the path to the hg executable :return: The string path to the executable or False on error"""
<|body_0|>
def run(self):
"""Updates the repository w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HgUpgrader:
"""Allows upgrading a local mercurial-repository-based package"""
def retrieve_binary(self):
"""Returns the path to the hg executable :return: The string path to the executable or False on error"""
name = 'hg'
if os.name == 'nt':
name += '.exe'
bina... | the_stack_v2_python_sparse | EthanBrown.SublimeText2.UtilPackages/tools/PackageCache/Package Control/package_control/upgraders/hg_upgrader.py | Iristyle/ChocolateyPackages | train | 19 |
a89af693fff9347b1baed5cb6e33c575bc0c47ab | [
"res = []\nfor s in strs:\n res.append(str(len(s)))\n res.append('/')\n res.append(s)\nreturn ''.join(res)",
"strs = []\ni = 0\nnum = 0\nwhile i < len(s):\n if s[i].isdigit():\n num = num * 10 + int(s[i])\n i += 1\n elif s[i] == '/':\n i += 1\n strs.append(s[i:i + num])\... | <|body_start_0|>
res = []
for s in strs:
res.append(str(len(s)))
res.append('/')
res.append(s)
return ''.join(res)
<|end_body_0|>
<|body_start_1|>
strs = []
i = 0
num = 0
while i < len(s):
if s[i].isdigit():
... | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_10k_train_003108 | 3,656 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | null | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: ... | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: ... | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | <|skeleton|>
class Codec1:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec1:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
res = []
for s in strs:
res.append(str(len(s)))
res.append('/')
res.append(s)
return ''.join(res)
def decode(self, s):
... | the_stack_v2_python_sparse | 0271. Encode and Decode Strings.py | pwang867/LeetCode-Solutions-Python | train | 0 | |
5976a2dd80d24ba694dad84da69c4cae4b9f5dd8 | [
"super().__init__(n_feat, n_head, dropout)\nprecision = torch.float\nself.rotary_ndims = self.d_k\nif precision == 'fp16':\n precision = torch.half\nself.rotary_emb = RotaryPositionalEmbedding(self.rotary_ndims, base=rotary_emd_base, precision=precision)",
"T, B, C = value.size()\nquery = query.view(T, B, self... | <|body_start_0|>
super().__init__(n_feat, n_head, dropout)
precision = torch.float
self.rotary_ndims = self.d_k
if precision == 'fp16':
precision = torch.half
self.rotary_emb = RotaryPositionalEmbedding(self.rotary_ndims, base=rotary_emd_base, precision=precision)
<|e... | RotaryPositionMultiHeadedAttention | [
"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 RotaryPositionMultiHeadedAttention:
def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000):
"""Construct an RotaryPositionMultiHeadedAttention object."""
<|body_0|>
def forward(self, query, key, value, key_padding_mask=None, **kwargs):
"""Compu... | stack_v2_sparse_classes_10k_train_003109 | 9,673 | permissive | [
{
"docstring": "Construct an RotaryPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000)"
},
{
"docstring": "Compute rotary position attention. Args: query: Query tensor T X B X C key: Key tensor T X... | 2 | null | Implement the Python class `RotaryPositionMultiHeadedAttention` described below.
Class description:
Implement the RotaryPositionMultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000): Construct an RotaryPositionMultiHeadedAttention... | Implement the Python class `RotaryPositionMultiHeadedAttention` described below.
Class description:
Implement the RotaryPositionMultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000): Construct an RotaryPositionMultiHeadedAttention... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class RotaryPositionMultiHeadedAttention:
def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000):
"""Construct an RotaryPositionMultiHeadedAttention object."""
<|body_0|>
def forward(self, query, key, value, key_padding_mask=None, **kwargs):
"""Compu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RotaryPositionMultiHeadedAttention:
def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000):
"""Construct an RotaryPositionMultiHeadedAttention object."""
super().__init__(n_feat, n_head, dropout)
precision = torch.float
self.rotary_ndims = self.d_k
... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/espnet_multihead_attention.py | microsoft/unilm | train | 15,313 | |
3d727342e706e426f0caaedef1cae0e7363776b9 | [
"self._pid = PID(kp, ki, kd, **kwargs)\nBetterColorSensor.__init__(self, port_cs)\nself.grey_soll = (127.5 - black) / (white - black) * 255\nself.avgsize_c = avgsize_c\nself.black = black\nself.white = white",
"if self.avgsize_c > 1:\n grey = self.grey_avg\nelse:\n grey = self.grey\ngrey = (grey - self.blac... | <|body_start_0|>
self._pid = PID(kp, ki, kd, **kwargs)
BetterColorSensor.__init__(self, port_cs)
self.grey_soll = (127.5 - black) / (white - black) * 255
self.avgsize_c = avgsize_c
self.black = black
self.white = white
<|end_body_0|>
<|body_start_1|>
if self.avgs... | Berechnet die noetige Aenderung der Geschwindigkeit(dv) um auf der Linie zu bleiben TODO:Um die PID-Parameter bei sich aendernden Bedingungen gleich zuhalten, wird der soll und ist-Wert auf 0...255 gemappt | LineKeep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineKeep:
"""Berechnet die noetige Aenderung der Geschwindigkeit(dv) um auf der Linie zu bleiben TODO:Um die PID-Parameter bei sich aendernden Bedingungen gleich zuhalten, wird der soll und ist-Wert auf 0...255 gemappt"""
def __init__(self, port_cs, kp, ki=0, kd=0, avgsize_c=1, white=255, bl... | stack_v2_sparse_classes_10k_train_003110 | 8,924 | no_license | [
{
"docstring": "INIT-PARAM: kp, ki, kd:Konstanten des PID-Reglers port_cs:Port des FarbSensors avgsize_c: zu mittelnde Farbwerte( koennte sinnvoll sein wg Schwankungen, default = 1) white: Farbe des Untergrunds(default:255) black: Farbe der Linie(default:0)",
"name": "__init__",
"signature": "def __init... | 3 | stack_v2_sparse_classes_30k_train_001764 | Implement the Python class `LineKeep` described below.
Class description:
Berechnet die noetige Aenderung der Geschwindigkeit(dv) um auf der Linie zu bleiben TODO:Um die PID-Parameter bei sich aendernden Bedingungen gleich zuhalten, wird der soll und ist-Wert auf 0...255 gemappt
Method signatures and docstrings:
- de... | Implement the Python class `LineKeep` described below.
Class description:
Berechnet die noetige Aenderung der Geschwindigkeit(dv) um auf der Linie zu bleiben TODO:Um die PID-Parameter bei sich aendernden Bedingungen gleich zuhalten, wird der soll und ist-Wert auf 0...255 gemappt
Method signatures and docstrings:
- de... | a9a7160bf7fb3b528716ebabd4c16b4482d8d9cf | <|skeleton|>
class LineKeep:
"""Berechnet die noetige Aenderung der Geschwindigkeit(dv) um auf der Linie zu bleiben TODO:Um die PID-Parameter bei sich aendernden Bedingungen gleich zuhalten, wird der soll und ist-Wert auf 0...255 gemappt"""
def __init__(self, port_cs, kp, ki=0, kd=0, avgsize_c=1, white=255, bl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LineKeep:
"""Berechnet die noetige Aenderung der Geschwindigkeit(dv) um auf der Linie zu bleiben TODO:Um die PID-Parameter bei sich aendernden Bedingungen gleich zuhalten, wird der soll und ist-Wert auf 0...255 gemappt"""
def __init__(self, port_cs, kp, ki=0, kd=0, avgsize_c=1, white=255, black=0, **kwar... | the_stack_v2_python_sparse | node/ev3con/linienverfolgung/control.py | Fuzzyma/network-controlled-line-follower | train | 0 |
d7756767682fa35205d69a52e75038e1112ccc70 | [
"try:\n release = Release.objects.get(organization_id=organization.id, version=version)\nexcept Release.DoesNotExist:\n raise ResourceDoesNotExist\nif not self.has_release_permission(request, organization, release):\n raise ResourceDoesNotExist\nreturn self.get_releasefiles(request, release, organization.i... | <|body_start_0|>
try:
release = Release.objects.get(organization_id=organization.id, version=version)
except Release.DoesNotExist:
raise ResourceDoesNotExist
if not self.has_release_permission(request, organization, release):
raise ResourceDoesNotExist
... | OrganizationReleaseFilesEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationReleaseFilesEndpoint:
def get(self, request: Request, organization, version) -> Response:
"""List an Organization Release's Files ```````````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization ... | stack_v2_sparse_classes_10k_train_003111 | 3,119 | permissive | [
{
"docstring": "List an Organization Release's Files ```````````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization the release belongs to. :pparam string version: the version identifier of the release. :auth: required",
"nam... | 2 | null | Implement the Python class `OrganizationReleaseFilesEndpoint` described below.
Class description:
Implement the OrganizationReleaseFilesEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, organization, version) -> Response: List an Organization Release's Files `````````````````````````... | Implement the Python class `OrganizationReleaseFilesEndpoint` described below.
Class description:
Implement the OrganizationReleaseFilesEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, organization, version) -> Response: List an Organization Release's Files `````````````````````````... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class OrganizationReleaseFilesEndpoint:
def get(self, request: Request, organization, version) -> Response:
"""List an Organization Release's Files ```````````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrganizationReleaseFilesEndpoint:
def get(self, request: Request, organization, version) -> Response:
"""List an Organization Release's Files ```````````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization the release be... | the_stack_v2_python_sparse | src/sentry/api/endpoints/organization_release_files.py | nagyist/sentry | train | 0 | |
81315d181d68d575d57fbdf2a02865af4763efa8 | [
"EasyFrame.__init__(self, title='Temperature Converter')\nself.model = model\nself.addLabel(text='Celsius', row=0, column=0)\nself.celsiusField = self.addFloatField(value=model.getCelsius(), row=1, column=0, precision=2)\nself.addLabel(text='Fahrenheit', row=0, column=1)\nself.fahrField = self.addFloatField(value=m... | <|body_start_0|>
EasyFrame.__init__(self, title='Temperature Converter')
self.model = model
self.addLabel(text='Celsius', row=0, column=0)
self.celsiusField = self.addFloatField(value=model.getCelsius(), row=1, column=0, precision=2)
self.addLabel(text='Fahrenheit', row=0, column... | A termperature conversion program. | ThermometerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThermometerView:
"""A termperature conversion program."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
<|body_0|>
def computeFahr(self):
"""Inputs the Celsius degrees and outputs the Fahrenheit degrees."""
<|body_1... | stack_v2_sparse_classes_10k_train_003112 | 2,234 | no_license | [
{
"docstring": "Sets up the view. The model comes in as an argument.",
"name": "__init__",
"signature": "def __init__(self, model)"
},
{
"docstring": "Inputs the Celsius degrees and outputs the Fahrenheit degrees.",
"name": "computeFahr",
"signature": "def computeFahr(self)"
},
{
... | 3 | null | Implement the Python class `ThermometerView` described below.
Class description:
A termperature conversion program.
Method signatures and docstrings:
- def __init__(self, model): Sets up the view. The model comes in as an argument.
- def computeFahr(self): Inputs the Celsius degrees and outputs the Fahrenheit degrees... | Implement the Python class `ThermometerView` described below.
Class description:
A termperature conversion program.
Method signatures and docstrings:
- def __init__(self, model): Sets up the view. The model comes in as an argument.
- def computeFahr(self): Inputs the Celsius degrees and outputs the Fahrenheit degrees... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class ThermometerView:
"""A termperature conversion program."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
<|body_0|>
def computeFahr(self):
"""Inputs the Celsius degrees and outputs the Fahrenheit degrees."""
<|body_1... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ThermometerView:
"""A termperature conversion program."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
EasyFrame.__init__(self, title='Temperature Converter')
self.model = model
self.addLabel(text='Celsius', row=0, column=0)
... | the_stack_v2_python_sparse | gui/breezy/thermometerview1.py | lforet/robomow | train | 11 |
af037bb5ad00faf28b049035574e0958ac91e08f | [
"super(MotionFieldEncoder, self).__init__()\nconv_prop_0 = {'kernel_size': 3, 'strides': 2, 'activation': 'relu', 'padding': 'same', 'kernel_regularizer': tf.keras.regularizers.L2(weight_reg)}\nself.conv_encoder = []\nnum_conv_enc = 7\nchannels = [6]\nfor i in range(1, num_conv_enc + 1):\n channels.append(2 ** (... | <|body_start_0|>
super(MotionFieldEncoder, self).__init__()
conv_prop_0 = {'kernel_size': 3, 'strides': 2, 'activation': 'relu', 'padding': 'same', 'kernel_regularizer': tf.keras.regularizers.L2(weight_reg)}
self.conv_encoder = []
num_conv_enc = 7
channels = [6]
for i in ... | MotionFieldEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotionFieldEncoder:
def __init__(self, weight_reg=0.0):
"""Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.""... | stack_v2_sparse_classes_10k_train_003113 | 18,266 | no_license | [
{
"docstring": "Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.",
"name": "__init__",
"signature": "def __init__(self, weigh... | 2 | stack_v2_sparse_classes_30k_train_005921 | Implement the Python class `MotionFieldEncoder` described below.
Class description:
Implement the MotionFieldEncoder class.
Method signatures and docstrings:
- def __init__(self, weight_reg=0.0): Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translatio... | Implement the Python class `MotionFieldEncoder` described below.
Class description:
Implement the MotionFieldEncoder class.
Method signatures and docstrings:
- def __init__(self, weight_reg=0.0): Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translatio... | a7be32bad38fc9555f480d2db1174aa4dd4d5d37 | <|skeleton|>
class MotionFieldEncoder:
def __init__(self, weight_reg=0.0):
"""Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MotionFieldEncoder:
def __init__(self, weight_reg=0.0):
"""Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization."""
supe... | the_stack_v2_python_sparse | models/motion_filed_net.py | dexter2406/Monodepth2-TF2 | train | 3 | |
e41d79fa6fb06c039897aabb501031d61aaa3e7b | [
"self.id = id\nself.webhook_id = webhook_id\nself.event_id = event_id\nself.timestamp = APIHelper.RFC3339DateTime(timestamp) if timestamp else None\nself.url = url\nself.elapsed_ms = elapsed_ms\nself.request_headers = request_headers\nself.request_body = request_body\nself.response_headers = response_headers\nself.... | <|body_start_0|>
self.id = id
self.webhook_id = webhook_id
self.event_id = event_id
self.timestamp = APIHelper.RFC3339DateTime(timestamp) if timestamp else None
self.url = url
self.elapsed_ms = elapsed_ms
self.request_headers = request_headers
self.request... | Implementation of the 'WebhookDeliveryDto' model. TODO: type model description here. Attributes: id (uuid|string): The webhooks unique identifier. webhook_id (int): TODO: type description here. event_id (uuid|string): TODO: type description here. timestamp (datetime): TODO: type description here. url (string): TODO: ty... | WebhookDeliveryDto | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebhookDeliveryDto:
"""Implementation of the 'WebhookDeliveryDto' model. TODO: type model description here. Attributes: id (uuid|string): The webhooks unique identifier. webhook_id (int): TODO: type description here. event_id (uuid|string): TODO: type description here. timestamp (datetime): TODO:... | stack_v2_sparse_classes_10k_train_003114 | 5,192 | permissive | [
{
"docstring": "Constructor for the WebhookDeliveryDto class",
"name": "__init__",
"signature": "def __init__(self, id=None, webhook_id=None, event_id=None, timestamp=None, url=None, elapsed_ms=None, request_headers=None, request_body=None, response_headers=None, response_body=None, response_status_code... | 2 | stack_v2_sparse_classes_30k_test_000307 | Implement the Python class `WebhookDeliveryDto` described below.
Class description:
Implementation of the 'WebhookDeliveryDto' model. TODO: type model description here. Attributes: id (uuid|string): The webhooks unique identifier. webhook_id (int): TODO: type description here. event_id (uuid|string): TODO: type descri... | Implement the Python class `WebhookDeliveryDto` described below.
Class description:
Implementation of the 'WebhookDeliveryDto' model. TODO: type model description here. Attributes: id (uuid|string): The webhooks unique identifier. webhook_id (int): TODO: type description here. event_id (uuid|string): TODO: type descri... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class WebhookDeliveryDto:
"""Implementation of the 'WebhookDeliveryDto' model. TODO: type model description here. Attributes: id (uuid|string): The webhooks unique identifier. webhook_id (int): TODO: type description here. event_id (uuid|string): TODO: type description here. timestamp (datetime): TODO:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WebhookDeliveryDto:
"""Implementation of the 'WebhookDeliveryDto' model. TODO: type model description here. Attributes: id (uuid|string): The webhooks unique identifier. webhook_id (int): TODO: type description here. event_id (uuid|string): TODO: type description here. timestamp (datetime): TODO: type descrip... | the_stack_v2_python_sparse | idfy_rest_client/models/webhook_delivery_dto.py | dealflowteam/Idfy | train | 0 |
1a89821dfb9c81a24c2a14bbe5c1ab3db20ab1d9 | [
"app_label, model_name = get_app_label_and_model_name(self.data.model)\nmodel = get_model(app_label, model_name)\nqueryset = model._default_manager.all()\nfield_kwargs = {'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'queryset': queryset, '... | <|body_start_0|>
app_label, model_name = get_app_label_and_model_name(self.data.model)
model = get_model(app_label, model_name)
queryset = model._default_manager.all()
field_kwargs = {'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': se... | Select multiple MPTT model object field plugin. | SelectMultipleMPTTModelObjectsInputPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectMultipleMPTTModelObjectsInputPlugin:
"""Select multiple MPTT model object field plugin."""
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs):
"""Get form field instances."""
<|body_0|>
def submit_plugin_form_data... | stack_v2_sparse_classes_10k_train_003115 | 3,976 | permissive | [
{
"docstring": "Get form field instances.",
"name": "get_form_field_instances",
"signature": "def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs)"
},
{
"docstring": "Submit plugin form data/process. :param fobi.models.FormEntry form_entry: Insta... | 2 | stack_v2_sparse_classes_30k_train_002700 | Implement the Python class `SelectMultipleMPTTModelObjectsInputPlugin` described below.
Class description:
Select multiple MPTT model object field plugin.
Method signatures and docstrings:
- def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): Get form field instance... | Implement the Python class `SelectMultipleMPTTModelObjectsInputPlugin` described below.
Class description:
Select multiple MPTT model object field plugin.
Method signatures and docstrings:
- def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): Get form field instance... | 4f6ca37bc600dcba3f74400d299826882d53b7d2 | <|skeleton|>
class SelectMultipleMPTTModelObjectsInputPlugin:
"""Select multiple MPTT model object field plugin."""
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs):
"""Get form field instances."""
<|body_0|>
def submit_plugin_form_data... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SelectMultipleMPTTModelObjectsInputPlugin:
"""Select multiple MPTT model object field plugin."""
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs):
"""Get form field instances."""
app_label, model_name = get_app_label_and_model_name(sel... | the_stack_v2_python_sparse | events/contrib/plugins/form_elements/fields/select_multiple_mptt_model_objects/base.py | mansonul/events | train | 0 |
199d4f7cb29c2c903341f6de229d16da916473d1 | [
"super(LocateDatabaseParser, self).__init__()\nself._cstring_map = self._GetDataTypeMap('cstring')\nself._directory_entry_header_map = self._GetDataTypeMap('directory_entry_header')\nself._directory_header_map = self._GetDataTypeMap('directory_header')",
"sub_entry_names = []\ntotal_data_size = 0\ndirectory_entry... | <|body_start_0|>
super(LocateDatabaseParser, self).__init__()
self._cstring_map = self._GetDataTypeMap('cstring')
self._directory_entry_header_map = self._GetDataTypeMap('directory_entry_header')
self._directory_header_map = self._GetDataTypeMap('directory_header')
<|end_body_0|>
<|body... | Parser for locate database (updatedb) files. | LocateDatabaseParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocateDatabaseParser:
"""Parser for locate database (updatedb) files."""
def __init__(self):
"""Initializes a locate database (updatedb) file parser."""
<|body_0|>
def _ParseDirectoryEntry(self, file_object, file_offset):
"""Parses a locate database (updatedb) di... | stack_v2_sparse_classes_10k_train_003116 | 5,609 | permissive | [
{
"docstring": "Initializes a locate database (updatedb) file parser.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parses a locate database (updatedb) directory entry. Args: file_object (dfvfs.FileIO): file-like object to be parsed. file_offset (int): offset of the ... | 4 | null | Implement the Python class `LocateDatabaseParser` described below.
Class description:
Parser for locate database (updatedb) files.
Method signatures and docstrings:
- def __init__(self): Initializes a locate database (updatedb) file parser.
- def _ParseDirectoryEntry(self, file_object, file_offset): Parses a locate d... | Implement the Python class `LocateDatabaseParser` described below.
Class description:
Parser for locate database (updatedb) files.
Method signatures and docstrings:
- def __init__(self): Initializes a locate database (updatedb) file parser.
- def _ParseDirectoryEntry(self, file_object, file_offset): Parses a locate d... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class LocateDatabaseParser:
"""Parser for locate database (updatedb) files."""
def __init__(self):
"""Initializes a locate database (updatedb) file parser."""
<|body_0|>
def _ParseDirectoryEntry(self, file_object, file_offset):
"""Parses a locate database (updatedb) di... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LocateDatabaseParser:
"""Parser for locate database (updatedb) files."""
def __init__(self):
"""Initializes a locate database (updatedb) file parser."""
super(LocateDatabaseParser, self).__init__()
self._cstring_map = self._GetDataTypeMap('cstring')
self._directory_entry_h... | the_stack_v2_python_sparse | plaso/parsers/locate.py | log2timeline/plaso | train | 1,506 |
bda0ce5682229a52140fb43b9f3618bba1a7c378 | [
"total_pairs = 0\nleft, right = (0, 1)\nnums.sort()\nwhile left < len(nums) and right < len(nums):\n if left == right or nums[right] - nums[left] < K:\n right += 1\n elif nums[right] - nums[left] > K:\n left += 1\n else:\n total_pairs += 1\n left += 1\n while left < len(n... | <|body_start_0|>
total_pairs = 0
left, right = (0, 1)
nums.sort()
while left < len(nums) and right < len(nums):
if left == right or nums[right] - nums[left] < K:
right += 1
elif nums[right] - nums[left] > K:
left += 1
el... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def k_diff_pairs(self, nums: List[int], K: int) -> int:
"""Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
<|body_0|>
def k_diff_pairs_(self, nums: List[int], K) -> int:
"""Approach: Hash Map Time Com... | stack_v2_sparse_classes_10k_train_003117 | 1,482 | no_license | [
{
"docstring": "Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:",
"name": "k_diff_pairs",
"signature": "def k_diff_pairs(self, nums: List[int], K: int) -> int"
},
{
"docstring": "Approach: Hash Map Time Complexity: O(N) Space Complexity: O... | 2 | null | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def k_diff_pairs(self, nums: List[int], K: int) -> int: Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:
- def k_diff_pairs_(sel... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def k_diff_pairs(self, nums: List[int], K: int) -> int: Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:
- def k_diff_pairs_(sel... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def k_diff_pairs(self, nums: List[int], K: int) -> int:
"""Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
<|body_0|>
def k_diff_pairs_(self, nums: List[int], K) -> int:
"""Approach: Hash Map Time Com... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Array:
def k_diff_pairs(self, nums: List[int], K: int) -> int:
"""Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
total_pairs = 0
left, right = (0, 1)
nums.sort()
while left < len(nums) and right < len(nums):
... | the_stack_v2_python_sparse | goldman_sachs/K_diff_pairs_in_array.py | Shiv2157k/leet_code | train | 1 | |
5159b0301198e69b3831e1e7d9e740a5defbcf32 | [
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_calibratorConcentrations(data.data)\ndata.clear_data()",
"data_O = []\nif met_ids_I:\n met_ids = met_ids_I\nelse:\n met_ids = []\n met_ids = self.get_metIDs_calibratorConcentrations()\nfor met_id in met_ids:\n rows = []\n... | <|body_start_0|>
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_calibratorConcentrations(data.data)
data.clear_data()
<|end_body_0|>
<|body_start_1|>
data_O = []
if met_ids_I:
met_ids = met_ids_I
else:
... | lims_calibratorsAndMixes_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lims_calibratorsAndMixes_io:
def import_calibratorConcentrations_add(self, filename):
"""table adds"""
<|body_0|>
def export_calibratorConcentrations_csv(self, filename, met_ids_I=[]):
"""export calibrator concentrations"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_003118 | 1,217 | permissive | [
{
"docstring": "table adds",
"name": "import_calibratorConcentrations_add",
"signature": "def import_calibratorConcentrations_add(self, filename)"
},
{
"docstring": "export calibrator concentrations",
"name": "export_calibratorConcentrations_csv",
"signature": "def export_calibratorConce... | 2 | stack_v2_sparse_classes_30k_train_003343 | Implement the Python class `lims_calibratorsAndMixes_io` described below.
Class description:
Implement the lims_calibratorsAndMixes_io class.
Method signatures and docstrings:
- def import_calibratorConcentrations_add(self, filename): table adds
- def export_calibratorConcentrations_csv(self, filename, met_ids_I=[]):... | Implement the Python class `lims_calibratorsAndMixes_io` described below.
Class description:
Implement the lims_calibratorsAndMixes_io class.
Method signatures and docstrings:
- def import_calibratorConcentrations_add(self, filename): table adds
- def export_calibratorConcentrations_csv(self, filename, met_ids_I=[]):... | 5dfd73689674953345d523178a67b8dda10e6d47 | <|skeleton|>
class lims_calibratorsAndMixes_io:
def import_calibratorConcentrations_add(self, filename):
"""table adds"""
<|body_0|>
def export_calibratorConcentrations_csv(self, filename, met_ids_I=[]):
"""export calibrator concentrations"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class lims_calibratorsAndMixes_io:
def import_calibratorConcentrations_add(self, filename):
"""table adds"""
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_calibratorConcentrations(data.data)
data.clear_data()
def export_calibratorCo... | the_stack_v2_python_sparse | SBaaS_LIMS/lims_calibratorsAndMixes_io.py | dmccloskey/SBaaS_LIMS | train | 0 | |
1f7f691e1f99e66cd931d86f44b09088c40b6866 | [
"context = context or {}\nwol_obj = self.pool.get('mrp.workorder.lot')\nres = False\nactive_id = context.get('active_id', False)\nactive_model = context.get('active_model', False)\nif active_id:\n if active_model == 'mrp.production':\n res = active_id\n elif active_model == 'mrp.workorder.lot':\n ... | <|body_start_0|>
context = context or {}
wol_obj = self.pool.get('mrp.workorder.lot')
res = False
active_id = context.get('active_id', False)
active_model = context.get('active_model', False)
if active_id:
if active_model == 'mrp.production':
r... | MrpProduce | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MrpProduce:
def _get_default_mo_id(self, cr, uid, context=None):
"""Return the production id."""
<|body_0|>
def _get_default_wo_lot(self, cr, uid, context=None):
"""@return: The first Work Order Lot ready to Produce (cardinal order)."""
<|body_1|>
def ac... | stack_v2_sparse_classes_10k_train_003119 | 14,637 | no_license | [
{
"docstring": "Return the production id.",
"name": "_get_default_mo_id",
"signature": "def _get_default_mo_id(self, cr, uid, context=None)"
},
{
"docstring": "@return: The first Work Order Lot ready to Produce (cardinal order).",
"name": "_get_default_wo_lot",
"signature": "def _get_def... | 5 | stack_v2_sparse_classes_30k_train_000147 | Implement the Python class `MrpProduce` described below.
Class description:
Implement the MrpProduce class.
Method signatures and docstrings:
- def _get_default_mo_id(self, cr, uid, context=None): Return the production id.
- def _get_default_wo_lot(self, cr, uid, context=None): @return: The first Work Order Lot ready... | Implement the Python class `MrpProduce` described below.
Class description:
Implement the MrpProduce class.
Method signatures and docstrings:
- def _get_default_mo_id(self, cr, uid, context=None): Return the production id.
- def _get_default_wo_lot(self, cr, uid, context=None): @return: The first Work Order Lot ready... | 9c588e45011a87ec8d9af73535c4c56485be92f7 | <|skeleton|>
class MrpProduce:
def _get_default_mo_id(self, cr, uid, context=None):
"""Return the production id."""
<|body_0|>
def _get_default_wo_lot(self, cr, uid, context=None):
"""@return: The first Work Order Lot ready to Produce (cardinal order)."""
<|body_1|>
def ac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MrpProduce:
def _get_default_mo_id(self, cr, uid, context=None):
"""Return the production id."""
context = context or {}
wol_obj = self.pool.get('mrp.workorder.lot')
res = False
active_id = context.get('active_id', False)
active_model = context.get('active_model... | the_stack_v2_python_sparse | addons-vauxoo/mrp_workorder_lot/wizard/mrp_consume_produce.py | OpenBusinessSolutions/odoo-fondeur-server | train | 1 | |
4d95b7f12dde84de2a60d1fabcae66ed0189e857 | [
"assert x_interpolated[-1] <= x_predicted[-1], 'x_predicted[-1]={} but x_interpolated[-1]={}'.format(x_predicted[-1], x_interpolated[-1])\nself.x_predicted = x_predicted\nself.x_interpolated = x_interpolated\nself.weights = tt.as_tensor_variable(interpolation_weights(x_predicted, x_interpolated))\nreturn super().__... | <|body_start_0|>
assert x_interpolated[-1] <= x_predicted[-1], 'x_predicted[-1]={} but x_interpolated[-1]={}'.format(x_predicted[-1], x_interpolated[-1])
self.x_predicted = x_predicted
self.x_interpolated = x_interpolated
self.weights = tt.as_tensor_variable(interpolation_weights(x_predi... | Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates. | InterpolationOps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolationOps:
"""Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates."""
def __init__(self, x_predicted, x_interpolated):
"""Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predi... | stack_v2_sparse_classes_10k_train_003120 | 10,590 | no_license | [
{
"docstring": "Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predicted (T_pred,) x_interpolated (ndarray): x-coordinates for which Y is desired (T_data,)",
"name": "__init__",
"signature": "def __init__(self, x_predicted, x_interpolated)"
},
{
... | 2 | stack_v2_sparse_classes_30k_val_000192 | Implement the Python class `InterpolationOps` described below.
Class description:
Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates.
Method signatures and docstrings:
- def __init__(self, x_predicted, x_interpolated): Prepare an interpolation subgraph. Args: x_pre... | Implement the Python class `InterpolationOps` described below.
Class description:
Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates.
Method signatures and docstrings:
- def __init__(self, x_predicted, x_interpolated): Prepare an interpolation subgraph. Args: x_pre... | da2b583efc7083a4d6bdbfc4c5deb3e92f380118 | <|skeleton|>
class InterpolationOps:
"""Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates."""
def __init__(self, x_predicted, x_interpolated):
"""Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InterpolationOps:
"""Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates."""
def __init__(self, x_predicted, x_interpolated):
"""Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predicted (T_pred,... | the_stack_v2_python_sparse | Find_RCR/RCR2_identification.py | PredictiveIntelligenceLab/1DBloodFlowPINNs | train | 44 |
97e64dfff814406b53f2dcbaa3b597ab8bb6e704 | [
"names = names or utils.generate_ids(count=count)\nkeypairs = []\nfor name in names:\n keypair = self._client.create(name, public_key=public_key)\n keypairs.append(keypair)\nif check:\n self.check_keypairs_presence(keypairs)\n for keypair in keypairs:\n if public_key is not None:\n ass... | <|body_start_0|>
names = names or utils.generate_ids(count=count)
keypairs = []
for name in names:
keypair = self._client.create(name, public_key=public_key)
keypairs.append(keypair)
if check:
self.check_keypairs_presence(keypairs)
for keyp... | Keypair steps. | KeypairSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeypairSteps:
"""Keypair steps."""
def create_keypairs(self, names=None, count=1, public_key=None, check=True):
"""Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. ... | stack_v2_sparse_classes_10k_train_003121 | 4,659 | no_license | [
{
"docstring": "Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. public_key (str, optional): Existing public key to import. check (bool, optional): Flag whether to check step or not. Returns: ... | 4 | stack_v2_sparse_classes_30k_train_003576 | Implement the Python class `KeypairSteps` described below.
Class description:
Keypair steps.
Method signatures and docstrings:
- def create_keypairs(self, names=None, count=1, public_key=None, check=True): Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count ... | Implement the Python class `KeypairSteps` described below.
Class description:
Keypair steps.
Method signatures and docstrings:
- def create_keypairs(self, names=None, count=1, public_key=None, check=True): Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count ... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class KeypairSteps:
"""Keypair steps."""
def create_keypairs(self, names=None, count=1, public_key=None, check=True):
"""Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KeypairSteps:
"""Keypair steps."""
def create_keypairs(self, names=None, count=1, public_key=None, check=True):
"""Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. public_key (s... | the_stack_v2_python_sparse | stepler/nova/steps/keypairs.py | Mirantis/stepler | train | 16 |
6e278751b2349560d1adc8299bde7d08ab4bc9ef | [
"syntax_options: SyntaxOptions = assert_not_none(self.config.syntax)\nspacy_model = spacy.load(syntax_options.spacy_model)\nutterances = batch[self.config.columns.text_input]\nrecords: List[TaggingResponse] = []\nfor utterance in utterances:\n tag: Dict[Tag, bool] = {smart_tag: False for family in [SmartTagFamil... | <|body_start_0|>
syntax_options: SyntaxOptions = assert_not_none(self.config.syntax)
spacy_model = spacy.load(syntax_options.spacy_model)
utterances = batch[self.config.columns.text_input]
records: List[TaggingResponse] = []
for utterance in utterances:
tag: Dict[Tag,... | Calculate smart tags related to syntax. | SyntaxTaggingModule | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyntaxTaggingModule:
"""Calculate smart tags related to syntax."""
def compute(self, batch: Dataset) -> List[TaggingResponse]:
"""Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags."""
... | stack_v2_sparse_classes_10k_train_003122 | 3,923 | permissive | [
{
"docstring": "Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags.",
"name": "compute",
"signature": "def compute(self, batch: Dataset) -> List[TaggingResponse]"
},
{
"docstring": "Save tags in a Dataset... | 2 | stack_v2_sparse_classes_30k_train_005659 | Implement the Python class `SyntaxTaggingModule` described below.
Class description:
Calculate smart tags related to syntax.
Method signatures and docstrings:
- def compute(self, batch: Dataset) -> List[TaggingResponse]: Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the sma... | Implement the Python class `SyntaxTaggingModule` described below.
Class description:
Calculate smart tags related to syntax.
Method signatures and docstrings:
- def compute(self, batch: Dataset) -> List[TaggingResponse]: Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the sma... | 34081048a4de3900ca29ac0d37bce7026113382c | <|skeleton|>
class SyntaxTaggingModule:
"""Calculate smart tags related to syntax."""
def compute(self, batch: Dataset) -> List[TaggingResponse]:
"""Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyntaxTaggingModule:
"""Calculate smart tags related to syntax."""
def compute(self, batch: Dataset) -> List[TaggingResponse]:
"""Get smart tags for provided indices. Args: batch: the batch on which we want to calculate the smart tags. Returns: tags: Newly calculated tags."""
syntax_optio... | the_stack_v2_python_sparse | azimuth/modules/dataset_analysis/syntax_tagging.py | ServiceNow/azimuth | train | 172 |
bfdd49cd90a026198a67008d7f3c9a5d10e9bb98 | [
"import itertools\nfor p in itertools.permutations(pieces):\n l = list(chain.from_iterable(p))\n if l == arr:\n return True\nreturn False",
"mp = {x[0]: x for x in pieces}\nret = []\nfor num in arr:\n ret += mp.get(num, [])\nreturn ret == arr"
] | <|body_start_0|>
import itertools
for p in itertools.permutations(pieces):
l = list(chain.from_iterable(p))
if l == arr:
return True
return False
<|end_body_0|>
<|body_start_1|>
mp = {x[0]: x for x in pieces}
ret = []
for num in ar... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFormArray_TLE(self, arr, pieces):
""":type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE."""
<|body_0|>
def canFormArra... | stack_v2_sparse_classes_10k_train_003123 | 2,422 | no_license | [
{
"docstring": ":type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE.",
"name": "canFormArray_TLE",
"signature": "def canFormArray_TLE(self, arr, pieces)"
},
{
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFormArray_TLE(self, arr, pieces): :type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFormArray_TLE(self, arr, pieces): :type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all ... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class Solution:
def canFormArray_TLE(self, arr, pieces):
""":type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE."""
<|body_0|>
def canFormArra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canFormArray_TLE(self, arr, pieces):
""":type arr: List[int] :type pieces: List[List[int]] :rtype: bool thought: get all permutation of pieces, choose length == len(arr) in all subset and compare with arr. general solution but TLE."""
import itertools
for p in itertools.p... | the_stack_v2_python_sparse | N1640_CheckArrayFormationThroughConcatenation.py | zerghua/leetcode-python | train | 2 | |
02f7cbfdcd0850f287bea5aca534dde80e41c411 | [
"super().at_object_creation()\nself.db.puzzle_value = 1\nself.db.success_teleport_msg = 'You are successful!'\nself.db.success_teleport_to = 'treasure room'\nself.db.failure_teleport_msg = 'You fail!'\nself.db.failure_teleport_to = 'dark cell'",
"if not character.has_account:\n return\nis_success = str(charact... | <|body_start_0|>
super().at_object_creation()
self.db.puzzle_value = 1
self.db.success_teleport_msg = 'You are successful!'
self.db.success_teleport_to = 'treasure room'
self.db.failure_teleport_msg = 'You fail!'
self.db.failure_teleport_to = 'dark cell'
<|end_body_0|>
<... | Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to success failure_teleport_to - wh... | TeleportRoom | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeleportRoom:
"""Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while telepor... | stack_v2_sparse_classes_10k_train_003124 | 42,922 | permissive | [
{
"docstring": "Called at first creation",
"name": "at_object_creation",
"signature": "def at_object_creation(self)"
},
{
"docstring": "This hook is called by the engine whenever the player is moved into this room.",
"name": "at_object_receive",
"signature": "def at_object_receive(self, ... | 2 | stack_v2_sparse_classes_30k_train_001843 | Implement the Python class `TeleportRoom` described below.
Class description:
Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_telep... | Implement the Python class `TeleportRoom` described below.
Class description:
Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_telep... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TeleportRoom:
"""Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while telepor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeleportRoom:
"""Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to succe... | the_stack_v2_python_sparse | evennia/contrib/tutorials/tutorial_world/rooms.py | evennia/evennia | train | 1,781 |
427a77aab7bee7ca1fc1aa9d8b5126cc4d11d290 | [
"parser.add_argument('--player', nargs=1, help='Player')\nparser.add_argument('--contest', nargs=1, help='Contest ID', type=int)\nparser.add_argument('--after-date', nargs=1, help='After date', type=convert_to_date)",
"players = Player.objects.all()\ncontest_id = None\nafter_date = None\nif 'player' in opts and o... | <|body_start_0|>
parser.add_argument('--player', nargs=1, help='Player')
parser.add_argument('--contest', nargs=1, help='Contest ID', type=int)
parser.add_argument('--after-date', nargs=1, help='After date', type=convert_to_date)
<|end_body_0|>
<|body_start_1|>
players = Player.objects.... | A command which loads checkins for a player or many players for a given contest. | Command | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""A command which loads checkins for a player or many players for a given contest."""
def add_arguments(self, parser):
"""There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which t... | stack_v2_sparse_classes_10k_train_003125 | 2,490 | permissive | [
{
"docstring": "There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which to filter the results",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Primarily call... | 2 | stack_v2_sparse_classes_30k_train_001571 | Implement the Python class `Command` described below.
Class description:
A command which loads checkins for a player or many players for a given contest.
Method signatures and docstrings:
- def add_arguments(self, parser): There are three optional arguments for the command: --player: the user name of the player --con... | Implement the Python class `Command` described below.
Class description:
A command which loads checkins for a player or many players for a given contest.
Method signatures and docstrings:
- def add_arguments(self, parser): There are three optional arguments for the command: --player: the user name of the player --con... | 96af46ad946e63736f9924cb3b966b0d597254f5 | <|skeleton|>
class Command:
"""A command which loads checkins for a player or many players for a given contest."""
def add_arguments(self, parser):
"""There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Command:
"""A command which loads checkins for a player or many players for a given contest."""
def add_arguments(self, parser):
"""There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which to filter the ... | the_stack_v2_python_sparse | beers/management/commands/load_checkins.py | nvembar/onehundredbeers | train | 1 |
f8a9102c69dabe6ce3b7eb3e049cc2498447e0f5 | [
"self.name = name\nself.client_balancing_enabled = client_balancing_enabled\nself.min_bitrate_type = min_bitrate_type\nself.band_selection_type = band_selection_type\nself.ap_band_settings = ap_band_settings\nself.two_four_ghz_settings = two_four_ghz_settings\nself.five_ghz_settings = five_ghz_settings",
"if dict... | <|body_start_0|>
self.name = name
self.client_balancing_enabled = client_balancing_enabled
self.min_bitrate_type = min_bitrate_type
self.band_selection_type = band_selection_type
self.ap_band_settings = ap_band_settings
self.two_four_ghz_settings = two_four_ghz_settings
... | Implementation of the 'createNetworkWirelessRfProfile' model. TODO: type model description here. Attributes: name (string): The name of the new profile. Must be unique. This param is required on creation. client_balancing_enabled (bool): Steers client to best available access point. Can be either true or false. Default... | CreateNetworkWirelessRfProfileModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateNetworkWirelessRfProfileModel:
"""Implementation of the 'createNetworkWirelessRfProfile' model. TODO: type model description here. Attributes: name (string): The name of the new profile. Must be unique. This param is required on creation. client_balancing_enabled (bool): Steers client to be... | stack_v2_sparse_classes_10k_train_003126 | 4,356 | permissive | [
{
"docstring": "Constructor for the CreateNetworkWirelessRfProfileModel class",
"name": "__init__",
"signature": "def __init__(self, name=None, band_selection_type=None, client_balancing_enabled=None, min_bitrate_type=None, ap_band_settings=None, two_four_ghz_settings=None, five_ghz_settings=None)"
},... | 2 | stack_v2_sparse_classes_30k_train_004595 | Implement the Python class `CreateNetworkWirelessRfProfileModel` described below.
Class description:
Implementation of the 'createNetworkWirelessRfProfile' model. TODO: type model description here. Attributes: name (string): The name of the new profile. Must be unique. This param is required on creation. client_balanc... | Implement the Python class `CreateNetworkWirelessRfProfileModel` described below.
Class description:
Implementation of the 'createNetworkWirelessRfProfile' model. TODO: type model description here. Attributes: name (string): The name of the new profile. Must be unique. This param is required on creation. client_balanc... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class CreateNetworkWirelessRfProfileModel:
"""Implementation of the 'createNetworkWirelessRfProfile' model. TODO: type model description here. Attributes: name (string): The name of the new profile. Must be unique. This param is required on creation. client_balancing_enabled (bool): Steers client to be... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateNetworkWirelessRfProfileModel:
"""Implementation of the 'createNetworkWirelessRfProfile' model. TODO: type model description here. Attributes: name (string): The name of the new profile. Must be unique. This param is required on creation. client_balancing_enabled (bool): Steers client to best available ... | the_stack_v2_python_sparse | meraki_sdk/models/create_network_wireless_rf_profile_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
c55960c80f23835a9bafb2dce4d22c3ae89bd214 | [
"request_payload = {}\nc = commons.parse_coordinates(coordinates).transform_to('icrs')\nra_dec_str = str(c.ra.hour) + ' ' + str(c.dec.degree)\nrequest_payload['RA'] = ra_dec_str\nrequest_payload['Equinox'] = 'J2000'\nrequest_payload['ImageSize'] = coord.Angle(image_size).arcmin\nrequest_payload['ImageType'] = 'FITS... | <|body_start_0|>
request_payload = {}
c = commons.parse_coordinates(coordinates).transform_to('icrs')
ra_dec_str = str(c.ra.hour) + ' ' + str(c.dec.degree)
request_payload['RA'] = ra_dec_str
request_payload['Equinox'] = 'J2000'
request_payload['ImageSize'] = coord.Angle(i... | FirstClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstClass:
def _args_to_payload(self, coordinates, *, image_size=1 * u.arcmin, maximsize=None):
"""Fetches image cutouts from FIRST survey. Parameters ---------- coordinates : str or `astropy.coordinates` object The target around which to search. It may be specified as a string in which... | stack_v2_sparse_classes_10k_train_003127 | 3,737 | permissive | [
{
"docstring": "Fetches image cutouts from FIRST survey. Parameters ---------- coordinates : str or `astropy.coordinates` object The target around which to search. It may be specified as a string in which case it is resolved using online services or as the appropriate `astropy.coordinates` object. ICRS coordina... | 3 | stack_v2_sparse_classes_30k_train_001762 | Implement the Python class `FirstClass` described below.
Class description:
Implement the FirstClass class.
Method signatures and docstrings:
- def _args_to_payload(self, coordinates, *, image_size=1 * u.arcmin, maximsize=None): Fetches image cutouts from FIRST survey. Parameters ---------- coordinates : str or `astr... | Implement the Python class `FirstClass` described below.
Class description:
Implement the FirstClass class.
Method signatures and docstrings:
- def _args_to_payload(self, coordinates, *, image_size=1 * u.arcmin, maximsize=None): Fetches image cutouts from FIRST survey. Parameters ---------- coordinates : str or `astr... | 51316d7417d7daf01a8b29d1df99037b9227c2bc | <|skeleton|>
class FirstClass:
def _args_to_payload(self, coordinates, *, image_size=1 * u.arcmin, maximsize=None):
"""Fetches image cutouts from FIRST survey. Parameters ---------- coordinates : str or `astropy.coordinates` object The target around which to search. It may be specified as a string in which... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FirstClass:
def _args_to_payload(self, coordinates, *, image_size=1 * u.arcmin, maximsize=None):
"""Fetches image cutouts from FIRST survey. Parameters ---------- coordinates : str or `astropy.coordinates` object The target around which to search. It may be specified as a string in which case it is re... | the_stack_v2_python_sparse | astroquery/image_cutouts/first/core.py | astropy/astroquery | train | 636 | |
27ba1038e570a31a52e853978f902685f04e0541 | [
"try:\n axes = tf_to_shape_axes(tf_node.attr['shape'])\nexcept:\n raise NotImplementedError('Shape must be know prior to execution')\nreturn ng.variable(axes).named(tf_node.name)",
"\"\"\"\n TODO: currently cannot fully support the TensorFlow semantics.\n 1. Assign in TF returns the assigned t... | <|body_start_0|>
try:
axes = tf_to_shape_axes(tf_node.attr['shape'])
except:
raise NotImplementedError('Shape must be know prior to execution')
return ng.variable(axes).named(tf_node.name)
<|end_body_0|>
<|body_start_1|>
"""
TODO: currently cannot... | Mix-in class for variable op | OpsVariable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpsVariable:
"""Mix-in class for variable op"""
def Variable(self, tf_node, inputs):
"""Creates a trainable variable. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to this node. Returns: A ngraph Op corresponding to the tenso... | stack_v2_sparse_classes_10k_train_003128 | 3,663 | permissive | [
{
"docstring": "Creates a trainable variable. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to this node. Returns: A ngraph Op corresponding to the tensorflow node.",
"name": "Variable",
"signature": "def Variable(self, tf_node, inputs)"
},
... | 4 | stack_v2_sparse_classes_30k_train_000129 | Implement the Python class `OpsVariable` described below.
Class description:
Mix-in class for variable op
Method signatures and docstrings:
- def Variable(self, tf_node, inputs): Creates a trainable variable. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to t... | Implement the Python class `OpsVariable` described below.
Class description:
Mix-in class for variable op
Method signatures and docstrings:
- def Variable(self, tf_node, inputs): Creates a trainable variable. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to t... | 4ee9c1ede6bd5ec83addcc3f4e7c383a12fffded | <|skeleton|>
class OpsVariable:
"""Mix-in class for variable op"""
def Variable(self, tf_node, inputs):
"""Creates a trainable variable. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to this node. Returns: A ngraph Op corresponding to the tenso... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpsVariable:
"""Mix-in class for variable op"""
def Variable(self, tf_node, inputs):
"""Creates a trainable variable. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to this node. Returns: A ngraph Op corresponding to the tensorflow node.""... | the_stack_v2_python_sparse | ngraph/frontends/tensorflow/tf_importer/ops_variable.py | millerhooks/ngraph | train | 0 |
91849bd87854fc621ce116483c69ee77ff3bd641 | [
"super().__init__(*args, data=data, **kwargs)\nif not data or not data.get('q', None):\n self.fields['sort'].widget.choices[0] = (self.SORT_CHOICES[0][0], {'label': self.SORT_CHOICES[0][1], 'disabled': True})",
"if self.is_valid():\n return bool({k: v for k, v in self.cleaned_data.items() if k not in ['q', ... | <|body_start_0|>
super().__init__(*args, data=data, **kwargs)
if not data or not data.get('q', None):
self.fields['sort'].widget.choices[0] = (self.SORT_CHOICES[0][0], {'label': self.SORT_CHOICES[0][1], 'disabled': True})
<|end_body_0|>
<|body_start_1|>
if self.is_valid():
... | DocumentSearchForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSearchForm:
def __init__(self, data=None, *args, **kwargs):
"""Override to set choices dynamically based on form kwargs."""
<|body_0|>
def filters_active(self):
"""Check if any filters are active; returns true if form fields other than sort or q are set"""
... | stack_v2_sparse_classes_10k_train_003129 | 15,339 | permissive | [
{
"docstring": "Override to set choices dynamically based on form kwargs.",
"name": "__init__",
"signature": "def __init__(self, data=None, *args, **kwargs)"
},
{
"docstring": "Check if any filters are active; returns true if form fields other than sort or q are set",
"name": "filters_active... | 5 | stack_v2_sparse_classes_30k_train_005098 | Implement the Python class `DocumentSearchForm` described below.
Class description:
Implement the DocumentSearchForm class.
Method signatures and docstrings:
- def __init__(self, data=None, *args, **kwargs): Override to set choices dynamically based on form kwargs.
- def filters_active(self): Check if any filters are... | Implement the Python class `DocumentSearchForm` described below.
Class description:
Implement the DocumentSearchForm class.
Method signatures and docstrings:
- def __init__(self, data=None, *args, **kwargs): Override to set choices dynamically based on form kwargs.
- def filters_active(self): Check if any filters are... | 65660de1a07c3bb3390d0161995f7fe305a5079b | <|skeleton|>
class DocumentSearchForm:
def __init__(self, data=None, *args, **kwargs):
"""Override to set choices dynamically based on form kwargs."""
<|body_0|>
def filters_active(self):
"""Check if any filters are active; returns true if form fields other than sort or q are set"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DocumentSearchForm:
def __init__(self, data=None, *args, **kwargs):
"""Override to set choices dynamically based on form kwargs."""
super().__init__(*args, data=data, **kwargs)
if not data or not data.get('q', None):
self.fields['sort'].widget.choices[0] = (self.SORT_CHOICE... | the_stack_v2_python_sparse | geniza/corpus/forms.py | Princeton-CDH/geniza | train | 14 | |
b42213ff3dbf14aa0a28da07419e8467e99ecd60 | [
"Command.__init__(self, device_name, configuration, plugin_manager, logger)\nself.device = self.configuration.get_device(self.device_name)\nif self.device.get('provisioner') is None:\n raise RuntimeError('No provisioner is specified in the config. Cannot perform command.')\nself.provisioner = self.plugin_manager... | <|body_start_0|>
Command.__init__(self, device_name, configuration, plugin_manager, logger)
self.device = self.configuration.get_device(self.device_name)
if self.device.get('provisioner') is None:
raise RuntimeError('No provisioner is specified in the config. Cannot perform command.'... | Delete a device from the provisioner. | ProvisionerDeleteCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProvisionerDeleteCommand:
"""Delete a device from the provisioner."""
def __init__(self, device_name, configuration, plugin_manager, logger=None):
"""Retrieve dependencies, prepare to perform command."""
<|body_0|>
def execute(self):
"""Execute the command"""
... | stack_v2_sparse_classes_10k_train_003130 | 1,450 | permissive | [
{
"docstring": "Retrieve dependencies, prepare to perform command.",
"name": "__init__",
"signature": "def __init__(self, device_name, configuration, plugin_manager, logger=None)"
},
{
"docstring": "Execute the command",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006605 | Implement the Python class `ProvisionerDeleteCommand` described below.
Class description:
Delete a device from the provisioner.
Method signatures and docstrings:
- def __init__(self, device_name, configuration, plugin_manager, logger=None): Retrieve dependencies, prepare to perform command.
- def execute(self): Execu... | Implement the Python class `ProvisionerDeleteCommand` described below.
Class description:
Delete a device from the provisioner.
Method signatures and docstrings:
- def __init__(self, device_name, configuration, plugin_manager, logger=None): Retrieve dependencies, prepare to perform command.
- def execute(self): Execu... | b0c88b877921dda20d0af4dab6497a50600d975d | <|skeleton|>
class ProvisionerDeleteCommand:
"""Delete a device from the provisioner."""
def __init__(self, device_name, configuration, plugin_manager, logger=None):
"""Retrieve dependencies, prepare to perform command."""
<|body_0|>
def execute(self):
"""Execute the command"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProvisionerDeleteCommand:
"""Delete a device from the provisioner."""
def __init__(self, device_name, configuration, plugin_manager, logger=None):
"""Retrieve dependencies, prepare to perform command."""
Command.__init__(self, device_name, configuration, plugin_manager, logger)
se... | the_stack_v2_python_sparse | actsys/control/commands/provisioner/provisioner_delete.py | intel-ctrlsys/actsys | train | 5 |
5f440a899da988eee813e52019ee88b6be330be3 | [
"params = {} if params is None else params\nparams.update({'type': params.get('type', 'hive')})\nwith self.post(create_url('/v3/schedule/create/{name}', name=name), params) as res:\n code, body = (res.status, res.read())\n if code != 200:\n self.raise_error('Create schedule failed', res, body)\n js ... | <|body_start_0|>
params = {} if params is None else params
params.update({'type': params.get('type', 'hive')})
with self.post(create_url('/v3/schedule/create/{name}', name=name), params) as res:
code, body = (res.status, res.read())
if code != 200:
self.ra... | Access to Schedule API This class is inherited by :class:`tdclient.api.API`. | ScheduleAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleAPI:
"""Access to Schedule API This class is inherited by :class:`tdclient.api.API`."""
def create_schedule(self, name, params=None):
"""Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - ... | stack_v2_sparse_classes_10k_train_003131 | 9,750 | permissive | [
{
"docstring": "Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - type (str): Query type. {\"presto\", \"hive\"}. Default: \"hive\" - database (str): Target database name. - timezone (str): Scheduled query's timezone. e.g. ... | 6 | stack_v2_sparse_classes_30k_train_002238 | Implement the Python class `ScheduleAPI` described below.
Class description:
Access to Schedule API This class is inherited by :class:`tdclient.api.API`.
Method signatures and docstrings:
- def create_schedule(self, name, params=None): Create a new scheduled query with the specified name. Args: name (str): Scheduled ... | Implement the Python class `ScheduleAPI` described below.
Class description:
Access to Schedule API This class is inherited by :class:`tdclient.api.API`.
Method signatures and docstrings:
- def create_schedule(self, name, params=None): Create a new scheduled query with the specified name. Args: name (str): Scheduled ... | aa6b1ffe886483cf4a41557d7e72063e49d6c787 | <|skeleton|>
class ScheduleAPI:
"""Access to Schedule API This class is inherited by :class:`tdclient.api.API`."""
def create_schedule(self, name, params=None):
"""Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScheduleAPI:
"""Access to Schedule API This class is inherited by :class:`tdclient.api.API`."""
def create_schedule(self, name, params=None):
"""Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - type (str): Q... | the_stack_v2_python_sparse | tdclient/schedule_api.py | treasure-data/td-client-python | train | 41 |
4d1eb8d7db518a4fcaf6c84aad66d55505a3e4c8 | [
"result = 0\nwhile n != 0:\n digit = n % 10\n result += digit\n n /= 10\n if n != 0:\n result *= 10\nreturn result",
"if x < 0:\n return False\nreturn self.reverseInteger(abs(x)) == abs(x)"
] | <|body_start_0|>
result = 0
while n != 0:
digit = n % 10
result += digit
n /= 10
if n != 0:
result *= 10
return result
<|end_body_0|>
<|body_start_1|>
if x < 0:
return False
return self.reverseInteger(ab... | Solution reverses the integer, then checks if the reversed integer equals the original integer. If it does, it's a palindrome | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution reverses the integer, then checks if the reversed integer equals the original integer. If it does, it's a palindrome"""
def reverseInteger(self, n):
"""Reverses a number and returns the reversed number"""
<|body_0|>
def isPalindrome(self, x):
... | stack_v2_sparse_classes_10k_train_003132 | 776 | no_license | [
{
"docstring": "Reverses a number and returns the reversed number",
"name": "reverseInteger",
"signature": "def reverseInteger(self, n)"
},
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004359 | Implement the Python class `Solution` described below.
Class description:
Solution reverses the integer, then checks if the reversed integer equals the original integer. If it does, it's a palindrome
Method signatures and docstrings:
- def reverseInteger(self, n): Reverses a number and returns the reversed number
- d... | Implement the Python class `Solution` described below.
Class description:
Solution reverses the integer, then checks if the reversed integer equals the original integer. If it does, it's a palindrome
Method signatures and docstrings:
- def reverseInteger(self, n): Reverses a number and returns the reversed number
- d... | f5bb79266f2bfed9fba0b92e06b93b308eb49767 | <|skeleton|>
class Solution:
"""Solution reverses the integer, then checks if the reversed integer equals the original integer. If it does, it's a palindrome"""
def reverseInteger(self, n):
"""Reverses a number and returns the reversed number"""
<|body_0|>
def isPalindrome(self, x):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution reverses the integer, then checks if the reversed integer equals the original integer. If it does, it's a palindrome"""
def reverseInteger(self, n):
"""Reverses a number and returns the reversed number"""
result = 0
while n != 0:
digit = n % 10
... | the_stack_v2_python_sparse | palindrome_number.py | DarinM223/leetcode | train | 0 |
596414087501bbbf78c8c5b7a198a82ffe5727c9 | [
"self.require_collection()\nrequest = http.Request('POST', self.get_url(), self.wrap_object({}))\nreturn (request, parsers.parse_json)",
"self.require_collection()\nrequest = http.Request('DELETE', self.get_url())\nreturn (request, parsers.parse_empty)"
] | <|body_start_0|>
self.require_collection()
request = http.Request('POST', self.get_url(), self.wrap_object({}))
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
self.require_collection()
request = http.Request('DELETE', self.get_url())
return (request... | Likes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Likes:
def create(self):
"""Set a like on this media by the currently authenticated user."""
<|body_0|>
def delete(self):
"""Remove a like on this media by the currently authenticated user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.requir... | stack_v2_sparse_classes_10k_train_003133 | 832 | permissive | [
{
"docstring": "Set a like on this media by the currently authenticated user.",
"name": "create",
"signature": "def create(self)"
},
{
"docstring": "Remove a like on this media by the currently authenticated user.",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | null | Implement the Python class `Likes` described below.
Class description:
Implement the Likes class.
Method signatures and docstrings:
- def create(self): Set a like on this media by the currently authenticated user.
- def delete(self): Remove a like on this media by the currently authenticated user. | Implement the Python class `Likes` described below.
Class description:
Implement the Likes class.
Method signatures and docstrings:
- def create(self): Set a like on this media by the currently authenticated user.
- def delete(self): Remove a like on this media by the currently authenticated user.
<|skeleton|>
class... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Likes:
def create(self):
"""Set a like on this media by the currently authenticated user."""
<|body_0|>
def delete(self):
"""Remove a like on this media by the currently authenticated user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Likes:
def create(self):
"""Set a like on this media by the currently authenticated user."""
self.require_collection()
request = http.Request('POST', self.get_url(), self.wrap_object({}))
return (request, parsers.parse_json)
def delete(self):
"""Remove a like on th... | the_stack_v2_python_sparse | libsaas/services/instagram/likes.py | piplcom/libsaas | train | 1 | |
11d7ad0146b63656733bc07d42cab8febb365031 | [
"super().__init__()\nout_channels = channels * self.expansion\nif cardinality == 1:\n rc = channels\nelse:\n width_ratio = channels * (width / self.start_filts)\n rc = cardinality * math.floor(width_ratio)\nself.conv_reduce = ConvNd(n_dim, in_channels, rc, kernel_size=1, stride=1, padding=0, bias=False)\ns... | <|body_start_0|>
super().__init__()
out_channels = channels * self.expansion
if cardinality == 1:
rc = channels
else:
width_ratio = channels * (width / self.start_filts)
rc = cardinality * math.floor(width_ratio)
self.conv_reduce = ConvNd(n_dim... | _BottleneckX | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BottleneckX:
def __init__(self, in_channels: int, channels: int, stride: Union[int, Sequence[int]], cardinality: int, width: int, n_dim: int, norm_layer: str):
"""Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer cardinality : ... | stack_v2_sparse_classes_10k_train_003134 | 12,047 | permissive | [
{
"docstring": "Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer cardinality : int number of convolution groups width : int width of resnext block n_dim : int dimensionality of convolutions norm_layer: str type of normalization layer",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_005031 | Implement the Python class `_BottleneckX` described below.
Class description:
Implement the _BottleneckX class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, channels: int, stride: Union[int, Sequence[int]], cardinality: int, width: int, n_dim: int, norm_layer: str): Parameters ---------- i... | Implement the Python class `_BottleneckX` described below.
Class description:
Implement the _BottleneckX class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, channels: int, stride: Union[int, Sequence[int]], cardinality: int, width: int, n_dim: int, norm_layer: str): Parameters ---------- i... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class _BottleneckX:
def __init__(self, in_channels: int, channels: int, stride: Union[int, Sequence[int]], cardinality: int, width: int, n_dim: int, norm_layer: str):
"""Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer cardinality : ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _BottleneckX:
def __init__(self, in_channels: int, channels: int, stride: Union[int, Sequence[int]], cardinality: int, width: int, n_dim: int, norm_layer: str):
"""Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer cardinality : int number of ... | the_stack_v2_python_sparse | dlutils/models/resnext.py | justusschock/dl-utils | train | 15 | |
f34ed7cefef032834977ea80bb5298dd76215b3e | [
"warning_suffix = 'which will cause some Telemetry tests to stall when run on a headless machine (e.g. perf bot).'\nif keychain_helper.IsKeychainLocked():\n logging.warning('The default keychain is locked, %s', warning_suffix)\nif keychain_helper.DoesKeychainHaveTimeout():\n logging.warning('The default keych... | <|body_start_0|>
warning_suffix = 'which will cause some Telemetry tests to stall when run on a headless machine (e.g. perf bot).'
if keychain_helper.IsKeychainLocked():
logging.warning('The default keychain is locked, %s', warning_suffix)
if keychain_helper.DoesKeychainHaveTimeout()... | KeychainMetric gathers keychain statistics from the browser object. This includes the number of times that the keychain was accessed. | KeychainMetric | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeychainMetric:
"""KeychainMetric gathers keychain statistics from the browser object. This includes the number of times that the keychain was accessed."""
def _CheckKeychainConfiguration():
"""On OSX, it is possible for a misconfigured keychain to cause the Telemetry tests to stall.... | stack_v2_sparse_classes_10k_train_003135 | 2,966 | permissive | [
{
"docstring": "On OSX, it is possible for a misconfigured keychain to cause the Telemetry tests to stall. This method confirms that the keychain is in a sane state that will not cause this behavior. Three conditions are checked: - The keychain is unlocked. - The keychain will not auto-lock after a period of ti... | 3 | stack_v2_sparse_classes_30k_train_001071 | Implement the Python class `KeychainMetric` described below.
Class description:
KeychainMetric gathers keychain statistics from the browser object. This includes the number of times that the keychain was accessed.
Method signatures and docstrings:
- def _CheckKeychainConfiguration(): On OSX, it is possible for a misc... | Implement the Python class `KeychainMetric` described below.
Class description:
KeychainMetric gathers keychain statistics from the browser object. This includes the number of times that the keychain was accessed.
Method signatures and docstrings:
- def _CheckKeychainConfiguration(): On OSX, it is possible for a misc... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class KeychainMetric:
"""KeychainMetric gathers keychain statistics from the browser object. This includes the number of times that the keychain was accessed."""
def _CheckKeychainConfiguration():
"""On OSX, it is possible for a misconfigured keychain to cause the Telemetry tests to stall.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KeychainMetric:
"""KeychainMetric gathers keychain statistics from the browser object. This includes the number of times that the keychain was accessed."""
def _CheckKeychainConfiguration():
"""On OSX, it is possible for a misconfigured keychain to cause the Telemetry tests to stall. This method ... | the_stack_v2_python_sparse | tools/perf/metrics/keychain_metric.py | metux/chromium-suckless | train | 5 |
2aee99df7590ac9a3497af616c93d882ecadc554 | [
"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... | Missing associated documentation comment in .proto file. | ResultServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultServiceServicer:
"""Missing associated documentation comment in .proto file."""
def SignalResultsReady(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def FinishSequence(self, request, context):
"""Missing ... | stack_v2_sparse_classes_10k_train_003136 | 10,385 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "SignalResultsReady",
"signature": "def SignalResultsReady(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "FinishSequence",
"signature": "def... | 4 | stack_v2_sparse_classes_30k_val_000096 | Implement the Python class `ResultServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def SignalResultsReady(self, request, context): Missing associated documentation comment in .proto file.
- def FinishSequence(self, reques... | Implement the Python class `ResultServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def SignalResultsReady(self, request, context): Missing associated documentation comment in .proto file.
- def FinishSequence(self, reques... | a83a60c40eda7051a73363f67cb806ad73637e7a | <|skeleton|>
class ResultServiceServicer:
"""Missing associated documentation comment in .proto file."""
def SignalResultsReady(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def FinishSequence(self, request, context):
"""Missing ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResultServiceServicer:
"""Missing associated documentation comment in .proto file."""
def SignalResultsReady(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not impl... | the_stack_v2_python_sparse | sap-toolkit/sap_toolkit/generated/eval_server_pb2_grpc.py | jelasus/sap-starterkit | train | 0 |
d020b4ba0f5d54bcc91221ef2c1503192c9c019c | [
"if not isinstance(expr, (str, list, int)):\n raise TypeError('expr must be a string, int or a list of string, int.'.format(expr))\nself.expr = expr\nself.to = to\nself.container = cont",
"if id(self.container) != id(col2.container):\n raise RuntimeError('Only one container is allowed.')\nif self.to is not ... | <|body_start_0|>
if not isinstance(expr, (str, list, int)):
raise TypeError('expr must be a string, int or a list of string, int.'.format(expr))
self.expr = expr
self.to = to
self.container = cont
<|end_body_0|>
<|body_start_1|>
if id(self.container) != id(col2.conta... | Column selector. | COL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be ... | stack_v2_sparse_classes_10k_train_003137 | 35,835 | permissive | [
{
"docstring": ":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be the previous transform in the pipeline",
"name": "__init__",
"signature": "def __... | 4 | null | Implement the Python class `COL` described below.
Class description:
Column selector.
Method signatures and docstrings:
- def __init__(self, expr, to=None, cont=None): :param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists),... | Implement the Python class `COL` described below.
Class description:
Column selector.
Method signatures and docstrings:
- def __init__(self, expr, to=None, cont=None): :param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists),... | b5f1c2e3422fadc81e21337bcddb7372682dd455 | <|skeleton|>
class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be the previous ... | the_stack_v2_python_sparse | src/python/nimbusml/internal/utils/data_schema.py | zyw400/NimbusML-1 | train | 3 |
8d8a27c96722f40c718b80d25ad8ee9d178e2899 | [
"m = defaultdict(int)\nn = len(A)\nS = [0] * (n + 1)\nans = 0\nfor i, num in enumerate(A):\n S[i + 1] = S[i] + num\nm[S[0]] += 1\nfor s in S[1:]:\n t = s % K\n if t in m:\n ans += m[t]\n m[t] += 1\nreturn ans",
"m = defaultdict(int)\nm[0] = 1\nsums, ans = (0, 0)\nfor a in A:\n sums += a\n ... | <|body_start_0|>
m = defaultdict(int)
n = len(A)
S = [0] * (n + 1)
ans = 0
for i, num in enumerate(A):
S[i + 1] = S[i] + num
m[S[0]] += 1
for s in S[1:]:
t = s % K
if t in m:
ans += m[t]
m[t] += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraysDivByK(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def subarraysDivByK2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = defaultdict(... | stack_v2_sparse_classes_10k_train_003138 | 1,475 | no_license | [
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "subarraysDivByK",
"signature": "def subarraysDivByK(self, A, K)"
},
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "subarraysDivByK2",
"signature": "def subarraysDivByK2(self, A, K)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006228 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK(self, A, K): :type A: List[int] :type K: int :rtype: int
- def subarraysDivByK2(self, A, K): :type A: List[int] :type K: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK(self, A, K): :type A: List[int] :type K: int :rtype: int
- def subarraysDivByK2(self, A, K): :type A: List[int] :type K: int :rtype: int
<|skeleton|>
class S... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def subarraysDivByK(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def subarraysDivByK2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraysDivByK(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
m = defaultdict(int)
n = len(A)
S = [0] * (n + 1)
ans = 0
for i, num in enumerate(A):
S[i + 1] = S[i] + num
m[S[0]] += 1
for s in S[1:]:
... | the_stack_v2_python_sparse | S/SubarraySumsDivisibleByK.py | bssrdf/pyleet | train | 2 | |
0a11d970678b1787807bb3d4a261fb5f33e2c368 | [
"hashMap = {}\nfor c in s:\n if c not in hashMap:\n hashMap[c] = 1\n else:\n hashMap[c] += 1\nfor c in t:\n if c not in hashMap:\n return False\n else:\n hashMap[c] -= 1\nfor key in hashMap:\n if hashMap[key] != 0:\n return False\nreturn True",
"if len(s) != len(t... | <|body_start_0|>
hashMap = {}
for c in s:
if c not in hashMap:
hashMap[c] = 1
else:
hashMap[c] += 1
for c in t:
if c not in hashMap:
return False
else:
hashMap[c] -= 1
for key ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isAnagram_self(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hashMap = {}
for c in s:
... | stack_v2_sparse_classes_10k_train_003139 | 1,068 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram",
"signature": "def isAnagram(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram_self",
"signature": "def isAnagram_self(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def isAnagram_self(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def isAnagram_self(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solution:
def ... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isAnagram_self(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
hashMap = {}
for c in s:
if c not in hashMap:
hashMap[c] = 1
else:
hashMap[c] += 1
for c in t:
if c not in hashMap:
... | the_stack_v2_python_sparse | 242_valid_anagram/sol.py | lianke123321/leetcode_sol | train | 0 | |
0de487015e419e1eae5c0f4aba925b44bcf5b009 | [
"assert len(character) == 1\nself.character = character\nself.bold = bold\nself.italic = italic\nself.underline = underline",
"bold = '*' if self.bold else ''\nitalic = '/' if self.italic else ''\nunderline = '_' if self.underline else ''\nreturn bold + italic + underline + self.character"
] | <|body_start_0|>
assert len(character) == 1
self.character = character
self.bold = bold
self.italic = italic
self.underline = underline
<|end_body_0|>
<|body_start_1|>
bold = '*' if self.bold else ''
italic = '/' if self.italic else ''
underline = '_' if ... | Represents a character with formatting information. | Character | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Character:
"""Represents a character with formatting information."""
def __init__(self, character, bold=False, italic=False, underline=False):
"""Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :para... | stack_v2_sparse_classes_10k_train_003140 | 4,762 | no_license | [
{
"docstring": "Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :param italic: True for italic character. :param underline: True for underline character.",
"name": "__init__",
"signature": "def __init__(self, character,... | 2 | stack_v2_sparse_classes_30k_train_001202 | Implement the Python class `Character` described below.
Class description:
Represents a character with formatting information.
Method signatures and docstrings:
- def __init__(self, character, bold=False, italic=False, underline=False): Initialise a character with formatting. :param character: The character this clas... | Implement the Python class `Character` described below.
Class description:
Represents a character with formatting information.
Method signatures and docstrings:
- def __init__(self, character, bold=False, italic=False, underline=False): Initialise a character with formatting. :param character: The character this clas... | de836492ae951ae3d82a55affc824dc2e6ac6b99 | <|skeleton|>
class Character:
"""Represents a character with formatting information."""
def __init__(self, character, bold=False, italic=False, underline=False):
"""Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :para... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Character:
"""Represents a character with formatting information."""
def __init__(self, character, bold=False, italic=False, underline=False):
"""Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :param italic: Tru... | the_stack_v2_python_sparse | ch05/document/document.py | DreEleventh/python-3-object-oriented-programming | train | 0 |
1492bf743dc047775912780013abdc7a40967e4a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn InvitedUserMessageInfo()",
"from .recipient import Recipient\nfrom .recipient import Recipient\nfields: Dict[str, Callable[[Any], None]] = {'ccRecipients': lambda n: setattr(self, 'cc_recipients', n.get_collection_of_object_values(Reci... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return InvitedUserMessageInfo()
<|end_body_0|>
<|body_start_1|>
from .recipient import Recipient
from .recipient import Recipient
fields: Dict[str, Callable[[Any], None]] = {'ccRecipien... | InvitedUserMessageInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvitedUserMessageInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo:
"""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 ... | stack_v2_sparse_classes_10k_train_003141 | 3,574 | 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: InvitedUserMessageInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `InvitedUserMessageInfo` described below.
Class description:
Implement the InvitedUserMessageInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: Creates a new instance of the appropriate class b... | Implement the Python class `InvitedUserMessageInfo` described below.
Class description:
Implement the InvitedUserMessageInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class InvitedUserMessageInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo:
"""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 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InvitedUserMessageInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | the_stack_v2_python_sparse | msgraph/generated/models/invited_user_message_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a32042b9b4e4880db0f7f2b220bcd15349d90c89 | [
"GroupFactory(type_id='area')\nurl = reverse('ietf.secr.areas.views.list_areas')\nself.client.login(username='secretary', password='secretary+password')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)",
"area = GroupEventFactory(type='started', group__type_id='area').group\nurl = rev... | <|body_start_0|>
GroupFactory(type_id='area')
url = reverse('ietf.secr.areas.views.list_areas')
self.client.login(username='secretary', password='secretary+password')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
<|end_body_0|>
<|body_start_1|>
... | SecrAreasTestCase | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecrAreasTestCase:
def test_main(self):
"""Main Test"""
<|body_0|>
def test_view(self):
"""View Test"""
<|body_1|>
def test_add(self):
"""Add Test"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
GroupFactory(type_id='area')
... | stack_v2_sparse_classes_10k_train_003142 | 1,934 | permissive | [
{
"docstring": "Main Test",
"name": "test_main",
"signature": "def test_main(self)"
},
{
"docstring": "View Test",
"name": "test_view",
"signature": "def test_view(self)"
},
{
"docstring": "Add Test",
"name": "test_add",
"signature": "def test_add(self)"
}
] | 3 | null | Implement the Python class `SecrAreasTestCase` described below.
Class description:
Implement the SecrAreasTestCase class.
Method signatures and docstrings:
- def test_main(self): Main Test
- def test_view(self): View Test
- def test_add(self): Add Test | Implement the Python class `SecrAreasTestCase` described below.
Class description:
Implement the SecrAreasTestCase class.
Method signatures and docstrings:
- def test_main(self): Main Test
- def test_view(self): View Test
- def test_add(self): Add Test
<|skeleton|>
class SecrAreasTestCase:
def test_main(self):
... | aeaae292fbd55aca1b6043227ec105e67d73367f | <|skeleton|>
class SecrAreasTestCase:
def test_main(self):
"""Main Test"""
<|body_0|>
def test_view(self):
"""View Test"""
<|body_1|>
def test_add(self):
"""Add Test"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SecrAreasTestCase:
def test_main(self):
"""Main Test"""
GroupFactory(type_id='area')
url = reverse('ietf.secr.areas.views.list_areas')
self.client.login(username='secretary', password='secretary+password')
response = self.client.get(url)
self.assertEqual(respons... | the_stack_v2_python_sparse | ietf/secr/areas/tests.py | omunroe-com/ietfdb2 | train | 2 | |
cd3e8572e1e7bfc4607a40f4198109b33d10a843 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\ntry:\n obs = observaciones_pre_asf.read(id)\nexcept psycopg2.Error as err:\n ns.abort(400, message=get_msg_pgerror(err))\nexcept EmptySetError:\n ns.abort(404, message=ObservacionPreAsf.obs_not_found)\nexcep... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
try:
obs = observaciones_pre_asf.read(id)
except psycopg2.Error as err:
ns.abort(400, message=get_msg_pgerror(err))
except Empty... | ObservacionPreAsf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservacionPreAsf:
def get(self, id):
"""To fetch an observation (preliminar de la ASF)"""
<|body_0|>
def put(self, id):
"""To update an observation (preliminar de la ASF)"""
<|body_1|>
def delete(self, id):
"""To delete an observation (prelimina... | stack_v2_sparse_classes_10k_train_003143 | 13,540 | no_license | [
{
"docstring": "To fetch an observation (preliminar de la ASF)",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "To update an observation (preliminar de la ASF)",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "To delete an observation (preli... | 3 | stack_v2_sparse_classes_30k_train_006391 | Implement the Python class `ObservacionPreAsf` described below.
Class description:
Implement the ObservacionPreAsf class.
Method signatures and docstrings:
- def get(self, id): To fetch an observation (preliminar de la ASF)
- def put(self, id): To update an observation (preliminar de la ASF)
- def delete(self, id): T... | Implement the Python class `ObservacionPreAsf` described below.
Class description:
Implement the ObservacionPreAsf class.
Method signatures and docstrings:
- def get(self, id): To fetch an observation (preliminar de la ASF)
- def put(self, id): To update an observation (preliminar de la ASF)
- def delete(self, id): T... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ObservacionPreAsf:
def get(self, id):
"""To fetch an observation (preliminar de la ASF)"""
<|body_0|>
def put(self, id):
"""To update an observation (preliminar de la ASF)"""
<|body_1|>
def delete(self, id):
"""To delete an observation (prelimina... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObservacionPreAsf:
def get(self, id):
"""To fetch an observation (preliminar de la ASF)"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
try:
obs = observaciones_pre_asf.read(id)
except psycopg... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/observaciones_pre_asf.py | Telematica/knight-rider | train | 1 | |
b24607c000e916e6f6618946d56e6c255bb15044 | [
"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... | Missing associated documentation comment in .proto file. | DualToRActiveServicer | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualToRActiveServicer:
"""Missing associated documentation comment in .proto file."""
def QueryAdminForwardingPortState(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SetAdminForwardingPortState(self, request, conte... | stack_v2_sparse_classes_10k_train_003144 | 12,711 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "QueryAdminForwardingPortState",
"signature": "def QueryAdminForwardingPortState(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "SetAdminForwardi... | 6 | null | Implement the Python class `DualToRActiveServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def QueryAdminForwardingPortState(self, request, context): Missing associated documentation comment in .proto file.
- def SetAdminForwardi... | Implement the Python class `DualToRActiveServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def QueryAdminForwardingPortState(self, request, context): Missing associated documentation comment in .proto file.
- def SetAdminForwardi... | a86f0e5b1742d01b8d8a28a537f79bf608955695 | <|skeleton|>
class DualToRActiveServicer:
"""Missing associated documentation comment in .proto file."""
def QueryAdminForwardingPortState(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SetAdminForwardingPortState(self, request, conte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DualToRActiveServicer:
"""Missing associated documentation comment in .proto file."""
def QueryAdminForwardingPortState(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Meth... | the_stack_v2_python_sparse | ansible/dualtor/nic_simulator/nic_simulator_grpc_service_pb2_grpc.py | ramakristipati/sonic-mgmt | train | 2 |
0116bdc5f6efcf46a510532a671916891f7bd2f8 | [
"def serialize(root):\n if not root:\n return\n nodes.append(root.val)\n serialize(root.left)\n serialize(root.right)\nnodes = []\nserialize(root)\nreturn ' '.join(map(str, nodes))",
"def deseralize(stop):\n if inorder and inorder[-1] != stop:\n root = TreeNode(preorder.pop())\n ... | <|body_start_0|>
def serialize(root):
if not root:
return
nodes.append(root.val)
serialize(root.left)
serialize(root.right)
nodes = []
serialize(root)
return ' '.join(map(str, nodes))
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_003145 | 1,379 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | fa02b469344cf7c82510249fba9aa59ae0cb4cc0 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def serialize(root):
if not root:
return
nodes.append(root.val)
serialize(root.left)
serialize(root.right)
nodes =... | the_stack_v2_python_sparse | SerializeandDeserializeBST3.py | jiangshen95/UbuntuLeetCode | train | 0 | |
b1bf98d5a2673a7878b261bdf63093cff0a8f234 | [
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nobj = self.filter_queryset(self.get_queryset().filter(cluster=cluster))\nreturn self.get_page(obj, request, {'cluster_id': cluster_id})",
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nserializer = self.serializer_class(data=request.... | <|body_start_0|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
obj = self.filter_queryset(self.get_queryset().filter(cluster=cluster))
return self.get_page(obj, request, {'cluster_id': cluster_id})
<|end_body_0|>
<|body_start_1|>
cluster = check_obj(Cluster, cluster_id, ... | ClusterServiceList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterServiceList:
def get(self, request, cluster_id):
"""List all services of a specified cluster"""
<|body_0|>
def post(self, request, cluster_id):
"""Add service to specified cluster"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cluster = chec... | stack_v2_sparse_classes_10k_train_003146 | 32,530 | permissive | [
{
"docstring": "List all services of a specified cluster",
"name": "get",
"signature": "def get(self, request, cluster_id)"
},
{
"docstring": "Add service to specified cluster",
"name": "post",
"signature": "def post(self, request, cluster_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003078 | Implement the Python class `ClusterServiceList` described below.
Class description:
Implement the ClusterServiceList class.
Method signatures and docstrings:
- def get(self, request, cluster_id): List all services of a specified cluster
- def post(self, request, cluster_id): Add service to specified cluster | Implement the Python class `ClusterServiceList` described below.
Class description:
Implement the ClusterServiceList class.
Method signatures and docstrings:
- def get(self, request, cluster_id): List all services of a specified cluster
- def post(self, request, cluster_id): Add service to specified cluster
<|skelet... | e1c67e3041437ad9e17dccc6c95c5ac02184eddb | <|skeleton|>
class ClusterServiceList:
def get(self, request, cluster_id):
"""List all services of a specified cluster"""
<|body_0|>
def post(self, request, cluster_id):
"""Add service to specified cluster"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterServiceList:
def get(self, request, cluster_id):
"""List all services of a specified cluster"""
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
obj = self.filter_queryset(self.get_queryset().filter(cluster=cluster))
return self.get_page(obj, request, {'clus... | the_stack_v2_python_sparse | api/cluster_views.py | amleshkov/adcm | train | 0 | |
d0d9b172170d949fd68ececae325326edbedb092 | [
"if not root:\n return root\nleftmost = root\nwhile leftmost.left:\n head = leftmost\n while head:\n head.left.next = head.right\n if head.next:\n head.right.next = head.next.left\n head = head.next\n leftmost = leftmost.left\nreturn root",
"if not root:\n return roo... | <|body_start_0|>
if not root:
return root
leftmost = root
while leftmost.left:
head = leftmost
while head:
head.left.next = head.right
if head.next:
head.right.next = head.next.left
head = hea... | PointerTrees | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointerTrees:
def connect(self, root: 'Node') -> 'Node':
"""Approach: Next pointers O(1) space Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def connect_(self, root: 'Node') -> 'Node':
"""Approach: Next pointers stack Time Complexit... | stack_v2_sparse_classes_10k_train_003147 | 1,557 | no_license | [
{
"docstring": "Approach: Next pointers O(1) space Time Complexity: O(N) Space Complexity: O(1) :param root: :return:",
"name": "connect",
"signature": "def connect(self, root: 'Node') -> 'Node'"
},
{
"docstring": "Approach: Next pointers stack Time Complexity: O(N) Space Complexity: O(N) :param... | 2 | null | Implement the Python class `PointerTrees` described below.
Class description:
Implement the PointerTrees class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': Approach: Next pointers O(1) space Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def connect_(self, root... | Implement the Python class `PointerTrees` described below.
Class description:
Implement the PointerTrees class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': Approach: Next pointers O(1) space Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def connect_(self, root... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class PointerTrees:
def connect(self, root: 'Node') -> 'Node':
"""Approach: Next pointers O(1) space Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def connect_(self, root: 'Node') -> 'Node':
"""Approach: Next pointers stack Time Complexit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PointerTrees:
def connect(self, root: 'Node') -> 'Node':
"""Approach: Next pointers O(1) space Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
if not root:
return root
leftmost = root
while leftmost.left:
head = leftmost
... | the_stack_v2_python_sparse | revisited/node/populating_next_right_pointer_i.py | Shiv2157k/leet_code | train | 1 | |
c87b5f435ace6e515cb65a064ee8eecbaad7fad9 | [
"yield (None, 'port grouping is determined by the global default.')\nyield (False, 'ports are not grouped in an additional record.')\nyield (re.compile('[a-zA-Z][a-zA-Z0-9_]*'), 'ports are grouped in a record with the specified name.')",
"yield (None, 'port flattening is determined by the global default.')\nyield... | <|body_start_0|>
yield (None, 'port grouping is determined by the global default.')
yield (False, 'ports are not grouped in an additional record.')
yield (re.compile('[a-zA-Z][a-zA-Z0-9_]*'), 'ports are grouped in a record with the specified name.')
<|end_body_0|>
<|body_start_1|>
yield... | Each field and interrupt in `vhdmmio` can register scalar and vector inputs and outputs, as well as generics. This configuration structure determines how these interfaces are exposed in the entity. By default, the ports are grouped by field/interrupt into records while generics are flattened, but either can be overridd... | InterfaceConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceConfig:
"""Each field and interrupt in `vhdmmio` can register scalar and vector inputs and outputs, as well as generics. This configuration structure determines how these interfaces are exposed in the entity. By default, the ports are grouped by field/interrupt into records while generic... | stack_v2_sparse_classes_10k_train_003148 | 3,434 | permissive | [
{
"docstring": "Name of the group record used for ports, if any. The ports for any objects that share the same non-null `group` tag are combined into a single record pair (`in` and `out`).",
"name": "group",
"signature": "def group()"
},
{
"docstring": "Whether the ports for this object should b... | 4 | stack_v2_sparse_classes_30k_train_000313 | Implement the Python class `InterfaceConfig` described below.
Class description:
Each field and interrupt in `vhdmmio` can register scalar and vector inputs and outputs, as well as generics. This configuration structure determines how these interfaces are exposed in the entity. By default, the ports are grouped by fie... | Implement the Python class `InterfaceConfig` described below.
Class description:
Each field and interrupt in `vhdmmio` can register scalar and vector inputs and outputs, as well as generics. This configuration structure determines how these interfaces are exposed in the entity. By default, the ports are grouped by fie... | d0417925cd72dfb973431d6948e65b662a75c5fa | <|skeleton|>
class InterfaceConfig:
"""Each field and interrupt in `vhdmmio` can register scalar and vector inputs and outputs, as well as generics. This configuration structure determines how these interfaces are exposed in the entity. By default, the ports are grouped by field/interrupt into records while generic... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InterfaceConfig:
"""Each field and interrupt in `vhdmmio` can register scalar and vector inputs and outputs, as well as generics. This configuration structure determines how these interfaces are exposed in the entity. By default, the ports are grouped by field/interrupt into records while generics are flatten... | the_stack_v2_python_sparse | vhdmmio/config/interface.py | abs-tudelft/vhdmmio | train | 5 |
8b4319838ed70326f9cab77ff3ee28036876bfde | [
"self.prefix = model.prefix\nself.text_token_ids_key = model.text_token_ids_key\nself.text_valid_length_key = model.text_valid_length_key\nself.text_segment_ids_key = model.text_segment_ids_key\nself.text_token_word_mapping_key = model.text_token_word_mapping_key\nself.text_word_offsets_key = model.text_word_offset... | <|body_start_0|>
self.prefix = model.prefix
self.text_token_ids_key = model.text_token_ids_key
self.text_valid_length_key = model.text_valid_length_key
self.text_segment_ids_key = model.text_segment_ids_key
self.text_token_word_mapping_key = model.text_token_word_mapping_key
... | Prepare NER data for the model specified by "prefix". | NerProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NerProcessor:
"""Prepare NER data for the model specified by "prefix"."""
def __init__(self, model: nn.Module, max_len: Optional[int]=None, entity_map: Optional[DictConfig]=None):
"""Parameters ---------- model The NER model. max_len The max length of the tokenizer. entity_map The ma... | stack_v2_sparse_classes_10k_train_003149 | 6,072 | permissive | [
{
"docstring": "Parameters ---------- model The NER model. max_len The max length of the tokenizer. entity_map The map between tags and tag indexes. e.g., {\"PER\":2, \"LOC\":3}.",
"name": "__init__",
"signature": "def __init__(self, model: nn.Module, max_len: Optional[int]=None, entity_map: Optional[Di... | 4 | null | Implement the Python class `NerProcessor` described below.
Class description:
Prepare NER data for the model specified by "prefix".
Method signatures and docstrings:
- def __init__(self, model: nn.Module, max_len: Optional[int]=None, entity_map: Optional[DictConfig]=None): Parameters ---------- model The NER model. m... | Implement the Python class `NerProcessor` described below.
Class description:
Prepare NER data for the model specified by "prefix".
Method signatures and docstrings:
- def __init__(self, model: nn.Module, max_len: Optional[int]=None, entity_map: Optional[DictConfig]=None): Parameters ---------- model The NER model. m... | 6af92e149491f6e5062495d87306b3625d12d992 | <|skeleton|>
class NerProcessor:
"""Prepare NER data for the model specified by "prefix"."""
def __init__(self, model: nn.Module, max_len: Optional[int]=None, entity_map: Optional[DictConfig]=None):
"""Parameters ---------- model The NER model. max_len The max length of the tokenizer. entity_map The ma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NerProcessor:
"""Prepare NER data for the model specified by "prefix"."""
def __init__(self, model: nn.Module, max_len: Optional[int]=None, entity_map: Optional[DictConfig]=None):
"""Parameters ---------- model The NER model. max_len The max length of the tokenizer. entity_map The map between tag... | the_stack_v2_python_sparse | multimodal/src/autogluon/multimodal/data/process_ner.py | stjordanis/autogluon | train | 0 |
7d5bc2f5393b30aec5a8dccda22a6f022009f48d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ContactFolder()",
"from .contact import Contact\nfrom .entity import Entity\nfrom .multi_value_legacy_extended_property import MultiValueLegacyExtendedProperty\nfrom .single_value_legacy_extended_property import SingleValueLegacyExtend... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ContactFolder()
<|end_body_0|>
<|body_start_1|>
from .contact import Contact
from .entity import Entity
from .multi_value_legacy_extended_property import MultiValueLegacyExtended... | ContactFolder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactFolder:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContactFolder:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_10k_train_003150 | 4,523 | 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: ContactFolder",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_test_000107 | Implement the Python class `ContactFolder` described below.
Class description:
Implement the ContactFolder class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContactFolder: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `ContactFolder` described below.
Class description:
Implement the ContactFolder class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContactFolder: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ContactFolder:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContactFolder:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContactFolder:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContactFolder:
"""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: ContactFolde... | the_stack_v2_python_sparse | msgraph/generated/models/contact_folder.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3163f2e8699e3fff3f90ce2297d0af3cde3b627e | [
"super(AggregateCell, self).__init__()\nself.pre_transform = pre_transform\nself.concat = concat\nself.agg_size = agg_size\nself.concat = concat\nself.data_format = data_format",
"if self.pre_transform:\n x1 = Conv(self.agg_size, 1, 1, data_format=self.data_format)(x1, training)\n x2 = Conv(self.agg_size, 1... | <|body_start_0|>
super(AggregateCell, self).__init__()
self.pre_transform = pre_transform
self.concat = concat
self.agg_size = agg_size
self.concat = concat
self.data_format = data_format
<|end_body_0|>
<|body_start_1|>
if self.pre_transform:
x1 = Con... | Aggregate two cells and sum or concat them up. | AggregateCell | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, agg_size, pre_transform=True, concat=False, data_format='channels_first'):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: ... | stack_v2_sparse_classes_10k_train_003151 | 12,491 | permissive | [
{
"docstring": "Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of aggregated tensor :param pre_transform: whether to do a transform on two inputs :param concat: concat the result if set to True, otherwise add the result",
"name"... | 2 | null | Implement the Python class `AggregateCell` described below.
Class description:
Aggregate two cells and sum or concat them up.
Method signatures and docstrings:
- def __init__(self, agg_size, pre_transform=True, concat=False, data_format='channels_first'): Construct AggregateCell. :param size_1: channel of first input... | Implement the Python class `AggregateCell` described below.
Class description:
Aggregate two cells and sum or concat them up.
Method signatures and docstrings:
- def __init__(self, agg_size, pre_transform=True, concat=False, data_format='channels_first'): Construct AggregateCell. :param size_1: channel of first input... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, agg_size, pre_transform=True, concat=False, data_format='channels_first'):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, agg_size, pre_transform=True, concat=False, data_format='channels_first'):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of ag... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/networks/tensorflow/customs/adelaide_nn/micro_decoders.py | Huawei-Ascend/modelzoo | train | 1 |
0e1e742ad5c20220e73e583fdd26976f642601bc | [
"dp = [0] * (n + 1)\ndp[0] = dp[1] = 1\nfor i in range(2, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nreturn dp[-1]",
"dp1 = dp2 = 1\nfor i in range(n - 1):\n dp2, dp1 = (dp1 + dp2, dp2)\nreturn dp2"
] | <|body_start_0|>
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
<|end_body_0|>
<|body_start_1|>
dp1 = dp2 = 1
for i in range(n - 1):
dp2, dp1 = (dp1 + dp2, dp2)
return dp2
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(... | stack_v2_sparse_classes_10k_train_003152 | 660 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n): :type n: int :rtype: int
- def climbStairs(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 climbStairs1(self, n): :type n: int :rtype: int
- def climbStairs(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs1(self, n):
"""... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def climbStairs1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(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 climbStairs1(self, n):
""":type n: int :rtype: int"""
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
def climbStairs(self, n):
""":type n: int :rtype: int"""
dp1 =... | the_stack_v2_python_sparse | DynamicProgramming/q070_climbing_stairs.py | sevenhe716/LeetCode | train | 0 | |
e1f1adea0a74380a433b20370dd4ef4fb09bf4b9 | [
"self.pathCKPT = PATH_TO_CKPT\nself.pathLabels = PATH_TO_LABELS\nself.numClasses = 3",
"with tf.device('/device:GPU:0'):\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(self.pathCKPT, 'rb') as fid:\n serialized... | <|body_start_0|>
self.pathCKPT = PATH_TO_CKPT
self.pathLabels = PATH_TO_LABELS
self.numClasses = 3
<|end_body_0|>
<|body_start_1|>
with tf.device('/device:GPU:0'):
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.G... | The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lights :ivar numClasses: number of classes used :iv... | TrafficLightDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lig... | stack_v2_sparse_classes_10k_train_003153 | 3,854 | no_license | [
{
"docstring": "Sets the paths to any necessary files for the neural network to function",
"name": "__init__",
"signature": "def __init__(self, PATH_TO_CKPT='tf/frozen_inference_graph.pb', PATH_TO_LABELS='tf/traffic_light.pbtxt')"
},
{
"docstring": "Performs all of the operations to set up the n... | 3 | stack_v2_sparse_classes_30k_train_001240 | Implement the Python class `TrafficLightDetector` described below.
Class description:
The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLab... | Implement the Python class `TrafficLightDetector` described below.
Class description:
The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLab... | 576b799fd6f85768cc4e0ad44b0a787fb5c80b29 | <|skeleton|>
class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lig... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lights :ivar num... | the_stack_v2_python_sparse | MV/trafficLightDetector.py | bohongbobo/draft-GUI | train | 0 |
4ee9b97a2e29075cfaa31b686d2a8023f7b47dbd | [
"if not head or not head.next:\n return head\ncur = head.next\nlast = head\nwhile cur:\n t = head\n last_t = None\n while t.val < cur.val:\n last_t = t\n t = t.next\n if cur == t:\n last = cur\n cur = cur.next\n else:\n last.next = cur.next\n if last_t:\n ... | <|body_start_0|>
if not head or not head.next:
return head
cur = head.next
last = head
while cur:
t = head
last_t = None
while t.val < cur.val:
last_t = t
t = t.next
if cur == t:
l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""链表插入排序"""
<|body_0|>
def insertionSortList2(self, head: ListNode) -> ListNode:
"""链表插入排序 优化后"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_10k_train_003154 | 2,451 | no_license | [
{
"docstring": "链表插入排序",
"name": "insertionSortList",
"signature": "def insertionSortList(self, head: ListNode) -> ListNode"
},
{
"docstring": "链表插入排序 优化后",
"name": "insertionSortList2",
"signature": "def insertionSortList2(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_000625 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: 链表插入排序
- def insertionSortList2(self, head: ListNode) -> ListNode: 链表插入排序 优化后 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: 链表插入排序
- def insertionSortList2(self, head: ListNode) -> ListNode: 链表插入排序 优化后
<|skeleton|>
class Solution:
def inse... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""链表插入排序"""
<|body_0|>
def insertionSortList2(self, head: ListNode) -> ListNode:
"""链表插入排序 优化后"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""链表插入排序"""
if not head or not head.next:
return head
cur = head.next
last = head
while cur:
t = head
last_t = None
while t.val < cur.val:
... | the_stack_v2_python_sparse | linked_list/147 Insertion Sort List.py | mofei952/leetcode_python | train | 0 | |
78f845f03bfe70fa64158a2e35c122d2760964bf | [
"PostProcessorInterfaceBase.initialize(self)\nself.inputFormat = 'HistorySet'\nself.outputFormat = 'HistorySet'",
"if len(inputDic) > 1:\n self.raiseAnError(IOError, 'testInterfacedPP Interfaced Post-Processor ' + str(self.name) + ' accepts only one dataObject')\nelse:\n return inputDic[0]",
"for child in... | <|body_start_0|>
PostProcessorInterfaceBase.initialize(self)
self.inputFormat = 'HistorySet'
self.outputFormat = 'HistorySet'
<|end_body_0|>
<|body_start_1|>
if len(inputDic) > 1:
self.raiseAnError(IOError, 'testInterfacedPP Interfaced Post-Processor ' + str(self.name) + ' a... | This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML | testInterfacedPP | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML"""
def initialize(self):
"""Method to... | stack_v2_sparse_classes_10k_train_003155 | 2,159 | permissive | [
{
"docstring": "Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "This method is transparent: it passes the inputDic directly as output @ In, inputDic, dict, dictionary which contains the dat... | 3 | stack_v2_sparse_classes_30k_val_000138 | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML
Method sig... | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML
Method sig... | fbee9e3def3c1ee576d1af85f3258cc816ceaaaf | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML"""
def initialize(self):
"""Method to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML"""
def initialize(self):
"""Method to initialize t... | the_stack_v2_python_sparse | framework/PostProcessorFunctions/testInterfacedPP.py | jbae11/raven | train | 0 |
0ad5bced8e5021e4b7e6ebb70d7a74a284885f84 | [
"if num <= 0 or num & num - 1 != 0:\n return False\nreturn bool(1431655765 & num)",
"if num <= 0 or num & num - 1 != 0:\n return False\nt = num & -num\nreturn num & 1431655765 and num == t",
"if num <= 0:\n return False\nnum_bin = bin(num)[2:]\nif len(num_bin) % 2 != 0 and num_bin[0] == '1':\n if nu... | <|body_start_0|>
if num <= 0 or num & num - 1 != 0:
return False
return bool(1431655765 & num)
<|end_body_0|>
<|body_start_1|>
if num <= 0 or num & num - 1 != 0:
return False
t = num & -num
return num & 1431655765 and num == t
<|end_body_1|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num: int) -> bool:
"""理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:"""
<|body_0|>
def isPowerOfFour5(self, num: int) -> bool:
""":param num: :ret... | stack_v2_sparse_classes_10k_train_003156 | 2,318 | no_license | [
{
"docstring": "理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:",
"name": "isPowerOfFour",
"signature": "def isPowerOfFour(self, num: int) -> bool"
},
{
"docstring": ":param num: :return:",
"name": "isPower... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num: int) -> bool: 理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num: int) -> bool: 理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:
-... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num: int) -> bool:
"""理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:"""
<|body_0|>
def isPowerOfFour5(self, num: int) -> bool:
""":param num: :ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfFour(self, num: int) -> bool:
"""理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:"""
if num <= 0 or num & num - 1 != 0:
return False
return bool(1431655765 & num)
... | the_stack_v2_python_sparse | 342_4的幂.py | lovehhf/LeetCode | train | 0 | |
810b9cbc5966d79143e3cbc15350517a7940fa6a | [
"threading.Thread.__init__(self)\nself.f2run = f\nself.results = None\nself.list_of_params = list_of_params",
"self.results = []\nfor params in self.list_of_params:\n l, p = (params, {}) if len(params) else params\n self.results.append(self.f2run(*l, **p))",
"th = []\nsplit = [list_of_params[i::nbthread] ... | <|body_start_0|>
threading.Thread.__init__(self)
self.f2run = f
self.results = None
self.list_of_params = list_of_params
<|end_body_0|>
<|body_start_1|>
self.results = []
for params in self.list_of_params:
l, p = (params, {}) if len(params) else params
... | Cette classe implémente un thread qui exécute en boucle une fonction sur tous les éléments d'une liste. | ParallelThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelThread:
"""Cette classe implémente un thread qui exécute en boucle une fonction sur tous les éléments d'une liste."""
def __init__(self, f, list_of_params):
"""Constructeur @param f fonction à exécuter @param list_of_params liste des paramètres à exécuter"""
<|body_0|... | stack_v2_sparse_classes_10k_train_003157 | 2,408 | permissive | [
{
"docstring": "Constructeur @param f fonction à exécuter @param list_of_params liste des paramètres à exécuter",
"name": "__init__",
"signature": "def __init__(self, f, list_of_params)"
},
{
"docstring": "Appelle une fonction plusieurs sur tous les paramètres dans une liste.",
"name": "run"... | 3 | null | Implement the Python class `ParallelThread` described below.
Class description:
Cette classe implémente un thread qui exécute en boucle une fonction sur tous les éléments d'une liste.
Method signatures and docstrings:
- def __init__(self, f, list_of_params): Constructeur @param f fonction à exécuter @param list_of_pa... | Implement the Python class `ParallelThread` described below.
Class description:
Cette classe implémente un thread qui exécute en boucle une fonction sur tous les éléments d'une liste.
Method signatures and docstrings:
- def __init__(self, f, list_of_params): Constructeur @param f fonction à exécuter @param list_of_pa... | 2abbc7a20c7437f9ab91d1ec83a6aecdefceb028 | <|skeleton|>
class ParallelThread:
"""Cette classe implémente un thread qui exécute en boucle une fonction sur tous les éléments d'une liste."""
def __init__(self, f, list_of_params):
"""Constructeur @param f fonction à exécuter @param list_of_params liste des paramètres à exécuter"""
<|body_0|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParallelThread:
"""Cette classe implémente un thread qui exécute en boucle une fonction sur tous les éléments d'une liste."""
def __init__(self, f, list_of_params):
"""Constructeur @param f fonction à exécuter @param list_of_params liste des paramètres à exécuter"""
threading.Thread.__ini... | the_stack_v2_python_sparse | src/ensae_teaching_cs/td_2a/parallel_thread.py | Pandinosaurus/ensae_teaching_cs | train | 1 |
b958414938ae9c1d9dff5805e3af523dad365175 | [
"try:\n from bs4 import BeautifulSoup\nexcept ImportError:\n raise ValueError('Could not import python packages. Please install it with `pip install beautifulsoup4`. ')\ntry:\n _ = BeautifulSoup('<html><body>Parser builder library test.</body></html>', **kwargs)\nexcept Exception as e:\n raise ValueErro... | <|body_start_0|>
try:
from bs4 import BeautifulSoup
except ImportError:
raise ValueError('Could not import python packages. Please install it with `pip install beautifulsoup4`. ')
try:
_ = BeautifulSoup('<html><body>Parser builder library test.</body></html>',... | Loader that loads ReadTheDocs documentation directory dump. | ReadTheDocsLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadTheDocsLoader:
"""Loader that loads ReadTheDocs documentation directory dump."""
def __init__(self, path: str, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Optional[Any]):
"""Initialize path."""
<|body_0|>
def load(self) -> List[Document]:
... | stack_v2_sparse_classes_10k_train_003158 | 2,094 | no_license | [
{
"docstring": "Initialize path.",
"name": "__init__",
"signature": "def __init__(self, path: str, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Optional[Any])"
},
{
"docstring": "Load documents.",
"name": "load",
"signature": "def load(self) -> List[Document]"
}
... | 2 | stack_v2_sparse_classes_30k_train_001567 | Implement the Python class `ReadTheDocsLoader` described below.
Class description:
Loader that loads ReadTheDocs documentation directory dump.
Method signatures and docstrings:
- def __init__(self, path: str, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Optional[Any]): Initialize path.
- def lo... | Implement the Python class `ReadTheDocsLoader` described below.
Class description:
Loader that loads ReadTheDocs documentation directory dump.
Method signatures and docstrings:
- def __init__(self, path: str, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Optional[Any]): Initialize path.
- def lo... | b7aaa920a52613e3f1f04fa5cd7568ad37302d11 | <|skeleton|>
class ReadTheDocsLoader:
"""Loader that loads ReadTheDocs documentation directory dump."""
def __init__(self, path: str, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Optional[Any]):
"""Initialize path."""
<|body_0|>
def load(self) -> List[Document]:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReadTheDocsLoader:
"""Loader that loads ReadTheDocs documentation directory dump."""
def __init__(self, path: str, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Optional[Any]):
"""Initialize path."""
try:
from bs4 import BeautifulSoup
except Impor... | the_stack_v2_python_sparse | openai/venv/lib/python3.10/site-packages/langchain/document_loaders/readthedocs.py | henrymendez/garage | train | 0 |
ba8a930db3af42b2ca17b90efc439dc39e395b1c | [
"super(PrintResourceStats, self).__init__(experiment, name='PrintResourceStats', label=label)\nself.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)\nself.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experiment.config.getint('Experiment',... | <|body_start_0|>
super(PrintResourceStats, self).__init__(experiment, name='PrintResourceStats', label=label)
self.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)
self.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.expe... | Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at w... | PrintResourceStats | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrintResourceStats:
"""Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of exp... | stack_v2_sparse_classes_10k_train_003159 | 3,818 | permissive | [
{
"docstring": "Initialize the PrintResourceStats Action",
"name": "__init__",
"signature": "def __init__(self, experiment, label=None)"
},
{
"docstring": "Execute the action",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000191 | Implement the Python class `PrintResourceStats` described below.
Class description:
Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which... | Implement the Python class `PrintResourceStats` described below.
Class description:
Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which... | a114ac66e62a960e18127faf52cff9e48831e212 | <|skeleton|>
class PrintResourceStats:
"""Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of exp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrintResourceStats:
"""Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) freq... | the_stack_v2_python_sparse | seeds/plugins/action/PrintResourceStats.py | namlehai/seeds | train | 0 |
b382f8ae1babd5929d7fed9ea426ef200a0c9a46 | [
"self.shape = (image_size, image_size)\nif min_pt is None:\n min_pt = [-self.shape[0] / 2, -self.shape[1] / 2]\nif max_pt is None:\n max_pt = [self.shape[0] / 2, self.shape[1] / 2]\nspace = uniform_discr(min_pt, max_pt, self.shape, dtype=np.float32)\nself.train_len = train_len\nself.validation_len = validatio... | <|body_start_0|>
self.shape = (image_size, image_size)
if min_pt is None:
min_pt = [-self.shape[0] / 2, -self.shape[1] / 2]
if max_pt is None:
max_pt = [self.shape[0] / 2, self.shape[1] / 2]
space = uniform_discr(min_pt, max_pt, self.shape, dtype=np.float32)
... | Dataset with images of multiple random ellipses. This dataset uses :meth:`odl.phantom.ellipsoid_phantom` to create the images. The images are normalized to have a value range of ``[0., 1.]`` with a background value of ``0.``. Attributes ---------- space ``odl.uniform_discr(min_pt, max_pt, (image_size, image_size), dtyp... | EllipsesDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EllipsesDataset:
"""Dataset with images of multiple random ellipses. This dataset uses :meth:`odl.phantom.ellipsoid_phantom` to create the images. The images are normalized to have a value range of ``[0., 1.]`` with a background value of ``0.``. Attributes ---------- space ``odl.uniform_discr(min... | stack_v2_sparse_classes_10k_train_003160 | 4,893 | permissive | [
{
"docstring": "Parameters ---------- image_size : int, optional Number of pixels per image dimension. Default: ``128``. min_pt : [int, int], optional Minimum values of the lp space. Default: ``[-image_size/2, -image_size/2]``. max_pt : [int, int], optional Maximum values of the lp space. Default: ``[image_size... | 2 | stack_v2_sparse_classes_30k_train_003520 | Implement the Python class `EllipsesDataset` described below.
Class description:
Dataset with images of multiple random ellipses. This dataset uses :meth:`odl.phantom.ellipsoid_phantom` to create the images. The images are normalized to have a value range of ``[0., 1.]`` with a background value of ``0.``. Attributes -... | Implement the Python class `EllipsesDataset` described below.
Class description:
Dataset with images of multiple random ellipses. This dataset uses :meth:`odl.phantom.ellipsoid_phantom` to create the images. The images are normalized to have a value range of ``[0., 1.]`` with a background value of ``0.``. Attributes -... | 56d39aaab0c99a918dac832171ca4310a74a33a3 | <|skeleton|>
class EllipsesDataset:
"""Dataset with images of multiple random ellipses. This dataset uses :meth:`odl.phantom.ellipsoid_phantom` to create the images. The images are normalized to have a value range of ``[0., 1.]`` with a background value of ``0.``. Attributes ---------- space ``odl.uniform_discr(min... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EllipsesDataset:
"""Dataset with images of multiple random ellipses. This dataset uses :meth:`odl.phantom.ellipsoid_phantom` to create the images. The images are normalized to have a value range of ``[0., 1.]`` with a background value of ``0.``. Attributes ---------- space ``odl.uniform_discr(min_pt, max_pt, ... | the_stack_v2_python_sparse | dival/datasets/ellipses_dataset.py | jleuschn/dival | train | 65 |
8a071d31064ba894c446a0212ab06d415af08d3d | [
"if not root:\n return []\nres = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]\nreturn res",
"if len(data) == 0:\n return None\nroot = TreeNode(data[0])\nroot.left = self.deserialize(data[1])\nroot.right = self.deserialize(data[2])\nreturn root"
] | <|body_start_0|>
if not root:
return []
res = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]
return res
<|end_body_0|>
<|body_start_1|>
if len(data) == 0:
return None
root = TreeNode(data[0])
root.left = self.deserialize(d... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_003161 | 5,388 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_003642 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
res = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]
return res
def deserialize(self, data):
"""D... | the_stack_v2_python_sparse | Python/SerializeandDeserializeBinaryTree.py | here0009/LeetCode | train | 1 | |
b3e39a1bb1553be909a04195dc2df49472001850 | [
"from components.slots.slots import CategoricalSlot\nif not reuse:\n slot = CategoricalSlot(name=name, questioner=questioner, silent_value=silent_value, categories_synsets=categories_domain_specification).save()\nelse:\n slot, created = CategoricalSlot.get_or_create(name=name, questioner=questioner, silent_va... | <|body_start_0|>
from components.slots.slots import CategoricalSlot
if not reuse:
slot = CategoricalSlot(name=name, questioner=questioner, silent_value=silent_value, categories_synsets=categories_domain_specification).save()
else:
slot, created = CategoricalSlot.get_or_cr... | Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object? | SlotsFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlotsFactory:
"""Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?"""
def produce_categorical_slot(cls, name, questioner, categories_domain_specification, requestioning_strategy='ResumeOnIdle', re... | stack_v2_sparse_classes_10k_train_003162 | 6,892 | no_license | [
{
"docstring": "factory method for production of unregistered slots with categorical values Args: name: name of slot questioner: categories_domain_specification: TODO specify format requestioning_strategy:",
"name": "produce_categorical_slot",
"signature": "def produce_categorical_slot(cls, name, questi... | 5 | stack_v2_sparse_classes_30k_train_002040 | Implement the Python class `SlotsFactory` described below.
Class description:
Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?
Method signatures and docstrings:
- def produce_categorical_slot(cls, name, questioner, catego... | Implement the Python class `SlotsFactory` described below.
Class description:
Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?
Method signatures and docstrings:
- def produce_categorical_slot(cls, name, questioner, catego... | 7a0bc78ca03ee8ca1202e8ad2a6860444f0ce75d | <|skeleton|>
class SlotsFactory:
"""Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?"""
def produce_categorical_slot(cls, name, questioner, categories_domain_specification, requestioning_strategy='ResumeOnIdle', re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SlotsFactory:
"""Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?"""
def produce_categorical_slot(cls, name, questioner, categories_domain_specification, requestioning_strategy='ResumeOnIdle', reuse=True, sil... | the_stack_v2_python_sparse | ruler_bot/components/slots/slots_factory.py | acriptis/dj_bot | train | 3 |
205d6d848c7c4171ccde137e7fc7c2521fe8c86a | [
"inputSpecification = super().getInputSpecification()\ninputSpecification.addSubSimple('label', InputTypes.StringType)\ninputSpecification.addSubSimple('clusterIDs', InputTypes.IntegerListType)\nreturn inputSpecification",
"super().__init__()\nself.setInputDataType('dict')\nself.keepInputMeta(True)\nself.outputMu... | <|body_start_0|>
inputSpecification = super().getInputSpecification()
inputSpecification.addSubSimple('label', InputTypes.StringType)
inputSpecification.addSubSimple('clusterIDs', InputTypes.IntegerListType)
return inputSpecification
<|end_body_0|>
<|body_start_1|>
super().__ini... | This Post-Processor filters out the points or histories accordingly to a chosen clustering label | dataObjectLabelFilter | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are ret... | stack_v2_sparse_classes_10k_train_003163 | 5,021 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signatur... | 4 | null | Implement the Python class `dataObjectLabelFilter` described below.
Class description:
This Post-Processor filters out the points or histories accordingly to a chosen clustering label
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data... | Implement the Python class `dataObjectLabelFilter` described below.
Class description:
This Post-Processor filters out the points or histories accordingly to a chosen clustering label
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the s... | the_stack_v2_python_sparse | ravenframework/Models/PostProcessors/dataObjectLabelFilter.py | idaholab/raven | train | 201 |
8669e0cf3eb4eba231b68600caf3123cc52c6bba | [
"super(MatchingEngine, self).__init__()\nself._logger = logging.getLogger(self.__class__.__name__)\nassert isinstance(matching_strategy, MatchingStrategy), type(matching_strategy)\nself.matching_strategy = matching_strategy",
"assert isinstance(order, Order), type(order)\nnow = time()\nproposed_trades = self.matc... | <|body_start_0|>
super(MatchingEngine, self).__init__()
self._logger = logging.getLogger(self.__class__.__name__)
assert isinstance(matching_strategy, MatchingStrategy), type(matching_strategy)
self.matching_strategy = matching_strategy
<|end_body_0|>
<|body_start_1|>
assert isi... | Matches ticks and orders to the order book | MatchingEngine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchingEngine:
"""Matches ticks and orders to the order book"""
def __init__(self, matching_strategy):
""":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy"""
<|body_0|>
def match_order(self, order):
""":param order: The ord... | stack_v2_sparse_classes_10k_train_003164 | 13,505 | no_license | [
{
"docstring": ":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy",
"name": "__init__",
"signature": "def __init__(self, matching_strategy)"
},
{
"docstring": ":param order: The order to match against :type order: Order :return: The proposed trades :rtype: [... | 2 | stack_v2_sparse_classes_30k_train_003721 | Implement the Python class `MatchingEngine` described below.
Class description:
Matches ticks and orders to the order book
Method signatures and docstrings:
- def __init__(self, matching_strategy): :param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy
- def match_order(self, order): ... | Implement the Python class `MatchingEngine` described below.
Class description:
Matches ticks and orders to the order book
Method signatures and docstrings:
- def __init__(self, matching_strategy): :param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy
- def match_order(self, order): ... | cc4d1c27166d68c39e5c38e77bb70093f34e19e5 | <|skeleton|>
class MatchingEngine:
"""Matches ticks and orders to the order book"""
def __init__(self, matching_strategy):
""":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy"""
<|body_0|>
def match_order(self, order):
""":param order: The ord... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MatchingEngine:
"""Matches ticks and orders to the order book"""
def __init__(self, matching_strategy):
""":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy"""
super(MatchingEngine, self).__init__()
self._logger = logging.getLogger(self.__clas... | the_stack_v2_python_sparse | market/core/matching_engine.py | devos50/decentralized-market | train | 0 |
a426a2b9275856820843a9dea91119b55dc69263 | [
"self.access_modes = access_modes\nself.data_source = data_source\nself.resources = resources\nself.selector = selector\nself.storage_class_name = storage_class_name\nself.volume_mode = volume_mode\nself.volume_name = volume_name",
"if dictionary is None:\n return None\naccess_modes = dictionary.get('accessMod... | <|body_start_0|>
self.access_modes = access_modes
self.data_source = data_source
self.resources = resources
self.selector = selector
self.storage_class_name = storage_class_name
self.volume_mode = volume_mode
self.volume_name = volume_name
<|end_body_0|>
<|body_s... | Implementation of the 'PVCInfo_PVCSpec' model. TODO: type description here. Attributes: access_modes (list of string): AccessModes contains the desired access modes the volume should have. data_source (ObjectReference): This field can be used to specify either: An existing VolumeSnapshot object An existing PVC (Persist... | PVCInfo_PVCSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PVCInfo_PVCSpec:
"""Implementation of the 'PVCInfo_PVCSpec' model. TODO: type description here. Attributes: access_modes (list of string): AccessModes contains the desired access modes the volume should have. data_source (ObjectReference): This field can be used to specify either: An existing Vol... | stack_v2_sparse_classes_10k_train_003165 | 3,920 | permissive | [
{
"docstring": "Constructor for the PVCInfo_PVCSpec class",
"name": "__init__",
"signature": "def __init__(self, access_modes=None, data_source=None, resources=None, selector=None, storage_class_name=None, volume_mode=None, volume_name=None)"
},
{
"docstring": "Creates an instance of this model ... | 2 | null | Implement the Python class `PVCInfo_PVCSpec` described below.
Class description:
Implementation of the 'PVCInfo_PVCSpec' model. TODO: type description here. Attributes: access_modes (list of string): AccessModes contains the desired access modes the volume should have. data_source (ObjectReference): This field can be ... | Implement the Python class `PVCInfo_PVCSpec` described below.
Class description:
Implementation of the 'PVCInfo_PVCSpec' model. TODO: type description here. Attributes: access_modes (list of string): AccessModes contains the desired access modes the volume should have. data_source (ObjectReference): This field can be ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PVCInfo_PVCSpec:
"""Implementation of the 'PVCInfo_PVCSpec' model. TODO: type description here. Attributes: access_modes (list of string): AccessModes contains the desired access modes the volume should have. data_source (ObjectReference): This field can be used to specify either: An existing Vol... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PVCInfo_PVCSpec:
"""Implementation of the 'PVCInfo_PVCSpec' model. TODO: type description here. Attributes: access_modes (list of string): AccessModes contains the desired access modes the volume should have. data_source (ObjectReference): This field can be used to specify either: An existing VolumeSnapshot o... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pvc_info_pvc_spec.py | cohesity/management-sdk-python | train | 24 |
4e85f75a5c5bb9bf3327b2fee1981d30571e5259 | [
"if len(money) <= 5:\n return sum(money)\nself.res = 0\nself.dfs(money, 0, len(money) - 1, 0)\nreturn self.res",
"if left + len(money) - 1 - right == 5:\n self.res = max(self.res, path)\n return\nself.dfs(money, left + 1, right, path + money[left])\nself.dfs(money, left, right - 1, path + money[right])"
... | <|body_start_0|>
if len(money) <= 5:
return sum(money)
self.res = 0
self.dfs(money, 0, len(money) - 1, 0)
return self.res
<|end_body_0|>
<|body_start_1|>
if left + len(money) - 1 - right == 5:
self.res = max(self.res, path)
return
self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def func(self, money):
"""回溯 Args: money: list[int] Return: int"""
<|body_0|>
def dfs(self, money, left, right, path):
"""Args: money: list[int] left: int right: int path: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(money) <... | stack_v2_sparse_classes_10k_train_003166 | 993 | no_license | [
{
"docstring": "回溯 Args: money: list[int] Return: int",
"name": "func",
"signature": "def func(self, money)"
},
{
"docstring": "Args: money: list[int] left: int right: int path: int",
"name": "dfs",
"signature": "def dfs(self, money, left, right, path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000407 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, money): 回溯 Args: money: list[int] Return: int
- def dfs(self, money, left, right, path): Args: money: list[int] left: int right: int path: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, money): 回溯 Args: money: list[int] Return: int
- def dfs(self, money, left, right, path): Args: money: list[int] left: int right: int path: int
<|skeleton|>
class ... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def func(self, money):
"""回溯 Args: money: list[int] Return: int"""
<|body_0|>
def dfs(self, money, left, right, path):
"""Args: money: list[int] left: int right: int path: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def func(self, money):
"""回溯 Args: money: list[int] Return: int"""
if len(money) <= 5:
return sum(money)
self.res = 0
self.dfs(money, 0, len(money) - 1, 0)
return self.res
def dfs(self, money, left, right, path):
"""Args: money: list[i... | the_stack_v2_python_sparse | 秋招/58/3.py | AiZhanghan/Leetcode | train | 0 | |
ff51308d8e2744fabb5bd7cfe8dadd167640afb1 | [
"super(ResBlk, self).__init__()\nself.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn1 = nn.BatchNorm2d(ch_out)\nself.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(ch_out)\nself.extra = nn.Sequential()\nif ch_out != ch_in:\n self.ex... | <|body_start_0|>
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
self.ex... | resnet block | ResBlk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: [b, ch, h, w] :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ResBlk, self).__init__()
... | stack_v2_sparse_classes_10k_train_003167 | 2,694 | no_license | [
{
"docstring": ":param ch_in: :param ch_out:",
"name": "__init__",
"signature": "def __init__(self, ch_in, ch_out)"
},
{
"docstring": ":param x: [b, ch, h, w] :return:",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000121 | Implement the Python class `ResBlk` described below.
Class description:
resnet block
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: :param ch_out:
- def forward(self, x): :param x: [b, ch, h, w] :return: | Implement the Python class `ResBlk` described below.
Class description:
resnet block
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: :param ch_out:
- def forward(self, x): :param x: [b, ch, h, w] :return:
<|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, c... | d3e44fad42809f23762c9028d8b1d478acf42ab2 | <|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: [b, ch, h, w] :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out... | the_stack_v2_python_sparse | modules/performance/core/custom_resnet.py | CaravanPassenger/pytorch-learning-notes | train | 0 |
09044019ba370ade295f50c0ae833a08be63a174 | [
"self.queue_url = queue_url\nself.profile_name = profile_name\nself.region_name = region_name\nself.filters = list(filters) if filters else []\nself.session = None\nself.client = None\nif connect:\n self.connect()",
"pname = self.profile_name if profile_name is None else profile_name\nrname = self.region_name ... | <|body_start_0|>
self.queue_url = queue_url
self.profile_name = profile_name
self.region_name = region_name
self.filters = list(filters) if filters else []
self.session = None
self.client = None
if connect:
self.connect()
<|end_body_0|>
<|body_start_1... | AWS SQS queue message receiver and handler selector. | SQSSifter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQSSifter:
"""AWS SQS queue message receiver and handler selector."""
def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None):
"""Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name... | stack_v2_sparse_classes_10k_train_003168 | 8,134 | permissive | [
{
"docstring": "Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name (str) Session parameter for the AWS connection. region_name (str, default='us-east-1') Session parameter for the AWS connection. connect (bool, default=True) If ``True``, a session will b... | 5 | stack_v2_sparse_classes_30k_train_006427 | Implement the Python class `SQSSifter` described below.
Class description:
AWS SQS queue message receiver and handler selector.
Method signatures and docstrings:
- def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None): Initialize an SQS Sifter instance. Arguments: queue... | Implement the Python class `SQSSifter` described below.
Class description:
AWS SQS queue message receiver and handler selector.
Method signatures and docstrings:
- def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None): Initialize an SQS Sifter instance. Arguments: queue... | b78fc02b93f2ed1320ba253b01f28f5e2f45afa0 | <|skeleton|>
class SQSSifter:
"""AWS SQS queue message receiver and handler selector."""
def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None):
"""Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SQSSifter:
"""AWS SQS queue message receiver and handler selector."""
def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None):
"""Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name (str) Sessio... | the_stack_v2_python_sparse | boogio/sqs_sifter.py | osgirl/boogio | train | 0 |
b857f4095cf36042baa38810ad2a0995c717e324 | [
"warnings.warn('SequentialDTNNGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)\nself.graph = tf.Graph()\nwith self.graph.as_default():\n self.graph_topology = DTNNGraphTopology(n_distance, distance_min=distance_min, distance_max=distance_max)\n self.output = self.graph_topology.get_... | <|body_start_0|>
warnings.warn('SequentialDTNNGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)
self.graph = tf.Graph()
with self.graph.as_default():
self.graph_topology = DTNNGraphTopology(n_distance, distance_min=distance_min, distance_max=distance_max)
... | An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer. | SequentialDTNNGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialDTNNGraph:
"""An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer."""
def __init__(self, n_distance=100, distance_min=-1.0, distance_max=18.0):
"""Parameters ---------- n_distance: int, optional... | stack_v2_sparse_classes_10k_train_003169 | 11,824 | permissive | [
{
"docstring": "Parameters ---------- n_distance: int, optional granularity of distance matrix step size will be (distance_max-distance_min)/n_distance distance_min: float, optional minimum distance of atom pairs, default = -1 Angstorm distance_max: float, optional maximum distance of atom pairs, default = 18 A... | 2 | null | Implement the Python class `SequentialDTNNGraph` described below.
Class description:
An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer.
Method signatures and docstrings:
- def __init__(self, n_distance=100, distance_min=-1.0, distance_m... | Implement the Python class `SequentialDTNNGraph` described below.
Class description:
An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer.
Method signatures and docstrings:
- def __init__(self, n_distance=100, distance_min=-1.0, distance_m... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class SequentialDTNNGraph:
"""An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer."""
def __init__(self, n_distance=100, distance_min=-1.0, distance_max=18.0):
"""Parameters ---------- n_distance: int, optional... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SequentialDTNNGraph:
"""An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer."""
def __init__(self, n_distance=100, distance_min=-1.0, distance_max=18.0):
"""Parameters ---------- n_distance: int, optional granularity ... | the_stack_v2_python_sparse | contrib/one_shot_models/graph_models.py | deepchem/deepchem | train | 4,876 |
6c41c3664c97b94a9784bb3a8a818a6be334354b | [
"if not p and (not q):\n return True\nif p == None and q != None:\n return False\nif p != None and q == None:\n return False\nif p.val != q.val:\n return False\nreturn self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)",
"def InOrder(root):\n if not root:\n return [None]\n... | <|body_start_0|>
if not p and (not q):
return True
if p == None and q != None:
return False
if p != None and q == None:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
"""递归法"""
<|body_0|>
def isSameTree_1(self, p: TreeNode, q: TreeNode) -> bool:
"""遍历法 颜色标记法会超时"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not p and (not q):
return... | stack_v2_sparse_classes_10k_train_003170 | 1,054 | no_license | [
{
"docstring": "递归法",
"name": "isSameTree",
"signature": "def isSameTree(self, p: TreeNode, q: TreeNode) -> bool"
},
{
"docstring": "遍历法 颜色标记法会超时",
"name": "isSameTree_1",
"signature": "def isSameTree_1(self, p: TreeNode, q: TreeNode) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_006773 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 递归法
- def isSameTree_1(self, p: TreeNode, q: TreeNode) -> bool: 遍历法 颜色标记法会超时 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 递归法
- def isSameTree_1(self, p: TreeNode, q: TreeNode) -> bool: 遍历法 颜色标记法会超时
<|skeleton|>
class Solution:
def isSame... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
"""递归法"""
<|body_0|>
def isSameTree_1(self, p: TreeNode, q: TreeNode) -> bool:
"""遍历法 颜色标记法会超时"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
"""递归法"""
if not p and (not q):
return True
if p == None and q != None:
return False
if p != None and q == None:
return False
if p.val != q.val:
return Fals... | the_stack_v2_python_sparse | algorithm/leetcode/tree/11-相同的树.py | lxconfig/UbuntuCode_bak | train | 0 | |
4a84eb3aa952bf8953b0759c21ebec5cd268da9f | [
"super().__init__(app, pipeline, id=id, config=config)\nself.Loop = app.Loop\nself.Pipeline = pipeline\nself.Queue = asyncio.Queue()\nself.Connection = pipeline.locate_connection(app, connection)\nself.Filename = self.Config.get('filename', None)\nself.RemotePath = self.Config['remote_path']\nself._conn_future = No... | <|body_start_0|>
super().__init__(app, pipeline, id=id, config=config)
self.Loop = app.Loop
self.Pipeline = pipeline
self.Queue = asyncio.Queue()
self.Connection = pipeline.locate_connection(app, connection)
self.Filename = self.Config.get('filename', None)
self.R... | Description: | | FTPSource | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FTPSource:
"""Description: |"""
def __init__(self, app, pipeline, connection, id=None, config=None):
"""Description: **Parameters** app : Application Name of the Application pipeline : connection : id : ID, default = None config : JSON, default = None"""
<|body_0|>
async... | stack_v2_sparse_classes_10k_train_003171 | 2,392 | permissive | [
{
"docstring": "Description: **Parameters** app : Application Name of the Application pipeline : connection : id : ID, default = None config : JSON, default = None",
"name": "__init__",
"signature": "def __init__(self, app, pipeline, connection, id=None, config=None)"
},
{
"docstring": "Descript... | 4 | stack_v2_sparse_classes_30k_train_006989 | Implement the Python class `FTPSource` described below.
Class description:
Description: |
Method signatures and docstrings:
- def __init__(self, app, pipeline, connection, id=None, config=None): Description: **Parameters** app : Application Name of the Application pipeline : connection : id : ID, default = None confi... | Implement the Python class `FTPSource` described below.
Class description:
Description: |
Method signatures and docstrings:
- def __init__(self, app, pipeline, connection, id=None, config=None): Description: **Parameters** app : Application Name of the Application pipeline : connection : id : ID, default = None confi... | 11ee3689d0ff6e9b662deeb3fc5e18bb0aabc8f2 | <|skeleton|>
class FTPSource:
"""Description: |"""
def __init__(self, app, pipeline, connection, id=None, config=None):
"""Description: **Parameters** app : Application Name of the Application pipeline : connection : id : ID, default = None config : JSON, default = None"""
<|body_0|>
async... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FTPSource:
"""Description: |"""
def __init__(self, app, pipeline, connection, id=None, config=None):
"""Description: **Parameters** app : Application Name of the Application pipeline : connection : id : ID, default = None config : JSON, default = None"""
super().__init__(app, pipeline, id... | the_stack_v2_python_sparse | bspump/ftp/source.py | LibertyAces/BitSwanPump | train | 24 |
dfafe1811e4e32eb633e9632afb0744456af769e | [
"self._publishers = {}\nself._parameters = self._setup_ros_parameters()\nself._publishers['info'] = rospy.Publisher('info', rocon_std_msgs.MasterInfo, latch=True, queue_size=1)\nmaster_info = rocon_std_msgs.MasterInfo()\nmaster_info.name = self._parameters['name']\nmaster_info.description = self._parameters['descri... | <|body_start_0|>
self._publishers = {}
self._parameters = self._setup_ros_parameters()
self._publishers['info'] = rospy.Publisher('info', rocon_std_msgs.MasterInfo, latch=True, queue_size=1)
master_info = rocon_std_msgs.MasterInfo()
master_info.name = self._parameters['name']
... | This class accepts a few parameters describing the ros master and then publishes the ros master info on a latched publisher. Publishing is necessary because an icon can only be represented by it's location as a parameter. It is easier directly publishing the icon rather than having clients go do the lookup themselves. | RoconMaster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoconMaster:
"""This class accepts a few parameters describing the ros master and then publishes the ros master info on a latched publisher. Publishing is necessary because an icon can only be represented by it's location as a parameter. It is easier directly publishing the icon rather than havin... | stack_v2_sparse_classes_10k_train_003172 | 3,575 | no_license | [
{
"docstring": "Retrieves ``name``, ``description`` and ``icon`` parameters from the parameter server and publishes them on a latched ``info`` topic. The icon parameter must be a ros resource name (pkg/filename).",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Paramete... | 2 | stack_v2_sparse_classes_30k_train_004863 | Implement the Python class `RoconMaster` described below.
Class description:
This class accepts a few parameters describing the ros master and then publishes the ros master info on a latched publisher. Publishing is necessary because an icon can only be represented by it's location as a parameter. It is easier directl... | Implement the Python class `RoconMaster` described below.
Class description:
This class accepts a few parameters describing the ros master and then publishes the ros master info on a latched publisher. Publishing is necessary because an icon can only be represented by it's location as a parameter. It is easier directl... | dfc8bb2026c06d0f97696a726a6773ff8b99496e | <|skeleton|>
class RoconMaster:
"""This class accepts a few parameters describing the ros master and then publishes the ros master info on a latched publisher. Publishing is necessary because an icon can only be represented by it's location as a parameter. It is easier directly publishing the icon rather than havin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RoconMaster:
"""This class accepts a few parameters describing the ros master and then publishes the ros master info on a latched publisher. Publishing is necessary because an icon can only be represented by it's location as a parameter. It is easier directly publishing the icon rather than having clients go ... | the_stack_v2_python_sparse | src/rocon_tools/rocon_master_info/src/rocon_master_info/master.py | uml-robotics/catkin_tester | train | 0 |
3bc759d84927e1675421058f327f7f1437a1a626 | [
"self.prot_attr = prot_attr\nself.estimator = estimator\nself.constraints = constraints\nself.eps = eps\nself.max_iter = max_iter\nself.nu = nu\nself.eta0 = eta0\nself.run_linprog_step = run_linprog_step\nself.drop_prot_attr = drop_prot_attr",
"self.estimator_ = clone(self.estimator)\nmoments = {'DemographicParit... | <|body_start_0|>
self.prot_attr = prot_attr
self.estimator = estimator
self.constraints = constraints
self.eps = eps
self.max_iter = max_iter
self.nu = nu
self.eta0 = eta0
self.run_linprog_step = run_linprog_step
self.drop_prot_attr = drop_prot_att... | Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest empirical error subject to fair classification constraints ... | ExponentiatedGradientReduction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExponentiatedGradientReduction:
"""Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest e... | stack_v2_sparse_classes_10k_train_003173 | 6,304 | permissive | [
{
"docstring": "Args: prot_attr: String or array-like column indices or column names of protected attributes. estimator: An estimator implementing methods ``fit(X, y, sample_weight)`` and ``predict(X)``, where ``X`` is the matrix of features, ``y`` is the vector of labels, and ``sample_weight`` is a vector of w... | 4 | stack_v2_sparse_classes_30k_train_001026 | Implement the Python class `ExponentiatedGradientReduction` described below.
Class description:
Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a ... | Implement the Python class `ExponentiatedGradientReduction` described below.
Class description:
Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a ... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class ExponentiatedGradientReduction:
"""Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExponentiatedGradientReduction:
"""Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest empirical erro... | the_stack_v2_python_sparse | aif360/sklearn/inprocessing/exponentiated_gradient_reduction.py | Trusted-AI/AIF360 | train | 1,157 |
f72b942970e8d27d1939c7d400d412bad7831328 | [
"for vehicle in self:\n if vehicle.issue_date and vehicle.target_date:\n if vehicle.target_date < vehicle.issue_date:\n msg = _('Target Completion Date Should Be Greater Than Issue Date.')\n raise ValidationError(msg)",
"for vehicle in self:\n if vehicle.target_date and vehicle.... | <|body_start_0|>
for vehicle in self:
if vehicle.issue_date and vehicle.target_date:
if vehicle.target_date < vehicle.issue_date:
msg = _('Target Completion Date Should Be Greater Than Issue Date.')
raise ValidationError(msg)
<|end_body_0|>
<|... | Service Repair Line. | ServiceRepairLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceRepairLine:
"""Service Repair Line."""
def check_target_completion_date(self):
"""Method to check target completion date."""
<|body_0|>
def check_etic_date(self):
"""Method to check etic date."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003174 | 49,476 | no_license | [
{
"docstring": "Method to check target completion date.",
"name": "check_target_completion_date",
"signature": "def check_target_completion_date(self)"
},
{
"docstring": "Method to check etic date.",
"name": "check_etic_date",
"signature": "def check_etic_date(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000500 | Implement the Python class `ServiceRepairLine` described below.
Class description:
Service Repair Line.
Method signatures and docstrings:
- def check_target_completion_date(self): Method to check target completion date.
- def check_etic_date(self): Method to check etic date. | Implement the Python class `ServiceRepairLine` described below.
Class description:
Service Repair Line.
Method signatures and docstrings:
- def check_target_completion_date(self): Method to check target completion date.
- def check_etic_date(self): Method to check etic date.
<|skeleton|>
class ServiceRepairLine:
... | 7618a365ac78c0f59390a3a6b5fcdd9f76a5ddec | <|skeleton|>
class ServiceRepairLine:
"""Service Repair Line."""
def check_target_completion_date(self):
"""Method to check target completion date."""
<|body_0|>
def check_etic_date(self):
"""Method to check etic date."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ServiceRepairLine:
"""Service Repair Line."""
def check_target_completion_date(self):
"""Method to check target completion date."""
for vehicle in self:
if vehicle.issue_date and vehicle.target_date:
if vehicle.target_date < vehicle.issue_date:
... | the_stack_v2_python_sparse | fleet_operations/models/fleet_service.py | JayVora-SerpentCS/fleet_management | train | 29 |
6ba4c6b4610048c9b939a6634a75709bf7df7ca5 | [
"self.tfrecord_paths = tfrecord_paths\nself.num_shards = len(self.tfrecord_paths)\nself.tfrecord_paths_tensor = tf.constant(self.tfrecord_paths)\nself.image_width = image_width\nself.image_channels = image_channels\nif seperate_background_channel:\n mask_channels += 1\nself.mask_channels = mask_channels\nprint('... | <|body_start_0|>
self.tfrecord_paths = tfrecord_paths
self.num_shards = len(self.tfrecord_paths)
self.tfrecord_paths_tensor = tf.constant(self.tfrecord_paths)
self.image_width = image_width
self.image_channels = image_channels
if seperate_background_channel:
m... | TFRecordSegmentationDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFRecordSegmentationDataset:
def __init__(self, tfrecord_paths: List[str], image_width: int, image_channels=3, mask_channels=1, seed=0, augmenter: Optional[Augmenter]=None, seperate_background_channel: bool=True):
"""Image segmentation tf.data.Dataset constructor for batching from tfreco... | stack_v2_sparse_classes_10k_train_003175 | 8,998 | permissive | [
{
"docstring": "Image segmentation tf.data.Dataset constructor for batching from tfrecords. Args: tfrecord_paths: list of paths to tfrecords image_width: side of images and masks (all images and masks assumed to be square and of the same size) image_channels: Int number of channels in the images. mask_channels:... | 3 | stack_v2_sparse_classes_30k_train_004104 | Implement the Python class `TFRecordSegmentationDataset` described below.
Class description:
Implement the TFRecordSegmentationDataset class.
Method signatures and docstrings:
- def __init__(self, tfrecord_paths: List[str], image_width: int, image_channels=3, mask_channels=1, seed=0, augmenter: Optional[Augmenter]=No... | Implement the Python class `TFRecordSegmentationDataset` described below.
Class description:
Implement the TFRecordSegmentationDataset class.
Method signatures and docstrings:
- def __init__(self, tfrecord_paths: List[str], image_width: int, image_channels=3, mask_channels=1, seed=0, augmenter: Optional[Augmenter]=No... | f40352e734f77609bcd5c4ad330ea73a897a217d | <|skeleton|>
class TFRecordSegmentationDataset:
def __init__(self, tfrecord_paths: List[str], image_width: int, image_channels=3, mask_channels=1, seed=0, augmenter: Optional[Augmenter]=None, seperate_background_channel: bool=True):
"""Image segmentation tf.data.Dataset constructor for batching from tfreco... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TFRecordSegmentationDataset:
def __init__(self, tfrecord_paths: List[str], image_width: int, image_channels=3, mask_channels=1, seed=0, augmenter: Optional[Augmenter]=None, seperate_background_channel: bool=True):
"""Image segmentation tf.data.Dataset constructor for batching from tfrecords. Args: tfr... | the_stack_v2_python_sparse | joint_train/data/input_fn.py | qilicun/mliis | train | 0 | |
043b1a0e573a27db5c05be879b7c747e6f1a5e91 | [
"if candidates == [] or min(candidates) > target:\n return []\ncandidates.sort()\nres = []\nn = len(candidates)\n\ndef helper(i, rem, cur):\n if rem == 0:\n res.append(cur)\n return\n elif rem < 0:\n return\n for j in range(i, n):\n if candidates[j] > rem:\n break\... | <|body_start_0|>
if candidates == [] or min(candidates) > target:
return []
candidates.sort()
res = []
n = len(candidates)
def helper(i, rem, cur):
if rem == 0:
res.append(cur)
return
elif rem < 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_10k_train_003176 | 1,694 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum",
"signature": "def combinationSum(self, candidates, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum(self, candidates, target): :type candidat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum(self, candidates, target): :type candidat... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
if candidates == [] or min(candidates) > target:
return []
candidates.sort()
res = []
n = len(candidates)
def helper(... | the_stack_v2_python_sparse | 0039_Combination_Sum.py | bingli8802/leetcode | train | 0 | |
8822bbcf1facb80731cc9c3f5bf5605c995ba5e4 | [
"self._implementations = []\nmisc.log(3, 'Start loading document reference resolver entry points ...')\nfor ep in pkg_resources.iter_entry_points(group=self.ADAPTER_ENTRY_POINT_GROUP):\n impl_cls = ep.load()\n regexp = re.compile(impl_cls.match_expression)\n misc.log(3, \" Loaded '%s' with priority %d\" %... | <|body_start_0|>
self._implementations = []
misc.log(3, 'Start loading document reference resolver entry points ...')
for ep in pkg_resources.iter_entry_points(group=self.ADAPTER_ENTRY_POINT_GROUP):
impl_cls = ep.load()
regexp = re.compile(impl_cls.match_expression)
... | _RegistryClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RegistryClass:
def __init__(self):
"""Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are ex... | stack_v2_sparse_classes_10k_train_003177 | 3,532 | no_license | [
{
"docstring": "Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are expected to have a class attribute 'priority', th... | 2 | null | Implement the Python class `_RegistryClass` described below.
Class description:
Implement the _RegistryClass class.
Method signatures and docstrings:
- def __init__(self): Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regula... | Implement the Python class `_RegistryClass` described below.
Class description:
Implement the _RegistryClass class.
Method signatures and docstrings:
- def __init__(self): Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regula... | 6bc932c67bc8d93b873838ae6d9fb8d33c72234d | <|skeleton|>
class _RegistryClass:
def __init__(self):
"""Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are ex... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _RegistryClass:
def __init__(self):
"""Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are expected to have... | the_stack_v2_python_sparse | site-packages/cs.documents-15.2.3.7-py2.7.egg/cs/documents/docref_resolver_registry.py | prachipainuly-rbei/devops-poc | train | 0 | |
1e611737a52ac21b9885d3d4a26c8c3de1a43cd7 | [
"global _SESSIONS\nif not _SESSIONS:\n from evennia.server.sessionhandler import SESSIONS as _SESSIONS\nif irc_botname:\n self.db.irc_botname = irc_botname\nelif not self.db.irc_botname:\n self.db.irc_botname = self.key\nif ev_channel:\n channel = search.channel_search(ev_channel)\n if not channel:\n... | <|body_start_0|>
global _SESSIONS
if not _SESSIONS:
from evennia.server.sessionhandler import SESSIONS as _SESSIONS
if irc_botname:
self.db.irc_botname = irc_botname
elif not self.db.irc_botname:
self.db.irc_botname = self.key
if ev_channel:
... | Bot for handling IRC connections. | IRCBot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IRCBot:
"""Bot for handling IRC connections."""
def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
"""Start by telling the portal to start a new session. Args: ev_channel (str): Key of the Evennia channel to connect to... | stack_v2_sparse_classes_10k_train_003178 | 13,744 | permissive | [
{
"docstring": "Start by telling the portal to start a new session. Args: ev_channel (str): Key of the Evennia channel to connect to. irc_botname (str): Name of bot to connect to irc channel. If not set, use `self.key`. irc_channel (str): Name of channel on the form `#channelname`. irc_network (str): URL of the... | 3 | stack_v2_sparse_classes_30k_test_000081 | Implement the Python class `IRCBot` described below.
Class description:
Bot for handling IRC connections.
Method signatures and docstrings:
- def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None): Start by telling the portal to start a new session. Args: e... | Implement the Python class `IRCBot` described below.
Class description:
Bot for handling IRC connections.
Method signatures and docstrings:
- def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None): Start by telling the portal to start a new session. Args: e... | 384d08f9d877c7ad758292822e6f04292fdad047 | <|skeleton|>
class IRCBot:
"""Bot for handling IRC connections."""
def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
"""Start by telling the portal to start a new session. Args: ev_channel (str): Key of the Evennia channel to connect to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IRCBot:
"""Bot for handling IRC connections."""
def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
"""Start by telling the portal to start a new session. Args: ev_channel (str): Key of the Evennia channel to connect to. irc_botname... | the_stack_v2_python_sparse | evennia/players/bots.py | robbintt/evennia | train | 1 |
61b8d91344a487b0817625b284b98fab4265bfb2 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.color = dict(((node, 0) for node in self.graph.iternodes()))\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')",
"base = 1\nis_colored = False\nwhil... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.color = dict(((node, 0) for node in self.graph.iternodes()))
for edge in self.graph.iteredges():
if edge.source == edge.target:
raise ValueEr... | Find an exact node coloring (slow). Based on http://eduinf.waw.pl/inf/alg/001_search/0142.php Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ... | ExactNodeColoring | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExactNodeColoring:
"""Find an exact node coloring (slow). Based on http://eduinf.waw.pl/inf/alg/001_search/0142.php Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ..."""
def __init__(self, graph):... | stack_v2_sparse_classes_10k_train_003179 | 2,229 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001142 | Implement the Python class `ExactNodeColoring` described below.
Class description:
Find an exact node coloring (slow). Based on http://eduinf.waw.pl/inf/alg/001_search/0142.php Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2,... | Implement the Python class `ExactNodeColoring` described below.
Class description:
Find an exact node coloring (slow). Based on http://eduinf.waw.pl/inf/alg/001_search/0142.php Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2,... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class ExactNodeColoring:
"""Find an exact node coloring (slow). Based on http://eduinf.waw.pl/inf/alg/001_search/0142.php Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ..."""
def __init__(self, graph):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExactNodeColoring:
"""Find an exact node coloring (slow). Based on http://eduinf.waw.pl/inf/alg/001_search/0142.php Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ..."""
def __init__(self, graph):
"""T... | the_stack_v2_python_sparse | graphtheory/coloring/nodecolorexact.py | kgashok/graphs-dict | train | 0 |
cd380f18c7d47aab90558f7754cf8554445a534b | [
"super(RND, self).__init__(state_size, action_size, eta)\nself.hidden_dim = hidden_dim\nself.state_rep_size = state_rep_size\nself.learning_rate = learning_rate\nself.predictor_dev = 'cpu'\nself.target_dev = 'cpu'\nself.predictor_model = RNDNetwork(state_size, action_size, hidden_dim, state_rep_size)\nself.target_m... | <|body_start_0|>
super(RND, self).__init__(state_size, action_size, eta)
self.hidden_dim = hidden_dim
self.state_rep_size = state_rep_size
self.learning_rate = learning_rate
self.predictor_dev = 'cpu'
self.target_dev = 'cpu'
self.predictor_model = RNDNetwork(state... | Random Network Distillation (RND) class Paper: Burda, Y., Edwards, H., Storkey, A., & Klimov, O. (2018). Exploration by random network distillation. arXiv preprint arXiv:1810.12894. Link: https://arxiv.org/abs/1810.12894 | RND | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RND:
"""Random Network Distillation (RND) class Paper: Burda, Y., Edwards, H., Storkey, A., & Klimov, O. (2018). Exploration by random network distillation. arXiv preprint arXiv:1810.12894. Link: https://arxiv.org/abs/1810.12894"""
def __init__(self, state_size, action_size, hidden_dim=128, ... | stack_v2_sparse_classes_10k_train_003180 | 3,425 | no_license | [
{
"docstring": "Initialise parameters for MARL training :param state_size: dimension of state input :param action_size: dimension of action input :param hidden_dim: hidden dimension of networks :param state_rep_size: dimension of state representation in network :param learning_rate: learning rate for ICM parame... | 3 | stack_v2_sparse_classes_30k_train_002094 | Implement the Python class `RND` described below.
Class description:
Random Network Distillation (RND) class Paper: Burda, Y., Edwards, H., Storkey, A., & Klimov, O. (2018). Exploration by random network distillation. arXiv preprint arXiv:1810.12894. Link: https://arxiv.org/abs/1810.12894
Method signatures and docstr... | Implement the Python class `RND` described below.
Class description:
Random Network Distillation (RND) class Paper: Burda, Y., Edwards, H., Storkey, A., & Klimov, O. (2018). Exploration by random network distillation. arXiv preprint arXiv:1810.12894. Link: https://arxiv.org/abs/1810.12894
Method signatures and docstr... | 2afa0a9d83bd66a151c1a19242c5ef22cf4eb1f6 | <|skeleton|>
class RND:
"""Random Network Distillation (RND) class Paper: Burda, Y., Edwards, H., Storkey, A., & Klimov, O. (2018). Exploration by random network distillation. arXiv preprint arXiv:1810.12894. Link: https://arxiv.org/abs/1810.12894"""
def __init__(self, state_size, action_size, hidden_dim=128, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RND:
"""Random Network Distillation (RND) class Paper: Burda, Y., Edwards, H., Storkey, A., & Klimov, O. (2018). Exploration by random network distillation. arXiv preprint arXiv:1810.12894. Link: https://arxiv.org/abs/1810.12894"""
def __init__(self, state_size, action_size, hidden_dim=128, state_rep_siz... | the_stack_v2_python_sparse | intrinsic_rewards/rnd/rnd.py | Jarvis-K/MSc_Curiosity_MARL | train | 0 |
14b0ec57320083bc44b3a228ac206941b7b9e587 | [
"super(MoveItemsForm, self).__init__(project, *args, **kwargs)\nif subdir is not None:\n choices = [(d.name, d.name) for d in display_dirs]\n if subdir:\n choices.insert(0, ('../', '(Parent directory)'))\n self.fields['destination_folder'].widget.choices = choices",
"cleaned_data = super(MoveItems... | <|body_start_0|>
super(MoveItemsForm, self).__init__(project, *args, **kwargs)
if subdir is not None:
choices = [(d.name, d.name) for d in display_dirs]
if subdir:
choices.insert(0, ('../', '(Parent directory)'))
self.fields['destination_folder'].widge... | Form for moving items into a target folder | MoveItemsForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoveItemsForm:
"""Form for moving items into a target folder"""
def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs):
"""Set the choices for the destination folder"""
<|body_0|>
def clean(self):
"""Selected destination folder: - May only b... | stack_v2_sparse_classes_10k_train_003181 | 39,361 | permissive | [
{
"docstring": "Set the choices for the destination folder",
"name": "__init__",
"signature": "def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs)"
},
{
"docstring": "Selected destination folder: - May only be '..' if subdir is not the top level - Must not be one of the ... | 3 | stack_v2_sparse_classes_30k_train_004052 | Implement the Python class `MoveItemsForm` described below.
Class description:
Form for moving items into a target folder
Method signatures and docstrings:
- def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): Set the choices for the destination folder
- def clean(self): Selected destination... | Implement the Python class `MoveItemsForm` described below.
Class description:
Form for moving items into a target folder
Method signatures and docstrings:
- def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs): Set the choices for the destination folder
- def clean(self): Selected destination... | e7c8ed0b07a4c9a1b4007f6089f59aafa6a3ac57 | <|skeleton|>
class MoveItemsForm:
"""Form for moving items into a target folder"""
def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs):
"""Set the choices for the destination folder"""
<|body_0|>
def clean(self):
"""Selected destination folder: - May only b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MoveItemsForm:
"""Form for moving items into a target folder"""
def __init__(self, project, subdir=None, display_dirs=None, *args, **kwargs):
"""Set the choices for the destination folder"""
super(MoveItemsForm, self).__init__(project, *args, **kwargs)
if subdir is not None:
... | the_stack_v2_python_sparse | physionet-django/project/forms.py | tompollard/physionet-build | train | 0 |
3a391091e6dc7f4b366b9f62d3c03c5da0bb8bb5 | [
"path = urls.WIDS['GET_CLIENT_ATTACKS']\nparams = {'limit': limit, 'offset': offset, 'sort': sort, 'calculate_total': calculate_total}\nif group:\n params['group'] = group\nif label:\n params['label'] = label\nif site:\n params['site'] = site\nif swarm_id:\n params['swarm_id'] = swarm_id\nif start:\n ... | <|body_start_0|>
path = urls.WIDS['GET_CLIENT_ATTACKS']
params = {'limit': limit, 'offset': offset, 'sort': sort, 'calculate_total': calculate_total}
if group:
params['group'] = group
if label:
params['label'] = label
if site:
params['site'] = ... | A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs. | WIDS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WIDS:
"""A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs."""
def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_timestamp=None, to_timestamp=None, limit=100, calculate_total=True, s... | stack_v2_sparse_classes_10k_train_003182 | 22,300 | permissive | [
{
"docstring": "Get client attacks over a time period :param conn: Instance of class:`pycentral.ArubaCentralBase` to make an API call. :type conn: class:`pycentral.ArubaCentralBase` :param group: List of group names, defaults to None :type group: list, optional :param label: List of label names, defaults to Non... | 3 | stack_v2_sparse_classes_30k_train_001656 | Implement the Python class `WIDS` described below.
Class description:
A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs.
Method signatures and docstrings:
- def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_t... | Implement the Python class `WIDS` described below.
Class description:
A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs.
Method signatures and docstrings:
- def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_t... | d938396a18193473afbe54e6cc6697d2bd4954a7 | <|skeleton|>
class WIDS:
"""A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs."""
def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_timestamp=None, to_timestamp=None, limit=100, calculate_total=True, s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WIDS:
"""A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs."""
def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_timestamp=None, to_timestamp=None, limit=100, calculate_total=True, sort='-ts', of... | the_stack_v2_python_sparse | pycentral/rapids.py | jayp193/pycentral | train | 0 |
b3107d9f37245b9800def315c79ee9d9df4fa0fa | [
"http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\nif http_x_forwarded_for:\n ip = http_x_forwarded_for.split(',')[-1].strip()\nelse:\n ip = request.META.get('REMOTE_ADDR')\nreturn ip",
"try:\n profile = request.user.profile\nexcept cls.DoesNotExist:\n profile = cls.objects.create(user=... | <|body_start_0|>
http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if http_x_forwarded_for:
ip = http_x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
<|end_body_0|>
<|body_start_1|>
try:
... | This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0 | Profile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django requ... | stack_v2_sparse_classes_10k_train_003183 | 3,000 | permissive | [
{
"docstring": "Return user IP from request. :param request: django request :return: IP",
"name": "get_user_ip",
"signature": "def get_user_ip(request)"
},
{
"docstring": "Check if self.timezone is empty - get timezone from pygeoip and store it there. :param request: django request :return: noth... | 2 | null | Implement the Python class `Profile` described below.
Class description:
This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0
Method signatures and docstrings:
- def get_user_ip(request):... | Implement the Python class `Profile` described below.
Class description:
This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0
Method signatures and docstrings:
- def get_user_ip(request):... | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | <|skeleton|>
class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django requ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django request :return: ... | the_stack_v2_python_sparse | mysite/accounts/models.py | cjlee112/socraticqs2 | train | 8 |
57fcbee6fcb7903b6bc15062ddcea300c5b89a3b | [
"SphericalPotential.__init__(self, amp=amp, ro=ro, vo=vo, amp_units='mass')\na = conversion.parse_length(a, ro=self._ro)\nself.a = a\nself.a2 = a ** 2\nif normalize or (isinstance(normalize, (int, float)) and (not isinstance(normalize, bool))):\n if self.a > 1.0:\n raise ValueError('SphericalShellPotentia... | <|body_start_0|>
SphericalPotential.__init__(self, amp=amp, ro=ro, vo=vo, amp_units='mass')
a = conversion.parse_length(a, ro=self._ro)
self.a = a
self.a2 = a ** 2
if normalize or (isinstance(normalize, (int, float)) and (not isinstance(normalize, bool))):
if self.a >... | Class that implements the potential of an infinitesimally-thin, spherical shell .. math:: \\rho(r) = \\frac{\\mathrm{amp}}{4\\pi\\,a^2}\\,\\delta(r-a) with :math:`\\mathrm{amp} = GM` the mass of the shell. | SphericalShellPotential | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalShellPotential:
"""Class that implements the potential of an infinitesimally-thin, spherical shell .. math:: \\rho(r) = \\frac{\\mathrm{amp}}{4\\pi\\,a^2}\\,\\delta(r-a) with :math:`\\mathrm{amp} = GM` the mass of the shell."""
def __init__(self, amp=1.0, a=0.75, normalize=False, ro... | stack_v2_sparse_classes_10k_train_003184 | 3,427 | permissive | [
{
"docstring": "NAME: __init__ PURPOSE: initialize a spherical shell potential INPUT: amp - mass of the shell (default: 1); can be a Quantity with units of mass or Gxmass a= (0.75) radius of the shell (can be Quantity) normalize - if True, normalize such that vc(1.,0.)=1., or, if given as a number, such that th... | 6 | stack_v2_sparse_classes_30k_train_004675 | Implement the Python class `SphericalShellPotential` described below.
Class description:
Class that implements the potential of an infinitesimally-thin, spherical shell .. math:: \\rho(r) = \\frac{\\mathrm{amp}}{4\\pi\\,a^2}\\,\\delta(r-a) with :math:`\\mathrm{amp} = GM` the mass of the shell.
Method signatures and d... | Implement the Python class `SphericalShellPotential` described below.
Class description:
Class that implements the potential of an infinitesimally-thin, spherical shell .. math:: \\rho(r) = \\frac{\\mathrm{amp}}{4\\pi\\,a^2}\\,\\delta(r-a) with :math:`\\mathrm{amp} = GM` the mass of the shell.
Method signatures and d... | 9654e2e181d26abaac4a4fba49375887fb290d36 | <|skeleton|>
class SphericalShellPotential:
"""Class that implements the potential of an infinitesimally-thin, spherical shell .. math:: \\rho(r) = \\frac{\\mathrm{amp}}{4\\pi\\,a^2}\\,\\delta(r-a) with :math:`\\mathrm{amp} = GM` the mass of the shell."""
def __init__(self, amp=1.0, a=0.75, normalize=False, ro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalShellPotential:
"""Class that implements the potential of an infinitesimally-thin, spherical shell .. math:: \\rho(r) = \\frac{\\mathrm{amp}}{4\\pi\\,a^2}\\,\\delta(r-a) with :math:`\\mathrm{amp} = GM` the mass of the shell."""
def __init__(self, amp=1.0, a=0.75, normalize=False, ro=None, vo=Non... | the_stack_v2_python_sparse | galpy/potential/SphericalShellPotential.py | davidhendel/galpy | train | 0 |
669321487c7e8da628aacbe3607a78982325e376 | [
"for model, trained_examples in trained_examples_by_model.items():\n if not trained_examples:\n continue\n if trained_examples[-1].span < max_span:\n return model\nraise exceptions.SkipSignal()",
"_validate_input_dict(input_dict)\nops_utils.validate_argument('wait_spans_before_eval', self.wait... | <|body_start_0|>
for model, trained_examples in trained_examples_by_model.items():
if not trained_examples:
continue
if trained_examples[-1].span < max_span:
return model
raise exceptions.SkipSignal()
<|end_body_0|>
<|body_start_1|>
_valid... | SpanDrivenEvaluatorInputs operator. | SpanDrivenEvaluatorInputs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpanDrivenEvaluatorInputs:
"""SpanDrivenEvaluatorInputs operator."""
def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]:
"""Finds the latest Model not trained on Examples with span max_spa... | stack_v2_sparse_classes_10k_train_003185 | 7,595 | permissive | [
{
"docstring": "Finds the latest Model not trained on Examples with span max_span.",
"name": "_get_model_to_evaluate",
"signature": "def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]"
},
{
"docstring... | 2 | null | Implement the Python class `SpanDrivenEvaluatorInputs` described below.
Class description:
SpanDrivenEvaluatorInputs operator.
Method signatures and docstrings:
- def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]: Finds t... | Implement the Python class `SpanDrivenEvaluatorInputs` described below.
Class description:
SpanDrivenEvaluatorInputs operator.
Method signatures and docstrings:
- def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]: Finds t... | 1b328504fa08a70388691e4072df76f143631325 | <|skeleton|>
class SpanDrivenEvaluatorInputs:
"""SpanDrivenEvaluatorInputs operator."""
def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]:
"""Finds the latest Model not trained on Examples with span max_spa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpanDrivenEvaluatorInputs:
"""SpanDrivenEvaluatorInputs operator."""
def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]:
"""Finds the latest Model not trained on Examples with span max_span."""
... | the_stack_v2_python_sparse | tfx/dsl/input_resolution/ops/span_driven_evaluator_inputs_op.py | tensorflow/tfx | train | 2,116 |
e8e1b6d01c20845e118259f704b02842d3ab6e24 | [
"selected = set([x, y])\nif root.val in selected:\n return False\nprev = [root]\nwhile prev:\n cur = []\n for node in prev:\n left, right = (node.left, node.right)\n if left and right and set([left.val, right.val]).issubset(selected):\n return False\n if left:\n c... | <|body_start_0|>
selected = set([x, y])
if root.val in selected:
return False
prev = [root]
while prev:
cur = []
for node in prev:
left, right = (node.left, node.right)
if left and right and set([left.val, right.val]).is... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isCousins1(self, root, x, y):
"""BFS, 28ms"""
<|body_0|>
def isCousins2(self, root, x, y):
"""DFS, 32ms"""
<|body_1|>
def isCousins3(self, root, x, y):
"""BFS 2, 32ms"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003186 | 3,166 | permissive | [
{
"docstring": "BFS, 28ms",
"name": "isCousins1",
"signature": "def isCousins1(self, root, x, y)"
},
{
"docstring": "DFS, 32ms",
"name": "isCousins2",
"signature": "def isCousins2(self, root, x, y)"
},
{
"docstring": "BFS 2, 32ms",
"name": "isCousins3",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_005597 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCousins1(self, root, x, y): BFS, 28ms
- def isCousins2(self, root, x, y): DFS, 32ms
- def isCousins3(self, root, x, y): BFS 2, 32ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCousins1(self, root, x, y): BFS, 28ms
- def isCousins2(self, root, x, y): DFS, 32ms
- def isCousins3(self, root, x, y): BFS 2, 32ms
<|skeleton|>
class Solution:
def i... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def isCousins1(self, root, x, y):
"""BFS, 28ms"""
<|body_0|>
def isCousins2(self, root, x, y):
"""DFS, 32ms"""
<|body_1|>
def isCousins3(self, root, x, y):
"""BFS 2, 32ms"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isCousins1(self, root, x, y):
"""BFS, 28ms"""
selected = set([x, y])
if root.val in selected:
return False
prev = [root]
while prev:
cur = []
for node in prev:
left, right = (node.left, node.right)
... | the_stack_v2_python_sparse | leetcode/0993_cousins_in_binary_tree.py | chaosWsF/Python-Practice | train | 1 | |
439f37b9d5652347b1f8a2ced50d36ca0c819500 | [
"super().__init__()\nself.cnn_layers = nn.Sequential()\nself.fc_layers = nn.Sequential()\nself.loss_criterion = None\nself.cnn_layers = nn.Sequential(nn.Conv2d(1, 10, 5), nn.MaxPool2d(3, 3), nn.ReLU(), nn.Conv2d(10, 20, 5), nn.MaxPool2d(3, 3), nn.ReLU(), nn.Flatten())\nself.fc_layers = nn.Sequential(nn.Dropout(0.1)... | <|body_start_0|>
super().__init__()
self.cnn_layers = nn.Sequential()
self.fc_layers = nn.Sequential()
self.loss_criterion = None
self.cnn_layers = nn.Sequential(nn.Conv2d(1, 10, 5), nn.MaxPool2d(3, 3), nn.ReLU(), nn.Conv2d(10, 20, 5), nn.MaxPool2d(3, 3), nn.ReLU(), nn.Flatten())... | SimpleNetDropout | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleNetDropout:
def __init__(self):
"""Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means"""
<|body_0|>
def forward(self, x: torch.tensor) -> torch.tensor:
"""Pe... | stack_v2_sparse_classes_10k_train_003187 | 1,913 | no_license | [
{
"docstring": "Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform the forward pass with the net Note: do not... | 2 | stack_v2_sparse_classes_30k_train_001639 | Implement the Python class `SimpleNetDropout` described below.
Class description:
Implement the SimpleNetDropout class.
Method signatures and docstrings:
- def __init__(self): Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand w... | Implement the Python class `SimpleNetDropout` described below.
Class description:
Implement the SimpleNetDropout class.
Method signatures and docstrings:
- def __init__(self): Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand w... | bc48e09844c70f28fc82cdbead405219a964f5aa | <|skeleton|>
class SimpleNetDropout:
def __init__(self):
"""Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means"""
<|body_0|>
def forward(self, x: torch.tensor) -> torch.tensor:
"""Pe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleNetDropout:
def __init__(self):
"""Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means"""
super().__init__()
self.cnn_layers = nn.Sequential()
self.fc_layers = nn.Sequen... | the_stack_v2_python_sparse | Computer Vision/proj2_part2_release/proj2_code/simple_net_dropout.py | karan-sarkar/GT | train | 1 | |
6da0cb332487b42897331ba993693676ef3937f0 | [
"if root:\n self.flatten(root.right)\n self.flatten(root.left)\n print(root.val)\n root.right = self.nex\n root.left = None\n self.nex = root",
"if not root:\n return root\n\ndef dfs(root):\n if root:\n arr.append(root)\n dfs(root.left)\n dfs(root.right)\narr = []\ndum... | <|body_start_0|>
if root:
self.flatten(root.right)
self.flatten(root.left)
print(root.val)
root.right = self.nex
root.left = None
self.nex = root
<|end_body_0|>
<|body_start_1|>
if not root:
return root
def dfs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""思路: 1. 记录中间变量"""
<|body_0|>
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root:
... | stack_v2_sparse_classes_10k_train_003188 | 1,503 | no_license | [
{
"docstring": "思路: 1. 记录中间变量",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_002637 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 思路: 1. 记录中间变量
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 思路: 1. 记录中间变量
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
<|skeleton|>
class So... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""思路: 1. 记录中间变量"""
<|body_0|>
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root: TreeNode) -> None:
"""思路: 1. 记录中间变量"""
if root:
self.flatten(root.right)
self.flatten(root.left)
print(root.val)
root.right = self.nex
root.left = None
self.nex = root
def flatten(sel... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/114. 二叉树展开为链表.py | yiming1012/MyLeetCode | train | 2 | |
692d9d81bd566d70c7fad026a9fb881f60bf92ef | [
"update_interval = REST_SENSORS_UPDATE_INTERVAL\nif device.settings['device']['type'] in BATTERY_DEVICES_WITH_PERMANENT_CONNECTION:\n update_interval = SLEEP_PERIOD_MULTIPLIER * device.settings['coiot']['update_period']\nsuper().__init__(hass, entry, device, update_interval)",
"LOGGER.debug('REST update for %s... | <|body_start_0|>
update_interval = REST_SENSORS_UPDATE_INTERVAL
if device.settings['device']['type'] in BATTERY_DEVICES_WITH_PERMANENT_CONNECTION:
update_interval = SLEEP_PERIOD_MULTIPLIER * device.settings['coiot']['update_period']
super().__init__(hass, entry, device, update_interv... | Coordinator for a Shelly REST device. | ShellyRestCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShellyRestCoordinator:
"""Coordinator for a Shelly REST device."""
def __init__(self, hass: HomeAssistant, device: BlockDevice, entry: ConfigEntry) -> None:
"""Initialize the Shelly REST device coordinator."""
<|body_0|>
async def _async_update_data(self) -> None:
... | stack_v2_sparse_classes_10k_train_003189 | 24,604 | permissive | [
{
"docstring": "Initialize the Shelly REST device coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, device: BlockDevice, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch data.",
"name": "_async_update_data",
"signature": "async def _async_updat... | 2 | null | Implement the Python class `ShellyRestCoordinator` described below.
Class description:
Coordinator for a Shelly REST device.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: BlockDevice, entry: ConfigEntry) -> None: Initialize the Shelly REST device coordinator.
- async def _async_u... | Implement the Python class `ShellyRestCoordinator` described below.
Class description:
Coordinator for a Shelly REST device.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: BlockDevice, entry: ConfigEntry) -> None: Initialize the Shelly REST device coordinator.
- async def _async_u... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ShellyRestCoordinator:
"""Coordinator for a Shelly REST device."""
def __init__(self, hass: HomeAssistant, device: BlockDevice, entry: ConfigEntry) -> None:
"""Initialize the Shelly REST device coordinator."""
<|body_0|>
async def _async_update_data(self) -> None:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShellyRestCoordinator:
"""Coordinator for a Shelly REST device."""
def __init__(self, hass: HomeAssistant, device: BlockDevice, entry: ConfigEntry) -> None:
"""Initialize the Shelly REST device coordinator."""
update_interval = REST_SENSORS_UPDATE_INTERVAL
if device.settings['devi... | the_stack_v2_python_sparse | homeassistant/components/shelly/coordinator.py | home-assistant/core | train | 35,501 |
97a04b0c50d19bd88a5e6b7769640588fba16294 | [
"self.kubeconfig = kubeconfig\nself.name = sname\nself.namespace = namespace\nself.data = {}\nself.create_dict()",
"self.data['apiVersion'] = 'v1'\nself.data['kind'] = 'Group'\nself.data['metadata'] = {}\nself.data['metadata']['name'] = self.name\nself.data['users'] = None"
] | <|body_start_0|>
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.data = {}
self.create_dict()
<|end_body_0|>
<|body_start_1|>
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Group'
self.data['metadata'] = {}
self... | Handle route options | GroupConfig | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupConfig:
"""Handle route options"""
def __init__(self, sname, namespace, kubeconfig):
"""constructor for handling group options"""
<|body_0|>
def create_dict(self):
"""return a service as a dict"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003190 | 1,002 | permissive | [
{
"docstring": "constructor for handling group options",
"name": "__init__",
"signature": "def __init__(self, sname, namespace, kubeconfig)"
},
{
"docstring": "return a service as a dict",
"name": "create_dict",
"signature": "def create_dict(self)"
}
] | 2 | null | Implement the Python class `GroupConfig` described below.
Class description:
Handle route options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig): constructor for handling group options
- def create_dict(self): return a service as a dict | Implement the Python class `GroupConfig` described below.
Class description:
Handle route options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig): constructor for handling group options
- def create_dict(self): return a service as a dict
<|skeleton|>
class GroupConfig:
"""Han... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class GroupConfig:
"""Handle route options"""
def __init__(self, sname, namespace, kubeconfig):
"""constructor for handling group options"""
<|body_0|>
def create_dict(self):
"""return a service as a dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupConfig:
"""Handle route options"""
def __init__(self, sname, namespace, kubeconfig):
"""constructor for handling group options"""
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.data = {}
self.create_dict()
def creat... | the_stack_v2_python_sparse | ansible/roles/lib_openshift_3.2/build/lib/group.py | openshift/openshift-tools | train | 170 |
20c96b2a15f9417079d418617824268e151a5b0a | [
"if not root:\n return ''\nres = str(root.val)\nif len(root.children) != 0:\n children_res = []\n for child in root.children:\n children_res.append(self.serialize(child))\n res = res + '[' + ' '.join(children_res) + ']'\nreturn res",
"if len(data) == 0:\n return None\nstart = data.find('[')\... | <|body_start_0|>
if not root:
return ''
res = str(root.val)
if len(root.children) != 0:
children_res = []
for child in root.children:
children_res.append(self.serialize(child))
res = res + '[' + ' '.join(children_res) + ']'
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_003191 | 1,698 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | stack_v2_sparse_classes_30k_train_002431 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | d87acd5481a2dbfad7288b73750e6e086650a17d | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
res = str(root.val)
if len(root.children) != 0:
children_res = []
for child in root.children:
child... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree/428. Serialize and Deserialize N-ary Tree(AC).py | BohaoLiGithub/Leetcode | train | 0 | |
3e027ec03dd5001bb1b73119933c71a9afaaba87 | [
"self.address = address\nself.port = port\nself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.sock.connect((self.address, self.port))\nself.t = paramiko.Transport(self.sock)\ntry:\n self.t.start_client()\nexcept paramiko.SSHException:\n raise ConnectionError('SSH negotiation failed')\ntry:\n ... | <|body_start_0|>
self.address = address
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.address, self.port))
self.t = paramiko.Transport(self.sock)
try:
self.t.start_client()
except paramiko.SSHExc... | FileServerClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileServerClient:
def __init__(self, address, port, key_path, print_func):
"""Opens tcp/ip socket to address:port"""
<|body_0|>
def close(self):
"""Closes the transport channel and connection"""
<|body_1|>
def receive_str(self, buf=1024):
"""Rece... | stack_v2_sparse_classes_10k_train_003192 | 5,225 | permissive | [
{
"docstring": "Opens tcp/ip socket to address:port",
"name": "__init__",
"signature": "def __init__(self, address, port, key_path, print_func)"
},
{
"docstring": "Closes the transport channel and connection",
"name": "close",
"signature": "def close(self)"
},
{
"docstring": "Rec... | 5 | stack_v2_sparse_classes_30k_train_006332 | Implement the Python class `FileServerClient` described below.
Class description:
Implement the FileServerClient class.
Method signatures and docstrings:
- def __init__(self, address, port, key_path, print_func): Opens tcp/ip socket to address:port
- def close(self): Closes the transport channel and connection
- def ... | Implement the Python class `FileServerClient` described below.
Class description:
Implement the FileServerClient class.
Method signatures and docstrings:
- def __init__(self, address, port, key_path, print_func): Opens tcp/ip socket to address:port
- def close(self): Closes the transport channel and connection
- def ... | ee48a3c8c56d332904030a2b996baa87620c8a79 | <|skeleton|>
class FileServerClient:
def __init__(self, address, port, key_path, print_func):
"""Opens tcp/ip socket to address:port"""
<|body_0|>
def close(self):
"""Closes the transport channel and connection"""
<|body_1|>
def receive_str(self, buf=1024):
"""Rece... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileServerClient:
def __init__(self, address, port, key_path, print_func):
"""Opens tcp/ip socket to address:port"""
self.address = address
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.address, self.port))
... | the_stack_v2_python_sparse | aim/engine/aim_protocol.py | Arman-Deghoyan/aim | train | 0 | |
db669baa521963388b76b5bea745c8adb0b63de1 | [
"_type = request.GET.get('type')\nif not _type:\n promotion_id = request.GET['id']\n promotion = models.Promotion.objects.get(owner=request.manager, type=models.PROMOTION_TYPE_PREMIUM_SALE, id=promotion_id)\n models.Promotion.fill_details(request.manager, [promotion], {'with_product': True, 'with_concrete_... | <|body_start_0|>
_type = request.GET.get('type')
if not _type:
promotion_id = request.GET['id']
promotion = models.Promotion.objects.get(owner=request.manager, type=models.PROMOTION_TYPE_PREMIUM_SALE, id=promotion_id)
models.Promotion.fill_details(request.manager, [pr... | PremiumSale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PremiumSale:
def get(request):
"""添加买赠"""
<|body_0|>
def api_put(request):
"""创建买赠活动"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_type = request.GET.get('type')
if not _type:
promotion_id = request.GET['id']
promo... | stack_v2_sparse_classes_10k_train_003193 | 7,295 | no_license | [
{
"docstring": "添加买赠",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "创建买赠活动",
"name": "api_put",
"signature": "def api_put(request)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000262 | Implement the Python class `PremiumSale` described below.
Class description:
Implement the PremiumSale class.
Method signatures and docstrings:
- def get(request): 添加买赠
- def api_put(request): 创建买赠活动 | Implement the Python class `PremiumSale` described below.
Class description:
Implement the PremiumSale class.
Method signatures and docstrings:
- def get(request): 添加买赠
- def api_put(request): 创建买赠活动
<|skeleton|>
class PremiumSale:
def get(request):
"""添加买赠"""
<|body_0|>
def api_put(request... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class PremiumSale:
def get(request):
"""添加买赠"""
<|body_0|>
def api_put(request):
"""创建买赠活动"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PremiumSale:
def get(request):
"""添加买赠"""
_type = request.GET.get('type')
if not _type:
promotion_id = request.GET['id']
promotion = models.Promotion.objects.get(owner=request.manager, type=models.PROMOTION_TYPE_PREMIUM_SALE, id=promotion_id)
models.... | the_stack_v2_python_sparse | weapp/mall/promotion/premium_sale.py | chengdg/weizoom | train | 1 | |
e64b1c33bf2cdace64ccf3b713b7680415e3bd3e | [
"if not matrix:\n self.sums = []\nelse:\n row, col = (len(matrix), len(matrix[0]))\n self.sums = [[0] * (col + 1) for _ in range(row + 1)]\n for i in range(1, row + 1):\n for j in range(1, col + 1):\n self.sums[i][j] = self.sums[i][j - 1] + self.sums[i - 1][j] - self.sums[i - 1][j - 1]... | <|body_start_0|>
if not matrix:
self.sums = []
else:
row, col = (len(matrix), len(matrix[0]))
self.sums = [[0] * (col + 1) for _ in range(row + 1)]
for i in range(1, row + 1):
for j in range(1, col + 1):
self.sums[i][j] ... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_10k_train_003194 | 1,331 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | stack_v2_sparse_classes_30k_train_002922 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 14e32f180c3f5eedd101fd2dbb57712498375a9a | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if not matrix:
self.sums = []
else:
row, col = (len(matrix), len(matrix[0]))
self.sums = [[0] * (col + 1) for _ in range(row + 1)]
... | the_stack_v2_python_sparse | 304RangeSumQuery2D-Immutable.py | xkoma007/leetcode | train | 0 | |
4967435a522581d9c1b420c57066b42bcd8a4ab1 | [
"self._bucket_capacity = 997\nself._capacity = 10 ** 6\nself._no_of_buckets = math.ceil(self._capacity / self._bucket_capacity)\nself._buckets = [Node(None) for _ in range(self._no_of_buckets)]",
"bucket = self._buckets[key % self._bucket_capacity]\nnode = bucket\nprev = None\nwhile node:\n if node.val and nod... | <|body_start_0|>
self._bucket_capacity = 997
self._capacity = 10 ** 6
self._no_of_buckets = math.ceil(self._capacity / self._bucket_capacity)
self._buckets = [Node(None) for _ in range(self._no_of_buckets)]
<|end_body_0|>
<|body_start_1|>
bucket = self._buckets[key % self._bucke... | MyHashMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyHashMap:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def put(self, key: int, value: int) -> None:
"""value will always be non-negative."""
<|body_1|>
def get(self, key: int) -> int:
"""Returns the value to which th... | stack_v2_sparse_classes_10k_train_003195 | 1,953 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "value will always be non-negative.",
"name": "put",
"signature": "def put(self, key: int, value: int) -> None"
},
{
"docstring": "Returns the value to w... | 4 | null | Implement the Python class `MyHashMap` described below.
Class description:
Implement the MyHashMap class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def put(self, key: int, value: int) -> None: value will always be non-negative.
- def get(self, key: int) -> int: Ret... | Implement the Python class `MyHashMap` described below.
Class description:
Implement the MyHashMap class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def put(self, key: int, value: int) -> None: value will always be non-negative.
- def get(self, key: int) -> int: Ret... | b7d3b9e2f45ba68a121951c0ca138bf94f035b26 | <|skeleton|>
class MyHashMap:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def put(self, key: int, value: int) -> None:
"""value will always be non-negative."""
<|body_1|>
def get(self, key: int) -> int:
"""Returns the value to which th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyHashMap:
def __init__(self):
"""Initialize your data structure here."""
self._bucket_capacity = 997
self._capacity = 10 ** 6
self._no_of_buckets = math.ceil(self._capacity / self._bucket_capacity)
self._buckets = [Node(None) for _ in range(self._no_of_buckets)]
d... | the_stack_v2_python_sparse | hash/design_hashmap.py | uma-c/CodingProblemSolving | train | 0 | |
dbf695dd17fc94fd4031e9b8fc57ef5896311ea6 | [
"dp, s1_ascii, s2_ascii, f = ([[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)], 0, 0, 0)\nfor i in range(1, len(s1) + 1):\n s1_ascii += ord(s1[i - 1])\n for j in range(1, len(s2) + 1):\n if not f:\n s2_ascii += ord(s2[j - 1])\n if s1[i - 1] == s2[j - 1]:\n dp[i... | <|body_start_0|>
dp, s1_ascii, s2_ascii, f = ([[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)], 0, 0, 0)
for i in range(1, len(s1) + 1):
s1_ascii += ord(s1[i - 1])
for j in range(1, len(s2) + 1):
if not f:
s2_ascii += ord(s2[j - 1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 802MS"""
<|body_0|>
def minimumDeleteSum_1(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 458MS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp, s... | stack_v2_sparse_classes_10k_train_003196 | 2,190 | no_license | [
{
"docstring": ":type s1: str :type s2: str :rtype: int 802MS",
"name": "minimumDeleteSum",
"signature": "def minimumDeleteSum(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: int 458MS",
"name": "minimumDeleteSum_1",
"signature": "def minimumDeleteSum_1(self, s1, s2... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeleteSum(self, s1, s2): :type s1: str :type s2: str :rtype: int 802MS
- def minimumDeleteSum_1(self, s1, s2): :type s1: str :type s2: str :rtype: int 458MS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeleteSum(self, s1, s2): :type s1: str :type s2: str :rtype: int 802MS
- def minimumDeleteSum_1(self, s1, s2): :type s1: str :type s2: str :rtype: int 458MS
<|skeleto... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 802MS"""
<|body_0|>
def minimumDeleteSum_1(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 458MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumDeleteSum(self, s1, s2):
""":type s1: str :type s2: str :rtype: int 802MS"""
dp, s1_ascii, s2_ascii, f = ([[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)], 0, 0, 0)
for i in range(1, len(s1) + 1):
s1_ascii += ord(s1[i - 1])
for ... | the_stack_v2_python_sparse | MinimumASCIIDeleteSumForTwoStrings_MID_712.py | 953250587/leetcode-python | train | 2 | |
62b9c5a4aee2982a60f53f8d0ae5a22d75dfcd97 | [
"if target < nums[0]:\n return 0\nelif target > nums[-1]:\n return len(nums)\nelse:\n for index, num in enumerate(nums):\n if target == num:\n return index\n elif num < target < nums[index + 1]:\n return index + 1",
"left = 0\nright = len(nums)\nif target > nums[-1]:\n... | <|body_start_0|>
if target < nums[0]:
return 0
elif target > nums[-1]:
return len(nums)
else:
for index, num in enumerate(nums):
if target == num:
return index
elif num < target < nums[index + 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsert_1(self, nums, target):
"""暴力法查找,一个一个比对 :param nums: 排序数组 :param target: 目标值 :return: 目标值插入排序数组的索引位置"""
<|body_0|>
def searchInsert_2(self, nums, target):
"""看到已知数组是排序数组时,要立刻想到使用二分查找来解决。 首先确定搜索空间,返回的索引取值范围为[0, len(nums)] 因此left = 0, right = ... | stack_v2_sparse_classes_10k_train_003197 | 2,156 | no_license | [
{
"docstring": "暴力法查找,一个一个比对 :param nums: 排序数组 :param target: 目标值 :return: 目标值插入排序数组的索引位置",
"name": "searchInsert_1",
"signature": "def searchInsert_1(self, nums, target)"
},
{
"docstring": "看到已知数组是排序数组时,要立刻想到使用二分查找来解决。 首先确定搜索空间,返回的索引取值范围为[0, len(nums)] 因此left = 0, right = len(nums) 再看空间收缩,因为当 n... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert_1(self, nums, target): 暴力法查找,一个一个比对 :param nums: 排序数组 :param target: 目标值 :return: 目标值插入排序数组的索引位置
- def searchInsert_2(self, nums, target): 看到已知数组是排序数组时,要立刻想到使用二分... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert_1(self, nums, target): 暴力法查找,一个一个比对 :param nums: 排序数组 :param target: 目标值 :return: 目标值插入排序数组的索引位置
- def searchInsert_2(self, nums, target): 看到已知数组是排序数组时,要立刻想到使用二分... | 746d77e9bfbcb3877fefae9a915004b3bfbcc612 | <|skeleton|>
class Solution:
def searchInsert_1(self, nums, target):
"""暴力法查找,一个一个比对 :param nums: 排序数组 :param target: 目标值 :return: 目标值插入排序数组的索引位置"""
<|body_0|>
def searchInsert_2(self, nums, target):
"""看到已知数组是排序数组时,要立刻想到使用二分查找来解决。 首先确定搜索空间,返回的索引取值范围为[0, len(nums)] 因此left = 0, right = ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def searchInsert_1(self, nums, target):
"""暴力法查找,一个一个比对 :param nums: 排序数组 :param target: 目标值 :return: 目标值插入排序数组的索引位置"""
if target < nums[0]:
return 0
elif target > nums[-1]:
return len(nums)
else:
for index, num in enumerate(nums):
... | the_stack_v2_python_sparse | LeetCode/Array/035.搜索插入位置.py | leilalu/algorithm | train | 0 | |
5ebefc01e80cdd571928bceeb277005ef622e265 | [
"args = request.args.to_dict()\nvalidator.validate(args, validator.USER_CONTENT)\nusername = get_jwt_identity()\nuser_titles = user_controller.get_user_titles(username, args)\nif not user_titles:\n return ('', 404)\nuser_titles_dto = user_schema.serialize_user_titles(username, user_titles)\nresponse = Response(r... | <|body_start_0|>
args = request.args.to_dict()
validator.validate(args, validator.USER_CONTENT)
username = get_jwt_identity()
user_titles = user_controller.get_user_titles(username, args)
if not user_titles:
return ('', 404)
user_titles_dto = user_schema.seria... | UserTitlesResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTitlesResource:
def get(self):
"""Get user related titles"""
<|body_0|>
def post(self, title_id):
"""Add a title to user's watchlist"""
<|body_1|>
def delete(self, title_id):
"""Remove a title from a watchlist"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_10k_train_003198 | 4,871 | no_license | [
{
"docstring": "Get user related titles",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a title to user's watchlist",
"name": "post",
"signature": "def post(self, title_id)"
},
{
"docstring": "Remove a title from a watchlist",
"name": "delete",
"signa... | 3 | stack_v2_sparse_classes_30k_train_002970 | Implement the Python class `UserTitlesResource` described below.
Class description:
Implement the UserTitlesResource class.
Method signatures and docstrings:
- def get(self): Get user related titles
- def post(self, title_id): Add a title to user's watchlist
- def delete(self, title_id): Remove a title from a watchli... | Implement the Python class `UserTitlesResource` described below.
Class description:
Implement the UserTitlesResource class.
Method signatures and docstrings:
- def get(self): Get user related titles
- def post(self, title_id): Add a title to user's watchlist
- def delete(self, title_id): Remove a title from a watchli... | e0c8ea99886f10aea14b9ca95af8a4f42f2af493 | <|skeleton|>
class UserTitlesResource:
def get(self):
"""Get user related titles"""
<|body_0|>
def post(self, title_id):
"""Add a title to user's watchlist"""
<|body_1|>
def delete(self, title_id):
"""Remove a title from a watchlist"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserTitlesResource:
def get(self):
"""Get user related titles"""
args = request.args.to_dict()
validator.validate(args, validator.USER_CONTENT)
username = get_jwt_identity()
user_titles = user_controller.get_user_titles(username, args)
if not user_titles:
... | the_stack_v2_python_sparse | imdb_api/resources/user_resources.py | Matiasmoratti7/imdb | train | 0 | |
c11179133354dad7ac0f741aa0f833edd005f689 | [
"super().__init__(coordinator)\nself._attr_unique_id = f'{device.address}-signal-strength'\nself._attr_device_info = device_info",
"if (data := self.coordinator.data):\n return data.rssi\nreturn None"
] | <|body_start_0|>
super().__init__(coordinator)
self._attr_unique_id = f'{device.address}-signal-strength'
self._attr_device_info = device_info
<|end_body_0|>
<|body_start_1|>
if (data := self.coordinator.data):
return data.rssi
return None
<|end_body_1|>
| Sensor device. | RssiSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RssiSensor:
"""Sensor device."""
def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None:
"""Init sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
<|... | stack_v2_sparse_classes_10k_train_003199 | 2,180 | permissive | [
{
"docstring": "Init sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None"
},
{
"docstring": "Return the value reported by the sensor.",
"name": "native_value",
"signature": "def native_value(... | 2 | null | Implement the Python class `RssiSensor` described below.
Class description:
Sensor device.
Method signatures and docstrings:
- def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None: Init sensor.
- def native_value(self) -> StateType: Return the value reported by the ... | Implement the Python class `RssiSensor` described below.
Class description:
Sensor device.
Method signatures and docstrings:
- def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None: Init sensor.
- def native_value(self) -> StateType: Return the value reported by the ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RssiSensor:
"""Sensor device."""
def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None:
"""Init sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RssiSensor:
"""Sensor device."""
def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None:
"""Init sensor."""
super().__init__(coordinator)
self._attr_unique_id = f'{device.address}-signal-strength'
self._attr_device_info = d... | the_stack_v2_python_sparse | homeassistant/components/fjaraskupan/sensor.py | home-assistant/core | train | 35,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.