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 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed86888836735d7daabb39265a6a8a33616f672f | [
"self.tree_name = tree_name\nself.Type = Type\nself.trunk_circumference = trunk_circumference\nself.age = age",
"tree_database = ['fir', 'deciduous']\ntree_list = []\nfor i in tree_database:\n if Type == i:\n tree_list.append(self.tree_name)\nraise TypeError(\"The type isn't match\")",
"if trunk_circu... | <|body_start_0|>
self.tree_name = tree_name
self.Type = Type
self.trunk_circumference = trunk_circumference
self.age = age
<|end_body_0|>
<|body_start_1|>
tree_database = ['fir', 'deciduous']
tree_list = []
for i in tree_database:
if Type == i:
... | TreeFarm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeFarm:
def __init__(self, tree_name, Type, age, trunk_circumference):
"""store the specs of input trees :param tree_name: what is the tree's name :param Type: what kind of species does the tree belongs to :param age: how old of the tree since it planted :param trunk_circumference: how... | stack_v2_sparse_classes_75kplus_train_005600 | 2,163 | no_license | [
{
"docstring": "store the specs of input trees :param tree_name: what is the tree's name :param Type: what kind of species does the tree belongs to :param age: how old of the tree since it planted :param trunk_circumference: how to wide is the tree",
"name": "__init__",
"signature": "def __init__(self, ... | 4 | stack_v2_sparse_classes_30k_train_053551 | Implement the Python class `TreeFarm` described below.
Class description:
Implement the TreeFarm class.
Method signatures and docstrings:
- def __init__(self, tree_name, Type, age, trunk_circumference): store the specs of input trees :param tree_name: what is the tree's name :param Type: what kind of species does the... | Implement the Python class `TreeFarm` described below.
Class description:
Implement the TreeFarm class.
Method signatures and docstrings:
- def __init__(self, tree_name, Type, age, trunk_circumference): store the specs of input trees :param tree_name: what is the tree's name :param Type: what kind of species does the... | 326edceb51d843bbf150863fcce72657a6043929 | <|skeleton|>
class TreeFarm:
def __init__(self, tree_name, Type, age, trunk_circumference):
"""store the specs of input trees :param tree_name: what is the tree's name :param Type: what kind of species does the tree belongs to :param age: how old of the tree since it planted :param trunk_circumference: how... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeFarm:
def __init__(self, tree_name, Type, age, trunk_circumference):
"""store the specs of input trees :param tree_name: what is the tree's name :param Type: what kind of species does the tree belongs to :param age: how old of the tree since it planted :param trunk_circumference: how to wide is th... | the_stack_v2_python_sparse | a4/assignment_four.py | foqiao/A01027086_1510 | train | 0 | |
4aa63c4221059587c1717673660e15da41e8851b | [
"if not nums or len(nums) == 0:\n return 0\nmax_so_far, max_at_here = (nums[0], nums[0])\nfor n in nums[1:]:\n max_at_here = max(0, max_at_here) + n\n max_so_far = max(max_so_far, max_at_here)\nreturn max_so_far",
"max_at_here = nums[0]\nmax_so_far = [max_at_here]\nfor i in range(1, len(nums)):\n if m... | <|body_start_0|>
if not nums or len(nums) == 0:
return 0
max_so_far, max_at_here = (nums[0], nums[0])
for n in nums[1:]:
max_at_here = max(0, max_at_here) + n
max_so_far = max(max_so_far, max_at_here)
return max_so_far
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArraySlow(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArrayA(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def maxSubArrayB(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_005601 | 1,236 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArraySlow",
"signature": "def maxSubArraySlow(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArrayA",
"signature": "def maxSubArrayA(self, nums)"
},
{
"docstring": ":type nums: ... | 3 | stack_v2_sparse_classes_30k_train_015863 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArraySlow(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayA(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayB(self, nums): :type nums: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArraySlow(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayA(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayB(self, nums): :type nums: L... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def maxSubArraySlow(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArrayA(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def maxSubArrayB(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSubArraySlow(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums or len(nums) == 0:
return 0
max_so_far, max_at_here = (nums[0], nums[0])
for n in nums[1:]:
max_at_here = max(0, max_at_here) + n
max_so_far = max(... | the_stack_v2_python_sparse | top_interview_questions/easy_collection/dynamic_programming/maximum_subarray.py | hwc1824/LeetCodeSolution | train | 0 | |
b9362c1a6d6902a91d5c8dda877c2dfc06f1836d | [
"self.env = env.copy() if env else None\nself.cwd = str(cwd) if cwd is not None else None\nif self.cwd and env is not None:\n self.env['PWD'] = self.cwd",
"if protocol is None:\n protocol = NoCapture\nif sys.platform == 'win32':\n event_loop = asyncio.ProactorEventLoop()\nelse:\n event_loop = asyncio.... | <|body_start_0|>
self.env = env.copy() if env else None
self.cwd = str(cwd) if cwd is not None else None
if self.cwd and env is not None:
self.env['PWD'] = self.cwd
<|end_body_0|>
<|body_start_1|>
if protocol is None:
protocol = NoCapture
if sys.platform ... | Minimal Runner with support for online command output processing It aims to be as simple as possible, providing only essential functionality. | WitlessRunner | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WitlessRunner:
"""Minimal Runner with support for online command output processing It aims to be as simple as possible, providing only essential functionality."""
def __init__(self, cwd=None, env=None):
"""Parameters ---------- cwd : path-like, optional If given, commands are execute... | stack_v2_sparse_classes_75kplus_train_005602 | 47,501 | permissive | [
{
"docstring": "Parameters ---------- cwd : path-like, optional If given, commands are executed with this path as PWD, the PWD of the parent process is used otherwise. env : dict, optional Environment to be passed to subprocess.Popen(). If `cwd` was given, 'PWD' in the environment is set to its value. This must... | 2 | stack_v2_sparse_classes_30k_train_003154 | Implement the Python class `WitlessRunner` described below.
Class description:
Minimal Runner with support for online command output processing It aims to be as simple as possible, providing only essential functionality.
Method signatures and docstrings:
- def __init__(self, cwd=None, env=None): Parameters ----------... | Implement the Python class `WitlessRunner` described below.
Class description:
Minimal Runner with support for online command output processing It aims to be as simple as possible, providing only essential functionality.
Method signatures and docstrings:
- def __init__(self, cwd=None, env=None): Parameters ----------... | fa34dbcbb6da962fa343866c907de6414f4dde53 | <|skeleton|>
class WitlessRunner:
"""Minimal Runner with support for online command output processing It aims to be as simple as possible, providing only essential functionality."""
def __init__(self, cwd=None, env=None):
"""Parameters ---------- cwd : path-like, optional If given, commands are execute... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WitlessRunner:
"""Minimal Runner with support for online command output processing It aims to be as simple as possible, providing only essential functionality."""
def __init__(self, cwd=None, env=None):
"""Parameters ---------- cwd : path-like, optional If given, commands are executed with this p... | the_stack_v2_python_sparse | datalad/cmd.py | kyleam/datalad | train | 1 |
9ef58a2323237dd6cdbddb991ff2d0980acc14b8 | [
"super(IperfSession, self).__init__()\nself.iperf_test = iperf_test\nself.nodes = nodes\nself.filename_base = filename_base\nself.tpc = tpc\nself._to_node_expression = None\nself._from_node_expression = None\nself.poll = None\nreturn",
"if self._from_node_expression is None:\n self._from_node_expression = re.c... | <|body_start_0|>
super(IperfSession, self).__init__()
self.iperf_test = iperf_test
self.nodes = nodes
self.filename_base = filename_base
self.tpc = tpc
self._to_node_expression = None
self._from_node_expression = None
self.poll = None
return
<|end_... | A bundler of nodes and the iperftest | IperfSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IperfSession:
"""A bundler of nodes and the iperftest"""
def __init__(self, iperf_test, nodes, tpc, filename_base=None):
"""IperfSession Constructor :param: - `iperf_test`: a bundle of parameters and storage - `nodes`: id:device pairs - `tpc`: traffic PC device - `filename_base`: An ... | stack_v2_sparse_classes_75kplus_train_005603 | 4,629 | permissive | [
{
"docstring": "IperfSession Constructor :param: - `iperf_test`: a bundle of parameters and storage - `nodes`: id:device pairs - `tpc`: traffic PC device - `filename_base`: An optional string to add to the filename",
"name": "__init__",
"signature": "def __init__(self, iperf_test, nodes, tpc, filename_b... | 6 | stack_v2_sparse_classes_30k_train_011490 | Implement the Python class `IperfSession` described below.
Class description:
A bundler of nodes and the iperftest
Method signatures and docstrings:
- def __init__(self, iperf_test, nodes, tpc, filename_base=None): IperfSession Constructor :param: - `iperf_test`: a bundle of parameters and storage - `nodes`: id:devic... | Implement the Python class `IperfSession` described below.
Class description:
A bundler of nodes and the iperftest
Method signatures and docstrings:
- def __init__(self, iperf_test, nodes, tpc, filename_base=None): IperfSession Constructor :param: - `iperf_test`: a bundle of parameters and storage - `nodes`: id:devic... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class IperfSession:
"""A bundler of nodes and the iperftest"""
def __init__(self, iperf_test, nodes, tpc, filename_base=None):
"""IperfSession Constructor :param: - `iperf_test`: a bundle of parameters and storage - `nodes`: id:device pairs - `tpc`: traffic PC device - `filename_base`: An ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IperfSession:
"""A bundler of nodes and the iperftest"""
def __init__(self, iperf_test, nodes, tpc, filename_base=None):
"""IperfSession Constructor :param: - `iperf_test`: a bundle of parameters and storage - `nodes`: id:device pairs - `tpc`: traffic PC device - `filename_base`: An optional stri... | the_stack_v2_python_sparse | apetools/tools/iperfsession.py | russell-n/oldape | train | 0 |
f6493388b9430c6503353191bb38481327964679 | [
"api = '/message/v4/send/'\nif isinstance(card, CardMessage):\n payload = card.dict(exclude_unset=True)\nelse:\n payload = dict(card)\nresult = self.client.request('POST', api=api, payload=payload)\nreturn result.get('data', {}).get('message_id')",
"api = '/ephemeral/v1/send'\nif isinstance(card, CardMessag... | <|body_start_0|>
api = '/message/v4/send/'
if isinstance(card, CardMessage):
payload = card.dict(exclude_unset=True)
else:
payload = dict(card)
result = self.client.request('POST', api=api, payload=payload)
return result.get('data', {}).get('message_id')
<... | CardAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CardAPI:
def send_card(self, card: Union[dict, CardMessage]) -> str:
"""发送卡片消息 https://open.feishu.cn/document/ukTMukTMukTM/uYTNwUjL2UDM14iN1ATN Args: card: dict或CardMessage类型 Returns: message_id 请求body示例 { "chat_id": "oc_abcdefg1234567890", "msg_type": "interactive", "root_id":"om_4****... | stack_v2_sparse_classes_75kplus_train_005604 | 7,942 | no_license | [
{
"docstring": "发送卡片消息 https://open.feishu.cn/document/ukTMukTMukTM/uYTNwUjL2UDM14iN1ATN Args: card: dict或CardMessage类型 Returns: message_id 请求body示例 { \"chat_id\": \"oc_abcdefg1234567890\", \"msg_type\": \"interactive\", \"root_id\":\"om_4*********************ad8\", \"update_multi\":false, \"card\": { // card c... | 3 | null | Implement the Python class `CardAPI` described below.
Class description:
Implement the CardAPI class.
Method signatures and docstrings:
- def send_card(self, card: Union[dict, CardMessage]) -> str: 发送卡片消息 https://open.feishu.cn/document/ukTMukTMukTM/uYTNwUjL2UDM14iN1ATN Args: card: dict或CardMessage类型 Returns: message... | Implement the Python class `CardAPI` described below.
Class description:
Implement the CardAPI class.
Method signatures and docstrings:
- def send_card(self, card: Union[dict, CardMessage]) -> str: 发送卡片消息 https://open.feishu.cn/document/ukTMukTMukTM/uYTNwUjL2UDM14iN1ATN Args: card: dict或CardMessage类型 Returns: message... | a2e6fe3851d68a04ba714737b31229aa5a137050 | <|skeleton|>
class CardAPI:
def send_card(self, card: Union[dict, CardMessage]) -> str:
"""发送卡片消息 https://open.feishu.cn/document/ukTMukTMukTM/uYTNwUjL2UDM14iN1ATN Args: card: dict或CardMessage类型 Returns: message_id 请求body示例 { "chat_id": "oc_abcdefg1234567890", "msg_type": "interactive", "root_id":"om_4****... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CardAPI:
def send_card(self, card: Union[dict, CardMessage]) -> str:
"""发送卡片消息 https://open.feishu.cn/document/ukTMukTMukTM/uYTNwUjL2UDM14iN1ATN Args: card: dict或CardMessage类型 Returns: message_id 请求body示例 { "chat_id": "oc_abcdefg1234567890", "msg_type": "interactive", "root_id":"om_4******************... | the_stack_v2_python_sparse | feishu/apis/card.py | Beiusxzw/feishu-python-sdk | train | 1 | |
a92890fbf3d9024fb00655f2b00b3a156b05ce0c | [
"handlers = [('/', misc.IndexHandler), ('/auth', auth.AuthenticateClient), ('/feedback-rating', feedback.FeedbackRating), ('/feedback-comment', feedback.FeedbackComment), ('^/results_table/(.*)', results_table.ResultsTableHandler), ('^/mzimage2/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)', iso_image_gen.AggIsoI... | <|body_start_0|>
handlers = [('/', misc.IndexHandler), ('/auth', auth.AuthenticateClient), ('/feedback-rating', feedback.FeedbackRating), ('/feedback-comment', feedback.FeedbackComment), ('^/results_table/(.*)', results_table.ResultsTableHandler), ('^/mzimage2/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)', i... | Main class of the tornado application. | Application | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Main class of the tornado application."""
def __init__(self, debug=False):
"""Initializes handlers, including the spark handler, sets up database connection."""
<|body_0|>
def update_all_jobs_callback(self):
"""For each job, checks whether its sta... | stack_v2_sparse_classes_75kplus_train_005605 | 6,321 | permissive | [
{
"docstring": "Initializes handlers, including the spark handler, sets up database connection.",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "For each job, checks whether its status has changed.",
"name": "update_all_jobs_callback",
"signature": ... | 3 | null | Implement the Python class `Application` described below.
Class description:
Main class of the tornado application.
Method signatures and docstrings:
- def __init__(self, debug=False): Initializes handlers, including the spark handler, sets up database connection.
- def update_all_jobs_callback(self): For each job, c... | Implement the Python class `Application` described below.
Class description:
Main class of the tornado application.
Method signatures and docstrings:
- def __init__(self, debug=False): Initializes handlers, including the spark handler, sets up database connection.
- def update_all_jobs_callback(self): For each job, c... | efa656ca05b6cb7433df3291bf6ebc5462be62a8 | <|skeleton|>
class Application:
"""Main class of the tornado application."""
def __init__(self, debug=False):
"""Initializes handlers, including the spark handler, sets up database connection."""
<|body_0|>
def update_all_jobs_callback(self):
"""For each job, checks whether its sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Main class of the tornado application."""
def __init__(self, debug=False):
"""Initializes handlers, including the spark handler, sets up database connection."""
handlers = [('/', misc.IndexHandler), ('/auth', auth.AuthenticateClient), ('/feedback-rating', feedback.Feedback... | the_stack_v2_python_sparse | sm/webapp/webserver.py | anasilviacs/sm-engine | train | 0 |
00b0482e9a5e0c4f432ce3f4e8665411a39057cc | [
"try:\n app_id_list = get_cc_app_id_by_user()\n data_result = machine_statistics(table_set=EsNodeInfo, field='ip', app_id_list=app_id_list)\n return JsonResponse({'result': True, 'code': 0, 'data': data_result, 'message': 'query success'})\nexcept Exception as err:\n logger.error(f'es机器查询汇总失败:{err}')\n ... | <|body_start_0|>
try:
app_id_list = get_cc_app_id_by_user()
data_result = machine_statistics(table_set=EsNodeInfo, field='ip', app_id_list=app_id_list)
return JsonResponse({'result': True, 'code': 0, 'data': data_result, 'message': 'query success'})
except Exception a... | es用户信息表视图 | EsNodeViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EsNodeViewSet:
"""es用户信息表视图"""
def get_machine_statistics(self, request, *args, **kwargs):
"""POST /es/nodes/get_machine_statistics 统计es投入已使用的机器数量"""
<|body_0|>
def get_machine_statistics_top_five(self, request, *args, **kwargs):
"""POST /es/nodes/get_machine_sta... | stack_v2_sparse_classes_75kplus_train_005606 | 10,026 | no_license | [
{
"docstring": "POST /es/nodes/get_machine_statistics 统计es投入已使用的机器数量",
"name": "get_machine_statistics",
"signature": "def get_machine_statistics(self, request, *args, **kwargs)"
},
{
"docstring": "POST /es/nodes/get_machine_statistics_top_five 根据用户已有业务权限,查询每个业务的机器投入数量,输出TOP5",
"name": "get_... | 2 | stack_v2_sparse_classes_30k_train_005599 | Implement the Python class `EsNodeViewSet` described below.
Class description:
es用户信息表视图
Method signatures and docstrings:
- def get_machine_statistics(self, request, *args, **kwargs): POST /es/nodes/get_machine_statistics 统计es投入已使用的机器数量
- def get_machine_statistics_top_five(self, request, *args, **kwargs): POST /es/... | Implement the Python class `EsNodeViewSet` described below.
Class description:
es用户信息表视图
Method signatures and docstrings:
- def get_machine_statistics(self, request, *args, **kwargs): POST /es/nodes/get_machine_statistics 统计es投入已使用的机器数量
- def get_machine_statistics_top_five(self, request, *args, **kwargs): POST /es/... | 97cfac2ba94d67980d837f0b541caae70b68a595 | <|skeleton|>
class EsNodeViewSet:
"""es用户信息表视图"""
def get_machine_statistics(self, request, *args, **kwargs):
"""POST /es/nodes/get_machine_statistics 统计es投入已使用的机器数量"""
<|body_0|>
def get_machine_statistics_top_five(self, request, *args, **kwargs):
"""POST /es/nodes/get_machine_sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EsNodeViewSet:
"""es用户信息表视图"""
def get_machine_statistics(self, request, *args, **kwargs):
"""POST /es/nodes/get_machine_statistics 统计es投入已使用的机器数量"""
try:
app_id_list = get_cc_app_id_by_user()
data_result = machine_statistics(table_set=EsNodeInfo, field='ip', app_i... | the_stack_v2_python_sparse | apps/es/views.py | sdgdsffdsfff/bk-dop | train | 0 |
14bab906c8b93a9d7b5a88709a98c6235ca44d59 | [
"self.interval = interval\nthread = threading.Thread(target=self.run, args=())\nthread.daemon = True\nthread.start()",
"while True:\n global processGlobalImport\n global processGlobalUpdate\n processGlobalImport = []\n processGlobalUpdate = []\n bpmnResourcesFolder = con.basedir + '/app/static/reso... | <|body_start_0|>
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
<|end_body_0|>
<|body_start_1|>
while True:
global processGlobalImport
global processGlobalUpdate
processGlobalIm... | Threading example class The run() method will be started and it will run in the background until the application exits. | ThreadingBpmn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadingBpmn:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body_0|>
def r... | stack_v2_sparse_classes_75kplus_train_005607 | 2,003 | no_license | [
{
"docstring": "Constructor :type interval: int :param interval: Check interval, in seconds",
"name": "__init__",
"signature": "def __init__(self, interval=1)"
},
{
"docstring": "Method that runs forever",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `ThreadingBpmn` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, interval=1): Constructor :type interval: int :param interval: Ch... | Implement the Python class `ThreadingBpmn` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, interval=1): Constructor :type interval: int :param interval: Ch... | 5bb2e2ed2b032c55cb5b4746ee01667d809750bc | <|skeleton|>
class ThreadingBpmn:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body_0|>
def r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadingBpmn:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
self.interval = interval
t... | the_stack_v2_python_sparse | app/utils/threadingBpmn.py | YanKon/processbot | train | 3 |
64f3719d093c2fbda2bc243bb9fd3f1649c9afdb | [
"super().__init__(ff_settings=ff_settings, box_relax=True, **kwargs)\nbulk_structure_relaxed, bulk_energy, _, _ = super().calculate([bulk_structure])[0]\nself.bulk_energy_per_atom = bulk_energy / bulk_structure_relaxed.num_sites\nfrom pymatgen.core.surface import SlabGenerator\nslab_generators = [SlabGenerator(init... | <|body_start_0|>
super().__init__(ff_settings=ff_settings, box_relax=True, **kwargs)
bulk_structure_relaxed, bulk_energy, _, _ = super().calculate([bulk_structure])[0]
self.bulk_energy_per_atom = bulk_energy / bulk_structure_relaxed.num_sites
from pymatgen.core.surface import SlabGenerat... | Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html | SurfaceEnergy | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SurfaceEnergy:
"""Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html"""
def __init__(self, ff_settings, ... | stack_v2_sparse_classes_75kplus_train_005608 | 39,049 | permissive | [
{
"docstring": "Init. Args: ff_settings (list/Potential): Configure the force field settings for LAMMPS calculation, if given a Potential object, should apply Potential.write_param method to get the force field setting. bulk_structure (Structure): The bulk structure of target system. Slab structures will be gen... | 2 | stack_v2_sparse_classes_30k_train_003302 | Implement the Python class `SurfaceEnergy` described below.
Class description:
Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html
... | Implement the Python class `SurfaceEnergy` described below.
Class description:
Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html
... | 6ae3c7029b939e1183684358a3ae2fef41053be5 | <|skeleton|>
class SurfaceEnergy:
"""Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html"""
def __init__(self, ff_settings, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SurfaceEnergy:
"""Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html"""
def __init__(self, ff_settings, bulk_structur... | the_stack_v2_python_sparse | maml/apps/pes/_lammps.py | materialsvirtuallab/maml | train | 266 |
78a12d8bff14792b00e4507e76858d1a178bc660 | [
"try:\n self.fragsize = int(args[0])\nexcept ValueError:\n raise ValueError('Parameter 1 unrecognized. Got {}'.format(args[0]))",
"new_pl = PacketList()\nfor pkt in pkt_list:\n if pkt.pkt.haslayer('IP'):\n fragments = scapy.layers.inet.fragment(pkt.pkt, self.fragsize)\n index = len(new_pl) ... | <|body_start_0|>
try:
self.fragsize = int(args[0])
except ValueError:
raise ValueError('Parameter 1 unrecognized. Got {}'.format(args[0]))
<|end_body_0|>
<|body_start_1|>
new_pl = PacketList()
for pkt in pkt_list:
if pkt.pkt.haslayer('IP'):
... | Fragments the IPv4 packets at the L3-layer. Fragment each IPv4 packet. the fragmentation size must be specified. It represents the maximum size of each packet (including headers). It uses the scapy's fragmentation function. Args: *args: The arguments of the mods. Attributes: fragsize: The fragmentation size (maximum le... | Ipv4Frag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ipv4Frag:
"""Fragments the IPv4 packets at the L3-layer. Fragment each IPv4 packet. the fragmentation size must be specified. It represents the maximum size of each packet (including headers). It uses the scapy's fragmentation function. Args: *args: The arguments of the mods. Attributes: fragsize... | stack_v2_sparse_classes_75kplus_train_005609 | 1,743 | permissive | [
{
"docstring": "See base class.",
"name": "parse_args",
"signature": "def parse_args(self, *args)"
},
{
"docstring": "Fragment each IPv6 packet. See `Mod.apply` for more details.",
"name": "apply",
"signature": "def apply(self, pkt_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023918 | Implement the Python class `Ipv4Frag` described below.
Class description:
Fragments the IPv4 packets at the L3-layer. Fragment each IPv4 packet. the fragmentation size must be specified. It represents the maximum size of each packet (including headers). It uses the scapy's fragmentation function. Args: *args: The argu... | Implement the Python class `Ipv4Frag` described below.
Class description:
Fragments the IPv4 packets at the L3-layer. Fragment each IPv4 packet. the fragmentation size must be specified. It represents the maximum size of each packet (including headers). It uses the scapy's fragmentation function. Args: *args: The argu... | 3ee7f5c73fc6c7eb64858e197c0b8d2b313734e0 | <|skeleton|>
class Ipv4Frag:
"""Fragments the IPv4 packets at the L3-layer. Fragment each IPv4 packet. the fragmentation size must be specified. It represents the maximum size of each packet (including headers). It uses the scapy's fragmentation function. Args: *args: The arguments of the mods. Attributes: fragsize... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ipv4Frag:
"""Fragments the IPv4 packets at the L3-layer. Fragment each IPv4 packet. the fragmentation size must be specified. It represents the maximum size of each packet (including headers). It uses the scapy's fragmentation function. Args: *args: The arguments of the mods. Attributes: fragsize: The fragmen... | the_stack_v2_python_sparse | fragscapy/modifications/ipv4_frag.py | daeon/Fragscapy | train | 0 |
9005b9e3d081f16c2f1e787e507a3f19864011c2 | [
"if type(t) is ET.ElementTree:\n return self._etree_to_dict(t.getroot())\nreturn {**t.attrib, 'text': t.text, **{e.tag: self._etree_to_dict(e) for e in t}}",
"password = get_netrc_auth(self._name)[1]\ndomain = '.'.join(hostname.split('.')[-2:])\nhost = '.'.join(hostname.split('.')[:-2])\nif domain == 'co.uk':\... | <|body_start_0|>
if type(t) is ET.ElementTree:
return self._etree_to_dict(t.getroot())
return {**t.attrib, 'text': t.text, **{e.tag: self._etree_to_dict(e) for e in t}}
<|end_body_0|>
<|body_start_1|>
password = get_netrc_auth(self._name)[1]
domain = '.'.join(hostname.split(... | Update a dns entry on namecheap.com As usual, any host updated must first be defined in the web UI. Supports most address plugins including default-web-ip, default-if and ip-disabled. ipv6 is supported Access to the service requires an API token. This is available in the website account. netrc: Use a line like machine ... | NamecheapPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamecheapPlugin:
"""Update a dns entry on namecheap.com As usual, any host updated must first be defined in the web UI. Supports most address plugins including default-web-ip, default-if and ip-disabled. ipv6 is supported Access to the service requires an API token. This is available in the websi... | stack_v2_sparse_classes_75kplus_train_005610 | 2,447 | permissive | [
{
"docstring": "https://stackoverflow.com/questions/7684333/converting-xml-to-dictionary-using-elementtree/68082847#68082847",
"name": "_etree_to_dict",
"signature": "def _etree_to_dict(self, t)"
},
{
"docstring": "Implement ServicePlugin.register().",
"name": "register",
"signature": "d... | 2 | null | Implement the Python class `NamecheapPlugin` described below.
Class description:
Update a dns entry on namecheap.com As usual, any host updated must first be defined in the web UI. Supports most address plugins including default-web-ip, default-if and ip-disabled. ipv6 is supported Access to the service requires an AP... | Implement the Python class `NamecheapPlugin` described below.
Class description:
Update a dns entry on namecheap.com As usual, any host updated must first be defined in the web UI. Supports most address plugins including default-web-ip, default-if and ip-disabled. ipv6 is supported Access to the service requires an AP... | 1ee437426e21eb19d2bbd8fefe3b5d446071b0eb | <|skeleton|>
class NamecheapPlugin:
"""Update a dns entry on namecheap.com As usual, any host updated must first be defined in the web UI. Supports most address plugins including default-web-ip, default-if and ip-disabled. ipv6 is supported Access to the service requires an API token. This is available in the websi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NamecheapPlugin:
"""Update a dns entry on namecheap.com As usual, any host updated must first be defined in the web UI. Supports most address plugins including default-web-ip, default-if and ip-disabled. ipv6 is supported Access to the service requires an API token. This is available in the website account. n... | the_stack_v2_python_sparse | plugins/namecheap.py | leamas/ddupdate | train | 45 |
9be1df0f3900efe5defe83a270c31f490374fdbe | [
"multi_band_list = kwargs_imaging['multi_band_list']\nmulti_band_type = kwargs_imaging['multi_band_type']\nif calibrate_bands is None:\n calibrate_bands = [False] * len(multi_band_list)\nif multi_band_type != 'joint-linear':\n raise ValueError('flux calibration should only be done with join-linear data model!... | <|body_start_0|>
multi_band_list = kwargs_imaging['multi_band_list']
multi_band_type = kwargs_imaging['multi_band_type']
if calibrate_bands is None:
calibrate_bands = [False] * len(multi_band_list)
if multi_band_type != 'joint-linear':
raise ValueError('flux calib... | class to fit coordinate system alignment and flux amplitude calibrations | FluxCalibration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FluxCalibration:
"""class to fit coordinate system alignment and flux amplitude calibrations"""
def __init__(self, kwargs_imaging, kwargs_model, kwargs_params, calibrate_bands):
"""initialise the classes of the chain and for parameter options for the flux calibration fitting :param k... | stack_v2_sparse_classes_75kplus_train_005611 | 6,167 | permissive | [
{
"docstring": "initialise the classes of the chain and for parameter options for the flux calibration fitting :param kwargs_imaging: keyword argument related to imaging data and imaging likelihood. Feeds into ImageLikelihood(**kwargs_imaging) :param kwargs_model: keyword argument of model components :param kwa... | 2 | stack_v2_sparse_classes_30k_train_053009 | Implement the Python class `FluxCalibration` described below.
Class description:
class to fit coordinate system alignment and flux amplitude calibrations
Method signatures and docstrings:
- def __init__(self, kwargs_imaging, kwargs_model, kwargs_params, calibrate_bands): initialise the classes of the chain and for pa... | Implement the Python class `FluxCalibration` described below.
Class description:
class to fit coordinate system alignment and flux amplitude calibrations
Method signatures and docstrings:
- def __init__(self, kwargs_imaging, kwargs_model, kwargs_params, calibrate_bands): initialise the classes of the chain and for pa... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class FluxCalibration:
"""class to fit coordinate system alignment and flux amplitude calibrations"""
def __init__(self, kwargs_imaging, kwargs_model, kwargs_params, calibrate_bands):
"""initialise the classes of the chain and for parameter options for the flux calibration fitting :param k... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FluxCalibration:
"""class to fit coordinate system alignment and flux amplitude calibrations"""
def __init__(self, kwargs_imaging, kwargs_model, kwargs_params, calibrate_bands):
"""initialise the classes of the chain and for parameter options for the flux calibration fitting :param kwargs_imaging... | the_stack_v2_python_sparse | lenstronomy/Workflow/flux_calibration.py | lenstronomy/lenstronomy | train | 41 |
e1538ccddd6c4add33317ccba78e440503fc5a7f | [
"if not stones:\n return 0\nif len(stones) == 1:\n return stones[0]\nsums = sum(stones)\nprint(sums)\ndp = [0 for _ in range(sums // 2 + 1)]\nfor i in range(len(stones)):\n for j in range(sums // 2, stones[i] - 1, -1):\n dp[j] = max(dp[j], dp[j - stones[i]] + stones[i])\nprint(dp)\nreturn sums - dp[... | <|body_start_0|>
if not stones:
return 0
if len(stones) == 1:
return stones[0]
sums = sum(stones)
print(sums)
dp = [0 for _ in range(sums // 2 + 1)]
for i in range(len(stones)):
for j in range(sums // 2, stones[i] - 1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lastStoneWeightII(self, stones):
""":type stones: List[int] :rtype: int //转换成01背包问题,求两堆石头的最小差值。由于石头总和为sum.则问题转换成了 //背包最多装sum / 2的石头,stones数组里有一大堆石头。求如何装能装下最多重量石头。"""
<|body_0|>
def lastStoneWeightII2(self, stones):
""":type stones: List[int] :rtype: int... | stack_v2_sparse_classes_75kplus_train_005612 | 2,037 | no_license | [
{
"docstring": ":type stones: List[int] :rtype: int //转换成01背包问题,求两堆石头的最小差值。由于石头总和为sum.则问题转换成了 //背包最多装sum / 2的石头,stones数组里有一大堆石头。求如何装能装下最多重量石头。",
"name": "lastStoneWeightII",
"signature": "def lastStoneWeightII(self, stones)"
},
{
"docstring": ":type stones: List[int] :rtype: int",
"name": "l... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastStoneWeightII(self, stones): :type stones: List[int] :rtype: int //转换成01背包问题,求两堆石头的最小差值。由于石头总和为sum.则问题转换成了 //背包最多装sum / 2的石头,stones数组里有一大堆石头。求如何装能装下最多重量石头。
- def lastSton... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastStoneWeightII(self, stones): :type stones: List[int] :rtype: int //转换成01背包问题,求两堆石头的最小差值。由于石头总和为sum.则问题转换成了 //背包最多装sum / 2的石头,stones数组里有一大堆石头。求如何装能装下最多重量石头。
- def lastSton... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def lastStoneWeightII(self, stones):
""":type stones: List[int] :rtype: int //转换成01背包问题,求两堆石头的最小差值。由于石头总和为sum.则问题转换成了 //背包最多装sum / 2的石头,stones数组里有一大堆石头。求如何装能装下最多重量石头。"""
<|body_0|>
def lastStoneWeightII2(self, stones):
""":type stones: List[int] :rtype: int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lastStoneWeightII(self, stones):
""":type stones: List[int] :rtype: int //转换成01背包问题,求两堆石头的最小差值。由于石头总和为sum.则问题转换成了 //背包最多装sum / 2的石头,stones数组里有一大堆石头。求如何装能装下最多重量石头。"""
if not stones:
return 0
if len(stones) == 1:
return stones[0]
sums = sum(s... | the_stack_v2_python_sparse | lastStoneWeightII.py | NeilWangziyu/Leetcode_py | train | 2 | |
726a31663114c0a97ef15807387b2e47466a51ae | [
"zero_cnt = 0\nnone_zero_mul = 1\nfor num in nums:\n if num == 0:\n zero_cnt += 1\n else:\n none_zero_mul *= num\nres = []\nfor num in nums:\n if zero_cnt == 0:\n res.append(none_zero_mul / num)\n elif zero_cnt == 1 and num == 0:\n res.append(none_zero_mul)\n elif zero_cnt... | <|body_start_0|>
zero_cnt = 0
none_zero_mul = 1
for num in nums:
if num == 0:
zero_cnt += 1
else:
none_zero_mul *= num
res = []
for num in nums:
if zero_cnt == 0:
res.append(none_zero_mul / num)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf(self, nums):
"""原数组: [1 2 3 4] 左部分的乘积: 1 1 1*2 1*2*3 右部分的乘积: 2*3*4 3*4 4 1 结果: 1*2*3*4 1*3*4 1*2*4 1*2*3*1 :type nums: List[int] :rtype: List[i... | stack_v2_sparse_classes_75kplus_train_005613 | 2,457 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
},
{
"docstring": "原数组: [1 2 3 4] 左部分的乘积: 1 1 1*2 1*2*3 右部分的乘积: 2*3*4 3*4 4 1 结果: 1*2*3*4 1*3*4 1*2*4 1*2*3*1 :type nums: List[int] :rtype: List[int]",
"nam... | 2 | stack_v2_sparse_classes_30k_train_035109 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): 原数组: [1 2 3 4] 左部分的乘积: 1 1 1*2 1*2*3 右部分的乘积: 2*3*4 3*4 4 1 结果: 1*2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): 原数组: [1 2 3 4] 左部分的乘积: 1 1 1*2 1*2*3 右部分的乘积: 2*3*4 3*4 4 1 结果: 1*2... | 860590239da0618c52967a55eda8d6bbe00bfa96 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf(self, nums):
"""原数组: [1 2 3 4] 左部分的乘积: 1 1 1*2 1*2*3 右部分的乘积: 2*3*4 3*4 4 1 结果: 1*2*3*4 1*3*4 1*2*4 1*2*3*1 :type nums: List[int] :rtype: List[i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
zero_cnt = 0
none_zero_mul = 1
for num in nums:
if num == 0:
zero_cnt += 1
else:
none_zero_mul *= num
res = []
for ... | the_stack_v2_python_sparse | LeetCode/p0283/I/product-of-array-except-self.py | Ynjxsjmh/PracticeMakesPerfect | train | 0 | |
bf87611ddb9cb181b40e10937d0c7dd9e34a7b42 | [
"self.sheet = Resources().ROCKET_SHEET\nself.sheet.set_clip(Rect(0, 0, 55, 103))\nself.elevation = 0\nself.frames = Constants.ROCKET_FRAMES\nsuper().__init__(position, self.sheet, *groups)",
"if self.rect.right > Constants.WINDOW_WIDTH:\n self.rect.right = Constants.WINDOW_WIDTH\nif self.rect.left < 0:\n se... | <|body_start_0|>
self.sheet = Resources().ROCKET_SHEET
self.sheet.set_clip(Rect(0, 0, 55, 103))
self.elevation = 0
self.frames = Constants.ROCKET_FRAMES
super().__init__(position, self.sheet, *groups)
<|end_body_0|>
<|body_start_1|>
if self.rect.right > Constants.WINDOW_... | The player sprite. | Rocket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rocket:
"""The player sprite."""
def __init__(self, position, *groups):
"""Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Grou... | stack_v2_sparse_classes_75kplus_train_005614 | 1,332 | no_license | [
{
"docstring": "Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Group or GroupSingle",
"name": "__init__",
"signature": "def __init__(self, positio... | 2 | stack_v2_sparse_classes_30k_train_029178 | Implement the Python class `Rocket` described below.
Class description:
The player sprite.
Method signatures and docstrings:
- def __init__(self, position, *groups): Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param g... | Implement the Python class `Rocket` described below.
Class description:
The player sprite.
Method signatures and docstrings:
- def __init__(self, position, *groups): Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param g... | fd6ceca39b4395daed165753cac7bb6cbfb2b485 | <|skeleton|>
class Rocket:
"""The player sprite."""
def __init__(self, position, *groups):
"""Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Grou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rocket:
"""The player sprite."""
def __init__(self, position, *groups):
"""Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Group or GroupSin... | the_stack_v2_python_sparse | src/playerSprite.py | logiczsniper/TakeOff-Revisited | train | 3 |
f020b6a2454831d5e24333952fea63f9bba16c89 | [
"super(MLP, self).__init__()\nself.input_layer = torch.nn.Linear(D_inp, D_hid)\nself.hidden_layer = torch.nn.Linear(D_hid, D_hid)\nself.output_layer = torch.nn.Linear(D_hid, D_out)\nself.layers = layers\nself.sigmoid = torch.nn.Sigmoid()\nself.x_scale = x_scale.cuda() if use_cuda else x_scale\nself.y_scale = y_scal... | <|body_start_0|>
super(MLP, self).__init__()
self.input_layer = torch.nn.Linear(D_inp, D_hid)
self.hidden_layer = torch.nn.Linear(D_hid, D_hid)
self.output_layer = torch.nn.Linear(D_hid, D_out)
self.layers = layers
self.sigmoid = torch.nn.Sigmoid()
self.x_scale = ... | MLP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
def __init__(self, D_inp, D_hid, D_out, layers, x_scale, y_scale):
"""Multilayer Perceptron with a variable amount of layers Args: D_inp: Dimension of the input layer D_hid: Dimension of all hidden layers D_out: Dimension of the output layer layers: The total amount of layers (2 mea... | stack_v2_sparse_classes_75kplus_train_005615 | 9,067 | permissive | [
{
"docstring": "Multilayer Perceptron with a variable amount of layers Args: D_inp: Dimension of the input layer D_hid: Dimension of all hidden layers D_out: Dimension of the output layer layers: The total amount of layers (2 means 1 hidden layer) x_scale: The maximum values for all input variables y_scale: The... | 3 | stack_v2_sparse_classes_30k_train_045379 | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, D_inp, D_hid, D_out, layers, x_scale, y_scale): Multilayer Perceptron with a variable amount of layers Args: D_inp: Dimension of the input layer D_hid: Dimension of all ... | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, D_inp, D_hid, D_out, layers, x_scale, y_scale): Multilayer Perceptron with a variable amount of layers Args: D_inp: Dimension of the input layer D_hid: Dimension of all ... | 257441138ebcce3928f100f28e58d9d5a7221d8a | <|skeleton|>
class MLP:
def __init__(self, D_inp, D_hid, D_out, layers, x_scale, y_scale):
"""Multilayer Perceptron with a variable amount of layers Args: D_inp: Dimension of the input layer D_hid: Dimension of all hidden layers D_out: Dimension of the output layer layers: The total amount of layers (2 mea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
def __init__(self, D_inp, D_hid, D_out, layers, x_scale, y_scale):
"""Multilayer Perceptron with a variable amount of layers Args: D_inp: Dimension of the input layer D_hid: Dimension of all hidden layers D_out: Dimension of the output layer layers: The total amount of layers (2 means 1 hidden la... | the_stack_v2_python_sparse | mlp.py | joramwessels/torcs-client | train | 2 | |
010a2cca34f818b3c87d3c6540625ac5905e200c | [
"super(DeepGP, self).__init__()\nself.linear1 = torch.nn.Linear(1, 100)\nself.tanh1 = torch.nn.Tanh()\nself.linear2 = torch.nn.Linear(100, 6)\nself.tanh2 = torch.nn.Tanh()\nself.linear3 = torch.nn.Linear(6, 1)\nself.tanh3 = torch.nn.Sigmoid()\nself.gp = gpr.GP_SE(sigma_f=1.0, lengthscale=[1, 1], sigma_n=1)",
"h =... | <|body_start_0|>
super(DeepGP, self).__init__()
self.linear1 = torch.nn.Linear(1, 100)
self.tanh1 = torch.nn.Tanh()
self.linear2 = torch.nn.Linear(100, 6)
self.tanh2 = torch.nn.Tanh()
self.linear3 = torch.nn.Linear(6, 1)
self.tanh3 = torch.nn.Sigmoid()
sel... | DeepGP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepGP:
def __init__(self):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x_train, y_train, x_test=None):
"""In the forward function we accept a Tensor of input data and we must return ... | stack_v2_sparse_classes_75kplus_train_005616 | 3,175 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use ... | 2 | null | Implement the Python class `DeepGP` described below.
Class description:
Implement the DeepGP class.
Method signatures and docstrings:
- def __init__(self): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x_train, y_train, x_test=None): In the forward fu... | Implement the Python class `DeepGP` described below.
Class description:
Implement the DeepGP class.
Method signatures and docstrings:
- def __init__(self): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x_train, y_train, x_test=None): In the forward fu... | 8a1d6792faec1292bd13e148d378c0eb7db9247a | <|skeleton|>
class DeepGP:
def __init__(self):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x_train, y_train, x_test=None):
"""In the forward function we accept a Tensor of input data and we must return ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeepGP:
def __init__(self):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(DeepGP, self).__init__()
self.linear1 = torch.nn.Linear(1, 100)
self.tanh1 = torch.nn.Tanh()
self.linear2 = torch.nn.Linear(100, 6)
... | the_stack_v2_python_sparse | example_NN_GP_Step.py | jnh277/deepGPforCT | train | 0 | |
a79ef3b8994006c5b0b0a02d5ab16020ecb60b50 | [
"super(RunJobFlow, self).__init__()\nself.__aws_emr_client = aws_emr_client\nself.__logger = logger\nself.__job_flow_configuration = job_flow_configuration",
"aws_arguments = self.__job_flow_configuration.convert_to_arguments(cluster_configuration)\nself.__logger.debug('Launching cluster with given configuration'... | <|body_start_0|>
super(RunJobFlow, self).__init__()
self.__aws_emr_client = aws_emr_client
self.__logger = logger
self.__job_flow_configuration = job_flow_configuration
<|end_body_0|>
<|body_start_1|>
aws_arguments = self.__job_flow_configuration.convert_to_arguments(cluster_con... | Run a job flow based on a given configuration | RunJobFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunJobFlow:
"""Run a job flow based on a given configuration"""
def __init__(self, aws_emr_client, logger, job_flow_configuration):
"""Initialize the class :param aws_emr_client: EMR.client :param logger: Logging"""
<|body_0|>
def run_cluster(self, cluster_configuration)... | stack_v2_sparse_classes_75kplus_train_005617 | 1,588 | permissive | [
{
"docstring": "Initialize the class :param aws_emr_client: EMR.client :param logger: Logging",
"name": "__init__",
"signature": "def __init__(self, aws_emr_client, logger, job_flow_configuration)"
},
{
"docstring": "Launch a cluster based on given configuration :param cluster_configuration: str... | 2 | null | Implement the Python class `RunJobFlow` described below.
Class description:
Run a job flow based on a given configuration
Method signatures and docstrings:
- def __init__(self, aws_emr_client, logger, job_flow_configuration): Initialize the class :param aws_emr_client: EMR.client :param logger: Logging
- def run_clus... | Implement the Python class `RunJobFlow` described below.
Class description:
Run a job flow based on a given configuration
Method signatures and docstrings:
- def __init__(self, aws_emr_client, logger, job_flow_configuration): Initialize the class :param aws_emr_client: EMR.client :param logger: Logging
- def run_clus... | d0e52277daff523eda63f5d3137b5a990413923d | <|skeleton|>
class RunJobFlow:
"""Run a job flow based on a given configuration"""
def __init__(self, aws_emr_client, logger, job_flow_configuration):
"""Initialize the class :param aws_emr_client: EMR.client :param logger: Logging"""
<|body_0|>
def run_cluster(self, cluster_configuration)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunJobFlow:
"""Run a job flow based on a given configuration"""
def __init__(self, aws_emr_client, logger, job_flow_configuration):
"""Initialize the class :param aws_emr_client: EMR.client :param logger: Logging"""
super(RunJobFlow, self).__init__()
self.__aws_emr_client = aws_em... | the_stack_v2_python_sparse | src/slippinj/emr/job_flow/run.py | cupid4/slippin-jimmy | train | 0 |
7455e90836872396a69544baea9336d193809cb3 | [
"if head is None:\n return last\nsecond = head.next\nhead.next = last\nlast = head\nhead = second\nreturn self.reverseList(head, last)",
"if head is None:\n return\ncount = 0\nstart_head = head\nwhile head.next != None:\n count += 1\n head = head.next\nhead = start_head\nsplit_point = count / 2\nwhile... | <|body_start_0|>
if head is None:
return last
second = head.next
head.next = last
last = head
head = second
return self.reverseList(head, last)
<|end_body_0|>
<|body_start_1|>
if head is None:
return
count = 0
start_head = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head, last=None):
"""reverse the linked list recursively :type head: ListNode :rtype: ListNode"""
<|body_0|>
def reorderList(self, head):
"""reorder the list :type head: ListNode :rtype: void Do not return anything, modify head in-plac... | stack_v2_sparse_classes_75kplus_train_005618 | 1,245 | no_license | [
{
"docstring": "reverse the linked list recursively :type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head, last=None)"
},
{
"docstring": "reorder the list :type head: ListNode :rtype: void Do not return anything, modify head in-place instead.",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head, last=None): reverse the linked list recursively :type head: ListNode :rtype: ListNode
- def reorderList(self, head): reorder the list :type head: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head, last=None): reverse the linked list recursively :type head: ListNode :rtype: ListNode
- def reorderList(self, head): reorder the list :type head: List... | 09355094c85496cc42f8cb3241da43e0ece1e45a | <|skeleton|>
class Solution:
def reverseList(self, head, last=None):
"""reverse the linked list recursively :type head: ListNode :rtype: ListNode"""
<|body_0|>
def reorderList(self, head):
"""reorder the list :type head: ListNode :rtype: void Do not return anything, modify head in-plac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head, last=None):
"""reverse the linked list recursively :type head: ListNode :rtype: ListNode"""
if head is None:
return last
second = head.next
head.next = last
last = head
head = second
return self.reverseLi... | the_stack_v2_python_sparse | Rakesh/linked-lists/reorder list.py | rakeshsukla53/interview-preparation | train | 9 | |
0d7013bde870150a09a59ac82cc2a5dd5a3efb8d | [
"TokenAuthenticator(request.headers.get('Authorization')).authenticate()\nbanned_list = Session().query(User.userID, User.username).join(BannedList, User.userID == BannedList.bannedUserID).filter(BannedList.userID == g.userID)\nreturn ([{'userID': userID, 'username': username} for userID, username in banned_list], ... | <|body_start_0|>
TokenAuthenticator(request.headers.get('Authorization')).authenticate()
banned_list = Session().query(User.userID, User.username).join(BannedList, User.userID == BannedList.bannedUserID).filter(BannedList.userID == g.userID)
return ([{'userID': userID, 'username': username} for ... | BannedLists | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BannedLists:
def get(self):
"""View your Banned List."""
<|body_0|>
def post(self):
"""Add a FilmFinder to your Banned List."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
TokenAuthenticator(request.headers.get('Authorization')).authenticate()
... | stack_v2_sparse_classes_75kplus_train_005619 | 3,081 | no_license | [
{
"docstring": "View your Banned List.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a FilmFinder to your Banned List.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018522 | Implement the Python class `BannedLists` described below.
Class description:
Implement the BannedLists class.
Method signatures and docstrings:
- def get(self): View your Banned List.
- def post(self): Add a FilmFinder to your Banned List. | Implement the Python class `BannedLists` described below.
Class description:
Implement the BannedLists class.
Method signatures and docstrings:
- def get(self): View your Banned List.
- def post(self): Add a FilmFinder to your Banned List.
<|skeleton|>
class BannedLists:
def get(self):
"""View your Bann... | db8862ea20ee441aed84099d44dd5695f0d950ee | <|skeleton|>
class BannedLists:
def get(self):
"""View your Banned List."""
<|body_0|>
def post(self):
"""Add a FilmFinder to your Banned List."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BannedLists:
def get(self):
"""View your Banned List."""
TokenAuthenticator(request.headers.get('Authorization')).authenticate()
banned_list = Session().query(User.userID, User.username).join(BannedList, User.userID == BannedList.bannedUserID).filter(BannedList.userID == g.userID)
... | the_stack_v2_python_sparse | server/apis/banned_list.py | NishantChokkarapu/capstone-project-comp9900-h16a-tahelka | train | 0 | |
2c4dc74b0cc6d6b49d8d769061b90863ffff3acb | [
"trackers_as_states = []\ntrackers_as_actions = []\nlogger.debug('Creating states and action examples from collected trackers (by {}({}))...'.format(type(self).__name__, type(self.state_featurizer).__name__))\npbar = tqdm(trackers, desc='Processed trackers', disable=rasa.shared.utils.io.is_logging_disabled())\nfor ... | <|body_start_0|>
trackers_as_states = []
trackers_as_actions = []
logger.debug('Creating states and action examples from collected trackers (by {}({}))...'.format(type(self).__name__, type(self.state_featurizer).__name__))
pbar = tqdm(trackers, desc='Processed trackers', disable=rasa.sha... | Creates full dialogue training data for time distributed architectures. Creates training data that uses each time output for prediction. Training data is padded up to the length of the longest dialogue with -1. | FullDialogueTrackerFeaturizer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullDialogueTrackerFeaturizer:
"""Creates full dialogue training data for time distributed architectures. Creates training data that uses each time output for prediction. Training data is padded up to the length of the longest dialogue with -1."""
def training_states_and_actions(self, tracke... | stack_v2_sparse_classes_75kplus_train_005620 | 15,652 | permissive | [
{
"docstring": "Transforms list of trackers to lists of states and actions. Training data is padded up to the length of the longest dialogue with -1. Args: trackers: The trackers to transform domain: The domain Returns: A tuple of list of states and list of actions.",
"name": "training_states_and_actions",
... | 2 | null | Implement the Python class `FullDialogueTrackerFeaturizer` described below.
Class description:
Creates full dialogue training data for time distributed architectures. Creates training data that uses each time output for prediction. Training data is padded up to the length of the longest dialogue with -1.
Method signa... | Implement the Python class `FullDialogueTrackerFeaturizer` described below.
Class description:
Creates full dialogue training data for time distributed architectures. Creates training data that uses each time output for prediction. Training data is padded up to the length of the longest dialogue with -1.
Method signa... | 4c60cbcb17ef33441e0876a596f1edc099191158 | <|skeleton|>
class FullDialogueTrackerFeaturizer:
"""Creates full dialogue training data for time distributed architectures. Creates training data that uses each time output for prediction. Training data is padded up to the length of the longest dialogue with -1."""
def training_states_and_actions(self, tracke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FullDialogueTrackerFeaturizer:
"""Creates full dialogue training data for time distributed architectures. Creates training data that uses each time output for prediction. Training data is padded up to the length of the longest dialogue with -1."""
def training_states_and_actions(self, trackers: List[Dial... | the_stack_v2_python_sparse | rasa/core/featurizers/tracker_featurizers.py | Crinmatic/rasa | train | 2 |
00c0208b632c26f2888acc3af9d3749b7acb8bcc | [
"self.name = n\nself.strength = float(s)\nself.x = float(xc)\nself.y = float(yc)\nself.radius = float(r)",
"dmg = bird.mass * bird.speed() ** 2\nself.strength -= dmg\nif self.strength < 0:\n self.strength = 0"
] | <|body_start_0|>
self.name = n
self.strength = float(s)
self.x = float(xc)
self.y = float(yc)
self.radius = float(r)
<|end_body_0|>
<|body_start_1|>
dmg = bird.mass * bird.speed() ** 2
self.strength -= dmg
if self.strength < 0:
self.strength =... | Barrier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Barrier:
def __init__(self, n, s, xc, yc, r):
"""Initialization method for barrier class -- takes name, strength (hitpoints), x position for center, y position for center, and radius"""
<|body_0|>
def calculate_damage(self, bird):
"""Given a bird, this method updates... | stack_v2_sparse_classes_75kplus_train_005621 | 784 | no_license | [
{
"docstring": "Initialization method for barrier class -- takes name, strength (hitpoints), x position for center, y position for center, and radius",
"name": "__init__",
"signature": "def __init__(self, n, s, xc, yc, r)"
},
{
"docstring": "Given a bird, this method updates the barrier's streng... | 2 | stack_v2_sparse_classes_30k_train_017366 | Implement the Python class `Barrier` described below.
Class description:
Implement the Barrier class.
Method signatures and docstrings:
- def __init__(self, n, s, xc, yc, r): Initialization method for barrier class -- takes name, strength (hitpoints), x position for center, y position for center, and radius
- def cal... | Implement the Python class `Barrier` described below.
Class description:
Implement the Barrier class.
Method signatures and docstrings:
- def __init__(self, n, s, xc, yc, r): Initialization method for barrier class -- takes name, strength (hitpoints), x position for center, y position for center, and radius
- def cal... | ef304616e3ef60a17838b85a3d6f1646a05ce327 | <|skeleton|>
class Barrier:
def __init__(self, n, s, xc, yc, r):
"""Initialization method for barrier class -- takes name, strength (hitpoints), x position for center, y position for center, and radius"""
<|body_0|>
def calculate_damage(self, bird):
"""Given a bird, this method updates... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Barrier:
def __init__(self, n, s, xc, yc, r):
"""Initialization method for barrier class -- takes name, strength (hitpoints), x position for center, y position for center, and radius"""
self.name = n
self.strength = float(s)
self.x = float(xc)
self.y = float(yc)
... | the_stack_v2_python_sparse | RPI-CSCI-1100 Computer Science I/hw/HW8/Barrier.py | WestonMJones/Coursework | train | 0 | |
1154bb2c6fb0d7c98e7c8225da88405d105efb12 | [
"super(PairwiseLinkPredictionLayer, self).__init__()\nself.dimensions = dimensions\nself.link_pred_method = link_pred_method\nif self.link_pred_method in ['addition', 'hadamard-product', 'l1-weighted', 'l2-weighted']:\n self.classif = torch.nn.Linear(self.dimensions, 1)",
"u_norm = torch.norm(u_embeddings, dim... | <|body_start_0|>
super(PairwiseLinkPredictionLayer, self).__init__()
self.dimensions = dimensions
self.link_pred_method = link_pred_method
if self.link_pred_method in ['addition', 'hadamard-product', 'l1-weighted', 'l2-weighted']:
self.classif = torch.nn.Linear(self.dimension... | Predicts pairwise links between nodes of a hyperedge. | PairwiseLinkPredictionLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairwiseLinkPredictionLayer:
"""Predicts pairwise links between nodes of a hyperedge."""
def __init__(self, dimensions, link_pred_method):
"""Initialize pairwise link prediction layer. Args: dimensions: int. Dimensions of node embedding. link_pred_method: str. The method used for lin... | stack_v2_sparse_classes_75kplus_train_005622 | 11,206 | no_license | [
{
"docstring": "Initialize pairwise link prediction layer. Args: dimensions: int. Dimensions of node embedding. link_pred_method: str. The method used for link prediciton from node embeddings. It can be either 'cosine', 'addition', 'hadamard-product', 'l1-weighted', 'l2-weighted'.",
"name": "__init__",
... | 3 | stack_v2_sparse_classes_30k_train_046594 | Implement the Python class `PairwiseLinkPredictionLayer` described below.
Class description:
Predicts pairwise links between nodes of a hyperedge.
Method signatures and docstrings:
- def __init__(self, dimensions, link_pred_method): Initialize pairwise link prediction layer. Args: dimensions: int. Dimensions of node ... | Implement the Python class `PairwiseLinkPredictionLayer` described below.
Class description:
Predicts pairwise links between nodes of a hyperedge.
Method signatures and docstrings:
- def __init__(self, dimensions, link_pred_method): Initialize pairwise link prediction layer. Args: dimensions: int. Dimensions of node ... | 0ce2f60c6efd62fc863d2649ba9a6b8ceaedb4aa | <|skeleton|>
class PairwiseLinkPredictionLayer:
"""Predicts pairwise links between nodes of a hyperedge."""
def __init__(self, dimensions, link_pred_method):
"""Initialize pairwise link prediction layer. Args: dimensions: int. Dimensions of node embedding. link_pred_method: str. The method used for lin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PairwiseLinkPredictionLayer:
"""Predicts pairwise links between nodes of a hyperedge."""
def __init__(self, dimensions, link_pred_method):
"""Initialize pairwise link prediction layer. Args: dimensions: int. Dimensions of node embedding. link_pred_method: str. The method used for link prediciton ... | the_stack_v2_python_sparse | Classifiers/custom_layers.py | govindjsk/shonens | train | 0 |
028fe614bb94faa72fe457bc86887d5423269cba | [
"q = None\nif analyzer.is_postcode_huisnummer_prefix():\n q = bag_qs.postcode_huisnummer_query(analyzer)\nelif analyzer.is_straatnaam_huisnummer_prefix():\n q = bag_qs.straatnaam_huisnummer_query(analyzer, self.features)\nelif analyzer.is_landelijk_id_prefix():\n q = bag_qs.landelijk_id_nummeraanduiding_qu... | <|body_start_0|>
q = None
if analyzer.is_postcode_huisnummer_prefix():
q = bag_qs.postcode_huisnummer_query(analyzer)
elif analyzer.is_straatnaam_huisnummer_prefix():
q = bag_qs.straatnaam_huisnummer_query(analyzer, self.features)
elif analyzer.is_landelijk_id_pre... | Given a query parameter `q`, this function returns a subset of nummeraanduiding objects that match the elastic search query. [/search/adres/?q=silodam 340](https://api.data.amsterdam.nl/atlas/search/adres/?q=silodam 340) Een nummeraanduiding, in de volksmond ook wel adres genoemd, is een door het bevoegde gemeentelijke... | SearchNummeraanduidingViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchNummeraanduidingViewSet:
"""Given a query parameter `q`, this function returns a subset of nummeraanduiding objects that match the elastic search query. [/search/adres/?q=silodam 340](https://api.data.amsterdam.nl/atlas/search/adres/?q=silodam 340) Een nummeraanduiding, in de volksmond ook ... | stack_v2_sparse_classes_75kplus_train_005623 | 35,280 | no_license | [
{
"docstring": "Execute search in Objects",
"name": "search_query",
"signature": "def search_query(self, request, elk_client, analyzer: QueryAnalyzer) -> Search"
},
{
"docstring": "Remove attribute fields not needed for enduser",
"name": "get_hit_data",
"signature": "def get_hit_data(sel... | 2 | stack_v2_sparse_classes_30k_train_028315 | Implement the Python class `SearchNummeraanduidingViewSet` described below.
Class description:
Given a query parameter `q`, this function returns a subset of nummeraanduiding objects that match the elastic search query. [/search/adres/?q=silodam 340](https://api.data.amsterdam.nl/atlas/search/adres/?q=silodam 340) Een... | Implement the Python class `SearchNummeraanduidingViewSet` described below.
Class description:
Given a query parameter `q`, this function returns a subset of nummeraanduiding objects that match the elastic search query. [/search/adres/?q=silodam 340](https://api.data.amsterdam.nl/atlas/search/adres/?q=silodam 340) Een... | cb97f574ae0822cab879588de157a847aa3a670f | <|skeleton|>
class SearchNummeraanduidingViewSet:
"""Given a query parameter `q`, this function returns a subset of nummeraanduiding objects that match the elastic search query. [/search/adres/?q=silodam 340](https://api.data.amsterdam.nl/atlas/search/adres/?q=silodam 340) Een nummeraanduiding, in de volksmond ook ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchNummeraanduidingViewSet:
"""Given a query parameter `q`, this function returns a subset of nummeraanduiding objects that match the elastic search query. [/search/adres/?q=silodam 340](https://api.data.amsterdam.nl/atlas/search/adres/?q=silodam 340) Een nummeraanduiding, in de volksmond ook wel adres gen... | the_stack_v2_python_sparse | bag/search/views.py | Amsterdam/bag_services | train | 3 |
c9e5c727cdaf74a6e36dce3b86f4e19d939ba413 | [
"super().__init__()\nself.val = 0\nself.avg = 0\nself.sum = 0\nself.count = 0",
"self.val = 0\nself.avg = 0\nself.sum = 0\nself.count = 0",
"self.val = val\nself.sum += val * n\nself.count += n\nself.avg = self.sum / self.count"
] | <|body_start_0|>
super().__init__()
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
<|end_body_0|>
<|body_start_1|>
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
<|end_body_1|>
<|body_start_2|>
self.val = val
self.su... | Computes and stores the average and current value | AverageMeter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
"""__init__"""
<|body_0|>
def reset(self):
"""reset"""
<|body_1|>
def update(self, val, n=1):
"""update"""
<|body_2|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_005624 | 3,108 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "reset",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "update",
"name": "update",
"signature": "def update(self, val, n=1)"
}
] | 3 | stack_v2_sparse_classes_30k_train_007542 | Implement the Python class `AverageMeter` described below.
Class description:
Computes and stores the average and current value
Method signatures and docstrings:
- def __init__(self): __init__
- def reset(self): reset
- def update(self, val, n=1): update | Implement the Python class `AverageMeter` described below.
Class description:
Computes and stores the average and current value
Method signatures and docstrings:
- def __init__(self): __init__
- def reset(self): reset
- def update(self, val, n=1): update
<|skeleton|>
class AverageMeter:
"""Computes and stores th... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
"""__init__"""
<|body_0|>
def reset(self):
"""reset"""
<|body_1|>
def update(self, val, n=1):
"""update"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
"""__init__"""
super().__init__()
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
"""reset"""
self.val = 0
self.avg... | the_stack_v2_python_sparse | official/cv/PVNet/src/net_utils.py | mindspore-ai/models | train | 301 |
5c247065e6b7794a8becc9aa5e092f7d5e2dd1bf | [
"super(MonomialBasisFunctionsMethod, self).__init__(A, B=B, p=p, ti=ti, options=options, verbose=verbose)\nif ti == []:\n self.t1 = 1.0 / self.tau0\nelse:\n if isinstance(ti, list):\n ti = numpy.array(ti)\n elif isinstance(ti, Number):\n ti = numpy.array([ti])\n if ti.size != 1:\n r... | <|body_start_0|>
super(MonomialBasisFunctionsMethod, self).__init__(A, B=B, p=p, ti=ti, options=options, verbose=verbose)
if ti == []:
self.t1 = 1.0 / self.tau0
else:
if isinstance(ti, list):
ti = numpy.array(ti)
elif isinstance(ti, Number):
... | Interpolate Schatten norm (or anti-norm) of an affine matrix function using monomial basis functions (MBF) method. This class accepts only *one* interpolant point (:math:`q = 1`). That is, the argument ``ti`` should be only one number or a list of the length 1. A better method is ``'imbf'`` which accepts arbitrary numb... | MonomialBasisFunctionsMethod | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonomialBasisFunctionsMethod:
"""Interpolate Schatten norm (or anti-norm) of an affine matrix function using monomial basis functions (MBF) method. This class accepts only *one* interpolant point (:math:`q = 1`). That is, the argument ``ti`` should be only one number or a list of the length 1. A ... | stack_v2_sparse_classes_75kplus_train_005625 | 14,850 | permissive | [
{
"docstring": "Initializes the base class and attributes, namely, the trace at the interpolant point.",
"name": "__init__",
"signature": "def __init__(self, A, B=None, p=2, options={}, verbose=False, ti=[])"
},
{
"docstring": "Computes the trace at the interpolant point. This function is used i... | 3 | stack_v2_sparse_classes_30k_train_048910 | Implement the Python class `MonomialBasisFunctionsMethod` described below.
Class description:
Interpolate Schatten norm (or anti-norm) of an affine matrix function using monomial basis functions (MBF) method. This class accepts only *one* interpolant point (:math:`q = 1`). That is, the argument ``ti`` should be only o... | Implement the Python class `MonomialBasisFunctionsMethod` described below.
Class description:
Interpolate Schatten norm (or anti-norm) of an affine matrix function using monomial basis functions (MBF) method. This class accepts only *one* interpolant point (:math:`q = 1`). That is, the argument ``ti`` should be only o... | de867f131a4cda7d60a68bf0558e896fae89d776 | <|skeleton|>
class MonomialBasisFunctionsMethod:
"""Interpolate Schatten norm (or anti-norm) of an affine matrix function using monomial basis functions (MBF) method. This class accepts only *one* interpolant point (:math:`q = 1`). That is, the argument ``ti`` should be only one number or a list of the length 1. A ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonomialBasisFunctionsMethod:
"""Interpolate Schatten norm (or anti-norm) of an affine matrix function using monomial basis functions (MBF) method. This class accepts only *one* interpolant point (:math:`q = 1`). That is, the argument ``ti`` should be only one number or a list of the length 1. A better method... | the_stack_v2_python_sparse | imate/interpolator/_monomial_basis_functions_method.py | ameli/imate | train | 5 |
bf9e32eb8dcede249c2534219c0c72518eea1c2f | [
"Fruit.__init__(self)\nself._flower_duration = flower_duration\nself._max_relative_growth_rate = max_relative_growth_rate\nself._lost_time = lost_time\nself._max_age = max_age\nself._probability = probability\nself._max_absolute_growth_rate = max_absolute_growth_rate\nself._r = self._max_absolute_growth_rate / self... | <|body_start_0|>
Fruit.__init__(self)
self._flower_duration = flower_duration
self._max_relative_growth_rate = max_relative_growth_rate
self._lost_time = lost_time
self._max_age = max_age
self._probability = probability
self._max_absolute_growth_rate = max_absolut... | A specialised fruit class for apple trees This class inherits methods and attributes from :class:`~openalea.stocatree.fruit.Fruit` and specialises the :meth:`compute_mass` method. >>> fruit = AppleFruit(max_age=100., flower_duration=12.) >>> fruit.state 'flower' >>> fruit.age 0 >>> fruit.mass 0.0 >>> fruit._flower_dura... | AppleFruit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppleFruit:
"""A specialised fruit class for apple trees This class inherits methods and attributes from :class:`~openalea.stocatree.fruit.Fruit` and specialises the :meth:`compute_mass` method. >>> fruit = AppleFruit(max_age=100., flower_duration=12.) >>> fruit.state 'flower' >>> fruit.age 0 >>>... | stack_v2_sparse_classes_75kplus_train_005626 | 6,591 | no_license | [
{
"docstring": "**Construtor** Inherits :meth:`get_state`, :meth:`set_state` from :class:`Fruit` class. The method :meth:`compute_mass` is redefined. The following arguments may be provided and are specific to apple trees. There are mainly used to compute the mass of the fruit as a function of its age except fo... | 2 | stack_v2_sparse_classes_30k_train_051899 | Implement the Python class `AppleFruit` described below.
Class description:
A specialised fruit class for apple trees This class inherits methods and attributes from :class:`~openalea.stocatree.fruit.Fruit` and specialises the :meth:`compute_mass` method. >>> fruit = AppleFruit(max_age=100., flower_duration=12.) >>> f... | Implement the Python class `AppleFruit` described below.
Class description:
A specialised fruit class for apple trees This class inherits methods and attributes from :class:`~openalea.stocatree.fruit.Fruit` and specialises the :meth:`compute_mass` method. >>> fruit = AppleFruit(max_age=100., flower_duration=12.) >>> f... | 090370f08271455f6c1b89592a0b7eb18212a6c9 | <|skeleton|>
class AppleFruit:
"""A specialised fruit class for apple trees This class inherits methods and attributes from :class:`~openalea.stocatree.fruit.Fruit` and specialises the :meth:`compute_mass` method. >>> fruit = AppleFruit(max_age=100., flower_duration=12.) >>> fruit.state 'flower' >>> fruit.age 0 >>>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppleFruit:
"""A specialised fruit class for apple trees This class inherits methods and attributes from :class:`~openalea.stocatree.fruit.Fruit` and specialises the :meth:`compute_mass` method. >>> fruit = AppleFruit(max_age=100., flower_duration=12.) >>> fruit.state 'flower' >>> fruit.age 0 >>> fruit.mass 0... | the_stack_v2_python_sparse | src/openalea/stocatree/fruit.py | junqi108/MAppleT | train | 0 |
4fef64a6531edc1a223496457077cb4c1367554d | [
"r = dcos_api_session.get('/')\nr.raise_for_status()\nfilenames = self.pat.findall(r.text)\nassert len(filenames) > 0\nfor filename in set(filenames):\n log.info('Load %r', filename)\n r = dcos_api_session.head(filename, headers={'Accept-Encoding': 'gzip'})\n r.raise_for_status()\n log.info('Response he... | <|body_start_0|>
r = dcos_api_session.get('/')
r.raise_for_status()
filenames = self.pat.findall(r.text)
assert len(filenames) > 0
for filename in set(filenames):
log.info('Load %r', filename)
r = dcos_api_session.head(filename, headers={'Accept-Encoding':... | TestEncodingGzip | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-oracle-bcl-javase-javafx-2012",
"ErlPL-1.1",
"MPL-2.0",
"ISC",
"BSL-1.0",
"Python-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEncodingGzip:
def test_accept_gzip(self, dcos_api_session: DcosApiSession) -> None:
"""Clients that send "Accept-Encoding: gzip" get gzipped responses for some assets."""
<|body_0|>
def test_not_accept_gzip(self, dcos_api_session: DcosApiSession) -> None:
"""Clie... | stack_v2_sparse_classes_75kplus_train_005627 | 5,135 | permissive | [
{
"docstring": "Clients that send \"Accept-Encoding: gzip\" get gzipped responses for some assets.",
"name": "test_accept_gzip",
"signature": "def test_accept_gzip(self, dcos_api_session: DcosApiSession) -> None"
},
{
"docstring": "Clients that do not send \"Accept-Encoding: gzip\" do not get gz... | 2 | stack_v2_sparse_classes_30k_train_025163 | Implement the Python class `TestEncodingGzip` described below.
Class description:
Implement the TestEncodingGzip class.
Method signatures and docstrings:
- def test_accept_gzip(self, dcos_api_session: DcosApiSession) -> None: Clients that send "Accept-Encoding: gzip" get gzipped responses for some assets.
- def test_... | Implement the Python class `TestEncodingGzip` described below.
Class description:
Implement the TestEncodingGzip class.
Method signatures and docstrings:
- def test_accept_gzip(self, dcos_api_session: DcosApiSession) -> None: Clients that send "Accept-Encoding: gzip" get gzipped responses for some assets.
- def test_... | 79b9a39b4e639dc2c9435a869918399b50bfaf24 | <|skeleton|>
class TestEncodingGzip:
def test_accept_gzip(self, dcos_api_session: DcosApiSession) -> None:
"""Clients that send "Accept-Encoding: gzip" get gzipped responses for some assets."""
<|body_0|>
def test_not_accept_gzip(self, dcos_api_session: DcosApiSession) -> None:
"""Clie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestEncodingGzip:
def test_accept_gzip(self, dcos_api_session: DcosApiSession) -> None:
"""Clients that send "Accept-Encoding: gzip" get gzipped responses for some assets."""
r = dcos_api_session.get('/')
r.raise_for_status()
filenames = self.pat.findall(r.text)
assert ... | the_stack_v2_python_sparse | packages/dcos-integration-test/extra/test_adminrouter_open.py | dcos/dcos | train | 2,613 | |
6e93616d3ce7cab0ad785a8a12ba5e8d3cf94c0a | [
"self.minPath = minPath\nself.maxPath = maxPath\nself.nBits = nBits",
"fp = RDKFingerprint(mol, minPath=self.minPath, maxPath=self.maxPath, fpSize=self.nBits)\nfp = list(fp)\nreturn fp"
] | <|body_start_0|>
self.minPath = minPath
self.maxPath = maxPath
self.nBits = nBits
<|end_body_0|>
<|body_start_1|>
fp = RDKFingerprint(mol, minPath=self.minPath, maxPath=self.maxPath, fpSize=self.nBits)
fp = list(fp)
return fp
<|end_body_1|>
| a Daylight-like fingerprint based on hashing molecular subgraphs 2^n bits :param minPath: minimum number of bonds to include in the subgraphs, defaults to 1 :type minPath: int, optional :param maxPath: maximum number of bonds to include in the subgraphs, defaults to 7 :type maxPath: int, optional :param nBits: number o... | Daylight | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Daylight:
"""a Daylight-like fingerprint based on hashing molecular subgraphs 2^n bits :param minPath: minimum number of bonds to include in the subgraphs, defaults to 1 :type minPath: int, optional :param maxPath: maximum number of bonds to include in the subgraphs, defaults to 7 :type maxPath: ... | stack_v2_sparse_classes_75kplus_train_005628 | 2,675 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, minPath, maxPath, nBits)"
},
{
"docstring": ":param mol: molecule :type mol: rdkit.Chem.rdchem.Mol :return: fingerprint :rtype: list",
"name": "CalculateDaylight",
"signature": "def CalculateDaylight(se... | 2 | null | Implement the Python class `Daylight` described below.
Class description:
a Daylight-like fingerprint based on hashing molecular subgraphs 2^n bits :param minPath: minimum number of bonds to include in the subgraphs, defaults to 1 :type minPath: int, optional :param maxPath: maximum number of bonds to include in the s... | Implement the Python class `Daylight` described below.
Class description:
a Daylight-like fingerprint based on hashing molecular subgraphs 2^n bits :param minPath: minimum number of bonds to include in the subgraphs, defaults to 1 :type minPath: int, optional :param maxPath: maximum number of bonds to include in the s... | 897f9f0f41a90e0cff1e2fd28a7e82cfac051306 | <|skeleton|>
class Daylight:
"""a Daylight-like fingerprint based on hashing molecular subgraphs 2^n bits :param minPath: minimum number of bonds to include in the subgraphs, defaults to 1 :type minPath: int, optional :param maxPath: maximum number of bonds to include in the subgraphs, defaults to 7 :type maxPath: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Daylight:
"""a Daylight-like fingerprint based on hashing molecular subgraphs 2^n bits :param minPath: minimum number of bonds to include in the subgraphs, defaults to 1 :type minPath: int, optional :param maxPath: maximum number of bonds to include in the subgraphs, defaults to 7 :type maxPath: int, optional... | the_stack_v2_python_sparse | scopy/fingerprint/daylight.py | SorchaYang/Scopy | train | 4 |
b59c1aadaf395e63ec8bb922729f602471793eab | [
"self.W1 = utils.weight_variable([n_x, n_z1], 'W1')\nself.b1 = utils.weight_variable([n_z1], 'b1')\nself.W2 = utils.weight_variable([n_z1, n_z2], 'W2')\nself.b2 = utils.weight_variable([n_z2], 'b2')\nself.W3 = utils.weight_variable([n_z2, n_y], 'W3')\nself.b3 = utils.weight_variable([n_y], 'b3')\nself.params = [sel... | <|body_start_0|>
self.W1 = utils.weight_variable([n_x, n_z1], 'W1')
self.b1 = utils.weight_variable([n_z1], 'b1')
self.W2 = utils.weight_variable([n_z1, n_z2], 'W2')
self.b2 = utils.weight_variable([n_z2], 'b2')
self.W3 = utils.weight_variable([n_z2, n_y], 'W3')
self.b3 =... | Code for feed forward network | FFN_network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFN_network:
"""Code for feed forward network"""
def __init__(self, n_x, n_z1, n_z2, n_y):
"""constructor of the network :param n_x: number of nodes in input layer :param n_z1: number of nodes in hidden layer 1 :param n_z2: number of nodes in hidden layer 2 :param n_y: number of node... | stack_v2_sparse_classes_75kplus_train_005629 | 3,409 | no_license | [
{
"docstring": "constructor of the network :param n_x: number of nodes in input layer :param n_z1: number of nodes in hidden layer 1 :param n_z2: number of nodes in hidden layer 2 :param n_y: number of nodes in the output layer :return: None",
"name": "__init__",
"signature": "def __init__(self, n_x, n_... | 4 | stack_v2_sparse_classes_30k_train_017959 | Implement the Python class `FFN_network` described below.
Class description:
Code for feed forward network
Method signatures and docstrings:
- def __init__(self, n_x, n_z1, n_z2, n_y): constructor of the network :param n_x: number of nodes in input layer :param n_z1: number of nodes in hidden layer 1 :param n_z2: num... | Implement the Python class `FFN_network` described below.
Class description:
Code for feed forward network
Method signatures and docstrings:
- def __init__(self, n_x, n_z1, n_z2, n_y): constructor of the network :param n_x: number of nodes in input layer :param n_z1: number of nodes in hidden layer 1 :param n_z2: num... | 02a580791d84b1d8f15c33638bda2304c91929c3 | <|skeleton|>
class FFN_network:
"""Code for feed forward network"""
def __init__(self, n_x, n_z1, n_z2, n_y):
"""constructor of the network :param n_x: number of nodes in input layer :param n_z1: number of nodes in hidden layer 1 :param n_z2: number of nodes in hidden layer 2 :param n_y: number of node... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FFN_network:
"""Code for feed forward network"""
def __init__(self, n_x, n_z1, n_z2, n_y):
"""constructor of the network :param n_x: number of nodes in input layer :param n_z1: number of nodes in hidden layer 1 :param n_z2: number of nodes in hidden layer 2 :param n_y: number of nodes in the outp... | the_stack_v2_python_sparse | src/FFN.py | hiteshvaidya/Thesis | train | 0 |
65b97a25227a2b59cf60a8d6a69058d8e9cc5339 | [
"self.left = left\nself.op = op\nself.right = right",
"left_val = self.left.evaluate(env)\nright_val = self.right.evaluate(env)\nif self.op == '+':\n return left_val + right_val\nelif self.op == '*':\n return left_val * right_val\nelse:\n raise ValueError(f'Invalid operator {self.op}')"
] | <|body_start_0|>
self.left = left
self.op = op
self.right = right
<|end_body_0|>
<|body_start_1|>
left_val = self.left.evaluate(env)
right_val = self.right.evaluate(env)
if self.op == '+':
return left_val + right_val
elif self.op == '*':
r... | An arithmetic binary operation. Attributes: ----------- left: the left operand op: the name of the operator right: the right operand Invariants: ----------- - self.op == '+' or self.op == '*' | BinOp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinOp:
"""An arithmetic binary operation. Attributes: ----------- left: the left operand op: the name of the operator right: the right operand Invariants: ----------- - self.op == '+' or self.op == '*'"""
def __init__(self, left: Expr, op: str, right: Expr) -> None:
"""Initialize a n... | stack_v2_sparse_classes_75kplus_train_005630 | 9,378 | permissive | [
{
"docstring": "Initialize a new binary operation express. Parameters: ----------- :param left: the left operand :param op: the name of the operator :param right: the right operand Preconditions: -------------- <op> is the string '+' or '*'.",
"name": "__init__",
"signature": "def __init__(self, left: E... | 2 | stack_v2_sparse_classes_30k_train_012414 | Implement the Python class `BinOp` described below.
Class description:
An arithmetic binary operation. Attributes: ----------- left: the left operand op: the name of the operator right: the right operand Invariants: ----------- - self.op == '+' or self.op == '*'
Method signatures and docstrings:
- def __init__(self, ... | Implement the Python class `BinOp` described below.
Class description:
An arithmetic binary operation. Attributes: ----------- left: the left operand op: the name of the operator right: the right operand Invariants: ----------- - self.op == '+' or self.op == '*'
Method signatures and docstrings:
- def __init__(self, ... | 81324825827ac776d45844d79f4aa75a4ad5af11 | <|skeleton|>
class BinOp:
"""An arithmetic binary operation. Attributes: ----------- left: the left operand op: the name of the operator right: the right operand Invariants: ----------- - self.op == '+' or self.op == '*'"""
def __init__(self, left: Expr, op: str, right: Expr) -> None:
"""Initialize a n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinOp:
"""An arithmetic binary operation. Attributes: ----------- left: the left operand op: the name of the operator right: the right operand Invariants: ----------- - self.op == '+' or self.op == '*'"""
def __init__(self, left: Expr, op: str, right: Expr) -> None:
"""Initialize a new binary ope... | the_stack_v2_python_sparse | DataStructures/Trees/ExpressionTree/ExpressionTree.py | m0sys/Algorithms | train | 0 |
45e60341ad6de3db97a2af626e0d1ac1067eb9d5 | [
"assert type(blue_print_genome) is dict\nself.n_genes = len(blue_print_genome)\nself.gene_names = blue_print_genome.keys()\nself.bp_genome = blue_print_genome\nself.bp_gene_type = {}\nfor name in self.gene_names:\n self.bp_gene_type[name] = type(self.bp_genome[name][0])",
"genes = {}\nfor name in self.gene_nam... | <|body_start_0|>
assert type(blue_print_genome) is dict
self.n_genes = len(blue_print_genome)
self.gene_names = blue_print_genome.keys()
self.bp_genome = blue_print_genome
self.bp_gene_type = {}
for name in self.gene_names:
self.bp_gene_type[name] = type(self.... | This is a sort of blue print gene. That can generate proper gene. | SuperGenome | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperGenome:
"""This is a sort of blue print gene. That can generate proper gene."""
def __init__(self, blue_print_genome):
""":param blue_print_segment_dictionary: A dictionary with keys corresponding to the name of a segment and the range of possible values as item."""
<|bo... | stack_v2_sparse_classes_75kplus_train_005631 | 9,293 | permissive | [
{
"docstring": ":param blue_print_segment_dictionary: A dictionary with keys corresponding to the name of a segment and the range of possible values as item.",
"name": "__init__",
"signature": "def __init__(self, blue_print_genome)"
},
{
"docstring": "Returns a random Gen instance.",
"name":... | 4 | null | Implement the Python class `SuperGenome` described below.
Class description:
This is a sort of blue print gene. That can generate proper gene.
Method signatures and docstrings:
- def __init__(self, blue_print_genome): :param blue_print_segment_dictionary: A dictionary with keys corresponding to the name of a segment ... | Implement the Python class `SuperGenome` described below.
Class description:
This is a sort of blue print gene. That can generate proper gene.
Method signatures and docstrings:
- def __init__(self, blue_print_genome): :param blue_print_segment_dictionary: A dictionary with keys corresponding to the name of a segment ... | e1daafb01e54e58fa034227aaff52a5fdade2d26 | <|skeleton|>
class SuperGenome:
"""This is a sort of blue print gene. That can generate proper gene."""
def __init__(self, blue_print_genome):
""":param blue_print_segment_dictionary: A dictionary with keys corresponding to the name of a segment and the range of possible values as item."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperGenome:
"""This is a sort of blue print gene. That can generate proper gene."""
def __init__(self, blue_print_genome):
""":param blue_print_segment_dictionary: A dictionary with keys corresponding to the name of a segment and the range of possible values as item."""
assert type(blue_... | the_stack_v2_python_sparse | ninolearn/learn/geneticProgramming.py | hossein-amini67/ninolearn | train | 1 |
30320a9cfbeb7999bf7cebd6f29d244942537849 | [
"self._clean_until = 0\nself._threshold = threshold\nself._prev_cleaning = None",
"if step_count == 0:\n self._clean_until = 0\nnot_me = 1 - observation['agent_slot']\nnear_river = observation['global']['observations']['POSITION'][..., 1] < 9\ncleaning = observation['global']['actions'] == CLEAN_UP_CLEAN_ACTIO... | <|body_start_0|>
self._clean_until = 0
self._threshold = threshold
self._prev_cleaning = None
<|end_body_0|>
<|body_start_1|>
if step_count == 0:
self._clean_until = 0
not_me = 1 - observation['agent_slot']
near_river = observation['global']['observations']['... | Cleanup puppeteer for a reciprocating agent. | ConditionalCleaner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalCleaner:
"""Cleanup puppeteer for a reciprocating agent."""
def __init__(self, threshold: int) -> None:
"""Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning."""
<|body_0|>
def __call__(self, step_count:... | stack_v2_sparse_classes_75kplus_train_005632 | 7,109 | permissive | [
{
"docstring": "Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning.",
"name": "__init__",
"signature": "def __init__(self, threshold: int) -> None"
},
{
"docstring": "Puppeteer step. Args: step_count: steps since episode started. observati... | 2 | stack_v2_sparse_classes_30k_train_004941 | Implement the Python class `ConditionalCleaner` described below.
Class description:
Cleanup puppeteer for a reciprocating agent.
Method signatures and docstrings:
- def __init__(self, threshold: int) -> None: Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning.
... | Implement the Python class `ConditionalCleaner` described below.
Class description:
Cleanup puppeteer for a reciprocating agent.
Method signatures and docstrings:
- def __init__(self, threshold: int) -> None: Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning.
... | e42b916b32771f7af5ad4eccbdf4ded410735299 | <|skeleton|>
class ConditionalCleaner:
"""Cleanup puppeteer for a reciprocating agent."""
def __init__(self, threshold: int) -> None:
"""Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning."""
<|body_0|>
def __call__(self, step_count:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConditionalCleaner:
"""Cleanup puppeteer for a reciprocating agent."""
def __init__(self, threshold: int) -> None:
"""Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning."""
self._clean_until = 0
self._threshold = threshold
... | the_stack_v2_python_sparse | meltingpot/python/utils/bots/puppeteer_functions.py | classicvalues/meltingpot | train | 0 |
b3001f977a60408917190461a205142bc38d27a4 | [
"super(MobiusLinear, self).__init__()\nself.zeros = Zeros()\nself.use_bias = use_bias\nself.in_features = in_features\nself.out_features = out_features\nself.c = c\nself.bias = Parameter(Tensor(ones([1, out_features]), mstype.float32))\nself.weight = Parameter(Tensor(randn(out_features, in_features), mstype.float32... | <|body_start_0|>
super(MobiusLinear, self).__init__()
self.zeros = Zeros()
self.use_bias = use_bias
self.in_features = in_features
self.out_features = out_features
self.c = c
self.bias = Parameter(Tensor(ones([1, out_features]), mstype.float32))
self.weigh... | Mobius linear layer. | MobiusLinear | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobiusLinear:
"""Mobius linear layer."""
def __init__(self, in_features, out_features, c, use_bias=True):
"""init fun"""
<|body_0|>
def construct(self, x):
"""class construction"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(MobiusLinear,... | stack_v2_sparse_classes_75kplus_train_005633 | 2,247 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, in_features, out_features, c, use_bias=True)"
},
{
"docstring": "class construction",
"name": "construct",
"signature": "def construct(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001218 | Implement the Python class `MobiusLinear` described below.
Class description:
Mobius linear layer.
Method signatures and docstrings:
- def __init__(self, in_features, out_features, c, use_bias=True): init fun
- def construct(self, x): class construction | Implement the Python class `MobiusLinear` described below.
Class description:
Mobius linear layer.
Method signatures and docstrings:
- def __init__(self, in_features, out_features, c, use_bias=True): init fun
- def construct(self, x): class construction
<|skeleton|>
class MobiusLinear:
"""Mobius linear layer."""... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class MobiusLinear:
"""Mobius linear layer."""
def __init__(self, in_features, out_features, c, use_bias=True):
"""init fun"""
<|body_0|>
def construct(self, x):
"""class construction"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MobiusLinear:
"""Mobius linear layer."""
def __init__(self, in_features, out_features, c, use_bias=True):
"""init fun"""
super(MobiusLinear, self).__init__()
self.zeros = Zeros()
self.use_bias = use_bias
self.in_features = in_features
self.out_features = ou... | the_stack_v2_python_sparse | research/nlp/hypertext/src/mobius_linear.py | mindspore-ai/models | train | 301 |
a471c50bc35df60e8decaa965b1a9f6cfea2631e | [
"if self.chunk_size is None:\n return None\nchunk_size = self.chunk_size\nd = {k: coords[k].size for k in self._dims}\ns = reduce(mul, d.values(), 1)\nfor dim in coords.dims[::-1]:\n if dim in self._dims:\n continue\n n = chunk_size // s\n if n == 0:\n d[dim] = 1\n elif n < coords[dim].... | <|body_start_0|>
if self.chunk_size is None:
return None
chunk_size = self.chunk_size
d = {k: coords[k].size for k in self._dims}
s = reduce(mul, d.values(), 1)
for dim in coords.dims[::-1]:
if dim in self._dims:
continue
n = ch... | Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the node must iterate through the Coor... | Reduce2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reduce2:
"""Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the... | stack_v2_sparse_classes_75kplus_train_005634 | 27,208 | permissive | [
{
"docstring": "Shape of chunks for parallel processing or large arrays that do not fit in memory. Returns ------- list List of integers giving the shape of each chunk.",
"name": "_get_chunk_shape",
"signature": "def _get_chunk_shape(self, coords)"
},
{
"docstring": "Generator for the chunks of ... | 3 | stack_v2_sparse_classes_30k_train_040942 | Implement the Python class `Reduce2` described below.
Class description:
Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For ... | Implement the Python class `Reduce2` described below.
Class description:
Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For ... | 0a96a9b3726aee9bb6208244ae96ed685667e16c | <|skeleton|>
class Reduce2:
"""Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Reduce2:
"""Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the node must it... | the_stack_v2_python_sparse | podpac/core/algorithm/stats.py | ccuadrado/podpac | train | 0 |
81cd97ef634a53da91b3f96d6b6ae204f580b2fc | [
"super().setup(*args, **kwargs)\nself._frame_number = 0\nif not ('{' in self.outfile and '}' in self.outfile):\n raise BetseMatplotlibException('Frame filename template \"{}\" contains no \"{{\"- and \"}}\"-delimited format specifier.'.format(self.outfile))\nself.frame_format = pathnames.get_filetype_undotted_or... | <|body_start_0|>
super().setup(*args, **kwargs)
self._frame_number = 0
if not ('{' in self.outfile and '}' in self.outfile):
raise BetseMatplotlibException('Frame filename template "{}" contains no "{{"- and "}}"-delimited format specifier.'.format(self.outfile))
self.frame_f... | Matplotlib animation writer writing animation frames to still image files rather than animated videos. For drop-in use as an animation writer (e.g., to the :meth:`Animation.save` method), this class masquerades as a :class:`MovieWriter` subclass by the unique name of ``image``. Nonetheless, no movie is written; only fr... | ImageMovieWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageMovieWriter:
"""Matplotlib animation writer writing animation frames to still image files rather than animated videos. For drop-in use as an animation writer (e.g., to the :meth:`Animation.save` method), this class masquerades as a :class:`MovieWriter` subclass by the unique name of ``image`... | stack_v2_sparse_classes_75kplus_train_005635 | 9,692 | no_license | [
{
"docstring": "Prepare to write animation frames. This method is implicitly called by the superclass :meth:`saving` method implicitly called by the :meth:`Anim.save` method. Note that, unfortunately, the design of both methods prohibits this method from accepting subclass-specific parameters. Parameters ------... | 2 | stack_v2_sparse_classes_30k_train_045616 | Implement the Python class `ImageMovieWriter` described below.
Class description:
Matplotlib animation writer writing animation frames to still image files rather than animated videos. For drop-in use as an animation writer (e.g., to the :meth:`Animation.save` method), this class masquerades as a :class:`MovieWriter` ... | Implement the Python class `ImageMovieWriter` described below.
Class description:
Matplotlib animation writer writing animation frames to still image files rather than animated videos. For drop-in use as an animation writer (e.g., to the :meth:`Animation.save` method), this class masquerades as a :class:`MovieWriter` ... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class ImageMovieWriter:
"""Matplotlib animation writer writing animation frames to still image files rather than animated videos. For drop-in use as an animation writer (e.g., to the :meth:`Animation.save` method), this class masquerades as a :class:`MovieWriter` subclass by the unique name of ``image`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageMovieWriter:
"""Matplotlib animation writer writing animation frames to still image files rather than animated videos. For drop-in use as an animation writer (e.g., to the :meth:`Animation.save` method), this class masquerades as a :class:`MovieWriter` subclass by the unique name of ``image``. Nonetheles... | the_stack_v2_python_sparse | betse/lib/matplotlib/writer/mplcls.py | R-Stefano/betse-ml | train | 0 |
ff14f9c959ef3a3497975e4138158316719050b0 | [
"T = len(self.x)\ndLdx = np.zeros((T, self.input_size))\nself.nodes.reset_error()\nfor t in xrange(T):\n dLdp = dLds[t] * self.acfun.derivate(self.s[t])\n self.nodes.dLdu += np.outer(dLdp, self.x[t])\n if self.en_bias:\n self.nodes.dLdb += dLdp\n dLdx[t] = np.dot(self.nodes.u.T, dLdp)\nself.nodes... | <|body_start_0|>
T = len(self.x)
dLdx = np.zeros((T, self.input_size))
self.nodes.reset_error()
for t in xrange(T):
dLdp = dLds[t] * self.acfun.derivate(self.s[t])
self.nodes.dLdu += np.outer(dLdp, self.x[t])
if self.en_bias:
self.nodes... | Feed-forward neural network. | FNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FNN:
"""Feed-forward neural network."""
def update(self, dLds, alpha, beta):
"""Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter"... | stack_v2_sparse_classes_75kplus_train_005636 | 1,800 | permissive | [
{
"docstring": "Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter",
"name": "update",
"signature": "def update(self, dLds, alpha, beta)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_027527 | Implement the Python class `FNN` described below.
Class description:
Feed-forward neural network.
Method signatures and docstrings:
- def update(self, dLds, alpha, beta): Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param al... | Implement the Python class `FNN` described below.
Class description:
Feed-forward neural network.
Method signatures and docstrings:
- def update(self, dLds, alpha, beta): Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param al... | 1a08b12767cf028626f0368b993933092390f28d | <|skeleton|>
class FNN:
"""Feed-forward neural network."""
def update(self, dLds, alpha, beta):
"""Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FNN:
"""Feed-forward neural network."""
def update(self, dLds, alpha, beta):
"""Update neural network's parameters using stochastic gradient descent(SGD) method. :Param dLds: error gradients of hidden layer's outputs. :Param alpha: learning rate :Param beta: regularization parameter"""
T ... | the_stack_v2_python_sparse | nnlm/nnm/fnn.py | dengliangshi/pynnlms | train | 11 |
896a2aec39f22ecabb20de999e5c490d68b13e12 | [
"self.queryFile = os.path.join(os.path.dirname(__file__), 'adh.fasta')\nconfig = Configure()\nself.BLASTDB = config.log['data']",
"self.blast = Blast(self.queryFile)\nstart, stop = (0, 2)\nnewQueryFile = self.blast.get_query_file('.', start, stop)\nqueryFileName = os.path.split(self.queryFile)[-1]\nqueryFilePath ... | <|body_start_0|>
self.queryFile = os.path.join(os.path.dirname(__file__), 'adh.fasta')
config = Configure()
self.BLASTDB = config.log['data']
<|end_body_0|>
<|body_start_1|>
self.blast = Blast(self.queryFile)
start, stop = (0, 2)
newQueryFile = self.blast.get_query_file(... | Run a number of tests using taxa id 7227 | BlastTest | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlastTest:
"""Run a number of tests using taxa id 7227"""
def setUp(self):
"""connect to the database"""
<|body_0|>
def testGetQueryFile(self):
"""test the function breaks the fasta file in to chunks"""
<|body_1|>
def testRunBlastX(self):
"""... | stack_v2_sparse_classes_75kplus_train_005637 | 2,543 | permissive | [
{
"docstring": "connect to the database",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test the function breaks the fasta file in to chunks",
"name": "testGetQueryFile",
"signature": "def testGetQueryFile(self)"
},
{
"docstring": "test running blastx",
"... | 4 | stack_v2_sparse_classes_30k_train_043967 | Implement the Python class `BlastTest` described below.
Class description:
Run a number of tests using taxa id 7227
Method signatures and docstrings:
- def setUp(self): connect to the database
- def testGetQueryFile(self): test the function breaks the fasta file in to chunks
- def testRunBlastX(self): test running bl... | Implement the Python class `BlastTest` described below.
Class description:
Run a number of tests using taxa id 7227
Method signatures and docstrings:
- def setUp(self): connect to the database
- def testGetQueryFile(self): test the function breaks the fasta file in to chunks
- def testRunBlastX(self): test running bl... | a343aff9b833979b4f5d4ba6d16fc2b65d8ccfc1 | <|skeleton|>
class BlastTest:
"""Run a number of tests using taxa id 7227"""
def setUp(self):
"""connect to the database"""
<|body_0|>
def testGetQueryFile(self):
"""test the function breaks the fasta file in to chunks"""
<|body_1|>
def testRunBlastX(self):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlastTest:
"""Run a number of tests using taxa id 7227"""
def setUp(self):
"""connect to the database"""
self.queryFile = os.path.join(os.path.dirname(__file__), 'adh.fasta')
config = Configure()
self.BLASTDB = config.log['data']
def testGetQueryFile(self):
""... | the_stack_v2_python_sparse | unittests/BlastTest.py | changanla/htsint | train | 0 |
2e75f3f70ab13799d3b163d4f2873035a0de5839 | [
"self.text_color = text_color\nLabel.__init__(self, name, text, pygame.rect.Rect((0, 0), (0, 0)))\nreturn",
"if self.text != self.cached_text:\n font_surface = BOLD_FONT.render(self.text, True, (0, 0, 0))\n target_surface = pygame.Surface(font_surface.get_rect().inflate(2, 2).size, flags=pygame.SRCALPHA)\n ... | <|body_start_0|>
self.text_color = text_color
Label.__init__(self, name, text, pygame.rect.Rect((0, 0), (0, 0)))
return
<|end_body_0|>
<|body_start_1|>
if self.text != self.cached_text:
font_surface = BOLD_FONT.render(self.text, True, (0, 0, 0))
target_surface = ... | A Label with outlined text and a transparent background. Additional attributes: OutlinedText.text_color A tuple (R, G, B) holding the color of the text. | OutlinedText | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutlinedText:
"""A Label with outlined text and a transparent background. Additional attributes: OutlinedText.text_color A tuple (R, G, B) holding the color of the text."""
def __init__(self, name, text, text_color=(255, 255, 255)):
"""Initialise the OutlinedText. text is the text to... | stack_v2_sparse_classes_75kplus_train_005638 | 27,668 | permissive | [
{
"docstring": "Initialise the OutlinedText. text is the text to be written on the Label. If text is None, it is replaced by an empty string.",
"name": "__init__",
"signature": "def __init__(self, name, text, text_color=(255, 255, 255))"
},
{
"docstring": "Redraw the Label if necessary.",
"n... | 2 | stack_v2_sparse_classes_30k_train_041687 | Implement the Python class `OutlinedText` described below.
Class description:
A Label with outlined text and a transparent background. Additional attributes: OutlinedText.text_color A tuple (R, G, B) holding the color of the text.
Method signatures and docstrings:
- def __init__(self, name, text, text_color=(255, 255... | Implement the Python class `OutlinedText` described below.
Class description:
A Label with outlined text and a transparent background. Additional attributes: OutlinedText.text_color A tuple (R, G, B) holding the color of the text.
Method signatures and docstrings:
- def __init__(self, name, text, text_color=(255, 255... | c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97 | <|skeleton|>
class OutlinedText:
"""A Label with outlined text and a transparent background. Additional attributes: OutlinedText.text_color A tuple (R, G, B) holding the color of the text."""
def __init__(self, name, text, text_color=(255, 255, 255)):
"""Initialise the OutlinedText. text is the text to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutlinedText:
"""A Label with outlined text and a transparent background. Additional attributes: OutlinedText.text_color A tuple (R, G, B) holding the color of the text."""
def __init__(self, name, text, text_color=(255, 255, 255)):
"""Initialise the OutlinedText. text is the text to be written o... | the_stack_v2_python_sparse | reference_scripts/clickndrag-0.4.1/clickndrag/gui.py | stivosaurus/rpi-snippets | train | 1 |
295bc941790719483fc054a5be6bbcc4758f9ae9 | [
"super().__init__()\nself.cell = SkipGRUCell(input_size, hidden_size)\nself.hidden_size = hidden_size",
"hidden = torch.zeros(input.shape[0], self.hidden_size, device=self.cell.inner_gru.weight_ih.device)\ninputs = input.unbind(1)\nmixtures = mix.unbind(1)\noutputs = jit.annotate(List[Tensor], [])\nfor i in range... | <|body_start_0|>
super().__init__()
self.cell = SkipGRUCell(input_size, hidden_size)
self.hidden_size = hidden_size
<|end_body_0|>
<|body_start_1|>
hidden = torch.zeros(input.shape[0], self.hidden_size, device=self.cell.inner_gru.weight_ih.device)
inputs = input.unbind(1)
... | SkipGRULayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkipGRULayer:
def __init__(self, input_size, hidden_size):
"""Layer consisted of SkipGRU cells. Args: input_size (int): size of input space of GRU hidden_size (int): size of hidden space of GRU"""
<|body_0|>
def forward(self, input, mix):
"""Forward pass on SkipGRU l... | stack_v2_sparse_classes_75kplus_train_005639 | 5,230 | permissive | [
{
"docstring": "Layer consisted of SkipGRU cells. Args: input_size (int): size of input space of GRU hidden_size (int): size of hidden space of GRU",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size)"
},
{
"docstring": "Forward pass on SkipGRU layer. Args: input (torc... | 2 | stack_v2_sparse_classes_30k_train_004837 | Implement the Python class `SkipGRULayer` described below.
Class description:
Implement the SkipGRULayer class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size): Layer consisted of SkipGRU cells. Args: input_size (int): size of input space of GRU hidden_size (int): size of hidden space ... | Implement the Python class `SkipGRULayer` described below.
Class description:
Implement the SkipGRULayer class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size): Layer consisted of SkipGRU cells. Args: input_size (int): size of input space of GRU hidden_size (int): size of hidden space ... | 7c1f37349d464b1b6bf8835520abad22b199f1ad | <|skeleton|>
class SkipGRULayer:
def __init__(self, input_size, hidden_size):
"""Layer consisted of SkipGRU cells. Args: input_size (int): size of input space of GRU hidden_size (int): size of hidden space of GRU"""
<|body_0|>
def forward(self, input, mix):
"""Forward pass on SkipGRU l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SkipGRULayer:
def __init__(self, input_size, hidden_size):
"""Layer consisted of SkipGRU cells. Args: input_size (int): size of input space of GRU hidden_size (int): size of hidden space of GRU"""
super().__init__()
self.cell = SkipGRUCell(input_size, hidden_size)
self.hidden_s... | the_stack_v2_python_sparse | skiprnn.py | ovechkinVT/SkipRNN | train | 1 | |
d3de82d4d3a34bf5e840280b765d2278d5c7d8ff | [
"super(ApplicationLauncher, self).__init__(application_store)\nself.plugin_path = plugin_path\nself.session = session",
"environment = super(ApplicationLauncher, self)._getApplicationEnvironment(application, context)\nentity = context['selection'][0]\ntask = self.session.query('Task where id is \"{}\"'.format(ent... | <|body_start_0|>
super(ApplicationLauncher, self).__init__(application_store)
self.plugin_path = plugin_path
self.session = session
<|end_body_0|>
<|body_start_1|>
environment = super(ApplicationLauncher, self)._getApplicationEnvironment(application, context)
entity = context['s... | Custom launcher to modify environment before launch. | ApplicationLauncher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationLauncher:
"""Custom launcher to modify environment before launch."""
def __init__(self, application_store, plugin_path, session):
"""."""
<|body_0|>
def _getApplicationEnvironment(self, application, context=None):
"""Override to modify environment befo... | stack_v2_sparse_classes_75kplus_train_005640 | 8,470 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, application_store, plugin_path, session)"
},
{
"docstring": "Override to modify environment before launch.",
"name": "_getApplicationEnvironment",
"signature": "def _getApplicationEnvironment(self, application, cont... | 2 | stack_v2_sparse_classes_30k_train_043092 | Implement the Python class `ApplicationLauncher` described below.
Class description:
Custom launcher to modify environment before launch.
Method signatures and docstrings:
- def __init__(self, application_store, plugin_path, session): .
- def _getApplicationEnvironment(self, application, context=None): Override to mo... | Implement the Python class `ApplicationLauncher` described below.
Class description:
Custom launcher to modify environment before launch.
Method signatures and docstrings:
- def __init__(self, application_store, plugin_path, session): .
- def _getApplicationEnvironment(self, application, context=None): Override to mo... | 05beaebfd0d59d8eae31c258e5bd6b93c17e1d5e | <|skeleton|>
class ApplicationLauncher:
"""Custom launcher to modify environment before launch."""
def __init__(self, application_store, plugin_path, session):
"""."""
<|body_0|>
def _getApplicationEnvironment(self, application, context=None):
"""Override to modify environment befo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationLauncher:
"""Custom launcher to modify environment before launch."""
def __init__(self, application_store, plugin_path, session):
"""."""
super(ApplicationLauncher, self).__init__(application_store)
self.plugin_path = plugin_path
self.session = session
def ... | the_stack_v2_python_sparse | resource/hook/ftrack_connect_houdini_hook.py | IngenuityEngine/ftrack-connect-houdini | train | 0 |
9100204240910d332c72742220f6042e659c3d8b | [
"self.source = source\nself.max_sentence_length = max_sentence_length\nself.limit = limit\nself.lowerBound = lowerBound\nself.upperBound = upperBound\nself.corpusSize = 0\nif os.path.isfile(self.source):\n logging.warning('single file read, better to use models.word2vec.LineSentence')\n self.input_files = [se... | <|body_start_0|>
self.source = source
self.max_sentence_length = max_sentence_length
self.limit = limit
self.lowerBound = lowerBound
self.upperBound = upperBound
self.corpusSize = 0
if os.path.isfile(self.source):
logging.warning('single file read, bet... | Simple format: date sentence = one line; words already preprocessed and separated by whitespace. Like LineSentence, but will process all files in a directory in alphabetical order by filename | PathLineSentences_mod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PathLineSentences_mod:
"""Simple format: date sentence = one line; words already preprocessed and separated by whitespace. Like LineSentence, but will process all files in a directory in alphabetical order by filename"""
def __init__(self, source, max_sentence_length=MAX_WORDS_IN_BATCH, limi... | stack_v2_sparse_classes_75kplus_train_005641 | 7,421 | no_license | [
{
"docstring": "`source` should be a path to a directory (as a string) where all files can be opened by the LineSentence class. Each file will be read up to `limit` lines (or no clipped if limit is None, the default). Example:: sentences = LineSentencePath_mod(os.getcwd() + '\\\\corpus\\\\') The files in the di... | 2 | stack_v2_sparse_classes_30k_train_025074 | Implement the Python class `PathLineSentences_mod` described below.
Class description:
Simple format: date sentence = one line; words already preprocessed and separated by whitespace. Like LineSentence, but will process all files in a directory in alphabetical order by filename
Method signatures and docstrings:
- def... | Implement the Python class `PathLineSentences_mod` described below.
Class description:
Simple format: date sentence = one line; words already preprocessed and separated by whitespace. Like LineSentence, but will process all files in a directory in alphabetical order by filename
Method signatures and docstrings:
- def... | cbd9df4feefbff2197484195cd2d98a115074967 | <|skeleton|>
class PathLineSentences_mod:
"""Simple format: date sentence = one line; words already preprocessed and separated by whitespace. Like LineSentence, but will process all files in a directory in alphabetical order by filename"""
def __init__(self, source, max_sentence_length=MAX_WORDS_IN_BATCH, limi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PathLineSentences_mod:
"""Simple format: date sentence = one line; words already preprocessed and separated by whitespace. Like LineSentence, but will process all files in a directory in alphabetical order by filename"""
def __init__(self, source, max_sentence_length=MAX_WORDS_IN_BATCH, limit=None, lower... | the_stack_v2_python_sparse | modules/dsm.py | kicasta/LSCDetection | train | 0 |
c191041baae2927717096453d17cd79a5a2e5fe6 | [
"def helper(left: int, right: int) -> 'TreeNode':\n if left > right:\n return None\n pivot = (left + right) // 2\n if (left + right) % 2:\n pivot += randint(0, 1)\n root = TreeNode(nums[pivot])\n root.left = helper(left, pivot - 1)\n root.right = helper(pivot + 1, right)\n return ... | <|body_start_0|>
def helper(left: int, right: int) -> 'TreeNode':
if left > right:
return None
pivot = (left + right) // 2
if (left + right) % 2:
pivot += randint(0, 1)
root = TreeNode(nums[pivot])
root.left = helper(lef... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def convert_to_bst__(self, nums: List[int]) -> 'TreeNode':
"""Approach: Recursion: Pre-order: choose rand int from 0 to 1 Time Complexity: O(N) Space Complexity: O(N) to store and O(log N) for recursion stack. :param nums: :return:"""
<|body_0|>
def convert_to_bst_(se... | stack_v2_sparse_classes_75kplus_train_005642 | 2,848 | no_license | [
{
"docstring": "Approach: Recursion: Pre-order: choose rand int from 0 to 1 Time Complexity: O(N) Space Complexity: O(N) to store and O(log N) for recursion stack. :param nums: :return:",
"name": "convert_to_bst__",
"signature": "def convert_to_bst__(self, nums: List[int]) -> 'TreeNode'"
},
{
"d... | 3 | null | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def convert_to_bst__(self, nums: List[int]) -> 'TreeNode': Approach: Recursion: Pre-order: choose rand int from 0 to 1 Time Complexity: O(N) Space Complexity: O(N) to store and O(log N... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def convert_to_bst__(self, nums: List[int]) -> 'TreeNode': Approach: Recursion: Pre-order: choose rand int from 0 to 1 Time Complexity: O(N) Space Complexity: O(N) to store and O(log N... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def convert_to_bst__(self, nums: List[int]) -> 'TreeNode':
"""Approach: Recursion: Pre-order: choose rand int from 0 to 1 Time Complexity: O(N) Space Complexity: O(N) to store and O(log N) for recursion stack. :param nums: :return:"""
<|body_0|>
def convert_to_bst_(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Array:
def convert_to_bst__(self, nums: List[int]) -> 'TreeNode':
"""Approach: Recursion: Pre-order: choose rand int from 0 to 1 Time Complexity: O(N) Space Complexity: O(N) to store and O(log N) for recursion stack. :param nums: :return:"""
def helper(left: int, right: int) -> 'TreeNode':
... | the_stack_v2_python_sparse | revisited/trees/convert_sorted_array_to_binary.py | Shiv2157k/leet_code | train | 1 | |
e3f4f19eb4c51975074cc592be1ff36169dafea1 | [
"try:\n self.file = open(self.fpath, 'r')\n cfg = pickle.load(self.file)\n self.file.close()\nexcept Exception as e:\n return (False, [str(e)])\nreturn (True, cfg)",
"try:\n self.file = open(self.fpath, 'w')\n pickle.dump(cfg, self.file)\n self.file.close()\nexcept Exception as e:\n return... | <|body_start_0|>
try:
self.file = open(self.fpath, 'r')
cfg = pickle.load(self.file)
self.file.close()
except Exception as e:
return (False, [str(e)])
return (True, cfg)
<|end_body_0|>
<|body_start_1|>
try:
self.file = open(sel... | pickle format | pickle_config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pickle_config:
"""pickle format"""
def do_load(self):
"""load from a file"""
<|body_0|>
def do_dump(self, cfg={}):
"""dump to a file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.file = open(self.fpath, 'r')
c... | stack_v2_sparse_classes_75kplus_train_005643 | 5,111 | no_license | [
{
"docstring": "load from a file",
"name": "do_load",
"signature": "def do_load(self)"
},
{
"docstring": "dump to a file",
"name": "do_dump",
"signature": "def do_dump(self, cfg={})"
}
] | 2 | stack_v2_sparse_classes_30k_train_013968 | Implement the Python class `pickle_config` described below.
Class description:
pickle format
Method signatures and docstrings:
- def do_load(self): load from a file
- def do_dump(self, cfg={}): dump to a file | Implement the Python class `pickle_config` described below.
Class description:
pickle format
Method signatures and docstrings:
- def do_load(self): load from a file
- def do_dump(self, cfg={}): dump to a file
<|skeleton|>
class pickle_config:
"""pickle format"""
def do_load(self):
"""load from a fil... | 12a25d06c8ea7971267aca43a63aafb71b29a3f1 | <|skeleton|>
class pickle_config:
"""pickle format"""
def do_load(self):
"""load from a file"""
<|body_0|>
def do_dump(self, cfg={}):
"""dump to a file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class pickle_config:
"""pickle format"""
def do_load(self):
"""load from a file"""
try:
self.file = open(self.fpath, 'r')
cfg = pickle.load(self.file)
self.file.close()
except Exception as e:
return (False, [str(e)])
return (True, ... | the_stack_v2_python_sparse | ml_config.py | poyhsiao/betapyweb-middleware | train | 0 |
e43616c4e676a8bfe77650d13ac0d1329ab880e7 | [
"username = get_jwt_identity()\nlist_object = list_controller.get_list_by_id(list_id, username)\nif not list_object:\n return ('', 404)\nlist_dto = list_schema.serialize_list(list_object)\nresponse = Response(response=json.dumps(list_dto), status=200, mimetype='application/json')\nreturn response",
"username =... | <|body_start_0|>
username = get_jwt_identity()
list_object = list_controller.get_list_by_id(list_id, username)
if not list_object:
return ('', 404)
list_dto = list_schema.serialize_list(list_object)
response = Response(response=json.dumps(list_dto), status=200, mimety... | ListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListResource:
def get(self, list_id):
"""Receives a list id and returns the list if available"""
<|body_0|>
def post(self):
"""Create a list for a user"""
<|body_1|>
def delete(self, list_id):
"""Delete a list"""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_005644 | 3,243 | no_license | [
{
"docstring": "Receives a list id and returns the list if available",
"name": "get",
"signature": "def get(self, list_id)"
},
{
"docstring": "Create a list for a user",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Delete a list",
"name": "delete",
"si... | 3 | stack_v2_sparse_classes_30k_train_044539 | Implement the Python class `ListResource` described below.
Class description:
Implement the ListResource class.
Method signatures and docstrings:
- def get(self, list_id): Receives a list id and returns the list if available
- def post(self): Create a list for a user
- def delete(self, list_id): Delete a list | Implement the Python class `ListResource` described below.
Class description:
Implement the ListResource class.
Method signatures and docstrings:
- def get(self, list_id): Receives a list id and returns the list if available
- def post(self): Create a list for a user
- def delete(self, list_id): Delete a list
<|skel... | e0c8ea99886f10aea14b9ca95af8a4f42f2af493 | <|skeleton|>
class ListResource:
def get(self, list_id):
"""Receives a list id and returns the list if available"""
<|body_0|>
def post(self):
"""Create a list for a user"""
<|body_1|>
def delete(self, list_id):
"""Delete a list"""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListResource:
def get(self, list_id):
"""Receives a list id and returns the list if available"""
username = get_jwt_identity()
list_object = list_controller.get_list_by_id(list_id, username)
if not list_object:
return ('', 404)
list_dto = list_schema.seriali... | the_stack_v2_python_sparse | imdb_api/resources/list_resources.py | Matiasmoratti7/imdb | train | 0 | |
abfa9b2a721a4235e10bffb7948f549d7556581c | [
"self.log_file = None\nfiles = glob.glob(LOG_DIR + '*')\nif len(files):\n index = int(max(files)[len(LOG_DIR):-4]) + 1\n if index < 10:\n index = '0' + str(index)\n else:\n index = str(index)\n file_name = LOG_DIR + index + '.txt'\nelse:\n file_name = LOG_DIR + '01.txt'\nself.log_file =... | <|body_start_0|>
self.log_file = None
files = glob.glob(LOG_DIR + '*')
if len(files):
index = int(max(files)[len(LOG_DIR):-4]) + 1
if index < 10:
index = '0' + str(index)
else:
index = str(index)
file_name = LOG_DIR ... | Class that performs all logging in game | Logger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
"""Class that performs all logging in game"""
def __init__(self):
"""(self) -> None Initialization and new file creation"""
<|body_0|>
def append(self, line, console=True, log=True):
"""(str, bool, bool) -> None Adds line in log and Python console."""
... | stack_v2_sparse_classes_75kplus_train_005645 | 8,168 | no_license | [
{
"docstring": "(self) -> None Initialization and new file creation",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "(str, bool, bool) -> None Adds line in log and Python console.",
"name": "append",
"signature": "def append(self, line, console=True, log=True)"
... | 3 | null | Implement the Python class `Logger` described below.
Class description:
Class that performs all logging in game
Method signatures and docstrings:
- def __init__(self): (self) -> None Initialization and new file creation
- def append(self, line, console=True, log=True): (str, bool, bool) -> None Adds line in log and P... | Implement the Python class `Logger` described below.
Class description:
Class that performs all logging in game
Method signatures and docstrings:
- def __init__(self): (self) -> None Initialization and new file creation
- def append(self, line, console=True, log=True): (str, bool, bool) -> None Adds line in log and P... | 447b365cd147a04f9b1c4a6576699e207e657354 | <|skeleton|>
class Logger:
"""Class that performs all logging in game"""
def __init__(self):
"""(self) -> None Initialization and new file creation"""
<|body_0|>
def append(self, line, console=True, log=True):
"""(str, bool, bool) -> None Adds line in log and Python console."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
"""Class that performs all logging in game"""
def __init__(self):
"""(self) -> None Initialization and new file creation"""
self.log_file = None
files = glob.glob(LOG_DIR + '*')
if len(files):
index = int(max(files)[len(LOG_DIR):-4]) + 1
if ... | the_stack_v2_python_sparse | source/tools.py | VadimKovalchuk/StoneAge-legacy | train | 0 |
e0bc3d590ef06e5afc258094d3feda0fe3efe2d6 | [
"data_sorted = False\nplot_options[CONFIG] = add_config_defaults(plot_options.get(CONFIG, {}))\nif visualization_options and GROUPBY in visualization_options:\n plot_options[LAYOUT] = add_toggle_layout_button(plot_options.get(LAYOUT, {}))\nfor index, plotly_data_dict in enumerate(plot_options[DATA]):\n if not... | <|body_start_0|>
data_sorted = False
plot_options[CONFIG] = add_config_defaults(plot_options.get(CONFIG, {}))
if visualization_options and GROUPBY in visualization_options:
plot_options[LAYOUT] = add_toggle_layout_button(plot_options.get(LAYOUT, {}))
for index, plotly_data_di... | PlotlyPlot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotlyPlot:
def make_dict_for_html_plot(data, plot_options, visualization_options=None):
"""Makes the json file that plotly takes in :param data: a pandas dataframe :param axis_to_data_columns: :param plot_options: :param visualization_options: :return:"""
<|body_0|>
def get... | stack_v2_sparse_classes_75kplus_train_005646 | 10,052 | permissive | [
{
"docstring": "Makes the json file that plotly takes in :param data: a pandas dataframe :param axis_to_data_columns: :param plot_options: :param visualization_options: :return:",
"name": "make_dict_for_html_plot",
"signature": "def make_dict_for_html_plot(data, plot_options, visualization_options=None)... | 2 | null | Implement the Python class `PlotlyPlot` described below.
Class description:
Implement the PlotlyPlot class.
Method signatures and docstrings:
- def make_dict_for_html_plot(data, plot_options, visualization_options=None): Makes the json file that plotly takes in :param data: a pandas dataframe :param axis_to_data_colu... | Implement the Python class `PlotlyPlot` described below.
Class description:
Implement the PlotlyPlot class.
Method signatures and docstrings:
- def make_dict_for_html_plot(data, plot_options, visualization_options=None): Makes the json file that plotly takes in :param data: a pandas dataframe :param axis_to_data_colu... | d4adb7901fc9e5b5e3ba316192a7e4e0468b80ac | <|skeleton|>
class PlotlyPlot:
def make_dict_for_html_plot(data, plot_options, visualization_options=None):
"""Makes the json file that plotly takes in :param data: a pandas dataframe :param axis_to_data_columns: :param plot_options: :param visualization_options: :return:"""
<|body_0|>
def get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotlyPlot:
def make_dict_for_html_plot(data, plot_options, visualization_options=None):
"""Makes the json file that plotly takes in :param data: a pandas dataframe :param axis_to_data_columns: :param plot_options: :param visualization_options: :return:"""
data_sorted = False
plot_opti... | the_stack_v2_python_sparse | escalation/graphics/plotly_plot.py | syedpeer/Escalation | train | 0 | |
0a0eade6fafb4cc8a63f31c2ee9a2ddf9e64020d | [
"s = set()\nfor num in nums:\n if num in s:\n return num\n else:\n s.add(num)\nreturn None",
"lo = 1\nhi = len(nums)\nwhile lo < hi:\n mid = lo + (hi - lo) / 2\n cnt = 0\n for num in nums:\n if num <= mid:\n cnt += 1\n if cnt <= mid:\n lo = mid + 1\n els... | <|body_start_0|>
s = set()
for num in nums:
if num in s:
return num
else:
s.add(num)
return None
<|end_body_0|>
<|body_start_1|>
lo = 1
hi = len(nums)
while lo < hi:
mid = lo + (hi - lo) / 2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
"""用集合记录出现过的数字,set 比 list 快 :type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
"""基于值的二分法: 因为数都在 [1,n] 之间,二分搜索, 统计列表中和 mid 相比的数量。 :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_005647 | 2,001 | no_license | [
{
"docstring": "用集合记录出现过的数字,set 比 list 快 :type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": "基于值的二分法: 因为数都在 [1,n] 之间,二分搜索, 统计列表中和 mid 相比的数量。 :type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_046268 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): 用集合记录出现过的数字,set 比 list 快 :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): 基于值的二分法: 因为数都在 [1,n] 之间,二分搜索, 统计列表中和 mid 相比的数量。 :type n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): 用集合记录出现过的数字,set 比 list 快 :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): 基于值的二分法: 因为数都在 [1,n] 之间,二分搜索, 统计列表中和 mid 相比的数量。 :type n... | 860590239da0618c52967a55eda8d6bbe00bfa96 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
"""用集合记录出现过的数字,set 比 list 快 :type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
"""基于值的二分法: 因为数都在 [1,n] 之间,二分搜索, 统计列表中和 mid 相比的数量。 :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicate(self, nums):
"""用集合记录出现过的数字,set 比 list 快 :type nums: List[int] :rtype: int"""
s = set()
for num in nums:
if num in s:
return num
else:
s.add(num)
return None
def findDuplicate(self, nums):
... | the_stack_v2_python_sparse | LeetCode/p0287/I/find-the-duplicate-number.py | Ynjxsjmh/PracticeMakesPerfect | train | 0 | |
a0b1525c6d9b870087b3485a44b80141c555c98d | [
"self.__users = []\nself.__lookup = set()\nself.__min_heap = []",
"if self.__min_heap:\n userID = heapq.heappop(self.__min_heap)\nelse:\n userID = len(self.__users) + 1\n self.__users.append(set())\nself.__users[userID - 1] = set(ownedChunks)\nself.__lookup.add(userID)\nreturn userID",
"if userID not i... | <|body_start_0|>
self.__users = []
self.__lookup = set()
self.__min_heap = []
<|end_body_0|>
<|body_start_1|>
if self.__min_heap:
userID = heapq.heappop(self.__min_heap)
else:
userID = len(self.__users) + 1
self.__users.append(set())
s... | FileSharing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSharing:
def __init__(self, m):
""":type m: int"""
<|body_0|>
def join(self, ownedChunks):
""":type ownedChunks: List[int] :rtype: int"""
<|body_1|>
def leave(self, userID):
""":type userID: int :rtype: None"""
<|body_2|>
def req... | stack_v2_sparse_classes_75kplus_train_005648 | 3,320 | permissive | [
{
"docstring": ":type m: int",
"name": "__init__",
"signature": "def __init__(self, m)"
},
{
"docstring": ":type ownedChunks: List[int] :rtype: int",
"name": "join",
"signature": "def join(self, ownedChunks)"
},
{
"docstring": ":type userID: int :rtype: None",
"name": "leave"... | 4 | stack_v2_sparse_classes_30k_val_002809 | Implement the Python class `FileSharing` described below.
Class description:
Implement the FileSharing class.
Method signatures and docstrings:
- def __init__(self, m): :type m: int
- def join(self, ownedChunks): :type ownedChunks: List[int] :rtype: int
- def leave(self, userID): :type userID: int :rtype: None
- def ... | Implement the Python class `FileSharing` described below.
Class description:
Implement the FileSharing class.
Method signatures and docstrings:
- def __init__(self, m): :type m: int
- def join(self, ownedChunks): :type ownedChunks: List[int] :rtype: int
- def leave(self, userID): :type userID: int :rtype: None
- def ... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class FileSharing:
def __init__(self, m):
""":type m: int"""
<|body_0|>
def join(self, ownedChunks):
""":type ownedChunks: List[int] :rtype: int"""
<|body_1|>
def leave(self, userID):
""":type userID: int :rtype: None"""
<|body_2|>
def req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileSharing:
def __init__(self, m):
""":type m: int"""
self.__users = []
self.__lookup = set()
self.__min_heap = []
def join(self, ownedChunks):
""":type ownedChunks: List[int] :rtype: int"""
if self.__min_heap:
userID = heapq.heappop(self.__min... | the_stack_v2_python_sparse | Python/design-a-file-sharing-system.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
741aa2cf730306226ab31e5f0ab0cbf634ab4849 | [
"self.object = None\nformclass = self.get_form_class()\nform = self.get_form(formclass)\npermisos = request.user.get_nombres_permisos()\nreturn self.render_to_response(self.get_context_data(form=form, permisos=permisos))",
"context = super().get_context_data(**kwargs)\ncontext['title'] = 'Crear Rol'\nreturn conte... | <|body_start_0|>
self.object = None
formclass = self.get_form_class()
form = self.get_form(formclass)
permisos = request.user.get_nombres_permisos()
return self.render_to_response(self.get_context_data(form=form, permisos=permisos))
<|end_body_0|>
<|body_start_1|>
contex... | Clase de la vista para la creacion de un nuevo Rol | CreateRolView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRolView:
"""Clase de la vista para la creacion de un nuevo Rol"""
def get(self, request, *args, **kwargs):
"""Metodo que es ejecutado al darse una consulta GET :param request: consulta recibida :param args: argumentos adicionales :param kwargs: diccionario de datos adicionales ... | stack_v2_sparse_classes_75kplus_train_005649 | 7,974 | no_license | [
{
"docstring": "Metodo que es ejecutado al darse una consulta GET :param request: consulta recibida :param args: argumentos adicionales :param kwargs: diccionario de datos adicionales :return: la respuesta a la consulta GET",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{... | 3 | null | Implement the Python class `CreateRolView` described below.
Class description:
Clase de la vista para la creacion de un nuevo Rol
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Metodo que es ejecutado al darse una consulta GET :param request: consulta recibida :param args: argumentos adi... | Implement the Python class `CreateRolView` described below.
Class description:
Clase de la vista para la creacion de un nuevo Rol
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Metodo que es ejecutado al darse una consulta GET :param request: consulta recibida :param args: argumentos adi... | 467be7bd8babccf4e1af89c956efc8e53abc4122 | <|skeleton|>
class CreateRolView:
"""Clase de la vista para la creacion de un nuevo Rol"""
def get(self, request, *args, **kwargs):
"""Metodo que es ejecutado al darse una consulta GET :param request: consulta recibida :param args: argumentos adicionales :param kwargs: diccionario de datos adicionales ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateRolView:
"""Clase de la vista para la creacion de un nuevo Rol"""
def get(self, request, *args, **kwargs):
"""Metodo que es ejecutado al darse una consulta GET :param request: consulta recibida :param args: argumentos adicionales :param kwargs: diccionario de datos adicionales :return: la r... | the_stack_v2_python_sparse | rol/views.py | vgarcete98/IS2 | train | 0 |
0e576c7d2279bc51d28a272d7f10e6d5dd985427 | [
"self.tweets_list = tweets_list\nself.counts_dict = counts_dict\nself.topic = topic\nself.TWEET_LIMIT = limit\nsuper().__init__(api)",
"tweet_data = get_tweet_content(status, location=True)\nif tweet_data['text'].startswith('RT') or self.topic.lower() not in tweet_data['text'].lower():\n return\nself.counts_di... | <|body_start_0|>
self.tweets_list = tweets_list
self.counts_dict = counts_dict
self.topic = topic
self.TWEET_LIMIT = limit
super().__init__(api)
<|end_body_0|>
<|body_start_1|>
tweet_data = get_tweet_content(status, location=True)
if tweet_data['text'].startswith... | Handles incoming Tweet stream to get location data. | LocationListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationListener:
"""Handles incoming Tweet stream to get location data."""
def __init__(self, api, counts_dict, tweets_list, topic, limit=10):
"""Configure the LocationListener."""
<|body_0|>
def on_status(self, status):
"""Called when Twitter pushes a new tweet... | stack_v2_sparse_classes_75kplus_train_005650 | 2,613 | no_license | [
{
"docstring": "Configure the LocationListener.",
"name": "__init__",
"signature": "def __init__(self, api, counts_dict, tweets_list, topic, limit=10)"
},
{
"docstring": "Called when Twitter pushes a new tweet to you.",
"name": "on_status",
"signature": "def on_status(self, status)"
}
... | 2 | stack_v2_sparse_classes_30k_train_050319 | Implement the Python class `LocationListener` described below.
Class description:
Handles incoming Tweet stream to get location data.
Method signatures and docstrings:
- def __init__(self, api, counts_dict, tweets_list, topic, limit=10): Configure the LocationListener.
- def on_status(self, status): Called when Twitt... | Implement the Python class `LocationListener` described below.
Class description:
Handles incoming Tweet stream to get location data.
Method signatures and docstrings:
- def __init__(self, api, counts_dict, tweets_list, topic, limit=10): Configure the LocationListener.
- def on_status(self, status): Called when Twitt... | 5db8bb69e55455f3fd4399c691a2b53c073c8377 | <|skeleton|>
class LocationListener:
"""Handles incoming Tweet stream to get location data."""
def __init__(self, api, counts_dict, tweets_list, topic, limit=10):
"""Configure the LocationListener."""
<|body_0|>
def on_status(self, status):
"""Called when Twitter pushes a new tweet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocationListener:
"""Handles incoming Tweet stream to get location data."""
def __init__(self, api, counts_dict, tweets_list, topic, limit=10):
"""Configure the LocationListener."""
self.tweets_list = tweets_list
self.counts_dict = counts_dict
self.topic = topic
se... | the_stack_v2_python_sparse | IntroToPythonSlides/ch13/locationlistener.py | Cocowtk/Intro-to-Python | train | 1 |
043aed6fda459e543e4cdaf58ad8e81d98c6b64d | [
"super(FCN, self).__init__()\nself.fcn = nn.Linear(cin, cout)\nself.dropout = nn.Dropout()",
"x = self.fcn(x)\nx = self.dropout(x)\nreturn x"
] | <|body_start_0|>
super(FCN, self).__init__()
self.fcn = nn.Linear(cin, cout)
self.dropout = nn.Dropout()
<|end_body_0|>
<|body_start_1|>
x = self.fcn(x)
x = self.dropout(x)
return x
<|end_body_1|>
| FCN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCN:
def __init__(self, cin, cout):
"""全连接层"""
<|body_0|>
def forward(self, x):
"""全连接层训练数据 :param x: 输入数据 :return: 训练结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(FCN, self).__init__()
self.fcn = nn.Linear(cin, cout)
self... | stack_v2_sparse_classes_75kplus_train_005651 | 12,220 | no_license | [
{
"docstring": "全连接层",
"name": "__init__",
"signature": "def __init__(self, cin, cout)"
},
{
"docstring": "全连接层训练数据 :param x: 输入数据 :return: 训练结果",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014196 | Implement the Python class `FCN` described below.
Class description:
Implement the FCN class.
Method signatures and docstrings:
- def __init__(self, cin, cout): 全连接层
- def forward(self, x): 全连接层训练数据 :param x: 输入数据 :return: 训练结果 | Implement the Python class `FCN` described below.
Class description:
Implement the FCN class.
Method signatures and docstrings:
- def __init__(self, cin, cout): 全连接层
- def forward(self, x): 全连接层训练数据 :param x: 输入数据 :return: 训练结果
<|skeleton|>
class FCN:
def __init__(self, cin, cout):
"""全连接层"""
<|... | b26ee9b3744e7b34f10715bbd1685f6f0db5867e | <|skeleton|>
class FCN:
def __init__(self, cin, cout):
"""全连接层"""
<|body_0|>
def forward(self, x):
"""全连接层训练数据 :param x: 输入数据 :return: 训练结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FCN:
def __init__(self, cin, cout):
"""全连接层"""
super(FCN, self).__init__()
self.fcn = nn.Linear(cin, cout)
self.dropout = nn.Dropout()
def forward(self, x):
"""全连接层训练数据 :param x: 输入数据 :return: 训练结果"""
x = self.fcn(x)
x = self.dropout(x)
retu... | the_stack_v2_python_sparse | model/octreeNet.py | befallenStar/molecularOctree | train | 0 | |
15ed22f7fffd066270fb8d0534cc859287a9c769 | [
"super().__init__(x, y)\nself.fill_color = QtCore.Qt.green\nself.line_color = QtCore.Qt.red\nself.center_x = self.x\nself.center_y = self.y\nself.time = random.randint(0, 360)\nself.radius = random.randint(10, 20)",
"self.time += 1\nself.x = math.sin(math.radians(self.time)) * self.radius + self.center_x\nself.y ... | <|body_start_0|>
super().__init__(x, y)
self.fill_color = QtCore.Qt.green
self.line_color = QtCore.Qt.red
self.center_x = self.x
self.center_y = self.y
self.time = random.randint(0, 360)
self.radius = random.randint(10, 20)
<|end_body_0|>
<|body_start_1|>
... | Class to represent a Hummingbird. | Hummingbird | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hummingbird:
"""Class to represent a Hummingbird."""
def __init__(self, x, y):
"""Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):... | stack_v2_sparse_classes_75kplus_train_005652 | 13,878 | no_license | [
{
"docstring": "Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "A Hummingbird flies in a circle centered arou... | 2 | stack_v2_sparse_classes_30k_train_025021 | Implement the Python class `Hummingbird` described below.
Class description:
Class to represent a Hummingbird.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default ... | Implement the Python class `Hummingbird` described below.
Class description:
Class to represent a Hummingbird.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default ... | 0e3470085083012f893adb22aa46d46039016965 | <|skeleton|>
class Hummingbird:
"""Class to represent a Hummingbird."""
def __init__(self, x, y):
"""Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hummingbird:
"""Class to represent a Hummingbird."""
def __init__(self, x, y):
"""Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
super().__init__(x, y)
self.fill_color = Q... | the_stack_v2_python_sparse | CS_210 (Introduction to Programming)/Labs/Lab34_AviaryApp.py | JacobOrner/USAFA | train | 0 |
a6b53bbce22d2a29aa6059f3beb983ced413a94a | [
"y = np.array(y)\ny = np.argmax(y, axis=2)[:, 0]\nreturn ''.join([Config.LABEL_LIST[x] for x in y])",
"x = np.zeros((1, height, width, channel), dtype=np.float32)\nimage = Image.open(BytesIO(imageByte)).convert('RGB')\nimage = ConvertFormat.convertImageFormat(image)\nimage = image.resize((width, height), Image.AN... | <|body_start_0|>
y = np.array(y)
y = np.argmax(y, axis=2)[:, 0]
return ''.join([Config.LABEL_LIST[x] for x in y])
<|end_body_0|>
<|body_start_1|>
x = np.zeros((1, height, width, channel), dtype=np.float32)
image = Image.open(BytesIO(imageByte)).convert('RGB')
image = Con... | PreprocessingCaptcha | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessingCaptcha:
def decode(cls, y: list) -> str:
"""decode np array predict result to string"""
<|body_0|>
def loadData(cls, imageByte: bytes, height: int, width: int, channel: int):
"""load data from image byte to np array"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_005653 | 1,102 | permissive | [
{
"docstring": "decode np array predict result to string",
"name": "decode",
"signature": "def decode(cls, y: list) -> str"
},
{
"docstring": "load data from image byte to np array",
"name": "loadData",
"signature": "def loadData(cls, imageByte: bytes, height: int, width: int, channel: i... | 2 | stack_v2_sparse_classes_30k_train_050566 | Implement the Python class `PreprocessingCaptcha` described below.
Class description:
Implement the PreprocessingCaptcha class.
Method signatures and docstrings:
- def decode(cls, y: list) -> str: decode np array predict result to string
- def loadData(cls, imageByte: bytes, height: int, width: int, channel: int): lo... | Implement the Python class `PreprocessingCaptcha` described below.
Class description:
Implement the PreprocessingCaptcha class.
Method signatures and docstrings:
- def decode(cls, y: list) -> str: decode np array predict result to string
- def loadData(cls, imageByte: bytes, height: int, width: int, channel: int): lo... | c03550dc5583b435192f220f871c71cabadd3e39 | <|skeleton|>
class PreprocessingCaptcha:
def decode(cls, y: list) -> str:
"""decode np array predict result to string"""
<|body_0|>
def loadData(cls, imageByte: bytes, height: int, width: int, channel: int):
"""load data from image byte to np array"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreprocessingCaptcha:
def decode(cls, y: list) -> str:
"""decode np array predict result to string"""
y = np.array(y)
y = np.argmax(y, axis=2)[:, 0]
return ''.join([Config.LABEL_LIST[x] for x in y])
def loadData(cls, imageByte: bytes, height: int, width: int, channel: int)... | the_stack_v2_python_sparse | controller/PreprocessingCaptcha.py | wudinaonao/FlaskMark12306Captcha | train | 1 | |
3d66ddf2bf6f83ea923cb661b9350f3ab2e4c3ed | [
"n = len(values)\nif n <= 2:\n return True\nF = [[0 for _ in xrange(n)] for _ in xrange(2)]\ns = [0 for _ in xrange(n)]\ns[n - 1] = values[n - 1]\nfor i in xrange(n - 2, -1, -1):\n s[i] = values[i] + s[i + 1]\nF[0][n - 1] = F[1][n - 1] = s[n - 1]\nF[0][n - 2] = F[1][n - 2] = s[n - 2]\nfor i in xrange(n - 3, -... | <|body_start_0|>
n = len(values)
if n <= 2:
return True
F = [[0 for _ in xrange(n)] for _ in xrange(2)]
s = [0 for _ in xrange(n)]
s[n - 1] = values[n - 1]
for i in xrange(n - 2, -1, -1):
s[i] = values[i] + s[i + 1]
F[0][n - 1] = F[1][n - 1... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstWillWin_MLE(self, values):
"""Starting from back Memory Limit Exceeded let F_i^p represents maximum values he can get at index i, for the person p. F_i^0 = max(A_i + sum - F_{i+1}^1, # if choose one coin A_i + A_{i+1} + sum - F_{i+2}^1 # if choose two coin ) :param val... | stack_v2_sparse_classes_75kplus_train_005654 | 2,772 | permissive | [
{
"docstring": "Starting from back Memory Limit Exceeded let F_i^p represents maximum values he can get at index i, for the person p. F_i^0 = max(A_i + sum - F_{i+1}^1, # if choose one coin A_i + A_{i+1} + sum - F_{i+2}^1 # if choose two coin ) :param values: a list of integers :return: a boolean which equals t... | 2 | stack_v2_sparse_classes_30k_train_016701 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstWillWin_MLE(self, values): Starting from back Memory Limit Exceeded let F_i^p represents maximum values he can get at index i, for the person p. F_i^0 = max(A_i + sum - ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstWillWin_MLE(self, values): Starting from back Memory Limit Exceeded let F_i^p represents maximum values he can get at index i, for the person p. F_i^0 = max(A_i + sum - ... | 4629a3857b2c57418b86a3b3a7180ecb15e763e3 | <|skeleton|>
class Solution:
def firstWillWin_MLE(self, values):
"""Starting from back Memory Limit Exceeded let F_i^p represents maximum values he can get at index i, for the person p. F_i^0 = max(A_i + sum - F_{i+1}^1, # if choose one coin A_i + A_{i+1} + sum - F_{i+2}^1 # if choose two coin ) :param val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstWillWin_MLE(self, values):
"""Starting from back Memory Limit Exceeded let F_i^p represents maximum values he can get at index i, for the person p. F_i^0 = max(A_i + sum - F_{i+1}^1, # if choose one coin A_i + A_{i+1} + sum - F_{i+2}^1 # if choose two coin ) :param values: a list of... | the_stack_v2_python_sparse | Coins in a Line II.py | RijuDasgupta9116/LintCode | train | 0 | |
392e13a14c9614d39a6ae478afd18406c5ce23eb | [
"print('Received GET on resource /books')\nargs = query_parser.parse_args()\nlist_of_books = BookChecker.get_books(args)\nreturn (list_of_books, 200)",
"print('Received POST on resource /book')\nrequest_body = request.get_json()\na_book = BookChecker.create_book(request_body)\nreturn (a_book, 201)"
] | <|body_start_0|>
print('Received GET on resource /books')
args = query_parser.parse_args()
list_of_books = BookChecker.get_books(args)
return (list_of_books, 200)
<|end_body_0|>
<|body_start_1|>
print('Received POST on resource /book')
request_body = request.get_json()
... | Books | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Books:
def get(self):
"""Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject,... | stack_v2_sparse_classes_75kplus_train_005655 | 14,158 | no_license | [
{
"docstring": "Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject, genre. :return: JSON List of boo... | 2 | stack_v2_sparse_classes_30k_train_013945 | Implement the Python class `Books` described below.
Class description:
Implement the Books class.
Method signatures and docstrings:
- def get(self): Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_... | Implement the Python class `Books` described below.
Class description:
Implement the Books class.
Method signatures and docstrings:
- def get(self): Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_... | 4c3fdf41a43a56c253faecacac5f9d977d9c99be | <|skeleton|>
class Books:
def get(self):
"""Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Books:
def get(self):
"""Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject, genre. :retur... | the_stack_v2_python_sparse | apis/books_api.py | neu-seattle-cs5500-fall18/book-library-web-service-scrumptious | train | 0 | |
81849e3d65ced44702ce74452740d6a4d2d74ca6 | [
"self._product = kwargs.pop('product', None)\nself._to_cart = kwargs.pop('to_cart')\nsuper().__init__(*args, **kwargs)\nif args[0] is not None and args[0].get('sku', None):\n return\ndel self.fields['sku']\noption_fields = ProductVariation.option_fields()\nif not option_fields:\n return\noption_names, option_... | <|body_start_0|>
self._product = kwargs.pop('product', None)
self._to_cart = kwargs.pop('to_cart')
super().__init__(*args, **kwargs)
if args[0] is not None and args[0].get('sku', None):
return
del self.fields['sku']
option_fields = ProductVariation.option_fiel... | A form for adding the given product to the cart or the wishlist. | AddProductForm | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddProductForm:
"""A form for adding the given product to the cart or the wishlist."""
def __init__(self, *args, **kwargs):
"""Handles adding a variation to the cart or wishlist. When adding from the product page, the product is provided from the view and a set of choice fields for a... | stack_v2_sparse_classes_75kplus_train_005656 | 21,988 | permissive | [
{
"docstring": "Handles adding a variation to the cart or wishlist. When adding from the product page, the product is provided from the view and a set of choice fields for all the product options for this product's variations are added to the form. When the form is validated, the selected options are used to de... | 2 | stack_v2_sparse_classes_30k_train_036353 | Implement the Python class `AddProductForm` described below.
Class description:
A form for adding the given product to the cart or the wishlist.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Handles adding a variation to the cart or wishlist. When adding from the product page, the product i... | Implement the Python class `AddProductForm` described below.
Class description:
A form for adding the given product to the cart or the wishlist.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Handles adding a variation to the cart or wishlist. When adding from the product page, the product i... | 065c9b71ec67141040c424ab3c26a17410581a43 | <|skeleton|>
class AddProductForm:
"""A form for adding the given product to the cart or the wishlist."""
def __init__(self, *args, **kwargs):
"""Handles adding a variation to the cart or wishlist. When adding from the product page, the product is provided from the view and a set of choice fields for a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddProductForm:
"""A form for adding the given product to the cart or the wishlist."""
def __init__(self, *args, **kwargs):
"""Handles adding a variation to the cart or wishlist. When adding from the product page, the product is provided from the view and a set of choice fields for all the produc... | the_stack_v2_python_sparse | cartridge/shop/forms.py | stephenmcd/cartridge | train | 477 |
82b718fc5568fefec52c88d1daf3e8211d634204 | [
"self.master = master\nmaster.title('Choose the G Code...')\nself.label = Label(master, text='Press to choose file whenever you are ready!')\nself.label.pack()\nself.choose_button = Button(master, text='Choose File', command=self.chooseFile)\nself.choose_button.pack()\nself.cancel_button = Button(master, text='Canc... | <|body_start_0|>
self.master = master
master.title('Choose the G Code...')
self.label = Label(master, text='Press to choose file whenever you are ready!')
self.label.pack()
self.choose_button = Button(master, text='Choose File', command=self.chooseFile)
self.choose_button... | GCodeChooser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCodeChooser:
def __init__(self, master):
"""Implements a simple GUI to ask for file selection."""
<|body_0|>
def chooseFile(self):
"""When the choose_button is pressed, a dialog is opened to choose the file that contains G Code."""
<|body_1|>
def getFil... | stack_v2_sparse_classes_75kplus_train_005657 | 1,439 | no_license | [
{
"docstring": "Implements a simple GUI to ask for file selection.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "When the choose_button is pressed, a dialog is opened to choose the file that contains G Code.",
"name": "chooseFile",
"signature": "def c... | 3 | null | Implement the Python class `GCodeChooser` described below.
Class description:
Implement the GCodeChooser class.
Method signatures and docstrings:
- def __init__(self, master): Implements a simple GUI to ask for file selection.
- def chooseFile(self): When the choose_button is pressed, a dialog is opened to choose the... | Implement the Python class `GCodeChooser` described below.
Class description:
Implement the GCodeChooser class.
Method signatures and docstrings:
- def __init__(self, master): Implements a simple GUI to ask for file selection.
- def chooseFile(self): When the choose_button is pressed, a dialog is opened to choose the... | 9fa0b4c3e241a3892629611989c23afc0c288548 | <|skeleton|>
class GCodeChooser:
def __init__(self, master):
"""Implements a simple GUI to ask for file selection."""
<|body_0|>
def chooseFile(self):
"""When the choose_button is pressed, a dialog is opened to choose the file that contains G Code."""
<|body_1|>
def getFil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GCodeChooser:
def __init__(self, master):
"""Implements a simple GUI to ask for file selection."""
self.master = master
master.title('Choose the G Code...')
self.label = Label(master, text='Press to choose file whenever you are ready!')
self.label.pack()
self.ch... | the_stack_v2_python_sparse | Python/GCodeGenerator/GCodeChooser.py | pedro-sidra/Projeto2 | train | 0 | |
9a1263ec291abec0a00dc82e958dd0c8fae5e719 | [
"ret = []\nfor i in range(numRows):\n ret.append([])\n for j in range(i + 1):\n if ret[i - 1]:\n if j > 0 and j < i:\n ret[i].append(ret[i - 1][j - 1] + ret[i - 1][j])\n else:\n ret[i].append(1)\n else:\n ret[i].append(1)\nreturn ret... | <|body_start_0|>
ret = []
for i in range(numRows):
ret.append([])
for j in range(i + 1):
if ret[i - 1]:
if j > 0 and j < i:
ret[i].append(ret[i - 1][j - 1] + ret[i - 1][j])
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generate_myself(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_0|>
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
for... | stack_v2_sparse_classes_75kplus_train_005658 | 1,546 | no_license | [
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generate_myself",
"signature": "def generate_myself(self, numRows)"
},
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generate",
"signature": "def generate(self, numRows)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate_myself(self, numRows): :type numRows: int :rtype: List[List[int]]
- def generate(self, numRows): :type numRows: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate_myself(self, numRows): :type numRows: int :rtype: List[List[int]]
- def generate(self, numRows): :type numRows: int :rtype: List[List[int]]
<|skeleton|>
class Solut... | 93266095329e2e8e949a72371b88b07382a60e0d | <|skeleton|>
class Solution:
def generate_myself(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_0|>
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generate_myself(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
ret = []
for i in range(numRows):
ret.append([])
for j in range(i + 1):
if ret[i - 1]:
if j > 0 and j < i:
... | the_stack_v2_python_sparse | generate.py | shivangi-prog/leetcode | train | 0 | |
c543375fc64a75e9b4d4cb7c62a963b60e397262 | [
"if not tab_label_text:\n tab_label_text = 'Red'\nif not instance_tab_color_list.rv.data:\n for hue in _colors[tab_label_text]:\n color = get_color_from_hex(_colors[tab_label_text][hue])\n if tab_label_text == 'Light':\n text_color = (0, 0, 0, 1)\n elif tab_label_text == 'Dark'... | <|body_start_0|>
if not tab_label_text:
tab_label_text = 'Red'
if not instance_tab_color_list.rv.data:
for hue in _colors[tab_label_text]:
color = get_color_from_hex(_colors[tab_label_text][hue])
if tab_label_text == 'Light':
te... | The class implements a tab with tabs with a list of colors. This is the second tab on the bottom navigation panel. | ColorListTab | [
"MIT",
"OFL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorListTab:
"""The class implements a tab with tabs with a list of colors. This is the second tab on the bottom navigation panel."""
def generates_list_colors(self, instance_color_list_tab, instance_tab_color_list: TabColorList, instance_tabs_label: MDTabsLabel, tab_label_text: str) -> Non... | stack_v2_sparse_classes_75kplus_train_005659 | 22,767 | permissive | [
{
"docstring": "Generates list of colors. Called when you click the tab of :class:`~TabColorList` class.",
"name": "generates_list_colors",
"signature": "def generates_list_colors(self, instance_color_list_tab, instance_tab_color_list: TabColorList, instance_tabs_label: MDTabsLabel, tab_label_text: str)... | 2 | stack_v2_sparse_classes_30k_train_010299 | Implement the Python class `ColorListTab` described below.
Class description:
The class implements a tab with tabs with a list of colors. This is the second tab on the bottom navigation panel.
Method signatures and docstrings:
- def generates_list_colors(self, instance_color_list_tab, instance_tab_color_list: TabColo... | Implement the Python class `ColorListTab` described below.
Class description:
The class implements a tab with tabs with a list of colors. This is the second tab on the bottom navigation panel.
Method signatures and docstrings:
- def generates_list_colors(self, instance_color_list_tab, instance_tab_color_list: TabColo... | 19f6b664f62db726e9da43a9372a4bd57b897732 | <|skeleton|>
class ColorListTab:
"""The class implements a tab with tabs with a list of colors. This is the second tab on the bottom navigation panel."""
def generates_list_colors(self, instance_color_list_tab, instance_tab_color_list: TabColorList, instance_tabs_label: MDTabsLabel, tab_label_text: str) -> Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColorListTab:
"""The class implements a tab with tabs with a list of colors. This is the second tab on the bottom navigation panel."""
def generates_list_colors(self, instance_color_list_tab, instance_tab_color_list: TabColorList, instance_tabs_label: MDTabsLabel, tab_label_text: str) -> None:
""... | the_stack_v2_python_sparse | kivymd/uix/pickers/colorpicker/colorpicker.py | gottadiveintopython/KivyMD | train | 0 |
870997702741431340535922d68e5d27ab502270 | [
"try:\n res = subprocess.run(['scontrol', 'show', 'job', str(job_id)], text=True, check=True, stdout=subprocess.PIPE)\nexcept subprocess.CalledProcessError:\n raise WorkerError(f'Failed to query job {job_id}') from None\n\ndef parse_key_val(pair):\n \"\"\"Parse the key-value pair.\"\"\"\n i = pair.find(... | <|body_start_0|>
try:
res = subprocess.run(['scontrol', 'show', 'job', str(job_id)], text=True, check=True, stdout=subprocess.PIPE)
except subprocess.CalledProcessError:
raise WorkerError(f'Failed to query job {job_id}') from None
def parse_key_val(pair):
"""... | Slurm worker interface that uses the CLI. | SlurmCLIWorker | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlurmCLIWorker:
"""Slurm worker interface that uses the CLI."""
def query_task(self, job_id):
"""Query job state for the task."""
<|body_0|>
def cancel_task(self, job_id):
"""Cancel task with job_id; returns job_state."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_005660 | 9,863 | permissive | [
{
"docstring": "Query job state for the task.",
"name": "query_task",
"signature": "def query_task(self, job_id)"
},
{
"docstring": "Cancel task with job_id; returns job_state.",
"name": "cancel_task",
"signature": "def cancel_task(self, job_id)"
}
] | 2 | null | Implement the Python class `SlurmCLIWorker` described below.
Class description:
Slurm worker interface that uses the CLI.
Method signatures and docstrings:
- def query_task(self, job_id): Query job state for the task.
- def cancel_task(self, job_id): Cancel task with job_id; returns job_state. | Implement the Python class `SlurmCLIWorker` described below.
Class description:
Slurm worker interface that uses the CLI.
Method signatures and docstrings:
- def query_task(self, job_id): Query job state for the task.
- def cancel_task(self, job_id): Cancel task with job_id; returns job_state.
<|skeleton|>
class Slu... | 4d2f965765bc0d54236898d62bbd9d01a4b850e8 | <|skeleton|>
class SlurmCLIWorker:
"""Slurm worker interface that uses the CLI."""
def query_task(self, job_id):
"""Query job state for the task."""
<|body_0|>
def cancel_task(self, job_id):
"""Cancel task with job_id; returns job_state."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlurmCLIWorker:
"""Slurm worker interface that uses the CLI."""
def query_task(self, job_id):
"""Query job state for the task."""
try:
res = subprocess.run(['scontrol', 'show', 'job', str(job_id)], text=True, check=True, stdout=subprocess.PIPE)
except subprocess.Called... | the_stack_v2_python_sparse | beeflow/common/worker/slurm_worker.py | lanl/BEE | train | 18 |
41b9054b47a190ffa1d1de68641affc7b48073d0 | [
"super().__init__()\nself.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.dropout = nn.Dropout(dropout)\nself.linear1 = nn.Linear(d_model, dim_feedforward)\nself.linear2 = nn.Linear(dim_feedforward, d_model)\nself... | <|body_start_0|>
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.dropout = nn.Dropout(dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
s... | A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhi... | TransformerDecoderLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDecoderLayer:
"""A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones... | stack_v2_sparse_classes_75kplus_train_005661 | 3,976 | no_license | [
{
"docstring": "Initialize a TransformerDecoder. Parameters ---------- d_model : int The number of expected features in the input. n_head : int The number of heads in the multiheadattention models. dim_feedforward : int, optional The dimension of the feedforward network (default=2048). dropout : float, optional... | 2 | null | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Ni... | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Ni... | 8b9fadded0e9eed7e16bf6ce6c3235f3ad5132e8 | <|skeleton|>
class TransformerDecoderLayer:
"""A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerDecoderLayer:
"""A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gom... | the_stack_v2_python_sparse | models/iwslt/teacher/decoder/layers.3/source.py | asappresearch/imitkd | train | 3 |
8db25d8068975d54c140c65ee9a58d80caac5a8b | [
"if isinstance(key, int):\n return HomeAddressReply(key)\nif key not in HomeAddressReply._member_map_:\n return extend_enum(HomeAddressReply, key, default)\nreturn HomeAddressReply[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__nam... | <|body_start_0|>
if isinstance(key, int):
return HomeAddressReply(key)
if key not in HomeAddressReply._member_map_:
return extend_enum(HomeAddressReply, key, default)
return HomeAddressReply[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and ... | [HomeAddressReply] IPv4 Home Address Reply Status Codes | HomeAddressReply | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeAddressReply:
"""[HomeAddressReply] IPv4 Home Address Reply Status Codes"""
def get(key: 'int | str', default: 'int'=-1) -> 'HomeAddressReply':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
... | stack_v2_sparse_classes_75kplus_train_005662 | 2,296 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'HomeAddressReply'"
},
{
"docstring": "Lookup function used when value is not f... | 2 | stack_v2_sparse_classes_30k_train_027383 | Implement the Python class `HomeAddressReply` described below.
Class description:
[HomeAddressReply] IPv4 Home Address Reply Status Codes
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HomeAddressReply': Backport support for original codes. Args: key: Key to get enum item. defaul... | Implement the Python class `HomeAddressReply` described below.
Class description:
[HomeAddressReply] IPv4 Home Address Reply Status Codes
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HomeAddressReply': Backport support for original codes. Args: key: Key to get enum item. defaul... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class HomeAddressReply:
"""[HomeAddressReply] IPv4 Home Address Reply Status Codes"""
def get(key: 'int | str', default: 'int'=-1) -> 'HomeAddressReply':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HomeAddressReply:
"""[HomeAddressReply] IPv4 Home Address Reply Status Codes"""
def get(key: 'int | str', default: 'int'=-1) -> 'HomeAddressReply':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance... | the_stack_v2_python_sparse | pcapkit/const/mh/home_address_reply.py | JarryShaw/PyPCAPKit | train | 204 |
9d6d95f62b7b9f14d0b42b2f7b90d8d9224c1446 | [
"self._config = config\nself._optimizer_config = config.optimizer.get()\nself._optimizer_type = config.optimizer.type\nif self._optimizer_config is None:\n raise ValueError('Optimizer type must be specified')\nself._lr_config = config.learning_rate.get()\nself._lr_type = config.learning_rate.type\nself._warmup_c... | <|body_start_0|>
self._config = config
self._optimizer_config = config.optimizer.get()
self._optimizer_type = config.optimizer.type
if self._optimizer_config is None:
raise ValueError('Optimizer type must be specified')
self._lr_config = config.learning_rate.get()
... | Optimizer factory class. This class builds learning rate and optimizer based on an optimization config. To use this class, you need to do the following: (1) Define optimization config, this includes optimizer, and learning rate schedule. (2) Initialize the class using the optimization config. (3) Build learning rate. (... | OptimizerFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerFactory:
"""Optimizer factory class. This class builds learning rate and optimizer based on an optimization config. To use this class, you need to do the following: (1) Define optimization config, this includes optimizer, and learning rate schedule. (2) Initialize the class using the opt... | stack_v2_sparse_classes_75kplus_train_005663 | 4,835 | permissive | [
{
"docstring": "Initializing OptimizerFactory. Args: config: OptimizationConfig instance contain optimization config.",
"name": "__init__",
"signature": "def __init__(self, config: opt_cfg.OptimizationConfig)"
},
{
"docstring": "Build learning rate. Builds learning rate from config. Learning rat... | 3 | stack_v2_sparse_classes_30k_train_019197 | Implement the Python class `OptimizerFactory` described below.
Class description:
Optimizer factory class. This class builds learning rate and optimizer based on an optimization config. To use this class, you need to do the following: (1) Define optimization config, this includes optimizer, and learning rate schedule.... | Implement the Python class `OptimizerFactory` described below.
Class description:
Optimizer factory class. This class builds learning rate and optimizer based on an optimization config. To use this class, you need to do the following: (1) Define optimization config, this includes optimizer, and learning rate schedule.... | ad48842549b61e171254cf4a895239022ef509d4 | <|skeleton|>
class OptimizerFactory:
"""Optimizer factory class. This class builds learning rate and optimizer based on an optimization config. To use this class, you need to do the following: (1) Define optimization config, this includes optimizer, and learning rate schedule. (2) Initialize the class using the opt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptimizerFactory:
"""Optimizer factory class. This class builds learning rate and optimizer based on an optimization config. To use this class, you need to do the following: (1) Define optimization config, this includes optimizer, and learning rate schedule. (2) Initialize the class using the optimization con... | the_stack_v2_python_sparse | ImageClassification-Resnet_50/TensorFlow2/source/resnet/include/modeling/optimization/optimizer_factory.py | tbd-ai/tbd-suite | train | 51 |
b8ea05e8f4d788fde8f1d24e3bbeb991b634c448 | [
"for i in range(1, len(arr) - 1):\n if arr[i - 1] < arr[i] > arr[i + 1]:\n return i",
"n = len(arr)\nleft, right, ans = (1, n - 2, 0)\nwhile left <= right:\n mid = (left + right) // 2\n if arr[mid] > arr[mid + 1]:\n ans = mid\n right = mid - 1\n else:\n left = mid + 1\nretu... | <|body_start_0|>
for i in range(1, len(arr) - 1):
if arr[i - 1] < arr[i] > arr[i + 1]:
return i
<|end_body_0|>
<|body_start_1|>
n = len(arr)
left, right, ans = (1, n - 2, 0)
while left <= right:
mid = (left + right) // 2
if arr[mid] > ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
"""遍历, :param arr: :return:"""
<|body_0|>
def peakIndexInMountainArray1(self, arr: List[int]) -> int:
"""二分查找 :param arr: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f... | stack_v2_sparse_classes_75kplus_train_005664 | 1,539 | no_license | [
{
"docstring": "遍历, :param arr: :return:",
"name": "peakIndexInMountainArray",
"signature": "def peakIndexInMountainArray(self, arr: List[int]) -> int"
},
{
"docstring": "二分查找 :param arr: :return:",
"name": "peakIndexInMountainArray1",
"signature": "def peakIndexInMountainArray1(self, ar... | 2 | stack_v2_sparse_classes_30k_train_044865 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, arr: List[int]) -> int: 遍历, :param arr: :return:
- def peakIndexInMountainArray1(self, arr: List[int]) -> int: 二分查找 :param arr: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, arr: List[int]) -> int: 遍历, :param arr: :return:
- def peakIndexInMountainArray1(self, arr: List[int]) -> int: 二分查找 :param arr: :return:
<|ske... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
"""遍历, :param arr: :return:"""
<|body_0|>
def peakIndexInMountainArray1(self, arr: List[int]) -> int:
"""二分查找 :param arr: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
"""遍历, :param arr: :return:"""
for i in range(1, len(arr) - 1):
if arr[i - 1] < arr[i] > arr[i + 1]:
return i
def peakIndexInMountainArray1(self, arr: List[int]) -> int:
"""二分查找 :param... | the_stack_v2_python_sparse | datastructure/binary_array/PeakIndexInMountainArray.py | yinhuax/leet_code | train | 0 | |
338ae2b6520b3b428bff0b53cfca80050f7c6a38 | [
"with tempfile.TemporaryDirectory() as tmp_dir:\n test_repo_manager = repo_manager.RepoManager(self.curl_repo, tmp_dir)\n git_path = os.path.join(test_repo_manager.base_dir, test_repo_manager.repo_name, '.git')\n self.assertTrue(os.path.isdir(git_path))\n test_repo_manager.remove_repo()\n with self.a... | <|body_start_0|>
with tempfile.TemporaryDirectory() as tmp_dir:
test_repo_manager = repo_manager.RepoManager(self.curl_repo, tmp_dir)
git_path = os.path.join(test_repo_manager.base_dir, test_repo_manager.repo_name, '.git')
self.assertTrue(os.path.isdir(git_path))
... | Class to test the functionality of the RepoManager class. | TestRepoManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRepoManager:
"""Class to test the functionality of the RepoManager class."""
def test_clone_correctly(self):
"""Tests the correct location of the git repo."""
<|body_0|>
def test_checkout_commit(self):
"""Tests that the git checkout command works."""
... | stack_v2_sparse_classes_75kplus_train_005665 | 3,505 | permissive | [
{
"docstring": "Tests the correct location of the git repo.",
"name": "test_clone_correctly",
"signature": "def test_clone_correctly(self)"
},
{
"docstring": "Tests that the git checkout command works.",
"name": "test_checkout_commit",
"signature": "def test_checkout_commit(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_031638 | Implement the Python class `TestRepoManager` described below.
Class description:
Class to test the functionality of the RepoManager class.
Method signatures and docstrings:
- def test_clone_correctly(self): Tests the correct location of the git repo.
- def test_checkout_commit(self): Tests that the git checkout comma... | Implement the Python class `TestRepoManager` described below.
Class description:
Class to test the functionality of the RepoManager class.
Method signatures and docstrings:
- def test_clone_correctly(self): Tests the correct location of the git repo.
- def test_checkout_commit(self): Tests that the git checkout comma... | 8e2d57684bd49355b80572592c3af5cefc19a69c | <|skeleton|>
class TestRepoManager:
"""Class to test the functionality of the RepoManager class."""
def test_clone_correctly(self):
"""Tests the correct location of the git repo."""
<|body_0|>
def test_checkout_commit(self):
"""Tests that the git checkout command works."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRepoManager:
"""Class to test the functionality of the RepoManager class."""
def test_clone_correctly(self):
"""Tests the correct location of the git repo."""
with tempfile.TemporaryDirectory() as tmp_dir:
test_repo_manager = repo_manager.RepoManager(self.curl_repo, tmp_di... | the_stack_v2_python_sparse | infra/repo_manager_test.py | DeepInThought/oss-fuzz | train | 2 |
7a67c87c216542f725da29ab7c9eda08fb04d12b | [
"super(SignupFormExtra, self).__init__(*args, **kw)\nnew_order = self.fields.keyOrder[:-2]\nnew_order.insert(0, 'first_name')\nnew_order.insert(1, 'last_name')\nself.fields.keyOrder = new_order",
"new_user = super(SignupFormExtra, self).save()\nnew_user.first_name = self.cleaned_data['first_name']\nnew_user.last_... | <|body_start_0|>
super(SignupFormExtra, self).__init__(*args, **kw)
new_order = self.fields.keyOrder[:-2]
new_order.insert(0, 'first_name')
new_order.insert(1, 'last_name')
self.fields.keyOrder = new_order
<|end_body_0|>
<|body_start_1|>
new_user = super(SignupFormExtra,... | A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name. | SignupFormExtra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupFormExtra:
"""A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name."""
def __init__(self, *args, **kw):
"""A bit of hackery to get the first name and last name at the top of the form instead at the end."""
<|body_... | stack_v2_sparse_classes_75kplus_train_005666 | 2,819 | no_license | [
{
"docstring": "A bit of hackery to get the first name and last name at the top of the form instead at the end.",
"name": "__init__",
"signature": "def __init__(self, *args, **kw)"
},
{
"docstring": "Override the save method to save the first and last name to the user field.",
"name": "save"... | 2 | stack_v2_sparse_classes_30k_train_005284 | Implement the Python class `SignupFormExtra` described below.
Class description:
A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name.
Method signatures and docstrings:
- def __init__(self, *args, **kw): A bit of hackery to get the first name and last name at t... | Implement the Python class `SignupFormExtra` described below.
Class description:
A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name.
Method signatures and docstrings:
- def __init__(self, *args, **kw): A bit of hackery to get the first name and last name at t... | 25e68e4c871edddeb9fc735f929e77872d33a216 | <|skeleton|>
class SignupFormExtra:
"""A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name."""
def __init__(self, *args, **kw):
"""A bit of hackery to get the first name and last name at the top of the form instead at the end."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignupFormExtra:
"""A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name."""
def __init__(self, *args, **kw):
"""A bit of hackery to get the first name and last name at the top of the form instead at the end."""
super(SignupFormExtr... | the_stack_v2_python_sparse | accounts/forms.py | ck520702002/TFT_project | train | 0 |
f1318d63bfead778c3c56f1c91ec9a95e7f8ef01 | [
"self.log = logging.getLogger()\nself.log.info(__name__ + ': ' + 'def ' + self.__init__.__name__ + '(): ' + self.__init__.__doc__)\nself.cols = cols\nself.rows = rows\nself.coordinates = [common.Coordinate(xy[0], xy[1]) for xy in list(product(range(self.rows), range(self.cols)))]\nself.player = None\nself.gamer = N... | <|body_start_0|>
self.log = logging.getLogger()
self.log.info(__name__ + ': ' + 'def ' + self.__init__.__name__ + '(): ' + self.__init__.__doc__)
self.cols = cols
self.rows = rows
self.coordinates = [common.Coordinate(xy[0], xy[1]) for xy in list(product(range(self.rows), range(s... | Behaviors class for ai player. | Behavior | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Behavior:
"""Behaviors class for ai player."""
def __init__(self, cols, rows):
"""Initialize behavior class."""
<|body_0|>
def set_controllers(self, ai_):
"""Set controllers player and ai."""
<|body_1|>
def scan(self):
"""Scan battle field an... | stack_v2_sparse_classes_75kplus_train_005667 | 3,897 | no_license | [
{
"docstring": "Initialize behavior class.",
"name": "__init__",
"signature": "def __init__(self, cols, rows)"
},
{
"docstring": "Set controllers player and ai.",
"name": "set_controllers",
"signature": "def set_controllers(self, ai_)"
},
{
"docstring": "Scan battle field and ret... | 6 | stack_v2_sparse_classes_30k_train_048235 | Implement the Python class `Behavior` described below.
Class description:
Behaviors class for ai player.
Method signatures and docstrings:
- def __init__(self, cols, rows): Initialize behavior class.
- def set_controllers(self, ai_): Set controllers player and ai.
- def scan(self): Scan battle field and return genera... | Implement the Python class `Behavior` described below.
Class description:
Behaviors class for ai player.
Method signatures and docstrings:
- def __init__(self, cols, rows): Initialize behavior class.
- def set_controllers(self, ai_): Set controllers player and ai.
- def scan(self): Scan battle field and return genera... | 4368f82ee0bcfed9230f8e5af9bf6f89ad173675 | <|skeleton|>
class Behavior:
"""Behaviors class for ai player."""
def __init__(self, cols, rows):
"""Initialize behavior class."""
<|body_0|>
def set_controllers(self, ai_):
"""Set controllers player and ai."""
<|body_1|>
def scan(self):
"""Scan battle field an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Behavior:
"""Behaviors class for ai player."""
def __init__(self, cols, rows):
"""Initialize behavior class."""
self.log = logging.getLogger()
self.log.info(__name__ + ': ' + 'def ' + self.__init__.__name__ + '(): ' + self.__init__.__doc__)
self.cols = cols
self.ro... | the_stack_v2_python_sparse | controllers/behaviors.py | DollaR84/forts | train | 0 |
79bb42c6df7916d01457a9c98d3c3ce854789abc | [
"request_json = request.get_json()\nvalid_format, errors = schema_utils.validate(request_json, 'org_product_subscription')\nif not valid_format:\n return ({'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST)\ntry:\n subscriptions = ProductService.create_product_subscription(org_id, r... | <|body_start_0|>
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription')
if not valid_format:
return ({'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST)
try:
subscriptions... | Resource for managing product subscriptions. | OrgProducts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrgProducts:
"""Resource for managing product subscriptions."""
def post(org_id):
"""Post a new product subscription to the org using the request body."""
<|body_0|>
def get(org_id):
"""GET a new product subscription to the org using the request body."""
... | stack_v2_sparse_classes_75kplus_train_005668 | 2,941 | permissive | [
{
"docstring": "Post a new product subscription to the org using the request body.",
"name": "post",
"signature": "def post(org_id)"
},
{
"docstring": "GET a new product subscription to the org using the request body.",
"name": "get",
"signature": "def get(org_id)"
}
] | 2 | null | Implement the Python class `OrgProducts` described below.
Class description:
Resource for managing product subscriptions.
Method signatures and docstrings:
- def post(org_id): Post a new product subscription to the org using the request body.
- def get(org_id): GET a new product subscription to the org using the requ... | Implement the Python class `OrgProducts` described below.
Class description:
Resource for managing product subscriptions.
Method signatures and docstrings:
- def post(org_id): Post a new product subscription to the org using the request body.
- def get(org_id): GET a new product subscription to the org using the requ... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class OrgProducts:
"""Resource for managing product subscriptions."""
def post(org_id):
"""Post a new product subscription to the org using the request body."""
<|body_0|>
def get(org_id):
"""GET a new product subscription to the org using the request body."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrgProducts:
"""Resource for managing product subscriptions."""
def post(org_id):
"""Post a new product subscription to the org using the request body."""
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription')
... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org_products.py | bcgov/sbc-auth | train | 13 |
94c5a8481b122d63b31660284efea93c4821c7ae | [
"self.N = 64\nself.num_channels = [1, 16]\nself.platforms = ['gpuNUFFT']",
"for num_channels in self.num_channels:\n for platform in self.platforms:\n _mask = np.random.randint(2, size=(self.N, self.N, self.N))\n _samples = convert_mask_to_locations(_mask)\n fourier_op_dir = NonCartesianFF... | <|body_start_0|>
self.N = 64
self.num_channels = [1, 16]
self.platforms = ['gpuNUFFT']
<|end_body_0|>
<|body_start_1|>
for num_channels in self.num_channels:
for platform in self.platforms:
_mask = np.random.randint(2, size=(self.N, self.N, self.N))
... | Test the adjoint operator of the NFFT both for 2D and 3D. | TestAdjointOperatorFourierTransformGPU | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdjointOperatorFourierTransformGPU:
"""Test the adjoint operator of the NFFT both for 2D and 3D."""
def setUp(self):
"""Set the number of iterations."""
<|body_0|>
def test_NUFFT_3D(self):
"""Test the adjoint operator for the 3D non-Cartesian Fourier transfor... | stack_v2_sparse_classes_75kplus_train_005669 | 3,812 | permissive | [
{
"docstring": "Set the number of iterations.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the adjoint operator for the 3D non-Cartesian Fourier transform on GPU",
"name": "test_NUFFT_3D",
"signature": "def test_NUFFT_3D(self)"
},
{
"docstring": "Test... | 3 | stack_v2_sparse_classes_30k_train_020481 | Implement the Python class `TestAdjointOperatorFourierTransformGPU` described below.
Class description:
Test the adjoint operator of the NFFT both for 2D and 3D.
Method signatures and docstrings:
- def setUp(self): Set the number of iterations.
- def test_NUFFT_3D(self): Test the adjoint operator for the 3D non-Carte... | Implement the Python class `TestAdjointOperatorFourierTransformGPU` described below.
Class description:
Test the adjoint operator of the NFFT both for 2D and 3D.
Method signatures and docstrings:
- def setUp(self): Set the number of iterations.
- def test_NUFFT_3D(self): Test the adjoint operator for the 3D non-Carte... | 9a3e1f046fb31add5f276dc7869051d6ef2caac0 | <|skeleton|>
class TestAdjointOperatorFourierTransformGPU:
"""Test the adjoint operator of the NFFT both for 2D and 3D."""
def setUp(self):
"""Set the number of iterations."""
<|body_0|>
def test_NUFFT_3D(self):
"""Test the adjoint operator for the 3D non-Cartesian Fourier transfor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAdjointOperatorFourierTransformGPU:
"""Test the adjoint operator of the NFFT both for 2D and 3D."""
def setUp(self):
"""Set the number of iterations."""
self.N = 64
self.num_channels = [1, 16]
self.platforms = ['gpuNUFFT']
def test_NUFFT_3D(self):
"""Test ... | the_stack_v2_python_sparse | mri/test_local/test_fourier_adjoint_gpu.py | CEA-COSMIC/pysap-mri | train | 38 |
5899b2b7789d06235ebf07a56e7e29a2077f4552 | [
"if self.jiakbot:\n self.jiakbot = JiakBot().reset()\nself.conversation = dict()\nclear = request.GET.get('clear', None)\nif clear:\n self.jiakbot = self.jiakbot.reset()\n self.conversation = dict()\ncontext = {'conversation': self.conversation}\nreturn render(request, self.template_name, context)",
"use... | <|body_start_0|>
if self.jiakbot:
self.jiakbot = JiakBot().reset()
self.conversation = dict()
clear = request.GET.get('clear', None)
if clear:
self.jiakbot = self.jiakbot.reset()
self.conversation = dict()
context = {'conversation': self.conver... | Main View for JiakBot | JiakBotView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiakBotView:
"""Main View for JiakBot"""
def get(self, request, *args, **kwargs):
"""Initializes JiakBot interface"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""AJAX handler for JiakBot"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005670 | 1,451 | no_license | [
{
"docstring": "Initializes JiakBot interface",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "AJAX handler for JiakBot",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002793 | Implement the Python class `JiakBotView` described below.
Class description:
Main View for JiakBot
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Initializes JiakBot interface
- def post(self, request, *args, **kwargs): AJAX handler for JiakBot | Implement the Python class `JiakBotView` described below.
Class description:
Main View for JiakBot
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Initializes JiakBot interface
- def post(self, request, *args, **kwargs): AJAX handler for JiakBot
<|skeleton|>
class JiakBotView:
"""Mai... | d7169b9af7b4ec11277622bb0493d526f2ac4201 | <|skeleton|>
class JiakBotView:
"""Main View for JiakBot"""
def get(self, request, *args, **kwargs):
"""Initializes JiakBot interface"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""AJAX handler for JiakBot"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JiakBotView:
"""Main View for JiakBot"""
def get(self, request, *args, **kwargs):
"""Initializes JiakBot interface"""
if self.jiakbot:
self.jiakbot = JiakBot().reset()
self.conversation = dict()
clear = request.GET.get('clear', None)
if clear:
... | the_stack_v2_python_sparse | webapp/jiakbot/views.py | junquant/taproject | train | 1 |
05d1d62ab832e48be89cba7579639f70cd739bb6 | [
"self.face = face if type(face) != str else mcpython.util.enums.EnumSide[face]\nself.texture = texture if texture.startswith('#') else '#' + texture\nself.uv = uv\nif any([e < 0 or e > 1 for e in uv]):\n logger.println('[DATA GEN][WARN] provided uv coordinates for side {} are out of bound'.format(face))\nif cull... | <|body_start_0|>
self.face = face if type(face) != str else mcpython.util.enums.EnumSide[face]
self.texture = texture if texture.startswith('#') else '#' + texture
self.uv = uv
if any([e < 0 or e > 1 for e in uv]):
logger.println('[DATA GEN][WARN] provided uv coordinates for ... | Class for the configuration of one face of an element in an BlockModel | SingleFaceConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleFaceConfiguration:
"""Class for the configuration of one face of an element in an BlockModel"""
def __init__(self, face: typing.Union[str, mcpython.util.enums.EnumSide], texture: str, uv=(0, 0, 1, 1), cull_face: typing.Union[str, mcpython.util.enums.EnumSide]=None, rotation=0):
... | stack_v2_sparse_classes_75kplus_train_005671 | 16,199 | permissive | [
{
"docstring": "Will create an new config :param face: the face to configure, as str for face in mcpython.util.enums.EnumSide or an entry of that enum :param texture: the texture variable name to use, \"#\" in front optional (auto-added when not provided) :param uv: the uv indexes. when out of the 0-1 bound, be... | 2 | stack_v2_sparse_classes_30k_train_017811 | Implement the Python class `SingleFaceConfiguration` described below.
Class description:
Class for the configuration of one face of an element in an BlockModel
Method signatures and docstrings:
- def __init__(self, face: typing.Union[str, mcpython.util.enums.EnumSide], texture: str, uv=(0, 0, 1, 1), cull_face: typing... | Implement the Python class `SingleFaceConfiguration` described below.
Class description:
Class for the configuration of one face of an element in an BlockModel
Method signatures and docstrings:
- def __init__(self, face: typing.Union[str, mcpython.util.enums.EnumSide], texture: str, uv=(0, 0, 1, 1), cull_face: typing... | 644ef36a70c45a70820f6f6069b2f36545a187e5 | <|skeleton|>
class SingleFaceConfiguration:
"""Class for the configuration of one face of an element in an BlockModel"""
def __init__(self, face: typing.Union[str, mcpython.util.enums.EnumSide], texture: str, uv=(0, 0, 1, 1), cull_face: typing.Union[str, mcpython.util.enums.EnumSide]=None, rotation=0):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleFaceConfiguration:
"""Class for the configuration of one face of an element in an BlockModel"""
def __init__(self, face: typing.Union[str, mcpython.util.enums.EnumSide], texture: str, uv=(0, 0, 1, 1), cull_face: typing.Union[str, mcpython.util.enums.EnumSide]=None, rotation=0):
"""Will crea... | the_stack_v2_python_sparse | mcpython/common/data/gen/BlockModelGenerator.py | mcpython4-coding/core | train | 4 |
3aa64e72cc636517ca89109166efc8580f0b3bfc | [
"if 'id_user' in request.data:\n id_user = request.data['id_user']\n del request.data['id_user']\n user = User.objects.get(id=id_user)\n queryset = Prompt.objects.filter(creater=user)\n serializer = MockPromptSerializer(queryset, many=True)\n return Response({'result': serializer.data})\nelse:\n ... | <|body_start_0|>
if 'id_user' in request.data:
id_user = request.data['id_user']
del request.data['id_user']
user = User.objects.get(id=id_user)
queryset = Prompt.objects.filter(creater=user)
serializer = MockPromptSerializer(queryset, many=True)
... | PromptViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PromptViewSet:
def my_prompts(self, request, *args, **kwargs):
"""Action to get your prompts."""
<|body_0|>
def others_prompts(self, request, *args, **kwargs):
"""Action to get prompts when you added in prompt."""
<|body_1|>
def all_prompts(self, request... | stack_v2_sparse_classes_75kplus_train_005672 | 2,872 | permissive | [
{
"docstring": "Action to get your prompts.",
"name": "my_prompts",
"signature": "def my_prompts(self, request, *args, **kwargs)"
},
{
"docstring": "Action to get prompts when you added in prompt.",
"name": "others_prompts",
"signature": "def others_prompts(self, request, *args, **kwargs... | 4 | stack_v2_sparse_classes_30k_train_003818 | Implement the Python class `PromptViewSet` described below.
Class description:
Implement the PromptViewSet class.
Method signatures and docstrings:
- def my_prompts(self, request, *args, **kwargs): Action to get your prompts.
- def others_prompts(self, request, *args, **kwargs): Action to get prompts when you added i... | Implement the Python class `PromptViewSet` described below.
Class description:
Implement the PromptViewSet class.
Method signatures and docstrings:
- def my_prompts(self, request, *args, **kwargs): Action to get your prompts.
- def others_prompts(self, request, *args, **kwargs): Action to get prompts when you added i... | b7c0ec39a01631f822035786d76aebbb96ba077c | <|skeleton|>
class PromptViewSet:
def my_prompts(self, request, *args, **kwargs):
"""Action to get your prompts."""
<|body_0|>
def others_prompts(self, request, *args, **kwargs):
"""Action to get prompts when you added in prompt."""
<|body_1|>
def all_prompts(self, request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PromptViewSet:
def my_prompts(self, request, *args, **kwargs):
"""Action to get your prompts."""
if 'id_user' in request.data:
id_user = request.data['id_user']
del request.data['id_user']
user = User.objects.get(id=id_user)
queryset = Prompt.obj... | the_stack_v2_python_sparse | backend/api/views_api.py | ZayJob/Mnemosyne | train | 3 | |
95381f61022132a181a0b5399a1854c8f40fbb40 | [
"AssessmentResults.__init__(self, controller, **kwargs)\nself._lst_labels.append(u'π<sub>C</sub>:')\nself._lblModel.set_tooltip_markup(_(u\"The assessment model used to calculate the inductive device's failure rate.\"))\nself.txtPiC = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'The construc... | <|body_start_0|>
AssessmentResults.__init__(self, controller, **kwargs)
self._lst_labels.append(u'π<sub>C</sub>:')
self._lblModel.set_tooltip_markup(_(u"The assessment model used to calculate the inductive device's failure rate."))
self.txtPiC = ramstk.RAMSTKEntry(width=125, editable=Fal... | Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. The attributes of an Inductor assessment result view a... | InductorAssessmentResults | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InductorAssessmentResults:
"""Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. T... | stack_v2_sparse_classes_75kplus_train_005673 | 20,499 | permissive | [
{
"docstring": "Initialize an instance of the Inductor assessment result view. :param controller: the hardware data controller instance. :type controller: :class:`ramstk.hardware.Controller.HardwareBoMDataController` :param int hardware_id: the hardware ID of the currently selected inductor. :param int subcateg... | 5 | stack_v2_sparse_classes_30k_val_001790 | Implement the Python class `InductorAssessmentResults` described below.
Class description:
Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2... | Implement the Python class `InductorAssessmentResults` described below.
Class description:
Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class InductorAssessmentResults:
"""Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InductorAssessmentResults:
"""Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. The attributes... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/workviews/components/Inductor.py | JmiXIII/ramstk | train | 0 |
bfeafaadc6fd0c350c3a59e02565ccf3be744853 | [
"products_db = ProductDbQueries()\norder_db = OrderDbQueries()\ndata = request.get_json()\nif validate_order(data) == 'valid':\n product_query = products_db.fetch_all_products()\n for product in product_query:\n if product['product_name'] == data['product_name']:\n username = current_user.us... | <|body_start_0|>
products_db = ProductDbQueries()
order_db = OrderDbQueries()
data = request.get_json()
if validate_order(data) == 'valid':
product_query = products_db.fetch_all_products()
for product in product_query:
if product['product_name'] ==... | OrderView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderView:
def post(self, current_user):
"""Create an order."""
<|body_0|>
def get(self, current_user):
"""Return single user orders."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
products_db = ProductDbQueries()
order_db = OrderDbQueries(... | stack_v2_sparse_classes_75kplus_train_005674 | 3,187 | no_license | [
{
"docstring": "Create an order.",
"name": "post",
"signature": "def post(self, current_user)"
},
{
"docstring": "Return single user orders.",
"name": "get",
"signature": "def get(self, current_user)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000675 | Implement the Python class `OrderView` described below.
Class description:
Implement the OrderView class.
Method signatures and docstrings:
- def post(self, current_user): Create an order.
- def get(self, current_user): Return single user orders. | Implement the Python class `OrderView` described below.
Class description:
Implement the OrderView class.
Method signatures and docstrings:
- def post(self, current_user): Create an order.
- def get(self, current_user): Return single user orders.
<|skeleton|>
class OrderView:
def post(self, current_user):
... | 4c02cb785ff39e99f678a9e36d992dcd62c01f2d | <|skeleton|>
class OrderView:
def post(self, current_user):
"""Create an order."""
<|body_0|>
def get(self, current_user):
"""Return single user orders."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderView:
def post(self, current_user):
"""Create an order."""
products_db = ProductDbQueries()
order_db = OrderDbQueries()
data = request.get_json()
if validate_order(data) == 'valid':
product_query = products_db.fetch_all_products()
for produc... | the_stack_v2_python_sparse | app/orders/api.py | alexkayabula/data-vizr | train | 0 | |
2256c3809d3279306e2c4e56d5dc511abdd05162 | [
"super(NormLayer, self).__init__()\nself.n_channels = n_channels\nself.scale = scale\nself.epsilon = epsilon\nself.weights = nn.Parameter(torch.Tensor(self.n_channels))\nself.weights.data *= 0.0\nself.weights.data += self.scale",
"norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.epsilon\nx = x / norm * self... | <|body_start_0|>
super(NormLayer, self).__init__()
self.n_channels = n_channels
self.scale = scale
self.epsilon = epsilon
self.weights = nn.Parameter(torch.Tensor(self.n_channels))
self.weights.data *= 0.0
self.weights.data += self.scale
<|end_body_0|>
<|body_sta... | Implementation of the L2 Norm Layer used in the S3FD paper. | NormLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormLayer:
"""Implementation of the L2 Norm Layer used in the S3FD paper."""
def __init__(self, n_channels, scale=1.0, epsilon=1e-10):
"""Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used... | stack_v2_sparse_classes_75kplus_train_005675 | 6,948 | no_license | [
{
"docstring": "Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used for the weighted L2-norm, by default 1.0. epsilon : float, optional Parameter that prevents division by zero, by default 1e-10. Returns ------- None"... | 2 | stack_v2_sparse_classes_30k_train_037120 | Implement the Python class `NormLayer` described below.
Class description:
Implementation of the L2 Norm Layer used in the S3FD paper.
Method signatures and docstrings:
- def __init__(self, n_channels, scale=1.0, epsilon=1e-10): Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channe... | Implement the Python class `NormLayer` described below.
Class description:
Implementation of the L2 Norm Layer used in the S3FD paper.
Method signatures and docstrings:
- def __init__(self, n_channels, scale=1.0, epsilon=1e-10): Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channe... | a7c30481822ecb945e3ff6ad184d104361a40ed1 | <|skeleton|>
class NormLayer:
"""Implementation of the L2 Norm Layer used in the S3FD paper."""
def __init__(self, n_channels, scale=1.0, epsilon=1e-10):
"""Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NormLayer:
"""Implementation of the L2 Norm Layer used in the S3FD paper."""
def __init__(self, n_channels, scale=1.0, epsilon=1e-10):
"""Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used for the weig... | the_stack_v2_python_sparse | cheapfake/FAN/detectors/SF3DNet.py | hu-simon/cheapfake | train | 0 |
f4b26ff15f55031f782a57b94e9011210b35d245 | [
"self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.value = value\nself.value_type = ApplicationRoleConnectionValueType.none\nreturn self",
"self.value = value\nself.name = name\nself.value_type = value_type\nself.INSTANCES[value] = self"
] | <|body_start_0|>
self = object.__new__(cls)
self.name = cls.DEFAULT_NAME
self.value = value
self.value_type = ApplicationRoleConnectionValueType.none
return self
<|end_body_0|>
<|body_start_1|>
self.value = value
self.name = name
self.value_type = value_t... | Represents an application role connection type. Attributes ---------- name : `str` The name of the application role connection type. value : `int` The Discord side identifier value of the application role connection type. value_type : ``ApplicationRoleConnectionValueType`` Additional information describing the metadata... | ApplicationRoleConnectionMetadataType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationRoleConnectionMetadataType:
"""Represents an application role connection type. Attributes ---------- name : `str` The name of the application role connection type. value : `int` The Discord side identifier value of the application role connection type. value_type : ``ApplicationRoleCon... | stack_v2_sparse_classes_75kplus_train_005676 | 9,302 | permissive | [
{
"docstring": "Creates a new application role connection metadata type with the given value. Parameters ---------- value : `int` The application role connection metadata type's identifier value. Returns ------- self : ``ApplicationRoleConnectionMetadataType`` The created instance.",
"name": "_from_value",
... | 2 | stack_v2_sparse_classes_30k_train_034474 | Implement the Python class `ApplicationRoleConnectionMetadataType` described below.
Class description:
Represents an application role connection type. Attributes ---------- name : `str` The name of the application role connection type. value : `int` The Discord side identifier value of the application role connection ... | Implement the Python class `ApplicationRoleConnectionMetadataType` described below.
Class description:
Represents an application role connection type. Attributes ---------- name : `str` The name of the application role connection type. value : `int` The Discord side identifier value of the application role connection ... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class ApplicationRoleConnectionMetadataType:
"""Represents an application role connection type. Attributes ---------- name : `str` The name of the application role connection type. value : `int` The Discord side identifier value of the application role connection type. value_type : ``ApplicationRoleCon... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationRoleConnectionMetadataType:
"""Represents an application role connection type. Attributes ---------- name : `str` The name of the application role connection type. value : `int` The Discord side identifier value of the application role connection type. value_type : ``ApplicationRoleConnectionValueT... | the_stack_v2_python_sparse | hata/discord/application/application_role_connection_metadata/preinstanced.py | HuyaneMatsu/hata | train | 3 |
4d1c4564bf2c9454cfa8bea2f063a8eff53e75f5 | [
"credentials = self._get_credentials()\nself.db_username = credentials.get('username', 'root')\nself.db_password = credentials.get('password')\nself.db_hostname = credentials.get('hostname', 'localhost')\nports = credentials.get('ports')\nself.db_port = int(ports['2424/tcp'])",
"try:\n services = os.environ[cl... | <|body_start_0|>
credentials = self._get_credentials()
self.db_username = credentials.get('username', 'root')
self.db_password = credentials.get('password')
self.db_hostname = credentials.get('hostname', 'localhost')
ports = credentials.get('ports')
self.db_port = int(por... | Main package configuration. | Config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Main package configuration."""
def __init__(self):
"""Reads configuration from environment variables, also those set by Cloud Foundry. If the application is run locally, export VCAP_SERVICES with the following value: { "orientdb": [ { "credentials": { "hostname": "<host_na... | stack_v2_sparse_classes_75kplus_train_005677 | 2,142 | no_license | [
{
"docstring": "Reads configuration from environment variables, also those set by Cloud Foundry. If the application is run locally, export VCAP_SERVICES with the following value: { \"orientdb\": [ { \"credentials\": { \"hostname\": \"<host_name>\", \"username\": \"<user_name>\", \"password\": \"<password>\", \"... | 2 | null | Implement the Python class `Config` described below.
Class description:
Main package configuration.
Method signatures and docstrings:
- def __init__(self): Reads configuration from environment variables, also those set by Cloud Foundry. If the application is run locally, export VCAP_SERVICES with the following value:... | Implement the Python class `Config` described below.
Class description:
Main package configuration.
Method signatures and docstrings:
- def __init__(self): Reads configuration from environment variables, also those set by Cloud Foundry. If the application is run locally, export VCAP_SERVICES with the following value:... | 4b9c65cf06912fe92d94b3989e0220aae3a31db4 | <|skeleton|>
class Config:
"""Main package configuration."""
def __init__(self):
"""Reads configuration from environment variables, also those set by Cloud Foundry. If the application is run locally, export VCAP_SERVICES with the following value: { "orientdb": [ { "credentials": { "hostname": "<host_na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
"""Main package configuration."""
def __init__(self):
"""Reads configuration from environment variables, also those set by Cloud Foundry. If the application is run locally, export VCAP_SERVICES with the following value: { "orientdb": [ { "credentials": { "hostname": "<host_name>", "userna... | the_stack_v2_python_sparse | project/applications/orientdb-api/app/config.py | trustedanalytics/platform-tests | train | 2 |
96612e95818daeac29a5a03c401d579774f4a7ea | [
"super(CTCModule, self).__init__()\nself.pred_output_position_inclu_blank = nn.LSTM(in_dim, out_seq_len + 1, num_layers=2, batch_first=True)\nself.out_seq_len = out_seq_len\nself.softmax = nn.Softmax(dim=2)",
"pred_output_position_inclu_blank, _ = self.pred_output_position_inclu_blank(x)\nprob_pred_output_positio... | <|body_start_0|>
super(CTCModule, self).__init__()
self.pred_output_position_inclu_blank = nn.LSTM(in_dim, out_seq_len + 1, num_layers=2, batch_first=True)
self.out_seq_len = out_seq_len
self.softmax = nn.Softmax(dim=2)
<|end_body_0|>
<|body_start_1|>
pred_output_position_inclu_... | CTCModule | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CTCModule:
def __init__(self, in_dim, out_seq_len):
"""This module is performing alignment from A (e.g., audio) to B (e.g., text). :param in_dim: Dimension for input modality A :param out_seq_len: Sequence length for output modality B From: https://github.com/yaohungt/Multimodal-Transfor... | stack_v2_sparse_classes_75kplus_train_005678 | 6,164 | permissive | [
{
"docstring": "This module is performing alignment from A (e.g., audio) to B (e.g., text). :param in_dim: Dimension for input modality A :param out_seq_len: Sequence length for output modality B From: https://github.com/yaohungt/Multimodal-Transformer",
"name": "__init__",
"signature": "def __init__(se... | 2 | null | Implement the Python class `CTCModule` described below.
Class description:
Implement the CTCModule class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_seq_len): This module is performing alignment from A (e.g., audio) to B (e.g., text). :param in_dim: Dimension for input modality A :param out_se... | Implement the Python class `CTCModule` described below.
Class description:
Implement the CTCModule class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_seq_len): This module is performing alignment from A (e.g., audio) to B (e.g., text). :param in_dim: Dimension for input modality A :param out_se... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class CTCModule:
def __init__(self, in_dim, out_seq_len):
"""This module is performing alignment from A (e.g., audio) to B (e.g., text). :param in_dim: Dimension for input modality A :param out_seq_len: Sequence length for output modality B From: https://github.com/yaohungt/Multimodal-Transfor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CTCModule:
def __init__(self, in_dim, out_seq_len):
"""This module is performing alignment from A (e.g., audio) to B (e.g., text). :param in_dim: Dimension for input modality A :param out_seq_len: Sequence length for output modality B From: https://github.com/yaohungt/Multimodal-Transformer"""
... | the_stack_v2_python_sparse | PyTorch/contrib/others/MMSA_ID2979_for_PyTorch/models/subNets/AlignNets.py | Ascend/ModelZoo-PyTorch | train | 23 | |
fc19620a0bc8c846d631b91f661043b1f9bac0bb | [
"self.agent = agent\nself.env = env\nassert not isinstance(self.env, VecEnv), 'The environment cannot be of type VecEnv. '\nself.gamma = gamma",
"D = []\nfor n in range(N):\n trajectory = Trajectory(gamma=self.gamma)\n obs = self.env.reset()\n for t in range(T):\n output_agent = self.agent.choose_... | <|body_start_0|>
self.agent = agent
self.env = env
assert not isinstance(self.env, VecEnv), 'The environment cannot be of type VecEnv. '
self.gamma = gamma
<|end_body_0|>
<|body_start_1|>
D = []
for n in range(N):
trajectory = Trajectory(gamma=self.gamma)
... | Batched data collection for an agent in one environment for a number of trajectories and a certain time steps. It includes successive transitions (observation, action, reward, next observation, done) and additional data useful for training the agent such as the action log-probabilities, policy entropies, Q values etc. ... | TrajectoryRunner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrajectoryRunner:
"""Batched data collection for an agent in one environment for a number of trajectories and a certain time steps. It includes successive transitions (observation, action, reward, next observation, done) and additional data useful for training the agent such as the action log-pro... | stack_v2_sparse_classes_75kplus_train_005679 | 5,657 | permissive | [
{
"docstring": "Args: agent (BaseAgent): agent env (Env): environment gamma (float): discount factor",
"name": "__init__",
"signature": "def __init__(self, agent, env, gamma)"
},
{
"docstring": "Run the agent in the environment and collect all necessary data for given number of trajectories and ... | 2 | stack_v2_sparse_classes_30k_train_009873 | Implement the Python class `TrajectoryRunner` described below.
Class description:
Batched data collection for an agent in one environment for a number of trajectories and a certain time steps. It includes successive transitions (observation, action, reward, next observation, done) and additional data useful for traini... | Implement the Python class `TrajectoryRunner` described below.
Class description:
Batched data collection for an agent in one environment for a number of trajectories and a certain time steps. It includes successive transitions (observation, action, reward, next observation, done) and additional data useful for traini... | 6dc636ea6102b69e631421688a238db5e0b2d9c0 | <|skeleton|>
class TrajectoryRunner:
"""Batched data collection for an agent in one environment for a number of trajectories and a certain time steps. It includes successive transitions (observation, action, reward, next observation, done) and additional data useful for training the agent such as the action log-pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrajectoryRunner:
"""Batched data collection for an agent in one environment for a number of trajectories and a certain time steps. It includes successive transitions (observation, action, reward, next observation, done) and additional data useful for training the agent such as the action log-probabilities, p... | the_stack_v2_python_sparse | lagom/runner/trajectory_runner.py | MuharremOkutan/lagom | train | 0 |
83cda42b9c115356c6760ea503a36ad97fe5c7a1 | [
"super().__init__(n_hl, num_features, n_classes, dropout, epochs, units, bias, lr, momentum, device, weights_init, hl_actfunct, out_actfunct, loss_funct, random_state, verbose)\nself.input_tensor, self.targets = (None, None)\nself.loader = loader",
"input_tensor = loader[0].to(self.device)\ntargets = loader[1].to... | <|body_start_0|>
super().__init__(n_hl, num_features, n_classes, dropout, epochs, units, bias, lr, momentum, device, weights_init, hl_actfunct, out_actfunct, loss_funct, random_state, verbose)
self.input_tensor, self.targets = (None, None)
self.loader = loader
<|end_body_0|>
<|body_start_1|>
... | MLPModel_wl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPModel_wl:
def __init__(self, n_hl: int=1, num_features: int=10, n_classes: int=10, dropout: float=0.2, epochs: int=50, units: int=128, bias: float=0.1, lr: float=0.01, momentum: float=0.9, device: torch.device=torch.device('cpu'), weights_init: str='xavier_normal', hl_actfunct: str='sigmoid',... | stack_v2_sparse_classes_75kplus_train_005680 | 14,461 | permissive | [
{
"docstring": "Creates a multilayer perceptron object with the specified parameters using the pytorch framework without dataloader. ______________________________________________________________ Parameters: n_hl: int = 1 Number of hidden layers, defaults to 1 num_features: int = 10 Number of features, defaults... | 2 | stack_v2_sparse_classes_30k_train_034575 | Implement the Python class `MLPModel_wl` described below.
Class description:
Implement the MLPModel_wl class.
Method signatures and docstrings:
- def __init__(self, n_hl: int=1, num_features: int=10, n_classes: int=10, dropout: float=0.2, epochs: int=50, units: int=128, bias: float=0.1, lr: float=0.01, momentum: floa... | Implement the Python class `MLPModel_wl` described below.
Class description:
Implement the MLPModel_wl class.
Method signatures and docstrings:
- def __init__(self, n_hl: int=1, num_features: int=10, n_classes: int=10, dropout: float=0.2, epochs: int=50, units: int=128, bias: float=0.1, lr: float=0.01, momentum: floa... | 4d3b2ed56b56e016413ae1544e19ad2a2c0ef047 | <|skeleton|>
class MLPModel_wl:
def __init__(self, n_hl: int=1, num_features: int=10, n_classes: int=10, dropout: float=0.2, epochs: int=50, units: int=128, bias: float=0.1, lr: float=0.01, momentum: float=0.9, device: torch.device=torch.device('cpu'), weights_init: str='xavier_normal', hl_actfunct: str='sigmoid',... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLPModel_wl:
def __init__(self, n_hl: int=1, num_features: int=10, n_classes: int=10, dropout: float=0.2, epochs: int=50, units: int=128, bias: float=0.1, lr: float=0.01, momentum: float=0.9, device: torch.device=torch.device('cpu'), weights_init: str='xavier_normal', hl_actfunct: str='sigmoid', out_actfunct:... | the_stack_v2_python_sparse | Oblig1/packages/ann_models.py | fabiorodp/IN5550_Neural_Methods_in_Natural_Language_Processing | train | 1 | |
809729a219ced3733dfe099388feae3132afec3c | [
"circuit = ic.IBMCircuit(10)\nw1 = iw.IBMInputWire('w1', circuit)\nconst = ci.Input([ib.IBMBatch([True, False])])\ng = igac.IBMAddConstGate('g', w1, const, circuit)\nself.assertEquals('g:LADDconst(w1,[10])', g.get_full_display_string())",
"circuit = ic.IBMCircuit(10)\nw1 = iw.IBMInputWire('w1', circuit)\ng1 = iga... | <|body_start_0|>
circuit = ic.IBMCircuit(10)
w1 = iw.IBMInputWire('w1', circuit)
const = ci.Input([ib.IBMBatch([True, False])])
g = igac.IBMAddConstGate('g', w1, const, circuit)
self.assertEquals('g:LADDconst(w1,[10])', g.get_full_display_string())
<|end_body_0|>
<|body_start_1|... | TestAddConstGate | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAddConstGate:
def test_get_full_display_string(self):
"""Tests that the method get_full_display_string returns the correct string."""
<|body_0|>
def test_get_depth(self):
"""Tests that the get_depth method returns the correct depth, as defined by IBM."""
... | stack_v2_sparse_classes_75kplus_train_005681 | 2,468 | permissive | [
{
"docstring": "Tests that the method get_full_display_string returns the correct string.",
"name": "test_get_full_display_string",
"signature": "def test_get_full_display_string(self)"
},
{
"docstring": "Tests that the get_depth method returns the correct depth, as defined by IBM.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_032014 | Implement the Python class `TestAddConstGate` described below.
Class description:
Implement the TestAddConstGate class.
Method signatures and docstrings:
- def test_get_full_display_string(self): Tests that the method get_full_display_string returns the correct string.
- def test_get_depth(self): Tests that the get_d... | Implement the Python class `TestAddConstGate` described below.
Class description:
Implement the TestAddConstGate class.
Method signatures and docstrings:
- def test_get_full_display_string(self): Tests that the method get_full_display_string returns the correct string.
- def test_get_depth(self): Tests that the get_d... | 264459a8fa1480c7b65d946f88d94af1a038fbf1 | <|skeleton|>
class TestAddConstGate:
def test_get_full_display_string(self):
"""Tests that the method get_full_display_string returns the correct string."""
<|body_0|>
def test_get_depth(self):
"""Tests that the get_depth method returns the correct depth, as defined by IBM."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAddConstGate:
def test_get_full_display_string(self):
"""Tests that the method get_full_display_string returns the correct string."""
circuit = ic.IBMCircuit(10)
w1 = iw.IBMInputWire('w1', circuit)
const = ci.Input([ib.IBMBatch([True, False])])
g = igac.IBMAddConstG... | the_stack_v2_python_sparse | hetest/python/circuit_generation/ibm/ibm_gate_add_const_test.py | y4n9squared/HEtest | train | 7 | |
83ad907c34c44eb7f73c8ad4886e4f767a23d56f | [
"example_id = single_example['id']\nquery = single_example['query']\ndocs = single_example['supports']\nif shuffle_docs_within_example:\n random.shuffle(docs)\ncandidate_answers = single_example['candidates']\ncandidate_answers = [candidate.strip() for candidate in candidate_answers]\ncandidate_answers = [candid... | <|body_start_0|>
example_id = single_example['id']
query = single_example['query']
docs = single_example['supports']
if shuffle_docs_within_example:
random.shuffle(docs)
candidate_answers = single_example['candidates']
candidate_answers = [candidate.strip() fo... | A single training/test example for the WikiHop dataset. | WikiHopExample | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiHopExample:
"""A single training/test example for the WikiHop dataset."""
def from_json(cls, single_example: Dict[Text, Any], shuffle_docs_within_example: bool=False) -> 'WikiHopExample':
"""Returns a single one `WikiHopExample` from the given json example."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_005682 | 34,106 | permissive | [
{
"docstring": "Returns a single one `WikiHopExample` from the given json example.",
"name": "from_json",
"signature": "def from_json(cls, single_example: Dict[Text, Any], shuffle_docs_within_example: bool=False) -> 'WikiHopExample'"
},
{
"docstring": "Parses multiple WikiHopExamples from the gi... | 2 | stack_v2_sparse_classes_30k_train_053058 | Implement the Python class `WikiHopExample` described below.
Class description:
A single training/test example for the WikiHop dataset.
Method signatures and docstrings:
- def from_json(cls, single_example: Dict[Text, Any], shuffle_docs_within_example: bool=False) -> 'WikiHopExample': Returns a single one `WikiHopExa... | Implement the Python class `WikiHopExample` described below.
Class description:
A single training/test example for the WikiHop dataset.
Method signatures and docstrings:
- def from_json(cls, single_example: Dict[Text, Any], shuffle_docs_within_example: bool=False) -> 'WikiHopExample': Returns a single one `WikiHopExa... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class WikiHopExample:
"""A single training/test example for the WikiHop dataset."""
def from_json(cls, single_example: Dict[Text, Any], shuffle_docs_within_example: bool=False) -> 'WikiHopExample':
"""Returns a single one `WikiHopExample` from the given json example."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WikiHopExample:
"""A single training/test example for the WikiHop dataset."""
def from_json(cls, single_example: Dict[Text, Any], shuffle_docs_within_example: bool=False) -> 'WikiHopExample':
"""Returns a single one `WikiHopExample` from the given json example."""
example_id = single_exam... | the_stack_v2_python_sparse | etcmodel/models/wikihop/data_utils.py | Jimmy-INL/google-research | train | 1 |
a970b507741bcd2b7bd2659887c6c90985b6b7c5 | [
"super(AlternatingCoattention, self).__init__()\nself.n_entities = 1 if weight_tying else 2\nwith self.init_scope():\n self.energy_layers_1 = chainer.ChainList(*[GraphLinear(hidden_dim + out_dim, head) for _ in range(self.n_entities)])\n self.energy_layers_2 = chainer.ChainList(*[GraphLinear(head, 1)])\n s... | <|body_start_0|>
super(AlternatingCoattention, self).__init__()
self.n_entities = 1 if weight_tying else 2
with self.init_scope():
self.energy_layers_1 = chainer.ChainList(*[GraphLinear(hidden_dim + out_dim, head) for _ in range(self.n_entities)])
self.energy_layers_2 = c... | AlternatingCoattention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlternatingCoattention:
def __init__(self, hidden_dim, out_dim, head, weight_tying=False):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism :param weight_tying: indicate whethe... | stack_v2_sparse_classes_75kplus_train_005683 | 3,771 | permissive | [
{
"docstring": ":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism :param weight_tying: indicate whether the weights should be shared between two attention computation",
"name": "__init__",
"signat... | 3 | stack_v2_sparse_classes_30k_train_041269 | Implement the Python class `AlternatingCoattention` described below.
Class description:
Implement the AlternatingCoattention class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, weight_tying=False): :param hidden_dim: dimension of atom representation :param out_dim: dimension of mo... | Implement the Python class `AlternatingCoattention` described below.
Class description:
Implement the AlternatingCoattention class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, weight_tying=False): :param hidden_dim: dimension of atom representation :param out_dim: dimension of mo... | 21b64a3c8cc9bc33718ae09c65aa917e575132eb | <|skeleton|>
class AlternatingCoattention:
def __init__(self, hidden_dim, out_dim, head, weight_tying=False):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism :param weight_tying: indicate whethe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlternatingCoattention:
def __init__(self, hidden_dim, out_dim, head, weight_tying=False):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism :param weight_tying: indicate whether the weights ... | the_stack_v2_python_sparse | models/coattention/alternating_coattention.py | Minys233/GCN-BMP | train | 1 | |
ba675f940f0520805fc9ab5875a3f81f8d3102b8 | [
"nc = []\nfor m in ObjectModel.objects.all():\n for c in m.connections:\n nc += [{'type': c.type.id, 'gender': c.gender, 'model': m.id, 'name': c.name}]\ncollection = ModelConnectionsCache._get_collection()\ncollection.drop()\nif nc:\n collection.insert(nc)",
"cache = {}\ncollection = ModelConnection... | <|body_start_0|>
nc = []
for m in ObjectModel.objects.all():
for c in m.connections:
nc += [{'type': c.type.id, 'gender': c.gender, 'model': m.id, 'name': c.name}]
collection = ModelConnectionsCache._get_collection()
collection.drop()
if nc:
... | ModelConnectionsCache | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelConnectionsCache:
def rebuild(cls):
"""Rebuild cache"""
<|body_0|>
def update_for_model(cls, model: 'ObjectModel'):
"""Update connection cache for object model :param model: ObjectModel instance :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005684 | 15,000 | permissive | [
{
"docstring": "Rebuild cache",
"name": "rebuild",
"signature": "def rebuild(cls)"
},
{
"docstring": "Update connection cache for object model :param model: ObjectModel instance :return:",
"name": "update_for_model",
"signature": "def update_for_model(cls, model: 'ObjectModel')"
}
] | 2 | null | Implement the Python class `ModelConnectionsCache` described below.
Class description:
Implement the ModelConnectionsCache class.
Method signatures and docstrings:
- def rebuild(cls): Rebuild cache
- def update_for_model(cls, model: 'ObjectModel'): Update connection cache for object model :param model: ObjectModel in... | Implement the Python class `ModelConnectionsCache` described below.
Class description:
Implement the ModelConnectionsCache class.
Method signatures and docstrings:
- def rebuild(cls): Rebuild cache
- def update_for_model(cls, model: 'ObjectModel'): Update connection cache for object model :param model: ObjectModel in... | 6e6d71574e9b9d822bec572cc629a0ea73604a59 | <|skeleton|>
class ModelConnectionsCache:
def rebuild(cls):
"""Rebuild cache"""
<|body_0|>
def update_for_model(cls, model: 'ObjectModel'):
"""Update connection cache for object model :param model: ObjectModel instance :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelConnectionsCache:
def rebuild(cls):
"""Rebuild cache"""
nc = []
for m in ObjectModel.objects.all():
for c in m.connections:
nc += [{'type': c.type.id, 'gender': c.gender, 'model': m.id, 'name': c.name}]
collection = ModelConnectionsCache._get_co... | the_stack_v2_python_sparse | inv/models/objectmodel.py | nocproject/noc | train | 105 | |
b3d45fbcfc82240332354bca5dbe5c5e20f7d859 | [
"data = request.form\nuid = g.uid\nuser = User.with_id(uid)\nfor key in data:\n if key not in ('nickname', 'github', 'avatar', 'favorite_public'):\n continue\n setattr(user, key, data[key])\ntry:\n user.save()\nexcept NotUniqueError:\n raise ArgsError(message='昵称已经被使用!')\nelse:\n return {'payl... | <|body_start_0|>
data = request.form
uid = g.uid
user = User.with_id(uid)
for key in data:
if key not in ('nickname', 'github', 'avatar', 'favorite_public'):
continue
setattr(user, key, data[key])
try:
user.save()
except... | UserSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSettings:
def post(self):
"""@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @a... | stack_v2_sparse_classes_75kplus_train_005685 | 8,793 | no_license | [
{
"docstring": "@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @apiSuccessExample {json} Success-Response:... | 2 | stack_v2_sparse_classes_30k_test_002772 | Implement the Python class `UserSettings` described below.
Class description:
Implement the UserSettings class.
Method signatures and docstrings:
- def post(self): @apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @a... | Implement the Python class `UserSettings` described below.
Class description:
Implement the UserSettings class.
Method signatures and docstrings:
- def post(self): @apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @a... | 4b7fdfe3f2bcf3d3d0e0bc7c687b75991db1f2df | <|skeleton|>
class UserSettings:
def post(self):
"""@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSettings:
def post(self):
"""@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @apiSuccessExamp... | the_stack_v2_python_sparse | app/modules/accounts/apis.py | geasyheart/git-share | train | 0 | |
4e277e8fd0901fed2693d88944c8c7e7f3abf393 | [
"if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15):\n raise ValueError('server_max_window_bits must be between 8 and 15')\nif not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15):\n raise ValueError('client_max_window_bits must be between 8 and 15')\nif compress... | <|body_start_0|>
if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15):
raise ValueError('server_max_window_bits must be between 8 and 15')
if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15):
raise ValueError('client_max_window_bit... | Server-side extension factory for the Per-Message Deflate extension. Parameters behave as described in `section 7.1 of RFC 7692`_. Set them to ``True`` to include them in the negotiation offer without a value or to an integer value to include them with this value. .. _section 7.1 of RFC 7692: https://tools.ietf.org/htm... | ServerPerMessageDeflateFactory | [
"BSD-3-Clause",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerPerMessageDeflateFactory:
"""Server-side extension factory for the Per-Message Deflate extension. Parameters behave as described in `section 7.1 of RFC 7692`_. Set them to ``True`` to include them in the negotiation offer without a value or to an integer value to include them with this valu... | stack_v2_sparse_classes_75kplus_train_005686 | 21,730 | permissive | [
{
"docstring": "Configure the Per-Message Deflate extension factory.",
"name": "__init__",
"signature": "def __init__(self, server_no_context_takeover: bool=False, client_no_context_takeover: bool=False, server_max_window_bits: Optional[int]=None, client_max_window_bits: Optional[int]=None, compress_set... | 2 | null | Implement the Python class `ServerPerMessageDeflateFactory` described below.
Class description:
Server-side extension factory for the Per-Message Deflate extension. Parameters behave as described in `section 7.1 of RFC 7692`_. Set them to ``True`` to include them in the negotiation offer without a value or to an integ... | Implement the Python class `ServerPerMessageDeflateFactory` described below.
Class description:
Server-side extension factory for the Per-Message Deflate extension. Parameters behave as described in `section 7.1 of RFC 7692`_. Set them to ``True`` to include them in the negotiation offer without a value or to an integ... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class ServerPerMessageDeflateFactory:
"""Server-side extension factory for the Per-Message Deflate extension. Parameters behave as described in `section 7.1 of RFC 7692`_. Set them to ``True`` to include them in the negotiation offer without a value or to an integer value to include them with this valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServerPerMessageDeflateFactory:
"""Server-side extension factory for the Per-Message Deflate extension. Parameters behave as described in `section 7.1 of RFC 7692`_. Set them to ``True`` to include them in the negotiation offer without a value or to an integer value to include them with this value. .. _sectio... | the_stack_v2_python_sparse | third_party/wpt_tools/wpt/tools/third_party/websockets/src/websockets/extensions/permessage_deflate.py | chromium/chromium | train | 17,408 |
e75302df942667cbcc8873ac4e9fa5213d9f3837 | [
"self.enable_bf16 = enable_bf16\nif enable_bf16:\n ipex.enable_auto_mixed_precision(mixed_dtype=torch.bfloat16)\nsuper().__init__(accelerator=accelerator, precision_plugin=precision_plugin)",
"super().setup(trainer)\ndtype = torch.bfloat16 if self.enable_bf16 else None\nif len(self.optimizers) == 0:\n ipex.... | <|body_start_0|>
self.enable_bf16 = enable_bf16
if enable_bf16:
ipex.enable_auto_mixed_precision(mixed_dtype=torch.bfloat16)
super().__init__(accelerator=accelerator, precision_plugin=precision_plugin)
<|end_body_0|>
<|body_start_1|>
super().setup(trainer)
dtype = to... | IPEX strategy. | IPEXStrategy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPEXStrategy:
"""IPEX strategy."""
def __init__(self, accelerator: Accelerator=IPEXAccelerator(), precision_plugin: PrecisionPlugin=PrecisionPlugin(), enable_bf16=False) -> None:
"""Create a IPEXStrategy. :param accelerator: the accelerator to handle hardware :param precision_plugin:... | stack_v2_sparse_classes_75kplus_train_005687 | 2,385 | permissive | [
{
"docstring": "Create a IPEXStrategy. :param accelerator: the accelerator to handle hardware :param precision_plugin: the plugin to handle precision-specific parts",
"name": "__init__",
"signature": "def __init__(self, accelerator: Accelerator=IPEXAccelerator(), precision_plugin: PrecisionPlugin=Precis... | 2 | stack_v2_sparse_classes_30k_test_001967 | Implement the Python class `IPEXStrategy` described below.
Class description:
IPEX strategy.
Method signatures and docstrings:
- def __init__(self, accelerator: Accelerator=IPEXAccelerator(), precision_plugin: PrecisionPlugin=PrecisionPlugin(), enable_bf16=False) -> None: Create a IPEXStrategy. :param accelerator: th... | Implement the Python class `IPEXStrategy` described below.
Class description:
IPEX strategy.
Method signatures and docstrings:
- def __init__(self, accelerator: Accelerator=IPEXAccelerator(), precision_plugin: PrecisionPlugin=PrecisionPlugin(), enable_bf16=False) -> None: Create a IPEXStrategy. :param accelerator: th... | 95f677ab34867f1d91df0ed8e1bc760ea610f791 | <|skeleton|>
class IPEXStrategy:
"""IPEX strategy."""
def __init__(self, accelerator: Accelerator=IPEXAccelerator(), precision_plugin: PrecisionPlugin=PrecisionPlugin(), enable_bf16=False) -> None:
"""Create a IPEXStrategy. :param accelerator: the accelerator to handle hardware :param precision_plugin:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPEXStrategy:
"""IPEX strategy."""
def __init__(self, accelerator: Accelerator=IPEXAccelerator(), precision_plugin: PrecisionPlugin=PrecisionPlugin(), enable_bf16=False) -> None:
"""Create a IPEXStrategy. :param accelerator: the accelerator to handle hardware :param precision_plugin: the plugin t... | the_stack_v2_python_sparse | python/nano/src/bigdl/nano/pytorch/strategies/ipex/ipex_strategy.py | helenlly/BigDL | train | 0 |
1ec205724032467c9c22fa6c21828829fd81a532 | [
"if not nums:\n return False\n_set = set(nums)\nreturn len(_set) != len(nums)",
"if not nums:\n return False\nnum_idx = {}\nfor idx, num in enumerate(nums):\n if num not in num_idx:\n num_idx[num] = idx\n continue\n if idx - num_idx[num] <= k:\n return True\n num_idx[num] = idx... | <|body_start_0|>
if not nums:
return False
_set = set(nums)
return len(_set) != len(nums)
<|end_body_0|>
<|body_start_1|>
if not nums:
return False
num_idx = {}
for idx, num in enumerate(nums):
if num not in num_idx:
nu... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
"""https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate_ii(self, nums, k):
"""https://leetcode.com/problems/contains-duplicate-ii/ :type nums: List[int] :... | stack_v2_sparse_classes_75kplus_train_005688 | 884 | permissive | [
{
"docstring": "https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool",
"name": "containsDuplicate",
"signature": "def containsDuplicate(self, nums)"
},
{
"docstring": "https://leetcode.com/problems/contains-duplicate-ii/ :type nums: List[int] :rtype: bool",
"n... | 2 | stack_v2_sparse_classes_30k_train_023429 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool
- def containsDuplicate_ii(self, nums, k): https://leetcod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool
- def containsDuplicate_ii(self, nums, k): https://leetcod... | 88f0a0eb377fbf9d233e599736c740bb83b8ccef | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
"""https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate_ii(self, nums, k):
"""https://leetcode.com/problems/contains-duplicate-ii/ :type nums: List[int] :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsDuplicate(self, nums):
"""https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool"""
if not nums:
return False
_set = set(nums)
return len(_set) != len(nums)
def containsDuplicate_ii(self, nums, k):
"""... | the_stack_v2_python_sparse | array_function/contains_duplicate.py | lycheng/leetcode | train | 0 | |
5b9d3901786b8d61cee24384f1ffefda23cb2939 | [
"assert type(params) in [SimpleTunnelSurveyImplicitParams], 'params must be a SimpleTunnelParams, not {}'.format(type(params))\nself.tunnelParams = deepcopy(params)\nxOrigin = self.tunnelParams.meshXOrigin\nhx, hy, hz = (self.tunnelParams.hx, self.tunnelParams.hy, self.tunnelParams.hz)\nMesh.TensorMesh.__init__(sel... | <|body_start_0|>
assert type(params) in [SimpleTunnelSurveyImplicitParams], 'params must be a SimpleTunnelParams, not {}'.format(type(params))
self.tunnelParams = deepcopy(params)
xOrigin = self.tunnelParams.meshXOrigin
hx, hy, hz = (self.tunnelParams.hx, self.tunnelParams.hy, self.tunne... | SimpleTunnelMesh represents tunnel and its surroundings. | SimpleTunnelMesh | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTunnelMesh:
"""SimpleTunnelMesh represents tunnel and its surroundings."""
def __init__(self, params):
"""SimpleTunnelMesh instance initialisation :param params:"""
<|body_0|>
def getCoreMesh(self):
"""Extracts and provides core mesh :return: indices of cor... | stack_v2_sparse_classes_75kplus_train_005689 | 14,228 | no_license | [
{
"docstring": "SimpleTunnelMesh instance initialisation :param params:",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Extracts and provides core mesh :return: indices of core mesh, core mesh",
"name": "getCoreMesh",
"signature": "def getCoreMesh(self)... | 4 | stack_v2_sparse_classes_30k_train_044408 | Implement the Python class `SimpleTunnelMesh` described below.
Class description:
SimpleTunnelMesh represents tunnel and its surroundings.
Method signatures and docstrings:
- def __init__(self, params): SimpleTunnelMesh instance initialisation :param params:
- def getCoreMesh(self): Extracts and provides core mesh :r... | Implement the Python class `SimpleTunnelMesh` described below.
Class description:
SimpleTunnelMesh represents tunnel and its surroundings.
Method signatures and docstrings:
- def __init__(self, params): SimpleTunnelMesh instance initialisation :param params:
- def getCoreMesh(self): Extracts and provides core mesh :r... | 22bc1a0cad78369ac3d4bf12252b89fe95a22d21 | <|skeleton|>
class SimpleTunnelMesh:
"""SimpleTunnelMesh represents tunnel and its surroundings."""
def __init__(self, params):
"""SimpleTunnelMesh instance initialisation :param params:"""
<|body_0|>
def getCoreMesh(self):
"""Extracts and provides core mesh :return: indices of cor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleTunnelMesh:
"""SimpleTunnelMesh represents tunnel and its surroundings."""
def __init__(self, params):
"""SimpleTunnelMesh instance initialisation :param params:"""
assert type(params) in [SimpleTunnelSurveyImplicitParams], 'params must be a SimpleTunnelParams, not {}'.format(type(p... | the_stack_v2_python_sparse | Jirina/dc_tunnel_inversion/Tunnel_ParamMeshTools.py | GeoMop/geostab | train | 1 |
09dc5b08544f1c579a47c0861aef266f7eb885f8 | [
"if n < 3:\n return 0\nelse:\n num_list = [1] * n\n num_list[0], num_list[1] = (0, 0)\n for i in range(2, int(n ** 0.5 + 1)):\n if num_list[i] == 1:\n num_list[i * i:n:i] = [0] * len(num_list[i * i:n:i])\n return sum(num_list)",
"pre = None\nwhile head:\n tmp = head.next\n h... | <|body_start_0|>
if n < 3:
return 0
else:
num_list = [1] * n
num_list[0], num_list[1] = (0, 0)
for i in range(2, int(n ** 0.5 + 1)):
if num_list[i] == 1:
num_list[i * i:n:i] = [0] * len(num_list[i * i:n:i])
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 3:
return 0
else:
... | stack_v2_sparse_classes_75kplus_train_005690 | 1,059 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012910 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def reverseList(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def countPrimes(self, n... | 4251f7d8f4b5c30546424f823a0ec527a06dda5d | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
if n < 3:
return 0
else:
num_list = [1] * n
num_list[0], num_list[1] = (0, 0)
for i in range(2, int(n ** 0.5 + 1)):
if num_list[i] == 1:
... | the_stack_v2_python_sparse | leetcode/11-27-test.py | MaLei666/learngit | train | 0 | |
c30279f41dc2b5b6bdd1b7dc28afcbd6c8aca00f | [
"if not board or not board[0]:\n return\nm, n = (len(board), len(board[0]))\nqueue = []\nfor i in [0, m - 1]:\n for j in range(n):\n if board[i][j] == 'O':\n board[i][j] = '0'\n queue.append((i, j))\nfor i in range(m):\n for j in [0, n - 1]:\n if board[i][j] == 'O':\n ... | <|body_start_0|>
if not board or not board[0]:
return
m, n = (len(board), len(board[0]))
queue = []
for i in [0, m - 1]:
for j in range(n):
if board[i][j] == 'O':
board[i][j] = '0'
queue.append((i, j))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, board):
"""记录下边界的O的坐标,放入队列,同时修改为零0, bfs搜索能传染到的相邻的O 同样修改为0 最后遍历board 将所有的O修改为X,0修改为O :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead."""
<|body_0|>
def solve2(self, board):
"""dfs 实现 :param boar... | stack_v2_sparse_classes_75kplus_train_005691 | 3,506 | no_license | [
{
"docstring": "记录下边界的O的坐标,放入队列,同时修改为零0, bfs搜索能传染到的相邻的O 同样修改为0 最后遍历board 将所有的O修改为X,0修改为O :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead.",
"name": "solve",
"signature": "def solve(self, board)"
},
{
"docstring": "dfs 实现 :param board: :return:",
... | 2 | stack_v2_sparse_classes_30k_val_001298 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board): 记录下边界的O的坐标,放入队列,同时修改为零0, bfs搜索能传染到的相邻的O 同样修改为0 最后遍历board 将所有的O修改为X,0修改为O :type board: List[List[str]] :rtype: None Do not return anything, modify board in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board): 记录下边界的O的坐标,放入队列,同时修改为零0, bfs搜索能传染到的相邻的O 同样修改为0 最后遍历board 将所有的O修改为X,0修改为O :type board: List[List[str]] :rtype: None Do not return anything, modify board in... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def solve(self, board):
"""记录下边界的O的坐标,放入队列,同时修改为零0, bfs搜索能传染到的相邻的O 同样修改为0 最后遍历board 将所有的O修改为X,0修改为O :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead."""
<|body_0|>
def solve2(self, board):
"""dfs 实现 :param boar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def solve(self, board):
"""记录下边界的O的坐标,放入队列,同时修改为零0, bfs搜索能传染到的相邻的O 同样修改为0 最后遍历board 将所有的O修改为X,0修改为O :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead."""
if not board or not board[0]:
return
m, n = (len(board), len(boa... | the_stack_v2_python_sparse | 130_被围绕的区域.py | lovehhf/LeetCode | train | 0 | |
c5db776460b6da3b20a20e7b870c6b0ae6671008 | [
"self.cluster_coreferents = []\nfor pdt_coreferent in list_of_corefs:\n target_cluster_coreferent = self.get_cluster_coreferent(pdt_coreferent.coref_node, pdt_coreferent.coref_dropped)\n own_cluster_coreferent = self.get_cluster_coreferent(pdt_coreferent.own_node, pdt_coreferent.own_dropped)\n target_clust... | <|body_start_0|>
self.cluster_coreferents = []
for pdt_coreferent in list_of_corefs:
target_cluster_coreferent = self.get_cluster_coreferent(pdt_coreferent.coref_node, pdt_coreferent.coref_dropped)
own_cluster_coreferent = self.get_cluster_coreferent(pdt_coreferent.own_node, pdt_... | Pdt_coreference_setter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pdt_coreference_setter:
def execute(self, list_of_corefs):
"""called from outside list of corefs - list of Pdt_coreferent"""
<|body_0|>
def get_cluster_coreferent(self, node, dropped):
"""finding cluster coreferent if this cluster was already used, returns it. otherw... | stack_v2_sparse_classes_75kplus_train_005692 | 3,033 | no_license | [
{
"docstring": "called from outside list of corefs - list of Pdt_coreferent",
"name": "execute",
"signature": "def execute(self, list_of_corefs)"
},
{
"docstring": "finding cluster coreferent if this cluster was already used, returns it. otherwise will create a new one",
"name": "get_cluster... | 2 | stack_v2_sparse_classes_30k_train_039716 | Implement the Python class `Pdt_coreference_setter` described below.
Class description:
Implement the Pdt_coreference_setter class.
Method signatures and docstrings:
- def execute(self, list_of_corefs): called from outside list of corefs - list of Pdt_coreferent
- def get_cluster_coreferent(self, node, dropped): find... | Implement the Python class `Pdt_coreference_setter` described below.
Class description:
Implement the Pdt_coreference_setter class.
Method signatures and docstrings:
- def execute(self, list_of_corefs): called from outside list of corefs - list of Pdt_coreferent
- def get_cluster_coreferent(self, node, dropped): find... | 41b13ce6422ac6c3d139474641e75e502c446162 | <|skeleton|>
class Pdt_coreference_setter:
def execute(self, list_of_corefs):
"""called from outside list of corefs - list of Pdt_coreferent"""
<|body_0|>
def get_cluster_coreferent(self, node, dropped):
"""finding cluster coreferent if this cluster was already used, returns it. otherw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pdt_coreference_setter:
def execute(self, list_of_corefs):
"""called from outside list of corefs - list of Pdt_coreferent"""
self.cluster_coreferents = []
for pdt_coreferent in list_of_corefs:
target_cluster_coreferent = self.get_cluster_coreferent(pdt_coreferent.coref_node... | the_stack_v2_python_sparse | PDT/pdt_coreference_setter.py | Jankus1994/Coreference | train | 0 | |
5d3c7b4bb2871d5630d0d34851071abb42abd614 | [
"count = 0\ntempNode = head\nwhile tempNode:\n tempNode = tempNode.next\n count += 1\nres = head\nfor i in range(count - k):\n res = res.next\nreturn res",
"former = latter = head\nfor i in range(k):\n former = former.next\nwhile former:\n former, latter = (former.next, latter.next)\nreturn latter"... | <|body_start_0|>
count = 0
tempNode = head
while tempNode:
tempNode = tempNode.next
count += 1
res = head
for i in range(count - k):
res = res.next
return res
<|end_body_0|>
<|body_start_1|>
former = latter = head
for i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
"""第一时间想到的解法: 1,通过遍历统计链表长度,记为 n 2,设置一个指针走(n-k)步,即可找到链表倒数第k个结点 (因为题目说了,计算从 1 开始,所以指针为(n-k)"""
<|body_0|>
def getKthFromEnd1(self, head: ListNode, k: int) -> ListNode:
"""使用双指针则可以不用统计链表长度,只遍历一次链表 算法... | stack_v2_sparse_classes_75kplus_train_005693 | 3,408 | no_license | [
{
"docstring": "第一时间想到的解法: 1,通过遍历统计链表长度,记为 n 2,设置一个指针走(n-k)步,即可找到链表倒数第k个结点 (因为题目说了,计算从 1 开始,所以指针为(n-k)",
"name": "getKthFromEnd",
"signature": "def getKthFromEnd(self, head: ListNode, k: int) -> ListNode"
},
{
"docstring": "使用双指针则可以不用统计链表长度,只遍历一次链表 算法流程: 1,初始化:前指针 fromer,后指针 latter,双指针都指向头节点 hea... | 4 | stack_v2_sparse_classes_30k_train_006913 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: 第一时间想到的解法: 1,通过遍历统计链表长度,记为 n 2,设置一个指针走(n-k)步,即可找到链表倒数第k个结点 (因为题目说了,计算从 1 开始,所以指针为(n-k)
- def getKthFromEnd1(self, hea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: 第一时间想到的解法: 1,通过遍历统计链表长度,记为 n 2,设置一个指针走(n-k)步,即可找到链表倒数第k个结点 (因为题目说了,计算从 1 开始,所以指针为(n-k)
- def getKthFromEnd1(self, hea... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
"""第一时间想到的解法: 1,通过遍历统计链表长度,记为 n 2,设置一个指针走(n-k)步,即可找到链表倒数第k个结点 (因为题目说了,计算从 1 开始,所以指针为(n-k)"""
<|body_0|>
def getKthFromEnd1(self, head: ListNode, k: int) -> ListNode:
"""使用双指针则可以不用统计链表长度,只遍历一次链表 算法... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
"""第一时间想到的解法: 1,通过遍历统计链表长度,记为 n 2,设置一个指针走(n-k)步,即可找到链表倒数第k个结点 (因为题目说了,计算从 1 开始,所以指针为(n-k)"""
count = 0
tempNode = head
while tempNode:
tempNode = tempNode.next
count += 1
res ... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/22_链表中倒数第K个结点.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
3a5f2b349868f6b2bdebece991fe1e18d0cf23da | [
"matrix = cm()\nmatrix['p']['p'] += 2\nmatrix['p']['n'] = 3\nself.assertEqual(matrix['p']['p'], 2)\nself.assertEqual(matrix['p']['n'], 3)\nself.assertEqual(matrix['p']['f'], 0)\nself.assertEqual(matrix['a']['b'], 0)",
"exception = False\nmatrix = cm()\ntry:\n matrix['a'] = 0\nexcept AttributeError:\n except... | <|body_start_0|>
matrix = cm()
matrix['p']['p'] += 2
matrix['p']['n'] = 3
self.assertEqual(matrix['p']['p'], 2)
self.assertEqual(matrix['p']['n'], 3)
self.assertEqual(matrix['p']['f'], 0)
self.assertEqual(matrix['a']['b'], 0)
<|end_body_0|>
<|body_start_1|>
... | Confusion matrix tests. | TestConfusionMatrix | [
"Apache-2.0",
"BSD-3-Clause",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConfusionMatrix:
"""Confusion matrix tests."""
def test_matrix_set_add(self):
"""Test matrix."""
<|body_0|>
def test_setitem(self):
"""Ensure that __setitem__ raises an AttributeError"""
<|body_1|>
def test_matrix_classes(self):
"""Test m... | stack_v2_sparse_classes_75kplus_train_005694 | 8,979 | permissive | [
{
"docstring": "Test matrix.",
"name": "test_matrix_set_add",
"signature": "def test_matrix_set_add(self)"
},
{
"docstring": "Ensure that __setitem__ raises an AttributeError",
"name": "test_setitem",
"signature": "def test_setitem(self)"
},
{
"docstring": "Test matrix.",
"na... | 3 | stack_v2_sparse_classes_30k_train_037114 | Implement the Python class `TestConfusionMatrix` described below.
Class description:
Confusion matrix tests.
Method signatures and docstrings:
- def test_matrix_set_add(self): Test matrix.
- def test_setitem(self): Ensure that __setitem__ raises an AttributeError
- def test_matrix_classes(self): Test matrix. | Implement the Python class `TestConfusionMatrix` described below.
Class description:
Confusion matrix tests.
Method signatures and docstrings:
- def test_matrix_set_add(self): Test matrix.
- def test_setitem(self): Ensure that __setitem__ raises an AttributeError
- def test_matrix_classes(self): Test matrix.
<|skele... | 50840a63de5449dff5f7e1a4066da7aa113d6be1 | <|skeleton|>
class TestConfusionMatrix:
"""Confusion matrix tests."""
def test_matrix_set_add(self):
"""Test matrix."""
<|body_0|>
def test_setitem(self):
"""Ensure that __setitem__ raises an AttributeError"""
<|body_1|>
def test_matrix_classes(self):
"""Test m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestConfusionMatrix:
"""Confusion matrix tests."""
def test_matrix_set_add(self):
"""Test matrix."""
matrix = cm()
matrix['p']['p'] += 2
matrix['p']['n'] = 3
self.assertEqual(matrix['p']['p'], 2)
self.assertEqual(matrix['p']['n'], 3)
self.assertEqua... | the_stack_v2_python_sparse | code/experiments/src/main/python/segeval/ml/test.py | habernal/emnlp2015 | train | 4 |
03c0812015844c4cb1651b49a56ad4bf100610b6 | [
"super().__init__(positioning)\nif default:\n self.default = default",
"try:\n return super().get_current_position()\nexcept CaptionReadSyntaxError:\n return self.default",
"if positioning:\n self.default = positioning\nsuper().update_positioning(positioning)"
] | <|body_start_0|>
super().__init__(positioning)
if default:
self.default = default
<|end_body_0|>
<|body_start_1|>
try:
return super().get_current_position()
except CaptionReadSyntaxError:
return self.default
<|end_body_1|>
<|body_start_2|>
if... | A _PositioningTracker that provides if needed a default value (14, 0), or uses the last positioning value set anywhere in the document | DefaultProvidingPositionTracker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultProvidingPositionTracker:
"""A _PositioningTracker that provides if needed a default value (14, 0), or uses the last positioning value set anywhere in the document"""
def __init__(self, positioning=None, default=None):
""":type positioning: tuple[int] :param positioning: a tup... | stack_v2_sparse_classes_75kplus_train_005695 | 4,658 | permissive | [
{
"docstring": ":type positioning: tuple[int] :param positioning: a tuple of ints (row, column) :type default: tuple[int] :param default: a tuple of ints (row, column) to use as fallback",
"name": "__init__",
"signature": "def __init__(self, positioning=None, default=None)"
},
{
"docstring": "Re... | 3 | stack_v2_sparse_classes_30k_train_006344 | Implement the Python class `DefaultProvidingPositionTracker` described below.
Class description:
A _PositioningTracker that provides if needed a default value (14, 0), or uses the last positioning value set anywhere in the document
Method signatures and docstrings:
- def __init__(self, positioning=None, default=None)... | Implement the Python class `DefaultProvidingPositionTracker` described below.
Class description:
A _PositioningTracker that provides if needed a default value (14, 0), or uses the last positioning value set anywhere in the document
Method signatures and docstrings:
- def __init__(self, positioning=None, default=None)... | 75cf981744d71fd0b4875bf21346a67014be81bf | <|skeleton|>
class DefaultProvidingPositionTracker:
"""A _PositioningTracker that provides if needed a default value (14, 0), or uses the last positioning value set anywhere in the document"""
def __init__(self, positioning=None, default=None):
""":type positioning: tuple[int] :param positioning: a tup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultProvidingPositionTracker:
"""A _PositioningTracker that provides if needed a default value (14, 0), or uses the last positioning value set anywhere in the document"""
def __init__(self, positioning=None, default=None):
""":type positioning: tuple[int] :param positioning: a tuple of ints (r... | the_stack_v2_python_sparse | pycaption/scc/state_machines.py | pbs/pycaption | train | 205 |
e24be568aa9f47113199c4a12fdce02f810c7802 | [
"begin, end = (0, len(S))\nq = (1 << 31) - 1\nanswer = ''\nwhile begin + 1 < end:\n mid = (begin + end) // 2\n found, candidate = self.RabinKarp(S, mid, q)\n if found:\n begin, answer = (mid, candidate)\n else:\n end = mid\nreturn answer",
"if M == 0:\n return True\nh = (1 << 8 * M - ... | <|body_start_0|>
begin, end = (0, len(S))
q = (1 << 31) - 1
answer = ''
while begin + 1 < end:
mid = (begin + end) // 2
found, candidate = self.RabinKarp(S, mid, q)
if found:
begin, answer = (mid, candidate)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestDupSubstring(self, S: str) -> str:
"""https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained"""
<|body_0|>
def RabinKarp(self, S: str, M: int, q: int) -> bool:
""... | stack_v2_sparse_classes_75kplus_train_005696 | 2,008 | no_license | [
{
"docstring": "https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained",
"name": "longestDupSubstring",
"signature": "def longestDupSubstring(self, S: str) -> str"
},
{
"docstring": "Using rolling hash to hash th... | 2 | stack_v2_sparse_classes_30k_train_022032 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestDupSubstring(self, S: str) -> str: https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-exp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestDupSubstring(self, S: str) -> str: https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-exp... | da1774fd07b7326e66d9478b3d2619e0499ac2b7 | <|skeleton|>
class Solution:
def longestDupSubstring(self, S: str) -> str:
"""https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained"""
<|body_0|>
def RabinKarp(self, S: str, M: int, q: int) -> bool:
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestDupSubstring(self, S: str) -> str:
"""https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained"""
begin, end = (0, len(S))
q = (1 << 31) - 1
answer = ''
while begin + ... | the_stack_v2_python_sparse | Python3/String/LongestDuplicateSubstring/BinarySearch_RabinKarp1044.py | daviddwlee84/LeetCode | train | 14 | |
d2e7bafe7c3ddadb5bc2f938da5d470908319348 | [
"self.path = path\nself._system_site_packages = system_site_packages\nself._pypi_index_url = pypi_index_url\nself._use_wheel = use_wheel\nself._python_interpreter = python_interpreter\nself._verbose = verbose\nself._out_stream = None\nif not self._verbose:\n self._out_stream = open(os.devnull, 'w')\nself._err_st... | <|body_start_0|>
self.path = path
self._system_site_packages = system_site_packages
self._pypi_index_url = pypi_index_url
self._use_wheel = use_wheel
self._python_interpreter = python_interpreter
self._verbose = verbose
self._out_stream = None
if not self.... | Object representing a ready-to-use virtualenv | VirtualenvProxy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualenvProxy:
"""Object representing a ready-to-use virtualenv"""
def __init__(self, path, system_site_packages=False, pypi_index_url=None, use_wheel=False, python_interpreter=None, verbose=False):
"""Creates the virtualenv with the options specified"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_005697 | 4,204 | permissive | [
{
"docstring": "Creates the virtualenv with the options specified",
"name": "__init__",
"signature": "def __init__(self, path, system_site_packages=False, pypi_index_url=None, use_wheel=False, python_interpreter=None, verbose=False)"
},
{
"docstring": "Creates the actual virtualenv",
"name":... | 5 | stack_v2_sparse_classes_30k_val_000402 | Implement the Python class `VirtualenvProxy` described below.
Class description:
Object representing a ready-to-use virtualenv
Method signatures and docstrings:
- def __init__(self, path, system_site_packages=False, pypi_index_url=None, use_wheel=False, python_interpreter=None, verbose=False): Creates the virtualenv ... | Implement the Python class `VirtualenvProxy` described below.
Class description:
Object representing a ready-to-use virtualenv
Method signatures and docstrings:
- def __init__(self, path, system_site_packages=False, pypi_index_url=None, use_wheel=False, python_interpreter=None, verbose=False): Creates the virtualenv ... | 4d9c14c9df470be6ff544f2ad82985f37e582d80 | <|skeleton|>
class VirtualenvProxy:
"""Object representing a ready-to-use virtualenv"""
def __init__(self, path, system_site_packages=False, pypi_index_url=None, use_wheel=False, python_interpreter=None, verbose=False):
"""Creates the virtualenv with the options specified"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VirtualenvProxy:
"""Object representing a ready-to-use virtualenv"""
def __init__(self, path, system_site_packages=False, pypi_index_url=None, use_wheel=False, python_interpreter=None, verbose=False):
"""Creates the virtualenv with the options specified"""
self.path = path
self._s... | the_stack_v2_python_sparse | pyleus/cli/virtualenv_proxy.py | earthmine/pyleus | train | 0 |
9337c48b67d1d779f77eb40ccd3be8df5b9f06b8 | [
"super(FileSystemWinRegistryFileReader, self).__init__()\nself._file_system = file_system\nself._path_resolver = windows_path_resolver.WindowsPathResolver(file_system, mount_point)\nif path_attributes:\n for attribute_name, attribute_value in iter(path_attributes.items()):\n if attribute_name == u'systemr... | <|body_start_0|>
super(FileSystemWinRegistryFileReader, self).__init__()
self._file_system = file_system
self._path_resolver = windows_path_resolver.WindowsPathResolver(file_system, mount_point)
if path_attributes:
for attribute_name, attribute_value in iter(path_attributes.i... | A file system-based Windows Registry file reader. | FileSystemWinRegistryFileReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSystemWinRegistryFileReader:
"""A file system-based Windows Registry file reader."""
def __init__(self, file_system, mount_point, path_attributes=None):
"""Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.Path... | stack_v2_sparse_classes_75kplus_train_005698 | 9,000 | permissive | [
{
"docstring": "Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.PathSpec): mount point path specification. path_attributes (Optional[dict[str, str]]): path attributes e.g. {'SystemRoot': '\\\\Windows'}",
"name": "__init__",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_035797 | Implement the Python class `FileSystemWinRegistryFileReader` described below.
Class description:
A file system-based Windows Registry file reader.
Method signatures and docstrings:
- def __init__(self, file_system, mount_point, path_attributes=None): Initializes a Windows Registry file reader object. Args: file_syste... | Implement the Python class `FileSystemWinRegistryFileReader` described below.
Class description:
A file system-based Windows Registry file reader.
Method signatures and docstrings:
- def __init__(self, file_system, mount_point, path_attributes=None): Initializes a Windows Registry file reader object. Args: file_syste... | 0ee446ebf03d17c515f76a666bd3795e91a2dd17 | <|skeleton|>
class FileSystemWinRegistryFileReader:
"""A file system-based Windows Registry file reader."""
def __init__(self, file_system, mount_point, path_attributes=None):
"""Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.Path... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileSystemWinRegistryFileReader:
"""A file system-based Windows Registry file reader."""
def __init__(self, file_system, mount_point, path_attributes=None):
"""Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.PathSpec): mount ... | the_stack_v2_python_sparse | plaso/preprocessors/manager.py | aarontp/plaso | train | 1 |
786c009cba9e1b88aa0f7ad5a544333e1b99a974 | [
"res = {}\nfor str1 in strs:\n key_str = [0] * 26\n for tmp_str in str1:\n key_str[ord(tmp_str) - 97] += 1\n key1 = tuple(key_str)\n if key1 in res:\n res[key1].append(str1)\n else:\n res[key1] = [str1]\nreturn list(res.values())",
"mp = collections.defaultdict(list)\nfor st in... | <|body_start_0|>
res = {}
for str1 in strs:
key_str = [0] * 26
for tmp_str in str1:
key_str[ord(tmp_str) - 97] += 1
key1 = tuple(key_str)
if key1 in res:
res[key1].append(str1)
else:
res[key1] = [... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗: 19.7 MB , 在所有 Python3 提交中击败了 7.26% 的用户 :param strs: :return:"""
<|body_0|>
def groupAnagrams6(self, strs: List[str]) -> List[List[str]]:
"""执行用... | stack_v2_sparse_classes_75kplus_train_005699 | 3,884 | no_license | [
{
"docstring": "执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗: 19.7 MB , 在所有 Python3 提交中击败了 7.26% 的用户 :param strs: :return:",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs: List[str]) -> List[List[str]]"
},
{
"docstring": "执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗... | 4 | stack_v2_sparse_classes_30k_train_052237 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗: 19.7 MB , 在所有 Python3 提交中击败了 7.26% 的用户 :param strs: :return:
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗: 19.7 MB , 在所有 Python3 提交中击败了 7.26% 的用户 :param strs: :return:
- def ... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗: 19.7 MB , 在所有 Python3 提交中击败了 7.26% 的用户 :param strs: :return:"""
<|body_0|>
def groupAnagrams6(self, strs: List[str]) -> List[List[str]]:
"""执行用... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""执行用时: 64 ms , 在所有 Python3 提交中击败了 46.63% 的用户 内存消耗: 19.7 MB , 在所有 Python3 提交中击败了 7.26% 的用户 :param strs: :return:"""
res = {}
for str1 in strs:
key_str = [0] * 26
for tmp_str in str1:
... | the_stack_v2_python_sparse | group_anagrams.py | nomboy/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.