blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55143eb2f173536f54dc8bd4c272610359ed8b62 | [
"window = event.window\nmanager = window.workbench.user_perspective_manager\nperspective = window.active_perspective\nmessage = 'Are you sure you want to delete the \"%s\" perspective?' % perspective.name\nanswer = window.confirm(message, title='Confirm Delete')\nif answer == YES:\n window.active_perspective = s... | <|body_start_0|>
window = event.window
manager = window.workbench.user_perspective_manager
perspective = window.active_perspective
message = 'Are you sure you want to delete the "%s" perspective?' % perspective.name
answer = window.confirm(message, title='Confirm Delete')
... | An action that deletes a user perspective. | DeleteUserPerspectiveAction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteUserPerspectiveAction:
"""An action that deletes a user perspective."""
def perform(self, event):
"""Perform the action."""
<|body_0|>
def _get_next_perspective(self, window):
"""Return the first perspective that is not the active one!"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_011800 | 2,864 | permissive | [
{
"docstring": "Perform the action.",
"name": "perform",
"signature": "def perform(self, event)"
},
{
"docstring": "Return the first perspective that is not the active one!",
"name": "_get_next_perspective",
"signature": "def _get_next_perspective(self, window)"
}
] | 2 | null | Implement the Python class `DeleteUserPerspectiveAction` described below.
Class description:
An action that deletes a user perspective.
Method signatures and docstrings:
- def perform(self, event): Perform the action.
- def _get_next_perspective(self, window): Return the first perspective that is not the active one! | Implement the Python class `DeleteUserPerspectiveAction` described below.
Class description:
An action that deletes a user perspective.
Method signatures and docstrings:
- def perform(self, event): Perform the action.
- def _get_next_perspective(self, window): Return the first perspective that is not the active one!
... | 5466f5858dbd2f1f082fa0d7417b57c8fb068fad | <|skeleton|>
class DeleteUserPerspectiveAction:
"""An action that deletes a user perspective."""
def perform(self, event):
"""Perform the action."""
<|body_0|>
def _get_next_perspective(self, window):
"""Return the first perspective that is not the active one!"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteUserPerspectiveAction:
"""An action that deletes a user perspective."""
def perform(self, event):
"""Perform the action."""
window = event.window
manager = window.workbench.user_perspective_manager
perspective = window.active_perspective
message = 'Are you su... | the_stack_v2_python_sparse | maps/build/TraitsGUI/enthought/pyface/workbench/action/delete_user_perspective_action.py | m-elhussieny/code | train | 0 |
c32d095a167e07f80dab1d517246515fb238d896 | [
"action = self.request.get('action')\nif action == 'save_plan':\n self.createEditPlan(None)\nif action == 'edit_plan':\n self.createEditPlan(self.request.get('k'))\nif action == 'delete_plan':\n self.deletePlan(self.request.get('k'))\nif action == 'check_code':\n self.checkCode(self.request.get('k'), se... | <|body_start_0|>
action = self.request.get('action')
if action == 'save_plan':
self.createEditPlan(None)
if action == 'edit_plan':
self.createEditPlan(self.request.get('k'))
if action == 'delete_plan':
self.deletePlan(self.request.get('k'))
if ... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def post(self):
"""Handles POST requests"""
<|body_0|>
def createEditPlan(self, plan_key):
"""Calls the function to save the plan into the datastore and responses the Ajax request. @param plan_key: it refers to the Plan that is going to be edited. If 'Non... | stack_v2_sparse_classes_36k_train_011801 | 5,552 | no_license | [
{
"docstring": "Handles POST requests",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Calls the function to save the plan into the datastore and responses the Ajax request. @param plan_key: it refers to the Plan that is going to be edited. If 'None', a new Plan will be created... | 6 | stack_v2_sparse_classes_30k_train_009106 | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def post(self): Handles POST requests
- def createEditPlan(self, plan_key): Calls the function to save the plan into the datastore and responses the Ajax request. @param plan... | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def post(self): Handles POST requests
- def createEditPlan(self, plan_key): Calls the function to save the plan into the datastore and responses the Ajax request. @param plan... | 95cc24e41590853cf0d2d35e6bf2ba1bd0701d48 | <|skeleton|>
class Controller:
def post(self):
"""Handles POST requests"""
<|body_0|>
def createEditPlan(self, plan_key):
"""Calls the function to save the plan into the datastore and responses the Ajax request. @param plan_key: it refers to the Plan that is going to be edited. If 'Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Controller:
def post(self):
"""Handles POST requests"""
action = self.request.get('action')
if action == 'save_plan':
self.createEditPlan(None)
if action == 'edit_plan':
self.createEditPlan(self.request.get('k'))
if action == 'delete_plan':
... | the_stack_v2_python_sparse | python/src/plan.py | cjlallana/gae-course-application | train | 0 | |
26f3a3ca0a23ec146f2a09951431c242944ff4c1 | [
"try:\n if input.get('range_type', None):\n structure_type = extract_value_from_input(input, 'range_type', 'Settings', settings_model)\nexcept ObjectDoesNotExist:\n raise GraphQLError(u'Problemi durante il recupero di una struttura.')\nranges = extract_value_from_input(input, 'range_id', 'Range', range... | <|body_start_0|>
try:
if input.get('range_type', None):
structure_type = extract_value_from_input(input, 'range_type', 'Settings', settings_model)
except ObjectDoesNotExist:
raise GraphQLError(u'Problemi durante il recupero di una struttura.')
ranges = ext... | RangeMutationService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangeMutationService:
def updateRange(self, input):
"""aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range"""
<|body_0|>
def createRange(self, input):
"""creazione di un nuovo range input: inp... | stack_v2_sparse_classes_36k_train_011802 | 4,054 | no_license | [
{
"docstring": "aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range",
"name": "updateRange",
"signature": "def updateRange(self, input)"
},
{
"docstring": "creazione di un nuovo range input: input: dict con i parametri pe... | 2 | null | Implement the Python class `RangeMutationService` described below.
Class description:
Implement the RangeMutationService class.
Method signatures and docstrings:
- def updateRange(self, input): aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del ran... | Implement the Python class `RangeMutationService` described below.
Class description:
Implement the RangeMutationService class.
Method signatures and docstrings:
- def updateRange(self, input): aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del ran... | 7929b244a40a2faf834f55f1803d131cc6324a49 | <|skeleton|>
class RangeMutationService:
def updateRange(self, input):
"""aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range"""
<|body_0|>
def createRange(self, input):
"""creazione di un nuovo range input: inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RangeMutationService:
def updateRange(self, input):
"""aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range"""
try:
if input.get('range_type', None):
structure_type = extract_value_from_input(... | the_stack_v2_python_sparse | legionella/graphqlapp/range/mutationservice.py | RedTurtle/legionella-backend | train | 0 | |
0b8e38dcafb0b1a1d2a9e3df8a0873a8681916a1 | [
"invoice_line_obj = self.pool.get('account.invoice.line')\ninvoice_obj = self.pool.get('account.invoice')\nacc_mv_obj = self.pool.get('account.move')\nacc_mv_l_obj = self.pool.get('account.move.line')\ntax_obj = self.pool.get('account.invoice.tax')\ninvoice = {}\nif inv_brw.nro_ctrl:\n invoice.update({'name': 'P... | <|body_start_0|>
invoice_line_obj = self.pool.get('account.invoice.line')
invoice_obj = self.pool.get('account.invoice')
acc_mv_obj = self.pool.get('account.move')
acc_mv_l_obj = self.pool.get('account.move.line')
tax_obj = self.pool.get('account.invoice.tax')
invoice = {... | WizardInvoiceNroCtrl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WizardInvoiceNroCtrl:
def action_invoice_create(self, cr, uid, ids, wizard_brw, inv_brw, context=None):
"""If the invoice has control number, this function is responsible for passing the bill to damaged paper @param wizard_brw: nothing for now @param inv_brw: damaged paper"""
<|b... | stack_v2_sparse_classes_36k_train_011803 | 6,304 | no_license | [
{
"docstring": "If the invoice has control number, this function is responsible for passing the bill to damaged paper @param wizard_brw: nothing for now @param inv_brw: damaged paper",
"name": "action_invoice_create",
"signature": "def action_invoice_create(self, cr, uid, ids, wizard_brw, inv_brw, conte... | 3 | null | Implement the Python class `WizardInvoiceNroCtrl` described below.
Class description:
Implement the WizardInvoiceNroCtrl class.
Method signatures and docstrings:
- def action_invoice_create(self, cr, uid, ids, wizard_brw, inv_brw, context=None): If the invoice has control number, this function is responsible for pass... | Implement the Python class `WizardInvoiceNroCtrl` described below.
Class description:
Implement the WizardInvoiceNroCtrl class.
Method signatures and docstrings:
- def action_invoice_create(self, cr, uid, ids, wizard_brw, inv_brw, context=None): If the invoice has control number, this function is responsible for pass... | 718327d01e5b4408add58682c5ad1901fa35b450 | <|skeleton|>
class WizardInvoiceNroCtrl:
def action_invoice_create(self, cr, uid, ids, wizard_brw, inv_brw, context=None):
"""If the invoice has control number, this function is responsible for passing the bill to damaged paper @param wizard_brw: nothing for now @param inv_brw: damaged paper"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WizardInvoiceNroCtrl:
def action_invoice_create(self, cr, uid, ids, wizard_brw, inv_brw, context=None):
"""If the invoice has control number, this function is responsible for passing the bill to damaged paper @param wizard_brw: nothing for now @param inv_brw: damaged paper"""
invoice_line_obj ... | the_stack_v2_python_sparse | l10n_ve_fiscal_requirements/wizard/wizard_invoice_nro_ctrl.py | Vauxoo/odoo-venezuela | train | 15 | |
ee85cf378da4d44bd933879c8189fc304af9a2c7 | [
"for key, value in row.items():\n if value.isdigit():\n msg = f'Converting string {value} to integer'\n LOGGER.debug(msg)\n row[key] = int(value)\nreturn row",
"file_path = os.path.join(directory, file_name)\ndb_collection = database[collection]\nerrors = 0\ntry:\n LOGGER.info('Attempti... | <|body_start_0|>
for key, value in row.items():
if value.isdigit():
msg = f'Converting string {value} to integer'
LOGGER.debug(msg)
row[key] = int(value)
return row
<|end_body_0|>
<|body_start_1|>
file_path = os.path.join(directory, fi... | A class that handles calls to the database. | DatabaseHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseHandler:
"""A class that handles calls to the database."""
def format_row_integers(self, row):
"""Formats all integer fields in a row from strings to integers :row: The CSV row to modify"""
<|body_0|>
def ingest_file(self, database, directory, file_name, collecti... | stack_v2_sparse_classes_36k_train_011804 | 9,787 | no_license | [
{
"docstring": "Formats all integer fields in a row from strings to integers :row: The CSV row to modify",
"name": "format_row_integers",
"signature": "def format_row_integers(self, row)"
},
{
"docstring": "Ingests a file into the MongoDB collection. Return how many errors was encounterd and how... | 5 | null | Implement the Python class `DatabaseHandler` described below.
Class description:
A class that handles calls to the database.
Method signatures and docstrings:
- def format_row_integers(self, row): Formats all integer fields in a row from strings to integers :row: The CSV row to modify
- def ingest_file(self, database... | Implement the Python class `DatabaseHandler` described below.
Class description:
A class that handles calls to the database.
Method signatures and docstrings:
- def format_row_integers(self, row): Formats all integer fields in a row from strings to integers :row: The CSV row to modify
- def ingest_file(self, database... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class DatabaseHandler:
"""A class that handles calls to the database."""
def format_row_integers(self, row):
"""Formats all integer fields in a row from strings to integers :row: The CSV row to modify"""
<|body_0|>
def ingest_file(self, database, directory, file_name, collecti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseHandler:
"""A class that handles calls to the database."""
def format_row_integers(self, row):
"""Formats all integer fields in a row from strings to integers :row: The CSV row to modify"""
for key, value in row.items():
if value.isdigit():
msg = f'Conv... | the_stack_v2_python_sparse | students/anthony_mckeever/lesson_10/assignment_1/database.py | JavaRod/SP_Python220B_2019 | train | 1 |
de91f1e729fd95136a37e58dd249d7b30aa5468c | [
"ans = []\nfrom collections import deque\nqueue = deque([root])\nwhile len(queue) > 0:\n item = queue.popleft()\n if item is not None:\n ans.append(item.val)\n queue.append(item.left)\n queue.append(item.right)\n else:\n ans.append(None)\nreturn pickle.dumps(ans)",
"ans = pick... | <|body_start_0|>
ans = []
from collections import deque
queue = deque([root])
while len(queue) > 0:
item = queue.popleft()
if item is not None:
ans.append(item.val)
queue.append(item.left)
queue.append(item.right)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_011805 | 2,741 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_011906 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d71e725d779d7b45402893b311939c2cce60fbca | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
ans = []
from collections import deque
queue = deque([root])
while len(queue) > 0:
item = queue.popleft()
if item is not None:
... | the_stack_v2_python_sparse | algorithm/0297Serialize_and_Deserialize_Binary_Tree.py | xkoma001/leetcode | train | 0 | |
3a2ced9752c0b22fbe9aa932b6084bd88f543a93 | [
"try:\n return settings.DATABASE_APP_MAPPING[model._meta.app_label]\nexcept KeyError:\n return None",
"try:\n return settings.DATABASE_APP_MAPPING[model._meta.app_label]\nexcept KeyError:\n return None",
"ffball_obj = settings.DATABASE_APP_MAPPING.get(obj1._meta.app_label)\nyahoo_obj = settings.DATA... | <|body_start_0|>
try:
return settings.DATABASE_APP_MAPPING[model._meta.app_label]
except KeyError:
return None
<|end_body_0|>
<|body_start_1|>
try:
return settings.DATABASE_APP_MAPPING[model._meta.app_label]
except KeyError:
return None
<|... | A router to control all database operations on models in the auth application. | DbRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read yahoo info, read from mongo_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write au... | stack_v2_sparse_classes_36k_train_011806 | 1,484 | no_license | [
{
"docstring": "Attempts to read yahoo info, read from mongo_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth models go to auth_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
... | 4 | stack_v2_sparse_classes_30k_train_007493 | Implement the Python class `DbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read yahoo info, read from mongo_db.
- def db_for_write(self, model, **hints):... | Implement the Python class `DbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read yahoo info, read from mongo_db.
- def db_for_write(self, model, **hints):... | e1e40558282cc671f26a04bdafc54536c28f47a4 | <|skeleton|>
class DbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read yahoo info, read from mongo_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write au... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read yahoo info, read from mongo_db."""
try:
return settings.DATABASE_APP_MAPPING[model._meta.app_label]
except KeyError... | the_stack_v2_python_sparse | ffball/db_router.py | rchatterjee/moneyball | train | 1 |
de8627e72009b23b70758efa5f46729af0a511b8 | [
"strSet = set()\nfor i in A:\n str = ''.join(sorted(i[0::2])) + '#'\n if len(i) > 1:\n str += ''.join(sorted(i[1::2]))\n if str not in strSet:\n strSet.add(str)\nreturn len(strSet)",
"def count(str):\n c = [0] * 52\n for i in range(len(str)):\n c[ord(str[i]) - ord('a') + 26 * (... | <|body_start_0|>
strSet = set()
for i in A:
str = ''.join(sorted(i[0::2])) + '#'
if len(i) > 1:
str += ''.join(sorted(i[1::2]))
if str not in strSet:
strSet.add(str)
return len(strSet)
<|end_body_0|>
<|body_start_1|>
de... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSpecialEquivGroups_1(self, A):
""":type A: List[str] :rtype: int"""
<|body_0|>
def numSpecialEquivGroups(self, A):
""":type A: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
strSet = set()
for i in A:
... | stack_v2_sparse_classes_36k_train_011807 | 1,910 | no_license | [
{
"docstring": ":type A: List[str] :rtype: int",
"name": "numSpecialEquivGroups_1",
"signature": "def numSpecialEquivGroups_1(self, A)"
},
{
"docstring": ":type A: List[str] :rtype: int",
"name": "numSpecialEquivGroups",
"signature": "def numSpecialEquivGroups(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017844 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSpecialEquivGroups_1(self, A): :type A: List[str] :rtype: int
- def numSpecialEquivGroups(self, A): :type A: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSpecialEquivGroups_1(self, A): :type A: List[str] :rtype: int
- def numSpecialEquivGroups(self, A): :type A: List[str] :rtype: int
<|skeleton|>
class Solution:
def n... | 0fdc1d60cfb3f4c26698a493da4986bfc873e02a | <|skeleton|>
class Solution:
def numSpecialEquivGroups_1(self, A):
""":type A: List[str] :rtype: int"""
<|body_0|>
def numSpecialEquivGroups(self, A):
""":type A: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSpecialEquivGroups_1(self, A):
""":type A: List[str] :rtype: int"""
strSet = set()
for i in A:
str = ''.join(sorted(i[0::2])) + '#'
if len(i) > 1:
str += ''.join(sorted(i[1::2]))
if str not in strSet:
... | the_stack_v2_python_sparse | 893_GroupsofSpecialEquivalentStrings/893_GroupsofSpecialEquivalentStrings.py | ranson/leetcode | train | 0 | |
f17a3d0979ff42510bd543dc08890c82b9ab80a0 | [
"mru = self._GetValueFromStructure(structure, 'mru')\nif not mru:\n return\nevent_data = PopularityContestEventData()\nevent_data.mru = mru\nevent_data.package = self._GetValueFromStructure(structure, 'package')\nevent_data.record_tag = self._GetValueFromStructure(structure, 'tag')\naccess_time = self._GetValueF... | <|body_start_0|>
mru = self._GetValueFromStructure(structure, 'mru')
if not mru:
return
event_data = PopularityContestEventData()
event_data.mru = mru
event_data.package = self._GetValueFromStructure(structure, 'package')
event_data.record_tag = self._GetValue... | Parse popularity contest log files. | PopularityContestParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopularityContestParser:
"""Parse popularity contest log files."""
def _ParseLogLine(self, parser_mediator, structure):
"""Extracts events from a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. s... | stack_v2_sparse_classes_36k_train_011808 | 11,054 | permissive | [
{
"docstring": "Extracts events from a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure parsed from the log file.",
"name": "_ParseLogLine",
"signature": "def _ParseLogLi... | 3 | stack_v2_sparse_classes_30k_train_007081 | Implement the Python class `PopularityContestParser` described below.
Class description:
Parse popularity contest log files.
Method signatures and docstrings:
- def _ParseLogLine(self, parser_mediator, structure): Extracts events from a log line. Args: parser_mediator (ParserMediator): mediates interactions between p... | Implement the Python class `PopularityContestParser` described below.
Class description:
Parse popularity contest log files.
Method signatures and docstrings:
- def _ParseLogLine(self, parser_mediator, structure): Extracts events from a log line. Args: parser_mediator (ParserMediator): mediates interactions between p... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class PopularityContestParser:
"""Parse popularity contest log files."""
def _ParseLogLine(self, parser_mediator, structure):
"""Extracts events from a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PopularityContestParser:
"""Parse popularity contest log files."""
def _ParseLogLine(self, parser_mediator, structure):
"""Extracts events from a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyp... | the_stack_v2_python_sparse | plaso/parsers/popcontest.py | cyb3rfox/plaso | train | 3 |
6789042fd28f7c65312f2d8dc337637d9dc2aa44 | [
"self.block_proc = cell_proc\nself.proc_block_np = proc_cell_np\nself.num_procs = len(proc_cell_np)\nself.c = kwargs.get('c', 0.3)\nif init:\n self.gen_clusters(**kwargs)",
"for cluster in self.clusters:\n cluster.cells[:] = []\nfor cell in self.block_proc:\n wdists = []\n for cluster in self.clusters... | <|body_start_0|>
self.block_proc = cell_proc
self.proc_block_np = proc_cell_np
self.num_procs = len(proc_cell_np)
self.c = kwargs.get('c', 0.3)
if init:
self.gen_clusters(**kwargs)
<|end_body_0|>
<|body_start_1|>
for cluster in self.clusters:
clus... | Partition of cells for parallel solvers | ParDecompose | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParDecompose:
"""Partition of cells for parallel solvers"""
def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from c... | stack_v2_sparse_classes_36k_train_011809 | 12,256 | permissive | [
{
"docstring": "constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from cluster center (the other component is scaled distance based on cluster size) t = (0.2) ratio of old component of center in the center calcula... | 6 | stack_v2_sparse_classes_30k_train_011427 | Implement the Python class `ParDecompose` described below.
Class description:
Partition of cells for parallel solvers
Method signatures and docstrings:
- def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs): constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance co... | Implement the Python class `ParDecompose` described below.
Class description:
Partition of cells for parallel solvers
Method signatures and docstrings:
- def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs): constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance co... | 5bb1fc46a9c84aefd42758356a9986689db05454 | <|skeleton|>
class ParDecompose:
"""Partition of cells for parallel solvers"""
def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParDecompose:
"""Partition of cells for parallel solvers"""
def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from cluster center... | the_stack_v2_python_sparse | source/pysph/parallel/load_balancer_mkmeans.py | pankajp/pysph | train | 1 |
d62c7a8609c490ad354eac74f29f3c1dd31433ce | [
"self.log.debug('[%s]: Getting manufacturer for server %s', self.name, self.server_conf['host'])\nserver_def = self.server_conf['host'].split(':')\nserver_addr = server_def[0]\nsys_cmd = 'ipmitool -I lanplus -H ' + server_addr + \" -U '\" + self.pod_auth[0] + \"'\" + \" -P '\" + self.pod_auth[1] + \"'\" + ' bmc inf... | <|body_start_0|>
self.log.debug('[%s]: Getting manufacturer for server %s', self.name, self.server_conf['host'])
server_def = self.server_conf['host'].split(':')
server_addr = server_def[0]
sys_cmd = 'ipmitool -I lanplus -H ' + server_addr + " -U '" + self.pod_auth[0] + "'" + " -P '" + s... | Collect power consumption via IPMI protocol. | IPMICollector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPMICollector:
"""Collect power consumption via IPMI protocol."""
def get_manufacturer_id(self):
"""Get Manufacturer id from IPMI."""
<|body_0|>
def get_sensors(self, manufacturer):
"""Return Power sensors list."""
<|body_1|>
def get_sensors_power(se... | stack_v2_sparse_classes_36k_train_011810 | 8,256 | no_license | [
{
"docstring": "Get Manufacturer id from IPMI.",
"name": "get_manufacturer_id",
"signature": "def get_manufacturer_id(self)"
},
{
"docstring": "Return Power sensors list.",
"name": "get_sensors",
"signature": "def get_sensors(self, manufacturer)"
},
{
"docstring": "Return power v... | 5 | stack_v2_sparse_classes_30k_train_008748 | Implement the Python class `IPMICollector` described below.
Class description:
Collect power consumption via IPMI protocol.
Method signatures and docstrings:
- def get_manufacturer_id(self): Get Manufacturer id from IPMI.
- def get_sensors(self, manufacturer): Return Power sensors list.
- def get_sensors_power(self, ... | Implement the Python class `IPMICollector` described below.
Class description:
Collect power consumption via IPMI protocol.
Method signatures and docstrings:
- def get_manufacturer_id(self): Get Manufacturer id from IPMI.
- def get_sensors(self, manufacturer): Return Power sensors list.
- def get_sensors_power(self, ... | a872f095f256b0dd63d292301426f0a807c04abb | <|skeleton|>
class IPMICollector:
"""Collect power consumption via IPMI protocol."""
def get_manufacturer_id(self):
"""Get Manufacturer id from IPMI."""
<|body_0|>
def get_sensors(self, manufacturer):
"""Return Power sensors list."""
<|body_1|>
def get_sensors_power(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IPMICollector:
"""Collect power consumption via IPMI protocol."""
def get_manufacturer_id(self):
"""Get Manufacturer id from IPMI."""
self.log.debug('[%s]: Getting manufacturer for server %s', self.name, self.server_conf['host'])
server_def = self.server_conf['host'].split(':')
... | the_stack_v2_python_sparse | server-collector/collectors/power/ipmicollector.py | bherard/energyrecorder | train | 2 |
21fbbfcad9794510e944e7cdd41421592ceb719d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationAssignmentResource()",
"from .education_resource import EducationResource\nfrom .entity import Entity\nfrom .education_resource import EducationResource\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationAssignmentResource()
<|end_body_0|>
<|body_start_1|>
from .education_resource import EducationResource
from .entity import Entity
from .education_resource import Educati... | EducationAssignmentResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationAssignmentResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_36k_train_011811 | 2,633 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EducationAssignmentResource",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_006522 | Implement the Python class `EducationAssignmentResource` described below.
Class description:
Implement the EducationAssignmentResource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentResource: Creates a new instance of the appr... | Implement the Python class `EducationAssignmentResource` described below.
Class description:
Implement the EducationAssignmentResource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentResource: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationAssignmentResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationAssignmentResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | the_stack_v2_python_sparse | msgraph/generated/models/education_assignment_resource.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3a57da770d749e5f44098e7398b089517e2d9395 | [
"assert gamma >= 1, 'gamma must be >= 1 (E^(-gamma))'\nassert 0 <= e_min <= e_max, 'energy limits must be 0 <= e_min <= e_max'\nmsg = 'direction must be None or direction in [0, 2pi)'\nassert direction is None or 0 <= direction < 2 * np.pi, msg\nself.name = name\nself.e_min = e_min\nself.e_max = e_max\nself.gamma =... | <|body_start_0|>
assert gamma >= 1, 'gamma must be >= 1 (E^(-gamma))'
assert 0 <= e_min <= e_max, 'energy limits must be 0 <= e_min <= e_max'
msg = 'direction must be None or direction in [0, 2pi)'
assert direction is None or 0 <= direction < 2 * np.pi, msg
self.name = name
... | Base particle generator class. This class is intended as a base class for particle generators. Each particle type must create their own generator class if the particle has new parameters other than the ones sampled here. A derived class must implement: __init__ generate(num, random_seed) Attributes ---------- direction... | BaseParticleGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseParticleGenerator:
"""Base particle generator class. This class is intended as a base class for particle generators. Each particle type must create their own generator class if the particle has new parameters other than the ones sampled here. A derived class must implement: __init__ generate(... | stack_v2_sparse_classes_36k_train_011812 | 7,692 | no_license | [
{
"docstring": "Initialize base particle generator. Parameters ---------- e_min : float The minimium particle energy to generate. This must be greater equal zero and not greater than e_max. e_max : float The maximum particle energy to generate. This must be greater equal zero and not less than e_min. gamma : fl... | 5 | null | Implement the Python class `BaseParticleGenerator` described below.
Class description:
Base particle generator class. This class is intended as a base class for particle generators. Each particle type must create their own generator class if the particle has new parameters other than the ones sampled here. A derived c... | Implement the Python class `BaseParticleGenerator` described below.
Class description:
Base particle generator class. This class is intended as a base class for particle generators. Each particle type must create their own generator class if the particle has new parameters other than the ones sampled here. A derived c... | 0d7442bd78f9899536a109e87a4c4639ade82a58 | <|skeleton|>
class BaseParticleGenerator:
"""Base particle generator class. This class is intended as a base class for particle generators. Each particle type must create their own generator class if the particle has new parameters other than the ones sampled here. A derived class must implement: __init__ generate(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseParticleGenerator:
"""Base particle generator class. This class is intended as a base class for particle generators. Each particle type must create their own generator class if the particle has new parameters other than the ones sampled here. A derived class must implement: __init__ generate(num, random_s... | the_stack_v2_python_sparse | project_a5/simulation/generator/base_generator.py | yungsalami/linuxtest | train | 0 |
6091571e2468bab57d647a6194a8f20bb24ef76b | [
"def preorder(root):\n if not root:\n return\n preorder.tree += ' ' + str(root.val)\n preorder(root.left)\n preorder(root.right)\npreorder.tree = ''\npreorder(root)\nreturn preorder.tree",
"if data == '':\n return None\n\ndef buildTree(start, end):\n if start > end:\n return None\n... | <|body_start_0|>
def preorder(root):
if not root:
return
preorder.tree += ' ' + str(root.val)
preorder(root.left)
preorder(root.right)
preorder.tree = ''
preorder(root)
return preorder.tree
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def preorder(r... | stack_v2_sparse_classes_36k_train_011813 | 1,671 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_000977 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 6fc047f8f5453ca91bad5cd7f28b308d201d3ccc | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(root):
if not root:
return
preorder.tree += ' ' + str(root.val)
preorder(root.left)
preorder(root.right)
preorder.tre... | the_stack_v2_python_sparse | Leetcode/Tree/serialize_dserialize_bst.py | shashank-22/Compititive | train | 0 | |
561b380415fe46aa91cbede0c4d6f4a445be428e | [
"res = []\nstack = []\nwhile True:\n while root:\n res.append(str(root.val))\n stack.append(root)\n root = root.left\n if not stack:\n return ' '.join(res)\n node = stack.pop()\n root = node.right",
"if not data:\n return []\nres = data.split(' ')\nhead = root = TreeNode... | <|body_start_0|>
res = []
stack = []
while True:
while root:
res.append(str(root.val))
stack.append(root)
root = root.left
if not stack:
return ' '.join(res)
node = stack.pop()
root = ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_011814 | 1,614 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_001023 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | b1a1d965ea99586e03fd975afca8815cd47a3c0f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
stack = []
while True:
while root:
res.append(str(root.val))
stack.append(root)
root = root.left
... | the_stack_v2_python_sparse | 449. Serialize and Deserialize BST.py | taochenlei/leetcode_algorithm | train | 0 | |
eb494d5823a5f611c6ab624a0c1ca7851b88ce91 | [
"super().__init__(*args, **kwargs)\nendpoints = current_app.config.get('RECORDS_REST_ENDPOINTS', [])\ndocument_endpoint = endpoints.get(DOCUMENT_PID_TYPE, {})\nself.max_result_window = document_endpoint.get('max_result_window', RECORDS_REST_MAX_RESULT_WINDOW)",
"size_param = request.args.get('size', self.default_... | <|body_start_0|>
super().__init__(*args, **kwargs)
endpoints = current_app.config.get('RECORDS_REST_ENDPOINTS', [])
document_endpoint = endpoints.get(DOCUMENT_PID_TYPE, {})
self.max_result_window = document_endpoint.get('max_result_window', RECORDS_REST_MAX_RESULT_WINDOW)
<|end_body_0|>
... | Statistics view for the documents with the most loans. | MostLoanedDocumentsResource | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MostLoanedDocumentsResource:
"""Statistics view for the documents with the most loans."""
def __init__(self, *args, **kwargs):
"""Constructor."""
<|body_0|>
def _validate_bucket_size(self):
"""Validate bucket size parameter."""
<|body_1|>
def _valida... | stack_v2_sparse_classes_36k_train_011815 | 4,933 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Validate bucket size parameter.",
"name": "_validate_bucket_size",
"signature": "def _validate_bucket_size(self)"
},
{
"docstring": "Validate start date range ... | 4 | null | Implement the Python class `MostLoanedDocumentsResource` described below.
Class description:
Statistics view for the documents with the most loans.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor.
- def _validate_bucket_size(self): Validate bucket size parameter.
- def _validate_s... | Implement the Python class `MostLoanedDocumentsResource` described below.
Class description:
Statistics view for the documents with the most loans.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor.
- def _validate_bucket_size(self): Validate bucket size parameter.
- def _validate_s... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class MostLoanedDocumentsResource:
"""Statistics view for the documents with the most loans."""
def __init__(self, *args, **kwargs):
"""Constructor."""
<|body_0|>
def _validate_bucket_size(self):
"""Validate bucket size parameter."""
<|body_1|>
def _valida... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MostLoanedDocumentsResource:
"""Statistics view for the documents with the most loans."""
def __init__(self, *args, **kwargs):
"""Constructor."""
super().__init__(*args, **kwargs)
endpoints = current_app.config.get('RECORDS_REST_ENDPOINTS', [])
document_endpoint = endpoint... | the_stack_v2_python_sparse | invenio_app_ils/circulation/stats/views.py | inveniosoftware/invenio-app-ils | train | 64 |
afe363e836334867591d5d647ca42df5461e3f40 | [
"self.session = aiohttp.ClientSession()\nif endpoint_config:\n self.endpoint_config = endpoint_config\nelse:\n self.endpoint_config = EndpointConfig(constants.DEFAULT_SERVER_URL)",
"default_return = {'intent': {INTENT_NAME_KEY: '', 'confidence': 0.0}, 'entities': [], 'text': ''}\nresult = await self._rasa_h... | <|body_start_0|>
self.session = aiohttp.ClientSession()
if endpoint_config:
self.endpoint_config = endpoint_config
else:
self.endpoint_config = EndpointConfig(constants.DEFAULT_SERVER_URL)
<|end_body_0|>
<|body_start_1|>
default_return = {'intent': {INTENT_NAME_K... | Allows for an HTTP endpoint to be used to parse messages. | RasaNLUHttpInterpreter | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasaNLUHttpInterpreter:
"""Allows for an HTTP endpoint to be used to parse messages."""
def __init__(self, endpoint_config: Optional[EndpointConfig]=None) -> None:
"""Initializes a `RasaNLUHttpInterpreter`."""
<|body_0|>
async def parse(self, message: UserMessage) -> Dic... | stack_v2_sparse_classes_36k_train_011816 | 3,033 | permissive | [
{
"docstring": "Initializes a `RasaNLUHttpInterpreter`.",
"name": "__init__",
"signature": "def __init__(self, endpoint_config: Optional[EndpointConfig]=None) -> None"
},
{
"docstring": "Parse a text message. Return a default value if the parsing of the text failed.",
"name": "parse",
"s... | 3 | null | Implement the Python class `RasaNLUHttpInterpreter` described below.
Class description:
Allows for an HTTP endpoint to be used to parse messages.
Method signatures and docstrings:
- def __init__(self, endpoint_config: Optional[EndpointConfig]=None) -> None: Initializes a `RasaNLUHttpInterpreter`.
- async def parse(se... | Implement the Python class `RasaNLUHttpInterpreter` described below.
Class description:
Allows for an HTTP endpoint to be used to parse messages.
Method signatures and docstrings:
- def __init__(self, endpoint_config: Optional[EndpointConfig]=None) -> None: Initializes a `RasaNLUHttpInterpreter`.
- async def parse(se... | 50857610bdf0c26dc61f3203a6cbb4bcf193768c | <|skeleton|>
class RasaNLUHttpInterpreter:
"""Allows for an HTTP endpoint to be used to parse messages."""
def __init__(self, endpoint_config: Optional[EndpointConfig]=None) -> None:
"""Initializes a `RasaNLUHttpInterpreter`."""
<|body_0|>
async def parse(self, message: UserMessage) -> Dic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasaNLUHttpInterpreter:
"""Allows for an HTTP endpoint to be used to parse messages."""
def __init__(self, endpoint_config: Optional[EndpointConfig]=None) -> None:
"""Initializes a `RasaNLUHttpInterpreter`."""
self.session = aiohttp.ClientSession()
if endpoint_config:
... | the_stack_v2_python_sparse | rasa/core/http_interpreter.py | RasaHQ/rasa | train | 13,167 |
ec33233536d7869246af2ec9a48aecbced517060 | [
"category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]\nvideo_evaluator = coco_evaluation_all_frames.CocoEvaluationAllFrames(category_list)\nvideo_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict=[{standard_fields.InputDataFields.groundtruth_boxes: np.array([[50.0, 50.... | <|body_start_0|>
category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]
video_evaluator = coco_evaluation_all_frames.CocoEvaluationAllFrames(category_list)
video_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict=[{standard_fields.InputDataFields.groun... | CocoEvaluationAllFramesTest | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CocoEvaluationAllFramesTest:
def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
"""Tests that mAP is calculated on several different frame results."""
<|body_0|>
def testGroundtruthAndDetections(self):
"""Tests that mAP is calculated correctly on GT and Detec... | stack_v2_sparse_classes_36k_train_011817 | 6,730 | permissive | [
{
"docstring": "Tests that mAP is calculated on several different frame results.",
"name": "testGroundtruthAndDetectionsDisagreeOnAllFrames",
"signature": "def testGroundtruthAndDetectionsDisagreeOnAllFrames(self)"
},
{
"docstring": "Tests that mAP is calculated correctly on GT and Detections.",... | 3 | stack_v2_sparse_classes_30k_train_016813 | Implement the Python class `CocoEvaluationAllFramesTest` described below.
Class description:
Implement the CocoEvaluationAllFramesTest class.
Method signatures and docstrings:
- def testGroundtruthAndDetectionsDisagreeOnAllFrames(self): Tests that mAP is calculated on several different frame results.
- def testGround... | Implement the Python class `CocoEvaluationAllFramesTest` described below.
Class description:
Implement the CocoEvaluationAllFramesTest class.
Method signatures and docstrings:
- def testGroundtruthAndDetectionsDisagreeOnAllFrames(self): Tests that mAP is calculated on several different frame results.
- def testGround... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class CocoEvaluationAllFramesTest:
def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
"""Tests that mAP is calculated on several different frame results."""
<|body_0|>
def testGroundtruthAndDetections(self):
"""Tests that mAP is calculated correctly on GT and Detec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CocoEvaluationAllFramesTest:
def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
"""Tests that mAP is calculated on several different frame results."""
category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]
video_evaluator = coco_evaluation_all_frames.CocoEvaluatio... | the_stack_v2_python_sparse | models/research/lstm_object_detection/metrics/coco_evaluation_all_frames_test.py | finnickniu/tensorflow_object_detection_tflite | train | 60 | |
44bf3002ed9767f038b4a469a2e181268abdd726 | [
"self.cosmology = cosmology\nself.settings_lens = settings_lens or SettingsLens()\nself.positions_likelihood = positions_likelihood",
"if hasattr(instance, 'perturbation'):\n instance.galaxies.subhalo = instance.perturbation\nif hasattr(instance.galaxies, 'subhalo'):\n subhalo_centre = ray_tracing_util.grid... | <|body_start_0|>
self.cosmology = cosmology
self.settings_lens = settings_lens or SettingsLens()
self.positions_likelihood = positions_likelihood
<|end_body_0|>
<|body_start_1|>
if hasattr(instance, 'perturbation'):
instance.galaxies.subhalo = instance.perturbation
i... | AnalysisLensing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisLensing:
def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.cosmo.LensingCosmology=ag.cosmo.Planck15()):
"""Analysis classes are used by PyAutoFit to fit a model to a da... | stack_v2_sparse_classes_36k_train_011818 | 18,150 | permissive | [
{
"docstring": "Analysis classes are used by PyAutoFit to fit a model to a dataset via a non-linear search. This abstract Analysis class has attributes and methods for all model-fits which include lensing calculations, but does not perform a model-fit by itself (and is therefore only inherited from). This class... | 3 | stack_v2_sparse_classes_30k_train_013706 | Implement the Python class `AnalysisLensing` described below.
Class description:
Implement the AnalysisLensing class.
Method signatures and docstrings:
- def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.co... | Implement the Python class `AnalysisLensing` described below.
Class description:
Implement the AnalysisLensing class.
Method signatures and docstrings:
- def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.co... | b31b9d7c8a55d7232695761a41383cb1cc30bd76 | <|skeleton|>
class AnalysisLensing:
def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.cosmo.LensingCosmology=ag.cosmo.Planck15()):
"""Analysis classes are used by PyAutoFit to fit a model to a da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalysisLensing:
def __init__(self, positions_likelihood: Optional[Union[PositionsLHResample, PositionsLHPenalty]]=None, settings_lens: SettingsLens=SettingsLens(), cosmology: ag.cosmo.LensingCosmology=ag.cosmo.Planck15()):
"""Analysis classes are used by PyAutoFit to fit a model to a dataset via a no... | the_stack_v2_python_sparse | autolens/analysis/analysis.py | Jammy2211/PyAutoLens | train | 142 | |
29ffd2b9b338c575073ab14803b0630c09e8af66 | [
"super(GANLoss, self).__init__()\nself.register_buffer('real_label', torch.tensor(target_real_label).cuda())\nself.register_buffer('fake_label', torch.tensor(target_fake_label).cuda())\nself.real_label_var = None\nself.fake_label_var = None\nself.Tensor = tensor\nself.gan_mode = gan_mode\nif gan_mode == 'lsgan':\n ... | <|body_start_0|>
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label).cuda())
self.register_buffer('fake_label', torch.tensor(target_fake_label).cuda())
self.real_label_var = None
self.fake_label_var = None
self.Tensor = tenso... | GANLoss | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANLoss:
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor):
"""Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wasserstein. target_real_label (bool) - - la... | stack_v2_sparse_classes_36k_train_011819 | 14,434 | permissive | [
{
"docstring": "Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wasserstein. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Disc... | 3 | stack_v2_sparse_classes_30k_train_013043 | Implement the Python class `GANLoss` described below.
Class description:
Implement the GANLoss class.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor): Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN o... | Implement the Python class `GANLoss` described below.
Class description:
Implement the GANLoss class.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor): Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN o... | 64669251584a7421cce3a5173983a2275dcb438a | <|skeleton|>
class GANLoss:
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor):
"""Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wasserstein. target_real_label (bool) - - la... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GANLoss:
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, tensor=torch.FloatTensor):
"""Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wasserstein. target_real_label (bool) - - label for a real... | the_stack_v2_python_sparse | models/networks.py | KreitnerL/mrs-gan | train | 0 | |
b64368d3884faf8c83ae2a8925399ebf9bd8e949 | [
"super().__init__(self.PROBLEM_NAME)\nself.input_range_list1 = input_range_list1\nself.input_range_list2 = input_range_list2",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nmerged_list = []\ninterval_list = sorted(self.input_range_list1 + self.input_range_list2, key=lambda x: x[0])\nfor interval in ... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_range_list1 = input_range_list1
self.input_range_list2 = input_range_list2
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
merged_list = []
interval_list = sorted(se... | Merge Intervals | MergeIntervals | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeIntervals:
"""Merge Intervals"""
def __init__(self, input_range_list1, input_range_list2):
"""Merge Intervals Args: input_range_list1: First range list input_range_list2: First range list Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the... | stack_v2_sparse_classes_36k_train_011820 | 2,067 | no_license | [
{
"docstring": "Merge Intervals Args: input_range_list1: First range list input_range_list2: First range list Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_range_list1, input_range_list2)"
},
{
"docstring": "Solve the problem Note: O(n logn) (runtime) an... | 2 | null | Implement the Python class `MergeIntervals` described below.
Class description:
Merge Intervals
Method signatures and docstrings:
- def __init__(self, input_range_list1, input_range_list2): Merge Intervals Args: input_range_list1: First range list input_range_list2: First range list Returns: None Raises: None
- def s... | Implement the Python class `MergeIntervals` described below.
Class description:
Merge Intervals
Method signatures and docstrings:
- def __init__(self, input_range_list1, input_range_list2): Merge Intervals Args: input_range_list1: First range list input_range_list2: First range list Returns: None Raises: None
- def s... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class MergeIntervals:
"""Merge Intervals"""
def __init__(self, input_range_list1, input_range_list2):
"""Merge Intervals Args: input_range_list1: First range list input_range_list2: First range list Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeIntervals:
"""Merge Intervals"""
def __init__(self, input_range_list1, input_range_list2):
"""Merge Intervals Args: input_range_list1: First range list input_range_list2: First range list Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
self.input_range_list1... | the_stack_v2_python_sparse | python/problems/array/merge_intervals.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
1e8339cf38b27859888f1a19ac7888653385306d | [
"self.nb_columns = nb_columns\nQtWidgets.QTableWidget.__init__(self)\nself.setColumnCount(self.nb_columns)\nself.changeRange(range_char)",
"if type(range_char) == tuple:\n size = range_char[1] + 1 - range_char[0]\n rge = list(range(range_char[0], range_char[1] + 1))\nelif type(range_char) == list:\n size... | <|body_start_0|>
self.nb_columns = nb_columns
QtWidgets.QTableWidget.__init__(self)
self.setColumnCount(self.nb_columns)
self.changeRange(range_char)
<|end_body_0|>
<|body_start_1|>
if type(range_char) == tuple:
size = range_char[1] + 1 - range_char[0]
rg... | TECharTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TECharTable:
def __init__(self, nb_columns=16, range_char=(int('0020', 16), int('024F', 16))):
"""A re-implementation of QTableWidget. It will display all the chars contained in the given range. - nb_columns : number of columns to display - range_char : a tuple that contains the borns of... | stack_v2_sparse_classes_36k_train_011821 | 6,561 | no_license | [
{
"docstring": "A re-implementation of QTableWidget. It will display all the chars contained in the given range. - nb_columns : number of columns to display - range_char : a tuple that contains the borns of the field range to display. Note : range_char=(0,10) includes 10.",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_019439 | Implement the Python class `TECharTable` described below.
Class description:
Implement the TECharTable class.
Method signatures and docstrings:
- def __init__(self, nb_columns=16, range_char=(int('0020', 16), int('024F', 16))): A re-implementation of QTableWidget. It will display all the chars contained in the given ... | Implement the Python class `TECharTable` described below.
Class description:
Implement the TECharTable class.
Method signatures and docstrings:
- def __init__(self, nb_columns=16, range_char=(int('0020', 16), int('024F', 16))): A re-implementation of QTableWidget. It will display all the chars contained in the given ... | 14c9e51fa31fd3ff4113f33e26619d07c9f1dc7c | <|skeleton|>
class TECharTable:
def __init__(self, nb_columns=16, range_char=(int('0020', 16), int('024F', 16))):
"""A re-implementation of QTableWidget. It will display all the chars contained in the given range. - nb_columns : number of columns to display - range_char : a tuple that contains the borns of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TECharTable:
def __init__(self, nb_columns=16, range_char=(int('0020', 16), int('024F', 16))):
"""A re-implementation of QTableWidget. It will display all the chars contained in the given range. - nb_columns : number of columns to display - range_char : a tuple that contains the borns of the field ran... | the_stack_v2_python_sparse | TextEdit/TextEditCharTable.py | grumpfou/AthenaWriter | train | 0 | |
000621a8c86da11bc12cd86ab52461cd54b6c2dd | [
"def field(name):\n return serialized.get(name) or serialized.get(name.lower())\nreturn Error(code=field('Code'), message=field('Message'), info=ErrorInfo.from_dict(field('Info')), version=bakery.LATEST_VERSION)",
"if self.info is None or self.code != ERR_INTERACTION_REQUIRED:\n raise InteractionError('not ... | <|body_start_0|>
def field(name):
return serialized.get(name) or serialized.get(name.lower())
return Error(code=field('Code'), message=field('Message'), info=ErrorInfo.from_dict(field('Info')), version=bakery.LATEST_VERSION)
<|end_body_0|>
<|body_start_1|>
if self.info is None or se... | This class defines an error value as returned from an httpbakery API. | Error | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Error:
"""This class defines an error value as returned from an httpbakery API."""
def from_dict(cls, serialized):
"""Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict}"""
<|body_0|>
def interaction_method(sel... | stack_v2_sparse_classes_36k_train_011822 | 8,215 | permissive | [
{
"docstring": "Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict}",
"name": "from_dict",
"signature": "def from_dict(cls, serialized)"
},
{
"docstring": "Checks whether the error is an InteractionRequired error that implements the me... | 2 | null | Implement the Python class `Error` described below.
Class description:
This class defines an error value as returned from an httpbakery API.
Method signatures and docstrings:
- def from_dict(cls, serialized): Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {di... | Implement the Python class `Error` described below.
Class description:
This class defines an error value as returned from an httpbakery API.
Method signatures and docstrings:
- def from_dict(cls, serialized): Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {di... | a5520738e6c5924b94f69980eba49a565c2561d7 | <|skeleton|>
class Error:
"""This class defines an error value as returned from an httpbakery API."""
def from_dict(cls, serialized):
"""Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict}"""
<|body_0|>
def interaction_method(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Error:
"""This class defines an error value as returned from an httpbakery API."""
def from_dict(cls, serialized):
"""Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict}"""
def field(name):
return serialized.get(name... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/macaroonbakery/httpbakery/_error.py | crazyzete/AppSecAssignment2 | train | 0 |
230f5f17b1dc1a7d637581d25d54f89adaa38d6f | [
"super(GRUCell, self).__init__()\nself.hidden = nn.CellList([nn.Dense(dim_hid, dim_hid, has_bias=bias) for _ in range(3)])\nself.input = nn.CellList([nn.Dense(dim_in, dim_hid, has_bias=bias) for _ in range(3)])\nself.sigmoid = nn.Sigmoid()\nself.tanh = nn.Tanh()",
"r = self.sigmoid(self.input[0](inputs) + self.hi... | <|body_start_0|>
super(GRUCell, self).__init__()
self.hidden = nn.CellList([nn.Dense(dim_hid, dim_hid, has_bias=bias) for _ in range(3)])
self.input = nn.CellList([nn.Dense(dim_in, dim_hid, has_bias=bias) for _ in range(3)])
self.sigmoid = nn.Sigmoid()
self.tanh = nn.Tanh()
<|end... | GRUCell | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
<|body_0|>
def construct(self, i... | stack_v2_sparse_classes_36k_train_011823 | 9,199 | permissive | [
{
"docstring": "Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True.",
"name": "__init__",
"signature": "def __init__(self, dim_in: int, dim_hid: int, bias: bool=True)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_009062 | Implement the Python class `GRUCell` described below.
Class description:
Implement the GRUCell class.
Method signatures and docstrings:
- def __init__(self, dim_in: int, dim_hid: int, bias: bool=True): Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional ... | Implement the Python class `GRUCell` described below.
Class description:
Implement the GRUCell class.
Method signatures and docstrings:
- def __init__(self, dim_in: int, dim_hid: int, bias: bool=True): Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
<|body_0|>
def construct(self, i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
super(GRUCell, self).__init__()
self.hidden... | the_stack_v2_python_sparse | research/gnn/nri-mpm/models/base.py | mindspore-ai/models | train | 301 | |
60eecbc9886dc6e7e022d5c87830e49e1975c31f | [
"self.quark = quark\nself.nucleon = nucleon\nself.ip = input_dict",
"if self.nucleon == 'p':\n if self.quark == 'u':\n return 2\n if self.quark == 'd':\n return 1\n if self.quark == 's':\n return 0\nif self.nucleon == 'n':\n if self.quark == 'u':\n return 1\n if self.qua... | <|body_start_0|>
self.quark = quark
self.nucleon = nucleon
self.ip = input_dict
<|end_body_0|>
<|body_start_1|>
if self.nucleon == 'p':
if self.quark == 'u':
return 2
if self.quark == 'd':
return 1
if self.quark == 's':... | F1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class F1:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor F1 Return the nuclear form factor F1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron)"""
<|body_0|>
def value... | stack_v2_sparse_classes_36k_train_011824 | 18,337 | permissive | [
{
"docstring": "The nuclear form factor F1 Return the nuclear form factor F1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron)",
"name": "__init__",
"signature": "def __init__(self, quark, nucleon, input_dict)"
},
... | 3 | stack_v2_sparse_classes_30k_train_021461 | Implement the Python class `F1` described below.
Class description:
Implement the F1 class.
Method signatures and docstrings:
- def __init__(self, quark, nucleon, input_dict): The nuclear form factor F1 Return the nuclear form factor F1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange)... | Implement the Python class `F1` described below.
Class description:
Implement the F1 class.
Method signatures and docstrings:
- def __init__(self, quark, nucleon, input_dict): The nuclear form factor F1 Return the nuclear form factor F1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange)... | 4a714e4701f817fdc96e10e461eef7c4756ef71d | <|skeleton|>
class F1:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor F1 Return the nuclear form factor F1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron)"""
<|body_0|>
def value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class F1:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor F1 Return the nuclear form factor F1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron)"""
self.quark = quark
self.nucleon... | the_stack_v2_python_sparse | directdm/num/single_nucleon_form_factors.py | DirectDM/directdm-py | train | 6 | |
38dc493f74d2ff34f553b8ce38a7c253325dbe4e | [
"self._x = x\nself._y = y\nself._radius = random.randint(25, 75)\nself._num_stars = random.randint(5, 20)\nself._star = random.choice(StarBurst._stars)",
"DEGREES_CIRCLE: int = 360\nangle: float\nangle = DEGREES_CIRCLE / num_points\nreturn angle",
"w: int = self._star.get_width()\nh: int = self._star.get_height... | <|body_start_0|>
self._x = x
self._y = y
self._radius = random.randint(25, 75)
self._num_stars = random.randint(5, 20)
self._star = random.choice(StarBurst._stars)
<|end_body_0|>
<|body_start_1|>
DEGREES_CIRCLE: int = 360
angle: float
angle = DEGREES_CIRC... | A class representing a fireworks starburst. Public methods: __init__, draw_burst | StarBurst | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarBurst:
"""A class representing a fireworks starburst. Public methods: __init__, draw_burst"""
def __init__(self, x: float, y: float) -> None:
"""Initialize an instance of StarBurst at x,y."""
<|body_0|>
def _calc_angle(self, num_points: int) -> float:
"""Calc... | stack_v2_sparse_classes_36k_train_011825 | 4,380 | no_license | [
{
"docstring": "Initialize an instance of StarBurst at x,y.",
"name": "__init__",
"signature": "def __init__(self, x: float, y: float) -> None"
},
{
"docstring": "Calculate and return the angle between points evenly distributed around a circle.",
"name": "_calc_angle",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_000031 | Implement the Python class `StarBurst` described below.
Class description:
A class representing a fireworks starburst. Public methods: __init__, draw_burst
Method signatures and docstrings:
- def __init__(self, x: float, y: float) -> None: Initialize an instance of StarBurst at x,y.
- def _calc_angle(self, num_points... | Implement the Python class `StarBurst` described below.
Class description:
A class representing a fireworks starburst. Public methods: __init__, draw_burst
Method signatures and docstrings:
- def __init__(self, x: float, y: float) -> None: Initialize an instance of StarBurst at x,y.
- def _calc_angle(self, num_points... | 0fe17edf6ffcb35265032c6449d866b9434fda00 | <|skeleton|>
class StarBurst:
"""A class representing a fireworks starburst. Public methods: __init__, draw_burst"""
def __init__(self, x: float, y: float) -> None:
"""Initialize an instance of StarBurst at x,y."""
<|body_0|>
def _calc_angle(self, num_points: int) -> float:
"""Calc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarBurst:
"""A class representing a fireworks starburst. Public methods: __init__, draw_burst"""
def __init__(self, x: float, y: float) -> None:
"""Initialize an instance of StarBurst at x,y."""
self._x = x
self._y = y
self._radius = random.randint(25, 75)
self._n... | the_stack_v2_python_sparse | Chapter5TextbookCode/Listing 5-3.py | ProfessorBurke/PythonObjectsGames | train | 3 |
ff56a8c3125cdb6b43bb933456350e796fa250c6 | [
"self.__test_statistic = test_statistic\nself.__network = network\nself.__diz = diz\nself.degree_bins = degree_bins\nself.node_2_bin_map = None\nself.bins = None\nif type(self.__network) is nx.Graph or type(self.__network) is nx.DiGraph:\n self.__universe = list(set(self.__network.nodes()))\nelif type(self.__net... | <|body_start_0|>
self.__test_statistic = test_statistic
self.__network = network
self.__diz = diz
self.degree_bins = degree_bins
self.node_2_bin_map = None
self.bins = None
if type(self.__network) is nx.Graph or type(self.__network) is nx.DiGraph:
self... | This class implements the statistical analysis performed by Pygna. It performs the statistical tests on the given network, elaborates the number of observed genes, the pvalue etc. Please refer to the single method documentation for the returning values | StatisticalTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatisticalTest:
"""This class implements the statistical analysis performed by Pygna. It performs the statistical tests on the given network, elaborates the number of observed genes, the pvalue etc. Please refer to the single method documentation for the returning values"""
def __init__(sel... | stack_v2_sparse_classes_36k_train_011826 | 10,759 | permissive | [
{
"docstring": ":param test_statistic: the statistical function to be used for the calculation of the empirical p-value and the null distribution :param network: the network to be used for the analysis :param diz: the dictionary containing the genes",
"name": "__init__",
"signature": "def __init__(self,... | 4 | stack_v2_sparse_classes_30k_train_011629 | Implement the Python class `StatisticalTest` described below.
Class description:
This class implements the statistical analysis performed by Pygna. It performs the statistical tests on the given network, elaborates the number of observed genes, the pvalue etc. Please refer to the single method documentation for the re... | Implement the Python class `StatisticalTest` described below.
Class description:
This class implements the statistical analysis performed by Pygna. It performs the statistical tests on the given network, elaborates the number of observed genes, the pvalue etc. Please refer to the single method documentation for the re... | 3c172abe4b5391c5fb9a41f5fdc104ba0a3ab86b | <|skeleton|>
class StatisticalTest:
"""This class implements the statistical analysis performed by Pygna. It performs the statistical tests on the given network, elaborates the number of observed genes, the pvalue etc. Please refer to the single method documentation for the returning values"""
def __init__(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatisticalTest:
"""This class implements the statistical analysis performed by Pygna. It performs the statistical tests on the given network, elaborates the number of observed genes, the pvalue etc. Please refer to the single method documentation for the returning values"""
def __init__(self, test_stati... | the_stack_v2_python_sparse | pygna/statistical_test.py | stracquadaniolab/pygna | train | 41 |
7bb51c9c08561ffda8401ab6b98a0071eb3c7fa4 | [
"if self.models:\n import django\n import django.core.management\n from django.core.exceptions import ImproperlyConfigured\n dbfile = django.conf.settings.DATABASES['default']['NAME']\n if django.VERSION[0] == 1 and django.VERSION[1] >= 7:\n for connection in django.db.connections.all():\n ... | <|body_start_0|>
if self.models:
import django
import django.core.management
from django.core.exceptions import ImproperlyConfigured
dbfile = django.conf.settings.DATABASES['default']['NAME']
if django.VERSION[0] == 1 and django.VERSION[1] >= 7:
... | Test case class for Django database models | DBModelTestCase | [
"LicenseRef-scancode-unknown-license-reference",
"mpich2",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBModelTestCase:
"""Test case class for Django database models"""
def test_syncdb(self):
"""Create the test database and sync the schema"""
<|body_0|>
def test_cleandb(self):
"""Ensure that we a) can connect to the database; b) start with a clean database"""
... | stack_v2_sparse_classes_36k_train_011827 | 12,205 | permissive | [
{
"docstring": "Create the test database and sync the schema",
"name": "test_syncdb",
"signature": "def test_syncdb(self)"
},
{
"docstring": "Ensure that we a) can connect to the database; b) start with a clean database",
"name": "test_cleandb",
"signature": "def test_cleandb(self)"
}
... | 2 | stack_v2_sparse_classes_30k_train_009008 | Implement the Python class `DBModelTestCase` described below.
Class description:
Test case class for Django database models
Method signatures and docstrings:
- def test_syncdb(self): Create the test database and sync the schema
- def test_cleandb(self): Ensure that we a) can connect to the database; b) start with a c... | Implement the Python class `DBModelTestCase` described below.
Class description:
Test case class for Django database models
Method signatures and docstrings:
- def test_syncdb(self): Create the test database and sync the schema
- def test_cleandb(self): Ensure that we a) can connect to the database; b) start with a c... | 8605cd3d0cb4d549cb8b43de945d447f6d82892a | <|skeleton|>
class DBModelTestCase:
"""Test case class for Django database models"""
def test_syncdb(self):
"""Create the test database and sync the schema"""
<|body_0|>
def test_cleandb(self):
"""Ensure that we a) can connect to the database; b) start with a clean database"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBModelTestCase:
"""Test case class for Django database models"""
def test_syncdb(self):
"""Create the test database and sync the schema"""
if self.models:
import django
import django.core.management
from django.core.exceptions import ImproperlyConfigur... | the_stack_v2_python_sparse | testsuite/common.py | Bcfg2/bcfg2 | train | 56 |
b5a82b8f307c595b857c22c5e57c654860f436ff | [
"super().__init__(feature_weight=np.array([0.1, 0.1, 1.0, 1.0, 1.0]), loss_weight=loss_weight)\nrgb_mean = tf.constant([0.485, 0.456, 0.406])\nrgb_std = tf.constant([0.229, 0.224, 0.225])\nself._rgb_mean = tf.reshape(rgb_mean, (1, 1, 1, 3))\nself._rgb_std = tf.reshape(rgb_std, (1, 1, 1, 3))\nmodel_path = file_util.... | <|body_start_0|>
super().__init__(feature_weight=np.array([0.1, 0.1, 1.0, 1.0, 1.0]), loss_weight=loss_weight)
rgb_mean = tf.constant([0.485, 0.456, 0.406])
rgb_std = tf.constant([0.229, 0.224, 0.225])
self._rgb_mean = tf.reshape(rgb_mean, (1, 1, 1, 3))
self._rgb_std = tf.reshape... | Perceptual loss based on VGG19 pretrained on the ImageNet dataset. Reference: - [Perceptual Losses for Real-Time Style Transfer and Super-Resolution]( https://arxiv.org/abs/1603.08155) (ECCV 2016) Perceptual loss measures high-level perceptual and semantic differences between images. | VGGPerceptualLoss | [
"Apache-2.0",
"dtoa"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGGPerceptualLoss:
"""Perceptual loss based on VGG19 pretrained on the ImageNet dataset. Reference: - [Perceptual Losses for Real-Time Style Transfer and Super-Resolution]( https://arxiv.org/abs/1603.08155) (ECCV 2016) Perceptual loss measures high-level perceptual and semantic differences betwee... | stack_v2_sparse_classes_36k_train_011828 | 13,820 | permissive | [
{
"docstring": "Initializes image quality loss essentials. Args: loss_weight: Loss weight coefficients.",
"name": "__init__",
"signature": "def __init__(self, loss_weight: Optional[PerceptualLossWeight]=None)"
},
{
"docstring": "Computes VGG19 features.",
"name": "_compute_features",
"si... | 2 | null | Implement the Python class `VGGPerceptualLoss` described below.
Class description:
Perceptual loss based on VGG19 pretrained on the ImageNet dataset. Reference: - [Perceptual Losses for Real-Time Style Transfer and Super-Resolution]( https://arxiv.org/abs/1603.08155) (ECCV 2016) Perceptual loss measures high-level per... | Implement the Python class `VGGPerceptualLoss` described below.
Class description:
Perceptual loss based on VGG19 pretrained on the ImageNet dataset. Reference: - [Perceptual Losses for Real-Time Style Transfer and Super-Resolution]( https://arxiv.org/abs/1603.08155) (ECCV 2016) Perceptual loss measures high-level per... | 007824594bf1d07c7c1467df03a43886f8a4b3ad | <|skeleton|>
class VGGPerceptualLoss:
"""Perceptual loss based on VGG19 pretrained on the ImageNet dataset. Reference: - [Perceptual Losses for Real-Time Style Transfer and Super-Resolution]( https://arxiv.org/abs/1603.08155) (ECCV 2016) Perceptual loss measures high-level perceptual and semantic differences betwee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGGPerceptualLoss:
"""Perceptual loss based on VGG19 pretrained on the ImageNet dataset. Reference: - [Perceptual Losses for Real-Time Style Transfer and Super-Resolution]( https://arxiv.org/abs/1603.08155) (ECCV 2016) Perceptual loss measures high-level perceptual and semantic differences between images."""
... | the_stack_v2_python_sparse | mediapipe/model_maker/python/core/utils/loss_functions.py | google/mediapipe | train | 23,940 |
04ce70de1e5ebc55ae65200088df561b8c34761a | [
"self.alive: bool = False\nself.console: Console = console\nsession = requests.session()\nretry = Retry(total=OtRobot.RETRIES, read=OtRobot.RETRIES, connect=OtRobot.RETRIES, backoff_factor=OtRobot.BACK_OFF_FACTOR, status_forcelist=OtRobot.ERROR_CODES)\nadapter = HTTPAdapter(max_retries=retry)\nsession.mount('http:/... | <|body_start_0|>
self.alive: bool = False
self.console: Console = console
session = requests.session()
retry = Retry(total=OtRobot.RETRIES, read=OtRobot.RETRIES, connect=OtRobot.RETRIES, backoff_factor=OtRobot.BACK_OFF_FACTOR, status_forcelist=OtRobot.ERROR_CODES)
adapter = HTTPA... | Opentrons Robot. | OtRobot | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OtRobot:
"""Opentrons Robot."""
def __init__(self, console: Console, robot_data: RobotDataType) -> None:
"""Initialize the robot."""
<|body_0|>
def is_alive(self) -> bool:
"""Is a robot available by http - request the openapi.json."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_011829 | 5,029 | permissive | [
{
"docstring": "Initialize the robot.",
"name": "__init__",
"signature": "def __init__(self, console: Console, robot_data: RobotDataType) -> None"
},
{
"docstring": "Is a robot available by http - request the openapi.json.",
"name": "is_alive",
"signature": "def is_alive(self) -> bool"
... | 6 | stack_v2_sparse_classes_30k_train_008674 | Implement the Python class `OtRobot` described below.
Class description:
Opentrons Robot.
Method signatures and docstrings:
- def __init__(self, console: Console, robot_data: RobotDataType) -> None: Initialize the robot.
- def is_alive(self) -> bool: Is a robot available by http - request the openapi.json.
- def get_... | Implement the Python class `OtRobot` described below.
Class description:
Opentrons Robot.
Method signatures and docstrings:
- def __init__(self, console: Console, robot_data: RobotDataType) -> None: Initialize the robot.
- def is_alive(self) -> bool: Is a robot available by http - request the openapi.json.
- def get_... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class OtRobot:
"""Opentrons Robot."""
def __init__(self, console: Console, robot_data: RobotDataType) -> None:
"""Initialize the robot."""
<|body_0|>
def is_alive(self) -> bool:
"""Is a robot available by http - request the openapi.json."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OtRobot:
"""Opentrons Robot."""
def __init__(self, console: Console, robot_data: RobotDataType) -> None:
"""Initialize the robot."""
self.alive: bool = False
self.console: Console = console
session = requests.session()
retry = Retry(total=OtRobot.RETRIES, read=OtRo... | the_stack_v2_python_sparse | app-testing/automation/resources/ot_robot.py | Opentrons/opentrons | train | 326 |
bce6490534e87e6eb8bba9a065a3be8f3e33c97b | [
"self.validate_parameters(network_id=options.get('network_id'))\n_url_path = '/networks/{networkId}/events'\n_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'networkId': options.get('network_id', None)})\n_query_builder = Configuration.base_uri\n_query_builder += _url_path\n_query_parameters =... | <|body_start_0|>
self.validate_parameters(network_id=options.get('network_id'))
_url_path = '/networks/{networkId}/events'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'networkId': options.get('network_id', None)})
_query_builder = Configuration.base_uri
... | A Controller to access Endpoints in the meraki API. | EventsController | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventsController:
"""A Controller to access Endpoints in the meraki API."""
def get_network_events(self, options=dict()):
"""Does a GET request to /networks/{networkId}/events. List the events for the network Args: options (dict, optional): Key-value pairs for any of the parameters t... | stack_v2_sparse_classes_36k_train_011830 | 8,417 | permissive | [
{
"docstring": "Does a GET request to /networks/{networkId}/events. List the events for the network Args: options (dict, optional): Key-value pairs for any of the parameters to this API Endpoint. All parameters to the endpoint are supplied through the dictionary with their names being the key and their desired ... | 2 | stack_v2_sparse_classes_30k_train_012668 | Implement the Python class `EventsController` described below.
Class description:
A Controller to access Endpoints in the meraki API.
Method signatures and docstrings:
- def get_network_events(self, options=dict()): Does a GET request to /networks/{networkId}/events. List the events for the network Args: options (dic... | Implement the Python class `EventsController` described below.
Class description:
A Controller to access Endpoints in the meraki API.
Method signatures and docstrings:
- def get_network_events(self, options=dict()): Does a GET request to /networks/{networkId}/events. List the events for the network Args: options (dic... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class EventsController:
"""A Controller to access Endpoints in the meraki API."""
def get_network_events(self, options=dict()):
"""Does a GET request to /networks/{networkId}/events. List the events for the network Args: options (dict, optional): Key-value pairs for any of the parameters t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventsController:
"""A Controller to access Endpoints in the meraki API."""
def get_network_events(self, options=dict()):
"""Does a GET request to /networks/{networkId}/events. List the events for the network Args: options (dict, optional): Key-value pairs for any of the parameters to this API En... | the_stack_v2_python_sparse | meraki/controllers/events_controller.py | RaulCatalano/meraki-python-sdk | train | 1 |
c2d80b623676d06bed2f2ee79d4791eb6e8033db | [
"Layer.__init__(self, name='approximated_smoothing')\nself.kernel_func = look_up_operations(type_str.lower(), SUPPORTED_KERNELS)\nself.sigma = sigma\nself.truncate = truncate",
"spatial_rank = infer_spatial_rank(image)\n_sigmas = expand_spatial_params(input_param=self.sigma, spatial_rank=spatial_rank, param_type=... | <|body_start_0|>
Layer.__init__(self, name='approximated_smoothing')
self.kernel_func = look_up_operations(type_str.lower(), SUPPORTED_KERNELS)
self.sigma = sigma
self.truncate = truncate
<|end_body_0|>
<|body_start_1|>
spatial_rank = infer_spatial_rank(image)
_sigmas = ... | computing 1d convolution one each spatial dimension of the input using one-dimensional filter. | SmoothingLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmoothingLayer:
"""computing 1d convolution one each spatial dimension of the input using one-dimensional filter."""
def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'):
""":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviatio... | stack_v2_sparse_classes_36k_train_011831 | 3,416 | permissive | [
{
"docstring": ":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviations :param type_str: type of kernels",
"name": "__init__",
"signature": "def __init__(self, sigma=1, truncate=3.0, type_str='gaussian')"
},
{
"docstring": ":param image: in shape `(... | 2 | null | Implement the Python class `SmoothingLayer` described below.
Class description:
computing 1d convolution one each spatial dimension of the input using one-dimensional filter.
Method signatures and docstrings:
- def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'): :param sigma: standard deviation :param tru... | Implement the Python class `SmoothingLayer` described below.
Class description:
computing 1d convolution one each spatial dimension of the input using one-dimensional filter.
Method signatures and docstrings:
- def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'): :param sigma: standard deviation :param tru... | 84dd0f85c9a1ab8a72f4c55fcf073379acf5ae1b | <|skeleton|>
class SmoothingLayer:
"""computing 1d convolution one each spatial dimension of the input using one-dimensional filter."""
def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'):
""":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmoothingLayer:
"""computing 1d convolution one each spatial dimension of the input using one-dimensional filter."""
def __init__(self, sigma=1, truncate=3.0, type_str='gaussian'):
""":param sigma: standard deviation :param truncate: Truncate the filter at this many standard deviations :param typ... | the_stack_v2_python_sparse | niftynet/layer/approximated_smoothing.py | 12SigmaTechnologies/NiftyNet-1 | train | 2 |
8f7e0dec1976d6cb361cd35f86a6a7b12fd5184f | [
"super(GaussianProcessStabilityAgent, self).__init__(candidate_data=candidate_data, seed_data=seed_data, n_query=n_query, hull_distance=hull_distance, parallel=parallel)\nself.multiprocessing = parallel\nself.alpha = alpha\nself.GP = GaussianProcessRegressor(kernel=ConstantKernel(1) * RBF(1), alpha=0.002)",
"X_ca... | <|body_start_0|>
super(GaussianProcessStabilityAgent, self).__init__(candidate_data=candidate_data, seed_data=seed_data, n_query=n_query, hull_distance=hull_distance, parallel=parallel)
self.multiprocessing = parallel
self.alpha = alpha
self.GP = GaussianProcessRegressor(kernel=ConstantK... | Simple Gaussian Process Regressor based Stability Agent | GaussianProcessStabilityAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcessStabilityAgent:
"""Simple Gaussian Process Regressor based Stability Agent"""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=cpu_count(), alpha=0.5):
"""Args: candidate_data (DataFrame): data about the candidates seed_dat... | stack_v2_sparse_classes_36k_train_011832 | 38,060 | permissive | [
{
"docstring": "Args: candidate_data (DataFrame): data about the candidates seed_data (DataFrame): data which to fit the Agent to n_query (int): number of hypotheses to generate hull_distance (float): hull distance as a criteria for which to deem a given material as \"stable\" parallel (bool): whether to use mu... | 2 | stack_v2_sparse_classes_30k_train_002940 | Implement the Python class `GaussianProcessStabilityAgent` described below.
Class description:
Simple Gaussian Process Regressor based Stability Agent
Method signatures and docstrings:
- def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=cpu_count(), alpha=0.5): Args: candi... | Implement the Python class `GaussianProcessStabilityAgent` described below.
Class description:
Simple Gaussian Process Regressor based Stability Agent
Method signatures and docstrings:
- def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=cpu_count(), alpha=0.5): Args: candi... | 905f5d577513d1ca5a54fac3d381525e0fe3576a | <|skeleton|>
class GaussianProcessStabilityAgent:
"""Simple Gaussian Process Regressor based Stability Agent"""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=cpu_count(), alpha=0.5):
"""Args: candidate_data (DataFrame): data about the candidates seed_dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcessStabilityAgent:
"""Simple Gaussian Process Regressor based Stability Agent"""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=cpu_count(), alpha=0.5):
"""Args: candidate_data (DataFrame): data about the candidates seed_data (DataFrame)... | the_stack_v2_python_sparse | camd/agent/stability.py | apalizha/CAMD | train | 0 |
0ecf8cdd2d74a740da3fa2ca28fd824a00d415ec | [
"self._watcher = watcher\nself._default_value = default_value\nself._flag = threading.Event()\nself.watch()",
"if self._default_value:\n return not self._flag.is_set()\nelse:\n return self._flag.is_set()",
"if self._watcher.watch():\n self._flag.set()\nelse:\n self._flag.clear()"
] | <|body_start_0|>
self._watcher = watcher
self._default_value = default_value
self._flag = threading.Event()
self.watch()
<|end_body_0|>
<|body_start_1|>
if self._default_value:
return not self._flag.is_set()
else:
return self._flag.is_set()
<|end_... | FeatureSwitch checks if a feature is enabled or not. | FeatureSwitch | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureSwitch:
"""FeatureSwitch checks if a feature is enabled or not."""
def __init__(self, watcher, default_value):
"""Constructor for FeatureSwitch. Args: watcher: the watcher object used to determine if the feature is enabled or not default_value: bool, value when the watcher obj... | stack_v2_sparse_classes_36k_train_011833 | 4,327 | permissive | [
{
"docstring": "Constructor for FeatureSwitch. Args: watcher: the watcher object used to determine if the feature is enabled or not default_value: bool, value when the watcher object returns False",
"name": "__init__",
"signature": "def __init__(self, watcher, default_value)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_016101 | Implement the Python class `FeatureSwitch` described below.
Class description:
FeatureSwitch checks if a feature is enabled or not.
Method signatures and docstrings:
- def __init__(self, watcher, default_value): Constructor for FeatureSwitch. Args: watcher: the watcher object used to determine if the feature is enabl... | Implement the Python class `FeatureSwitch` described below.
Class description:
FeatureSwitch checks if a feature is enabled or not.
Method signatures and docstrings:
- def __init__(self, watcher, default_value): Constructor for FeatureSwitch. Args: watcher: the watcher object used to determine if the feature is enabl... | 1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30 | <|skeleton|>
class FeatureSwitch:
"""FeatureSwitch checks if a feature is enabled or not."""
def __init__(self, watcher, default_value):
"""Constructor for FeatureSwitch. Args: watcher: the watcher object used to determine if the feature is enabled or not default_value: bool, value when the watcher obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureSwitch:
"""FeatureSwitch checks if a feature is enabled or not."""
def __init__(self, watcher, default_value):
"""Constructor for FeatureSwitch. Args: watcher: the watcher object used to determine if the feature is enabled or not default_value: bool, value when the watcher object returns F... | the_stack_v2_python_sparse | biggraphite/utils.py | criteo/biggraphite | train | 129 |
9099bec8b50df6444fe1e5fa5f9ffd2e4a1bca1b | [
"if level is not None:\n self._target_level = level\nif self._target_level and self._target_level == self._deep_level:\n desc = {'type': self.__class__.__name__}\n desc.update(self.desc)\n return desc\ndesc = {'modules': [], 'type': self.__class__.__name__}\nif self._losses:\n desc['loss'] = self._lo... | <|body_start_0|>
if level is not None:
self._target_level = level
if self._target_level and self._target_level == self._deep_level:
desc = {'type': self.__class__.__name__}
desc.update(self.desc)
return desc
desc = {'modules': [], 'type': self.__cl... | Seriablizable Module class. | ModuleSerializable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleSerializable:
"""Seriablizable Module class."""
def to_desc(self, level=None):
"""Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default."""
<|body_0|>
def update_from_desc(self, desc):
"""Updat... | stack_v2_sparse_classes_36k_train_011834 | 7,315 | permissive | [
{
"docstring": "Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default.",
"name": "to_desc",
"signature": "def to_desc(self, level=None)"
},
{
"docstring": "Update desc according to desc.",
"name": "update_from_desc",
"signat... | 3 | stack_v2_sparse_classes_30k_train_017686 | Implement the Python class `ModuleSerializable` described below.
Class description:
Seriablizable Module class.
Method signatures and docstrings:
- def to_desc(self, level=None): Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default.
- def update_from_de... | Implement the Python class `ModuleSerializable` described below.
Class description:
Seriablizable Module class.
Method signatures and docstrings:
- def to_desc(self, level=None): Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default.
- def update_from_de... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class ModuleSerializable:
"""Seriablizable Module class."""
def to_desc(self, level=None):
"""Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default."""
<|body_0|>
def update_from_desc(self, desc):
"""Updat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleSerializable:
"""Seriablizable Module class."""
def to_desc(self, level=None):
"""Convert Module to desc dict. :param level: Specifies witch level to convert. all conversions are performed as default."""
if level is not None:
self._target_level = level
if self._t... | the_stack_v2_python_sparse | zeus/modules/operators/functions/serializable.py | huawei-noah/xingtian | train | 308 |
cf9e6bef68f464922d94f22edb15f3ddd4077905 | [
"try:\n return super().make_context(info_name, args, parent, **extra)\nexcept Exception as e:\n telemetry_client = parent.obj['TELEMETRY_CLIENT']\n if isinstance(e, click.exceptions.Exit) and e.exit_code == 0:\n telemetry_client.send_command_telemetry(parent, extra_info_name=info_name, is_help=True)... | <|body_start_0|>
try:
return super().make_context(info_name, args, parent, **extra)
except Exception as e:
telemetry_client = parent.obj['TELEMETRY_CLIENT']
if isinstance(e, click.exceptions.Exit) and e.exit_code == 0:
telemetry_client.send_command_tel... | OctaviaCommand | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Elastic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OctaviaCommand:
def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context:
"""Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this... | stack_v2_sparse_classes_36k_train_011835 | 2,019 | permissive | [
{
"docstring": "Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this invocation. args (t.List[str]): The arguments to parse as list of strings. parent (t.Optional[click.Context], optional): The parent context if available.. Defaults to Non... | 2 | stack_v2_sparse_classes_30k_train_010351 | Implement the Python class `OctaviaCommand` described below.
Class description:
Implement the OctaviaCommand class.
Method signatures and docstrings:
- def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: Wrap parent make conte... | Implement the Python class `OctaviaCommand` described below.
Class description:
Implement the OctaviaCommand class.
Method signatures and docstrings:
- def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: Wrap parent make conte... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class OctaviaCommand:
def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context:
"""Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OctaviaCommand:
def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context:
"""Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this invocation. a... | the_stack_v2_python_sparse | dts/airbyte/octavia-cli/octavia_cli/base_commands.py | alldatacenter/alldata | train | 774 | |
3dc693208c8f21e78473005d633e64c6ec4c4191 | [
"result, max_value = (nums[0], 0)\nfor i in range(1, len(nums)):\n if result < 0:\n result = nums[i]\n else:\n result += nums[i]\n max_value = max(result, max_value)\nreturn max_value",
"if not nums:\n return 0\nresult, sum_value = (nums[0], nums[0])\nfor i in range(1, len(nums)):\n ... | <|body_start_0|>
result, max_value = (nums[0], 0)
for i in range(1, len(nums)):
if result < 0:
result = nums[i]
else:
result += nums[i]
max_value = max(result, max_value)
return max_value
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_sub_array(self, nums: List[int]) -> int:
"""获取到连续子数组最大值 Args: nums:数组 Returns: 最大值"""
<|body_0|>
def max_sub_array2(self, nums: List[int]) -> int:
"""获取到连续子数组最大值 Args: nums:数组 Returns: 最大值"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_011836 | 1,956 | permissive | [
{
"docstring": "获取到连续子数组最大值 Args: nums:数组 Returns: 最大值",
"name": "max_sub_array",
"signature": "def max_sub_array(self, nums: List[int]) -> int"
},
{
"docstring": "获取到连续子数组最大值 Args: nums:数组 Returns: 最大值",
"name": "max_sub_array2",
"signature": "def max_sub_array2(self, nums: List[int]) -... | 2 | stack_v2_sparse_classes_30k_val_000034 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_sub_array(self, nums: List[int]) -> int: 获取到连续子数组最大值 Args: nums:数组 Returns: 最大值
- def max_sub_array2(self, nums: List[int]) -> int: 获取到连续子数组最大值 Args: nums:数组 Returns: 最大值 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_sub_array(self, nums: List[int]) -> int: 获取到连续子数组最大值 Args: nums:数组 Returns: 最大值
- def max_sub_array2(self, nums: List[int]) -> int: 获取到连续子数组最大值 Args: nums:数组 Returns: 最大值... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def max_sub_array(self, nums: List[int]) -> int:
"""获取到连续子数组最大值 Args: nums:数组 Returns: 最大值"""
<|body_0|>
def max_sub_array2(self, nums: List[int]) -> int:
"""获取到连续子数组最大值 Args: nums:数组 Returns: 最大值"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def max_sub_array(self, nums: List[int]) -> int:
"""获取到连续子数组最大值 Args: nums:数组 Returns: 最大值"""
result, max_value = (nums[0], 0)
for i in range(1, len(nums)):
if result < 0:
result = nums[i]
else:
result += nums[i]
... | the_stack_v2_python_sparse | src/leetcodepython/array/maximum_subarray_53.py | zhangyu345293721/leetcode | train | 101 | |
ea39530987918fa76c39b5a057d092b60079e0e7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TargetResource()",
"from .group_type import GroupType\nfrom .modified_property import ModifiedProperty\nfrom .group_type import GroupType\nfrom .modified_property import ModifiedProperty\nfields: Dict[str, Callable[[Any], None]] = {'di... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TargetResource()
<|end_body_0|>
<|body_start_1|>
from .group_type import GroupType
from .modified_property import ModifiedProperty
from .group_type import GroupType
from ... | TargetResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k_train_011837 | 4,380 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TargetResource",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `TargetResource` described below.
Class description:
Implement the TargetResource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `TargetResource` described below.
Class description:
Implement the TargetResource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TargetResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetResource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TargetReso... | the_stack_v2_python_sparse | msgraph/generated/models/target_resource.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
743ea1ee86d43564569fc97b6f373f73fbb296bf | [
"if option.get_name() not in available_options:\n Logger().error(ErrorOptionUnavailable(option))\n raise ErrorOptionUnavailable(option)\nreturn 0",
"if type(option.get_value()) != eval(available_options['type']):\n Logger().error(ErrorOptionType(option, available_options))\n raise ErrorOptionType(opti... | <|body_start_0|>
if option.get_name() not in available_options:
Logger().error(ErrorOptionUnavailable(option))
raise ErrorOptionUnavailable(option)
return 0
<|end_body_0|>
<|body_start_1|>
if type(option.get_value()) != eval(available_options['type']):
Logger... | This class contain checking static methods. Can't be initialized. | Checker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
"""This class contain checking static methods. Can't be initialized."""
def is_option_available(option, available_options):
"""If option not in available_options, raise ErrorOptionUnavailable. Else, return 0."""
<|body_0|>
def verify_option_type(option, availabl... | stack_v2_sparse_classes_36k_train_011838 | 2,327 | no_license | [
{
"docstring": "If option not in available_options, raise ErrorOptionUnavailable. Else, return 0.",
"name": "is_option_available",
"signature": "def is_option_available(option, available_options)"
},
{
"docstring": "If option type wrong, raise ErrorOptionType. Else, return 0.",
"name": "veri... | 4 | stack_v2_sparse_classes_30k_train_001578 | Implement the Python class `Checker` described below.
Class description:
This class contain checking static methods. Can't be initialized.
Method signatures and docstrings:
- def is_option_available(option, available_options): If option not in available_options, raise ErrorOptionUnavailable. Else, return 0.
- def ver... | Implement the Python class `Checker` described below.
Class description:
This class contain checking static methods. Can't be initialized.
Method signatures and docstrings:
- def is_option_available(option, available_options): If option not in available_options, raise ErrorOptionUnavailable. Else, return 0.
- def ver... | 0377235647a1139a33dc0bffca4c6aa5ef665f6b | <|skeleton|>
class Checker:
"""This class contain checking static methods. Can't be initialized."""
def is_option_available(option, available_options):
"""If option not in available_options, raise ErrorOptionUnavailable. Else, return 0."""
<|body_0|>
def verify_option_type(option, availabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Checker:
"""This class contain checking static methods. Can't be initialized."""
def is_option_available(option, available_options):
"""If option not in available_options, raise ErrorOptionUnavailable. Else, return 0."""
if option.get_name() not in available_options:
Logger().... | the_stack_v2_python_sparse | src/util/Checker.py | lucgiffon/GASBI-PIB | train | 0 |
424b98d02139a8e614c6396761707edfb18a7635 | [
"if not identifier and (not location) or not parent:\n raise ValueError('Missing identifier and location, or parent value.')\nsuper(APFSPathSpec, self).__init__(parent=parent, **kwargs)\nself.identifier = identifier\nself.location = location",
"string_parts = []\nif self.identifier is not None:\n string_par... | <|body_start_0|>
if not identifier and (not location) or not parent:
raise ValueError('Missing identifier and location, or parent value.')
super(APFSPathSpec, self).__init__(parent=parent, **kwargs)
self.identifier = identifier
self.location = location
<|end_body_0|>
<|body_... | APFS path specification implementation. Attributes: identifier (int): identifier. location (str): location. | APFSPathSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APFSPathSpec:
"""APFS path specification implementation. Attributes: identifier (int): identifier. location (str): location."""
def __init__(self, identifier=None, location=None, parent=None, **kwargs):
"""Initializes a path specification. Note that an APFS path specification must ha... | stack_v2_sparse_classes_36k_train_011839 | 1,547 | permissive | [
{
"docstring": "Initializes a path specification. Note that an APFS path specification must have a parent. Args: identifier (Optional[int]): identifier. location (Optional[str]): location. parent (Optional[PathSpec]): parent path specification. Raises: ValueError: when parent or both identifier and location are... | 2 | stack_v2_sparse_classes_30k_train_013436 | Implement the Python class `APFSPathSpec` described below.
Class description:
APFS path specification implementation. Attributes: identifier (int): identifier. location (str): location.
Method signatures and docstrings:
- def __init__(self, identifier=None, location=None, parent=None, **kwargs): Initializes a path sp... | Implement the Python class `APFSPathSpec` described below.
Class description:
APFS path specification implementation. Attributes: identifier (int): identifier. location (str): location.
Method signatures and docstrings:
- def __init__(self, identifier=None, location=None, parent=None, **kwargs): Initializes a path sp... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class APFSPathSpec:
"""APFS path specification implementation. Attributes: identifier (int): identifier. location (str): location."""
def __init__(self, identifier=None, location=None, parent=None, **kwargs):
"""Initializes a path specification. Note that an APFS path specification must ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APFSPathSpec:
"""APFS path specification implementation. Attributes: identifier (int): identifier. location (str): location."""
def __init__(self, identifier=None, location=None, parent=None, **kwargs):
"""Initializes a path specification. Note that an APFS path specification must have a parent. ... | the_stack_v2_python_sparse | dfvfs/path/apfs_path_spec.py | log2timeline/dfvfs | train | 197 |
1cc0a83392147b06631e69d6a56a2ace7e36c513 | [
"view_id = self.env.ref('flsp_tktonhold.flsp_tktonhold_from_view').id\nname = 'Put ticket OnHold'\nticket_id = self.id\nreturn {'name': name, 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'flspticketsystem.onhold', 'view_id': view_id, 'views': [(view_id, 'form')], 'target': 'new', 'context': {'... | <|body_start_0|>
view_id = self.env.ref('flsp_tktonhold.flsp_tktonhold_from_view').id
name = 'Put ticket OnHold'
ticket_id = self.id
return {'name': name, 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'flspticketsystem.onhold', 'view_id': view_id, 'views': [(view_id,... | class_name: FlspTktOnhold model_name: inherits the flspticketsytem.ticket Purpose: To help in creating onhold for the ticket model Date: Feb/03/2021/W Author: Sami Byaruhanga | FlspTktOnhold | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlspTktOnhold:
"""class_name: FlspTktOnhold model_name: inherits the flspticketsytem.ticket Purpose: To help in creating onhold for the ticket model Date: Feb/03/2021/W Author: Sami Byaruhanga"""
def button_onhold(self):
"""Purpose: To call onhold wizard with context for the ticket""... | stack_v2_sparse_classes_36k_train_011840 | 3,998 | no_license | [
{
"docstring": "Purpose: To call onhold wizard with context for the ticket",
"name": "button_onhold",
"signature": "def button_onhold(self)"
},
{
"docstring": "Purpose: To remove from hold",
"name": "button_remove_hold",
"signature": "def button_remove_hold(self)"
}
] | 2 | null | Implement the Python class `FlspTktOnhold` described below.
Class description:
class_name: FlspTktOnhold model_name: inherits the flspticketsytem.ticket Purpose: To help in creating onhold for the ticket model Date: Feb/03/2021/W Author: Sami Byaruhanga
Method signatures and docstrings:
- def button_onhold(self): Pur... | Implement the Python class `FlspTktOnhold` described below.
Class description:
class_name: FlspTktOnhold model_name: inherits the flspticketsytem.ticket Purpose: To help in creating onhold for the ticket model Date: Feb/03/2021/W Author: Sami Byaruhanga
Method signatures and docstrings:
- def button_onhold(self): Pur... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class FlspTktOnhold:
"""class_name: FlspTktOnhold model_name: inherits the flspticketsytem.ticket Purpose: To help in creating onhold for the ticket model Date: Feb/03/2021/W Author: Sami Byaruhanga"""
def button_onhold(self):
"""Purpose: To call onhold wizard with context for the ticket""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlspTktOnhold:
"""class_name: FlspTktOnhold model_name: inherits the flspticketsytem.ticket Purpose: To help in creating onhold for the ticket model Date: Feb/03/2021/W Author: Sami Byaruhanga"""
def button_onhold(self):
"""Purpose: To call onhold wizard with context for the ticket"""
vie... | the_stack_v2_python_sparse | flsp_tktonhold/models/flsp_onhold.py | odoo-smg/firstlight | train | 3 |
74d1238680fb22a67c83447af0fe73406e31bc75 | [
"self.model = MRIBET().cuda()\nif weight_path is not None:\n weight = torch.load(weight_path, map_location='cuda:0')\n self.model.load_state_dict(weight['net'])",
"read_data = nib.load(path)\ndata = read_data.get_fdata().astype(np.float32)\nif img_type == 'T1':\n pass\nelif img_type == 'MRA':\n w_min ... | <|body_start_0|>
self.model = MRIBET().cuda()
if weight_path is not None:
weight = torch.load(weight_path, map_location='cuda:0')
self.model.load_state_dict(weight['net'])
<|end_body_0|>
<|body_start_1|>
read_data = nib.load(path)
data = read_data.get_fdata().ast... | MRI_BET | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRI_BET:
def __init__(self, weight_path: str=None):
"""Initialize the model with its weight. Args: (string) weight_path : model's weight path"""
<|body_0|>
def _preprocessing(self, path: str, img_type: str, min_percent: float=40.0, max_percent: float=98.5, out_min: int=0, ou... | stack_v2_sparse_classes_36k_train_011841 | 8,369 | permissive | [
{
"docstring": "Initialize the model with its weight. Args: (string) weight_path : model's weight path",
"name": "__init__",
"signature": "def __init__(self, weight_path: str=None)"
},
{
"docstring": "Preprocess the image from the path Args: (string) path : absolute path of data (string) img_typ... | 4 | stack_v2_sparse_classes_30k_train_008912 | Implement the Python class `MRI_BET` described below.
Class description:
Implement the MRI_BET class.
Method signatures and docstrings:
- def __init__(self, weight_path: str=None): Initialize the model with its weight. Args: (string) weight_path : model's weight path
- def _preprocessing(self, path: str, img_type: st... | Implement the Python class `MRI_BET` described below.
Class description:
Implement the MRI_BET class.
Method signatures and docstrings:
- def __init__(self, weight_path: str=None): Initialize the model with its weight. Args: (string) weight_path : model's weight path
- def _preprocessing(self, path: str, img_type: st... | 158a74985074f95fcd6a345c310903936dd2adbe | <|skeleton|>
class MRI_BET:
def __init__(self, weight_path: str=None):
"""Initialize the model with its weight. Args: (string) weight_path : model's weight path"""
<|body_0|>
def _preprocessing(self, path: str, img_type: str, min_percent: float=40.0, max_percent: float=98.5, out_min: int=0, ou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MRI_BET:
def __init__(self, weight_path: str=None):
"""Initialize the model with its weight. Args: (string) weight_path : model's weight path"""
self.model = MRIBET().cuda()
if weight_path is not None:
weight = torch.load(weight_path, map_location='cuda:0')
self... | the_stack_v2_python_sparse | medimodule/Brain/module.py | mi2rl/MI2RLNet | train | 13 | |
9620a20580fdfac9dfa7b9b7b4ac3ddd8662711b | [
"notification = ContainerChange(obj=self, name='measurements')\nif index is None:\n index = len(self.measurements)\n self.measurements.append(measurement)\nelse:\n self.measurements.insert(index, measurement)\nnotification.add_operation('added', (index, measurement))\nself.changed(notification)",
"if not... | <|body_start_0|>
notification = ContainerChange(obj=self, name='measurements')
if index is None:
index = len(self.measurements)
self.measurements.append(measurement)
else:
self.measurements.insert(index, measurement)
notification.add_operation('added',... | Generic container for measurements. | MeasurementContainer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasurementContainer:
"""Generic container for measurements."""
def add(self, measurement, index=None):
"""Add a measurement to the stored ones. Parameters ---------- measurement : Measurement Measurement to add. index : int | None Index at which to insert the measurement. If None th... | stack_v2_sparse_classes_36k_train_011842 | 2,809 | permissive | [
{
"docstring": "Add a measurement to the stored ones. Parameters ---------- measurement : Measurement Measurement to add. index : int | None Index at which to insert the measurement. If None the measurement is appended.",
"name": "add",
"signature": "def add(self, measurement, index=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_003168 | Implement the Python class `MeasurementContainer` described below.
Class description:
Generic container for measurements.
Method signatures and docstrings:
- def add(self, measurement, index=None): Add a measurement to the stored ones. Parameters ---------- measurement : Measurement Measurement to add. index : int | ... | Implement the Python class `MeasurementContainer` described below.
Class description:
Generic container for measurements.
Method signatures and docstrings:
- def add(self, measurement, index=None): Add a measurement to the stored ones. Parameters ---------- measurement : Measurement Measurement to add. index : int | ... | bb003a0ec74b622e1fb0e1dbfdd052f43531bfbd | <|skeleton|>
class MeasurementContainer:
"""Generic container for measurements."""
def add(self, measurement, index=None):
"""Add a measurement to the stored ones. Parameters ---------- measurement : Measurement Measurement to add. index : int | None Index at which to insert the measurement. If None th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasurementContainer:
"""Generic container for measurements."""
def add(self, measurement, index=None):
"""Add a measurement to the stored ones. Parameters ---------- measurement : Measurement Measurement to add. index : int | None Index at which to insert the measurement. If None the measurement... | the_stack_v2_python_sparse | exopy/measurement/container.py | Exopy/exopy | train | 17 |
0631eea7b21ec222ed5ccb4b2d934943d08c4f30 | [
"super().__init__(im_ids=im_ids, in_dir=in_dir, transforms=transforms, preprocessing=preprocessing)\nself.num_pseudo_slices = num_pseudo_slices\nassert num_pseudo_slices % 2 == 1, '`num_pseudo_slices` must be odd. i.e. 7 -> 3 above and 3 below'",
"case_fpath, center_slice_idx_str = self.split_case_slice_idx_str(c... | <|body_start_0|>
super().__init__(im_ids=im_ids, in_dir=in_dir, transforms=transforms, preprocessing=preprocessing)
self.num_pseudo_slices = num_pseudo_slices
assert num_pseudo_slices % 2 == 1, '`num_pseudo_slices` must be odd. i.e. 7 -> 3 above and 3 below'
<|end_body_0|>
<|body_start_1|>
... | Reads from a directory of 2D slice numpy arrays and samples positive slices. Assumes the data directory contains 2D slices processed by `io.Preprocessor.save_dir_as_2d()`. Generates 2.5D outputs B (background), K (kidney), KT (kidney + tumor) Stage 1: Sampled each class with p=0.33 Stage 2: Samples only K and KT (p=0.5... | PseudoSliceDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PseudoSliceDataset:
"""Reads from a directory of 2D slice numpy arrays and samples positive slices. Assumes the data directory contains 2D slices processed by `io.Preprocessor.save_dir_as_2d()`. Generates 2.5D outputs B (background), K (kidney), KT (kidney + tumor) Stage 1: Sampled each class wit... | stack_v2_sparse_classes_36k_train_011843 | 6,324 | permissive | [
{
"docstring": "Attributes im_ids (np.ndarray): of image names. in_dir (str): path to where all of the cases and slices are located transforms (albumentations.augmentation): transforms to apply before preprocessing. Defaults to HFlip and ToTensor preprocessing: ops to perform after transforms, such as z-score s... | 2 | stack_v2_sparse_classes_30k_train_005515 | Implement the Python class `PseudoSliceDataset` described below.
Class description:
Reads from a directory of 2D slice numpy arrays and samples positive slices. Assumes the data directory contains 2D slices processed by `io.Preprocessor.save_dir_as_2d()`. Generates 2.5D outputs B (background), K (kidney), KT (kidney +... | Implement the Python class `PseudoSliceDataset` described below.
Class description:
Reads from a directory of 2D slice numpy arrays and samples positive slices. Assumes the data directory contains 2D slices processed by `io.Preprocessor.save_dir_as_2d()`. Generates 2.5D outputs B (background), K (kidney), KT (kidney +... | 81d7413022220ea86a23212737b3682e84ae74a4 | <|skeleton|>
class PseudoSliceDataset:
"""Reads from a directory of 2D slice numpy arrays and samples positive slices. Assumes the data directory contains 2D slices processed by `io.Preprocessor.save_dir_as_2d()`. Generates 2.5D outputs B (background), K (kidney), KT (kidney + tumor) Stage 1: Sampled each class wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PseudoSliceDataset:
"""Reads from a directory of 2D slice numpy arrays and samples positive slices. Assumes the data directory contains 2D slices processed by `io.Preprocessor.save_dir_as_2d()`. Generates 2.5D outputs B (background), K (kidney), KT (kidney + tumor) Stage 1: Sampled each class with p=0.33 Stag... | the_stack_v2_python_sparse | kits19cnn/io/dataset.py | jchen42703/kits19-2d-reproduce | train | 9 |
3e5e6b59f567da9d7ac620a18efbb25eaa2b2054 | [
"len_nums = len(nums)\nif len_nums <= 1:\n return 0\np = 0\nstep = 0\nwhile p < len_nums:\n c_v = nums[p]\n temp_dict = dict()\n for i in range(1, c_v + 1):\n if p + i < len_nums:\n temp_dict[p + i + nums[p + i]] = p + i\n if p + i == len_nums - 1:\n return st... | <|body_start_0|>
len_nums = len(nums)
if len_nums <= 1:
return 0
p = 0
step = 0
while p < len_nums:
c_v = nums[p]
temp_dict = dict()
for i in range(1, c_v + 1):
if p + i < len_nums:
temp_dict[p + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums: List[int]) -> int:
"""贪心算法 :param nums: :return:"""
<|body_0|>
def jump2(self, nums: List[int]) -> int:
"""递归,遍历所有可能性 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
len_nums = len(nums)
i... | stack_v2_sparse_classes_36k_train_011844 | 4,406 | no_license | [
{
"docstring": "贪心算法 :param nums: :return:",
"name": "jump",
"signature": "def jump(self, nums: List[int]) -> int"
},
{
"docstring": "递归,遍历所有可能性 :param nums: :return:",
"name": "jump2",
"signature": "def jump2(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_001100 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums: List[int]) -> int: 贪心算法 :param nums: :return:
- def jump2(self, nums: List[int]) -> int: 递归,遍历所有可能性 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums: List[int]) -> int: 贪心算法 :param nums: :return:
- def jump2(self, nums: List[int]) -> int: 递归,遍历所有可能性 :param nums: :return:
<|skeleton|>
class Solution:
... | bbcb7c3c9aa51141695d73b90bf8f04c794be131 | <|skeleton|>
class Solution:
def jump(self, nums: List[int]) -> int:
"""贪心算法 :param nums: :return:"""
<|body_0|>
def jump2(self, nums: List[int]) -> int:
"""递归,遍历所有可能性 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums: List[int]) -> int:
"""贪心算法 :param nums: :return:"""
len_nums = len(nums)
if len_nums <= 1:
return 0
p = 0
step = 0
while p < len_nums:
c_v = nums[p]
temp_dict = dict()
for i in range(... | the_stack_v2_python_sparse | 00001_00100/00045_跳跃游戏II.py | xiphodon/leetcode_studio | train | 1 | |
baac4a6b30deb5f88f1c7404a7dc4da8613098f1 | [
"if IMPORT_KNACK:\n return\nlat = None\nlng = None\nvalue = json.loads(_coordinates)\npoint = value.get('coordinates', None) if value else None\nif point:\n lng, lat = point\nif lat and lng:\n self.timezone = timezone_from_coordinates(lat, lng)",
"data = super().to_dict(excludes=excludes, includes=includ... | <|body_start_0|>
if IMPORT_KNACK:
return
lat = None
lng = None
value = json.loads(_coordinates)
point = value.get('coordinates', None) if value else None
if point:
lng, lat = point
if lat and lng:
self.timezone = timezone_from_c... | Order location model. | OrderLocation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderLocation:
"""Order location model."""
def _update_timezone(self, _coordinates):
"""Update timezone when coordinates change."""
<|body_0|>
def to_dict(self, excludes: list=None, includes: list=None):
"""Return a dict representation of this object."""
... | stack_v2_sparse_classes_36k_train_011845 | 2,803 | no_license | [
{
"docstring": "Update timezone when coordinates change.",
"name": "_update_timezone",
"signature": "def _update_timezone(self, _coordinates)"
},
{
"docstring": "Return a dict representation of this object.",
"name": "to_dict",
"signature": "def to_dict(self, excludes: list=None, include... | 2 | stack_v2_sparse_classes_30k_train_002642 | Implement the Python class `OrderLocation` described below.
Class description:
Order location model.
Method signatures and docstrings:
- def _update_timezone(self, _coordinates): Update timezone when coordinates change.
- def to_dict(self, excludes: list=None, includes: list=None): Return a dict representation of thi... | Implement the Python class `OrderLocation` described below.
Class description:
Order location model.
Method signatures and docstrings:
- def _update_timezone(self, _coordinates): Update timezone when coordinates change.
- def to_dict(self, excludes: list=None, includes: list=None): Return a dict representation of thi... | e85c0ba0992bccb80878e89ec791ee64754646b0 | <|skeleton|>
class OrderLocation:
"""Order location model."""
def _update_timezone(self, _coordinates):
"""Update timezone when coordinates change."""
<|body_0|>
def to_dict(self, excludes: list=None, includes: list=None):
"""Return a dict representation of this object."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderLocation:
"""Order location model."""
def _update_timezone(self, _coordinates):
"""Update timezone when coordinates change."""
if IMPORT_KNACK:
return
lat = None
lng = None
value = json.loads(_coordinates)
point = value.get('coordinates', N... | the_stack_v2_python_sparse | src/briefy/leica/models/job/location.py | BriefyHQ/briefy.leica | train | 0 |
d71e749841df41e6b6c65a5ce2ab2e833d2c51a8 | [
"super(GCN_3, self).__init__()\nself.node_num = 2 * frames * slice * slice\nself.frames = frames\nself.batch = batch\nself.slice = slice\nself.fc1 = nn.Linear(in_features=2048, out_features=2048, bias=False)\nself.layer1 = nn.Sequential(nn.Linear(in_features=2048, out_features=2048, bias=False), nn.LayerNorm(normal... | <|body_start_0|>
super(GCN_3, self).__init__()
self.node_num = 2 * frames * slice * slice
self.frames = frames
self.batch = batch
self.slice = slice
self.fc1 = nn.Linear(in_features=2048, out_features=2048, bias=False)
self.layer1 = nn.Sequential(nn.Linear(in_feat... | base class for STGCN | GCN_3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCN_3:
"""base class for STGCN"""
def __init__(self, frames, slice, batch):
"""layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :pa... | stack_v2_sparse_classes_36k_train_011846 | 8,501 | no_license | [
{
"docstring": "layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :param batch: batch size divided by gpu number, int",
"name": "__init__",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_003222 | Implement the Python class `GCN_3` described below.
Class description:
base class for STGCN
Method signatures and docstrings:
- def __init__(self, frames, slice, batch): layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patc... | Implement the Python class `GCN_3` described below.
Class description:
base class for STGCN
Method signatures and docstrings:
- def __init__(self, frames, slice, batch): layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patc... | 9b0324b3d3a863d45680b09efef6d88bd4ddc3fb | <|skeleton|>
class GCN_3:
"""base class for STGCN"""
def __init__(self, frames, slice, batch):
"""layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GCN_3:
"""base class for STGCN"""
def __init__(self, frames, slice, batch):
"""layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :param batch: ba... | the_stack_v2_python_sparse | models/GCN_model.py | Timon0327/Video-inpainting | train | 1 |
69f12016b032b5b57d57f0c902888a282052f597 | [
"g_criterion = gtn.Graph(False)\nL = len(target)\nS = 2 * L + 1\nfor s in range(S):\n idx = (s - 1) // 2\n g_criterion.add_node(s == 0, s == S - 1 or s == S - 2)\n label = target[idx] if s % 2 else blank_idx\n g_criterion.add_arc(s, s, label)\n if s > 0:\n g_criterion.add_arc(s - 1, s, label)\... | <|body_start_0|>
g_criterion = gtn.Graph(False)
L = len(target)
S = 2 * L + 1
for s in range(S):
idx = (s - 1) // 2
g_criterion.add_node(s == 0, s == S - 1 or s == S - 2)
label = target[idx] if s % 2 else blank_idx
g_criterion.add_arc(s, s,... | GTN CTC module. | GTNCTCLossFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GTNCTCLossFunction:
"""GTN CTC module."""
def create_ctc_graph(target, blank_idx):
"""Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph"""
<|body_0|>
def forward(... | stack_v2_sparse_classes_36k_train_011847 | 3,974 | permissive | [
{
"docstring": "Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph",
"name": "create_ctc_graph",
"signature": "def create_ctc_graph(target, blank_idx)"
},
{
"docstring": "Forward computati... | 3 | null | Implement the Python class `GTNCTCLossFunction` described below.
Class description:
GTN CTC module.
Method signatures and docstrings:
- def create_ctc_graph(target, blank_idx): Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence ... | Implement the Python class `GTNCTCLossFunction` described below.
Class description:
GTN CTC module.
Method signatures and docstrings:
- def create_ctc_graph(target, blank_idx): Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence ... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class GTNCTCLossFunction:
"""GTN CTC module."""
def create_ctc_graph(target, blank_idx):
"""Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph"""
<|body_0|>
def forward(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GTNCTCLossFunction:
"""GTN CTC module."""
def create_ctc_graph(target, blank_idx):
"""Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph"""
g_criterion = gtn.Graph(False)
L ... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/gtn_ctc.py | espnet/espnet | train | 7,242 |
e7bec70d21dbd4d937ad1fc1ff2b58404ced6a95 | [
"BaseIO.__init__(self)\nself._path = filename\nself._filename = os.path.basename(filename)\nself._fsrc = None",
"assert not lazy, 'Do not support lazy'\nif kargs:\n raise NotImplementedError('This method does not have any arguments implemented yet')\nself._fsrc = None\nblock = Block(file_origin=self._filename)... | <|body_start_0|>
BaseIO.__init__(self)
self._path = filename
self._filename = os.path.basename(filename)
self._fsrc = None
<|end_body_0|>
<|body_start_1|>
assert not lazy, 'Do not support lazy'
if kargs:
raise NotImplementedError('This method does not have an... | Class for reading Brainware raw data files with the extension '.dam'. The read_block method returns the first Block of the file. It will automatically close the file after reading. The read method is the same as read_block. Note: The file format does not contain a sampling rate. The sampling rate is set to 1 Hz, but th... | BrainwareDamIO | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrainwareDamIO:
"""Class for reading Brainware raw data files with the extension '.dam'. The read_block method returns the first Block of the file. It will automatically close the file after reading. The read method is the same as read_block. Note: The file format does not contain a sampling rate... | stack_v2_sparse_classes_36k_train_011848 | 8,052 | permissive | [
{
"docstring": "Arguments: filename: the filename",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Reads a block from the raw data file \"fname\" generated with BrainWare",
"name": "read_block",
"signature": "def read_block(self, lazy=False, **kar... | 3 | null | Implement the Python class `BrainwareDamIO` described below.
Class description:
Class for reading Brainware raw data files with the extension '.dam'. The read_block method returns the first Block of the file. It will automatically close the file after reading. The read method is the same as read_block. Note: The file ... | Implement the Python class `BrainwareDamIO` described below.
Class description:
Class for reading Brainware raw data files with the extension '.dam'. The read_block method returns the first Block of the file. It will automatically close the file after reading. The read method is the same as read_block. Note: The file ... | 354c8d9d5fbc4daad3547773d2f281f8c163d208 | <|skeleton|>
class BrainwareDamIO:
"""Class for reading Brainware raw data files with the extension '.dam'. The read_block method returns the first Block of the file. It will automatically close the file after reading. The read method is the same as read_block. Note: The file format does not contain a sampling rate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrainwareDamIO:
"""Class for reading Brainware raw data files with the extension '.dam'. The read_block method returns the first Block of the file. It will automatically close the file after reading. The read method is the same as read_block. Note: The file format does not contain a sampling rate. The samplin... | the_stack_v2_python_sparse | neo/io/brainwaredamio.py | NeuralEnsemble/python-neo | train | 265 |
57a1f3b98f0341e5895302c6ebe88bb2d91b1d9b | [
"if not head or not head.next:\n return head\nnew = head.next\nhead.next = self.swapPairs(new.next)\nnew.next = head\nreturn new",
"dummy = ListNode(0)\ndummy.next = head\ntmp = dummy\nwhile tmp.next and tmp.next.next:\n nod1 = tmp.next\n nod2 = tmp.next.next\n tmp.next = nod2\n nod1.next = nod2.ne... | <|body_start_0|>
if not head or not head.next:
return head
new = head.next
head.next = self.swapPairs(new.next)
new.next = head
return new
<|end_body_0|>
<|body_start_1|>
dummy = ListNode(0)
dummy.next = head
tmp = dummy
while tmp.next... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""直接递归 :param head: :return:"""
<|body_0|>
def swapPairs2(self, head: ListNode) -> ListNode:
"""设置一个哨兵节点 :param head: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or... | stack_v2_sparse_classes_36k_train_011849 | 1,066 | no_license | [
{
"docstring": "直接递归 :param head: :return:",
"name": "swapPairs",
"signature": "def swapPairs(self, head: ListNode) -> ListNode"
},
{
"docstring": "设置一个哨兵节点 :param head: :return:",
"name": "swapPairs2",
"signature": "def swapPairs2(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_021341 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 直接递归 :param head: :return:
- def swapPairs2(self, head: ListNode) -> ListNode: 设置一个哨兵节点 :param head: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 直接递归 :param head: :return:
- def swapPairs2(self, head: ListNode) -> ListNode: 设置一个哨兵节点 :param head: :return:
<|skeleton|>
class... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""直接递归 :param head: :return:"""
<|body_0|>
def swapPairs2(self, head: ListNode) -> ListNode:
"""设置一个哨兵节点 :param head: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""直接递归 :param head: :return:"""
if not head or not head.next:
return head
new = head.next
head.next = self.swapPairs(new.next)
new.next = head
return new
def swapPairs2(self, head: List... | the_stack_v2_python_sparse | 两两交换链表中的节点.py | cjrzs/MyLeetCode | train | 8 | |
2806af3588bd07bcc8e715c777b099fdff581a09 | [
"n_bin_rev = n_bin[::-1]\npower_of_2 = 0\ndecimal = 0\nfor i in n_bin_rev:\n decimal += int(i) * 2 ** power_of_2\n power_of_2 += 1\nreturn decimal",
"binary = ''\nwhile n_dec != 0:\n remainder = str(n_dec % 2)\n binary = binary + remainder\n n_dec = n_dec // 2\nreturn binary[::-1]",
"a_dec = self... | <|body_start_0|>
n_bin_rev = n_bin[::-1]
power_of_2 = 0
decimal = 0
for i in n_bin_rev:
decimal += int(i) * 2 ** power_of_2
power_of_2 += 1
return decimal
<|end_body_0|>
<|body_start_1|>
binary = ''
while n_dec != 0:
remainder ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bin_to_dec(self, n_bin):
""":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right."""
<|body_0|>
def dec_to_bin(self, n_dec):
""":param n_de... | stack_v2_sparse_classes_36k_train_011850 | 1,647 | no_license | [
{
"docstring": ":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right.",
"name": "bin_to_dec",
"signature": "def bin_to_dec(self, n_bin)"
},
{
"docstring": ":param n_dec: string :retu... | 3 | stack_v2_sparse_classes_30k_train_014659 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_to_dec(self, n_bin): :param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conv... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_to_dec(self, n_bin): :param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conv... | c9c0d4dbeb583eaf8ec7899310bb4665ec5035d0 | <|skeleton|>
class Solution:
def bin_to_dec(self, n_bin):
""":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right."""
<|body_0|>
def dec_to_bin(self, n_dec):
""":param n_de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bin_to_dec(self, n_bin):
""":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right."""
n_bin_rev = n_bin[::-1]
power_of_2 = 0
decimal = 0
for i ... | the_stack_v2_python_sparse | Leetcode--Python-master/Directory1/BinarySum.py | sanaydevi/leetCodeSolutions | train | 0 | |
05fba5bbb6a9338fda8deb72943434016716930a | [
"super().handle_input(data_type)\nfilepath = os.path.join(self.artifact.uri, DEFAULT_FILENAME)\nwith open(filepath, 'rb') as fid:\n clf = pickle.load(fid)\nreturn clf",
"super().handle_return(clf)\nfilepath = os.path.join(self.artifact.uri, DEFAULT_FILENAME)\nwith open(filepath, 'wb') as fid:\n pickle.dump(... | <|body_start_0|>
super().handle_input(data_type)
filepath = os.path.join(self.artifact.uri, DEFAULT_FILENAME)
with open(filepath, 'rb') as fid:
clf = pickle.load(fid)
return clf
<|end_body_0|>
<|body_start_1|>
super().handle_return(clf)
filepath = os.path.joi... | Materializer to read data to and from sklearn. | SklearnMaterializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnMaterializer:
"""Materializer to read data to and from sklearn."""
def handle_input(self, data_type: Type[Any]) -> Union[BaseEstimator, ClassifierMixin, ClusterMixin, BiclusterMixin, OutlierMixin, RegressorMixin, MetaEstimatorMixin, MultiOutputMixin, DensityMixin, TransformerMixin]:
... | stack_v2_sparse_classes_36k_train_011851 | 2,624 | permissive | [
{
"docstring": "Reads a base sklearn model from a pickle file.",
"name": "handle_input",
"signature": "def handle_input(self, data_type: Type[Any]) -> Union[BaseEstimator, ClassifierMixin, ClusterMixin, BiclusterMixin, OutlierMixin, RegressorMixin, MetaEstimatorMixin, MultiOutputMixin, DensityMixin, Tra... | 2 | stack_v2_sparse_classes_30k_train_011570 | Implement the Python class `SklearnMaterializer` described below.
Class description:
Materializer to read data to and from sklearn.
Method signatures and docstrings:
- def handle_input(self, data_type: Type[Any]) -> Union[BaseEstimator, ClassifierMixin, ClusterMixin, BiclusterMixin, OutlierMixin, RegressorMixin, Meta... | Implement the Python class `SklearnMaterializer` described below.
Class description:
Materializer to read data to and from sklearn.
Method signatures and docstrings:
- def handle_input(self, data_type: Type[Any]) -> Union[BaseEstimator, ClassifierMixin, ClusterMixin, BiclusterMixin, OutlierMixin, RegressorMixin, Meta... | f1499e9c3fee00fd1d66de14cab66c4472c0085d | <|skeleton|>
class SklearnMaterializer:
"""Materializer to read data to and from sklearn."""
def handle_input(self, data_type: Type[Any]) -> Union[BaseEstimator, ClassifierMixin, ClusterMixin, BiclusterMixin, OutlierMixin, RegressorMixin, MetaEstimatorMixin, MultiOutputMixin, DensityMixin, TransformerMixin]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SklearnMaterializer:
"""Materializer to read data to and from sklearn."""
def handle_input(self, data_type: Type[Any]) -> Union[BaseEstimator, ClassifierMixin, ClusterMixin, BiclusterMixin, OutlierMixin, RegressorMixin, MetaEstimatorMixin, MultiOutputMixin, DensityMixin, TransformerMixin]:
"""Rea... | the_stack_v2_python_sparse | src/zenml/integrations/sklearn/materializers/sklearn_materializer.py | stefannica/zenml | train | 0 |
975c513fb390cf934b4c683289d0a80c97bc8644 | [
"context = super(PendingEntryListView, self).get_context_data(**kwargs)\ncontext['num_entries'] = self.get_queryset().count()\ncontext['unapproved'] = True\ncontext['entries'] = Entry.objects.filter(version=self.version)\nreturn context",
"if self.queryset is None:\n project_slug = self.kwargs.get('project_slu... | <|body_start_0|>
context = super(PendingEntryListView, self).get_context_data(**kwargs)
context['num_entries'] = self.get_queryset().count()
context['unapproved'] = True
context['entries'] = Entry.objects.filter(version=self.version)
return context
<|end_body_0|>
<|body_start_1|... | List view for pending Entry. | PendingEntryListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PendingEntryListView:
"""List view for pending Entry."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template... | stack_v2_sparse_classes_36k_train_011852 | 13,902 | no_license | [
{
"docstring": "Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template. :rtype: dict",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
... | 2 | stack_v2_sparse_classes_30k_val_001150 | Implement the Python class `PendingEntryListView` described below.
Class description:
List view for pending Entry.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :r... | Implement the Python class `PendingEntryListView` described below.
Class description:
List view for pending Entry.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :r... | ca489c38fdfde29f75c9c1e7f4b4c55d78d91c79 | <|skeleton|>
class PendingEntryListView:
"""List view for pending Entry."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PendingEntryListView:
"""List view for pending Entry."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template. :rtype: dic... | the_stack_v2_python_sparse | django_project/changes/views/entry.py | gitter-badger/projecta | train | 0 |
4e207470c952ab21691e899ea784c8695d74bc2f | [
"try:\n order = self.get_object()\n order.alive = False\n order.save()\n return Response(status.HTTP_200_OK)\nexcept Order.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)",
"serizelizer = OrderAPISerializer(data=request.data, context={'request': request})\nserizelizer.is_valid(rai... | <|body_start_0|>
try:
order = self.get_object()
order.alive = False
order.save()
return Response(status.HTTP_200_OK)
except Order.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
<|end_body_0|>
<|body_start_1|>
serizeliz... | 允许用户查看的或编辑的订单 API 路径. | OrderAPIViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderAPIViewSet:
"""允许用户查看的或编辑的订单 API 路径."""
def cancel(self, request, *args, **kwargs):
"""只接受一个 GET 取消一个订单。"""
<|body_0|>
def create_order(self, request, *args, **kwargs):
"""只接受一个 POST 创建一个订单, 该方法仅可 JWT 验证使用"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_011853 | 2,511 | no_license | [
{
"docstring": "只接受一个 GET 取消一个订单。",
"name": "cancel",
"signature": "def cancel(self, request, *args, **kwargs)"
},
{
"docstring": "只接受一个 POST 创建一个订单, 该方法仅可 JWT 验证使用",
"name": "create_order",
"signature": "def create_order(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011275 | Implement the Python class `OrderAPIViewSet` described below.
Class description:
允许用户查看的或编辑的订单 API 路径.
Method signatures and docstrings:
- def cancel(self, request, *args, **kwargs): 只接受一个 GET 取消一个订单。
- def create_order(self, request, *args, **kwargs): 只接受一个 POST 创建一个订单, 该方法仅可 JWT 验证使用 | Implement the Python class `OrderAPIViewSet` described below.
Class description:
允许用户查看的或编辑的订单 API 路径.
Method signatures and docstrings:
- def cancel(self, request, *args, **kwargs): 只接受一个 GET 取消一个订单。
- def create_order(self, request, *args, **kwargs): 只接受一个 POST 创建一个订单, 该方法仅可 JWT 验证使用
<|skeleton|>
class OrderAPIVie... | 326decac00a07c4fea09dce77f366b5b7155d3e9 | <|skeleton|>
class OrderAPIViewSet:
"""允许用户查看的或编辑的订单 API 路径."""
def cancel(self, request, *args, **kwargs):
"""只接受一个 GET 取消一个订单。"""
<|body_0|>
def create_order(self, request, *args, **kwargs):
"""只接受一个 POST 创建一个订单, 该方法仅可 JWT 验证使用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderAPIViewSet:
"""允许用户查看的或编辑的订单 API 路径."""
def cancel(self, request, *args, **kwargs):
"""只接受一个 GET 取消一个订单。"""
try:
order = self.get_object()
order.alive = False
order.save()
return Response(status.HTTP_200_OK)
except Order.DoesNot... | the_stack_v2_python_sparse | week09/DFR/order/views.py | jupiterchu/Python005-01 | train | 0 |
95b4876cecd977efb7ce4c4a20a7225950470702 | [
"this_folder = os.path.dirname(os.path.abspath(__file__))\nfile_name = os.path.join(this_folder, 'event-mapping.json')\nwith open(file_name) as f:\n self.event_mapping = json.load(f)",
"for tag, properties in tags.items():\n val = values_to_sub.get(tag)\n values_to_sub[tag] = self.transform_val(propertie... | <|body_start_0|>
this_folder = os.path.dirname(os.path.abspath(__file__))
file_name = os.path.join(this_folder, 'event-mapping.json')
with open(file_name) as f:
self.event_mapping = json.load(f)
<|end_body_0|>
<|body_start_1|>
for tag, properties in tags.items():
... | Events library class that loads and customizes event json files Methods --------------- expose_event_metadata(self): return the event mapping file generate-event(self, service_name, event_type, values_to_sub): load in and substitute values into json file (if necessary) | Events | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Events:
"""Events library class that loads and customizes event json files Methods --------------- expose_event_metadata(self): return the event mapping file generate-event(self, service_name, event_type, values_to_sub): load in and substitute values into json file (if necessary)"""
def __in... | stack_v2_sparse_classes_36k_train_011854 | 5,791 | permissive | [
{
"docstring": "Constructor for event library",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "transform (if needed) values_to_sub with given tags Parameters ---------- tags: dict the values of a particular event that can be substituted within the event json values_to_s... | 6 | stack_v2_sparse_classes_30k_train_000343 | Implement the Python class `Events` described below.
Class description:
Events library class that loads and customizes event json files Methods --------------- expose_event_metadata(self): return the event mapping file generate-event(self, service_name, event_type, values_to_sub): load in and substitute values into js... | Implement the Python class `Events` described below.
Class description:
Events library class that loads and customizes event json files Methods --------------- expose_event_metadata(self): return the event mapping file generate-event(self, service_name, event_type, values_to_sub): load in and substitute values into js... | b297ff015f2b69d7c74059c2d42ece1c29ea73ee | <|skeleton|>
class Events:
"""Events library class that loads and customizes event json files Methods --------------- expose_event_metadata(self): return the event mapping file generate-event(self, service_name, event_type, values_to_sub): load in and substitute values into json file (if necessary)"""
def __in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Events:
"""Events library class that loads and customizes event json files Methods --------------- expose_event_metadata(self): return the event mapping file generate-event(self, service_name, event_type, values_to_sub): load in and substitute values into json file (if necessary)"""
def __init__(self):
... | the_stack_v2_python_sparse | samcli/lib/generated_sample_events/events.py | aws/aws-sam-cli | train | 1,402 |
d0b5177b1acfa1fd3ff9c80ec5fa59ff2492335a | [
"self.shape = shape\nself.roll = shape[0] / 2\nself.probe_height = probe_height\nx_dist = np.zeros(shape)\ny_dist = np.zeros(shape)\nfor i in range(shape[1]):\n x_dist[:, i] = i\nfor i in range(shape[0]):\n y_dist[i] = i\nself.x_dist = x_dist\nself.y_dist = y_dist - self.roll\nself.ex = T.dmatrix('ex')\nself.... | <|body_start_0|>
self.shape = shape
self.roll = shape[0] / 2
self.probe_height = probe_height
x_dist = np.zeros(shape)
y_dist = np.zeros(shape)
for i in range(shape[1]):
x_dist[:, i] = i
for i in range(shape[0]):
y_dist[i] = i
self.... | ECG_single | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ECG_single:
def __init__(self, shape, probe_height):
"""Class for dynamically returning ECG voltage of a particular excitation state at a particular probe position. Initialise before running any animations."""
<|body_0|>
def voltage(self, excitation_matrix, probe_centre):
... | stack_v2_sparse_classes_36k_train_011855 | 18,145 | no_license | [
{
"docstring": "Class for dynamically returning ECG voltage of a particular excitation state at a particular probe position. Initialise before running any animations.",
"name": "__init__",
"signature": "def __init__(self, shape, probe_height)"
},
{
"docstring": "excitation_matrix is current syst... | 2 | stack_v2_sparse_classes_30k_val_000325 | Implement the Python class `ECG_single` described below.
Class description:
Implement the ECG_single class.
Method signatures and docstrings:
- def __init__(self, shape, probe_height): Class for dynamically returning ECG voltage of a particular excitation state at a particular probe position. Initialise before runnin... | Implement the Python class `ECG_single` described below.
Class description:
Implement the ECG_single class.
Method signatures and docstrings:
- def __init__(self, shape, probe_height): Class for dynamically returning ECG voltage of a particular excitation state at a particular probe position. Initialise before runnin... | 2949ac7e9aa0928001688dc6a8071e267d6026f5 | <|skeleton|>
class ECG_single:
def __init__(self, shape, probe_height):
"""Class for dynamically returning ECG voltage of a particular excitation state at a particular probe position. Initialise before running any animations."""
<|body_0|>
def voltage(self, excitation_matrix, probe_centre):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ECG_single:
def __init__(self, shape, probe_height):
"""Class for dynamically returning ECG voltage of a particular excitation state at a particular probe position. Initialise before running any animations."""
self.shape = shape
self.roll = shape[0] / 2
self.probe_height = prob... | the_stack_v2_python_sparse | analysis_theano.py | MaxFalkenberg/AF-Clean | train | 2 | |
ea5599556288a026dd04697e661fc1655989985d | [
"self.grid = matrix\nself.cache = []\nr = len(matrix)\nc = len(matrix[0])\nfor i in range(r):\n temp = []\n last = 0\n for j in range(c):\n last += matrix[i][j]\n temp.append(last)\n self.cache.append(temp)\nprint(self.cache)",
"ans = 0\nfor i in range(row1, row2 + 1):\n row_sum = sel... | <|body_start_0|>
self.grid = matrix
self.cache = []
r = len(matrix)
c = len(matrix[0])
for i in range(r):
temp = []
last = 0
for j in range(c):
last += matrix[i][j]
temp.append(last)
self.cache.append... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_011856 | 3,429 | permissive | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_006918 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | fe1928d8b10a63d7aa561118a70eeaec2f3a2f36 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.grid = matrix
self.cache = []
r = len(matrix)
c = len(matrix[0])
for i in range(r):
temp = []
last = 0
for j in range(c):
last += ... | the_stack_v2_python_sparse | May/Week2/Range Sum Query 2D - Immutable.py | vinaykumar7686/Leetcode-Monthly_Challenges | train | 0 | |
3615569900ca4fb2800158d5453528df61c53f26 | [
"self.db_name = name\nself.data = self.extract(version)\nself.strategies = [normalize_units, drop_unspecified_subcategories, ensure_categories_are_tuples]",
"def extract_flow_data(o):\n ds = {'categories': (o.compartment.compartment.text, o.compartment.subcompartment.text), 'code': o.get('id'), 'CAS number': o... | <|body_start_0|>
self.db_name = name
self.data = self.extract(version)
self.strategies = [normalize_units, drop_unspecified_subcategories, ensure_categories_are_tuples]
<|end_body_0|>
<|body_start_1|>
def extract_flow_data(o):
ds = {'categories': (o.compartment.compartment.t... | Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted data. See Also -------- https://github.com/brightway-... | Ecospold2BiosphereImporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ecospold2BiosphereImporter:
"""Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted... | stack_v2_sparse_classes_36k_train_011857 | 2,880 | permissive | [
{
"docstring": "Initialize the importer. Parameters ---------- name : str, optional Name of the database, by default \"biosphere3\". version : str, optional Version of the database, by default \"3.9\".",
"name": "__init__",
"signature": "def __init__(self, name='biosphere3', version='3.9')"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_007077 | Implement the Python class `Ecospold2BiosphereImporter` described below.
Class description:
Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List... | Implement the Python class `Ecospold2BiosphereImporter` described below.
Class description:
Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List... | 0c3c7288a897f57511ce17a6be1698e2cb9b08a1 | <|skeleton|>
class Ecospold2BiosphereImporter:
"""Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ecospold2BiosphereImporter:
"""Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted data. See Al... | the_stack_v2_python_sparse | bw2io/importers/ecospold2_biosphere.py | brightway-lca/brightway2-io | train | 13 |
31e4556dbf4f84186b1a20b03300fbf10e10504a | [
"self.ip = 'forward.xdaili.cn'\nself.port = '80'\nself.orderno = 'ZF2018***********'\nself.secert = '**********************************'",
"manifest_json = '\\n {\\n \"version\": \"1.0.0\",\\n \"manifest_version\": 2,\\n \"name\": \"Xdaili Proxy\",\\n ... | <|body_start_0|>
self.ip = 'forward.xdaili.cn'
self.port = '80'
self.orderno = 'ZF2018***********'
self.secert = '**********************************'
<|end_body_0|>
<|body_start_1|>
manifest_json = '\n {\n "version": "1.0.0",\n "manifest_... | Xdaili | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Xdaili:
def __init__(self):
"""初始化信息"""
<|body_0|>
def auth(self):
"""构造代理 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ip = 'forward.xdaili.cn'
self.port = '80'
self.orderno = 'ZF2018***********'
self.secert... | stack_v2_sparse_classes_36k_train_011858 | 2,357 | no_license | [
{
"docstring": "初始化信息",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "构造代理 :return:",
"name": "auth",
"signature": "def auth(self)"
}
] | 2 | null | Implement the Python class `Xdaili` described below.
Class description:
Implement the Xdaili class.
Method signatures and docstrings:
- def __init__(self): 初始化信息
- def auth(self): 构造代理 :return: | Implement the Python class `Xdaili` described below.
Class description:
Implement the Xdaili class.
Method signatures and docstrings:
- def __init__(self): 初始化信息
- def auth(self): 构造代理 :return:
<|skeleton|>
class Xdaili:
def __init__(self):
"""初始化信息"""
<|body_0|>
def auth(self):
"""... | 87cbae60f7a5b033851b0056dff741a3d5980d06 | <|skeleton|>
class Xdaili:
def __init__(self):
"""初始化信息"""
<|body_0|>
def auth(self):
"""构造代理 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Xdaili:
def __init__(self):
"""初始化信息"""
self.ip = 'forward.xdaili.cn'
self.port = '80'
self.orderno = 'ZF2018***********'
self.secert = '**********************************'
def auth(self):
"""构造代理 :return:"""
manifest_json = '\n {\n ... | the_stack_v2_python_sparse | 04-Selenium_Taobao/xdaili.py | Northxw/Python3_WebSpider | train | 545 | |
ae9d18ff5cd47707b62de44018aee927236d476b | [
"self._vehicle = vehicle\nself._K_P = K_P\nself._K_D = K_D\nself._K_I = K_I\nself._dt = dt\nself._e_buffer = deque(maxlen=30)",
"current_speed = get_speed(self._vehicle)\nif debug:\n print('Current speed = {}'.format(current_speed))\nreturn self._pid_control(target_speed, current_speed)",
"_e = target_speed ... | <|body_start_0|>
self._vehicle = vehicle
self._K_P = K_P
self._K_D = K_D
self._K_I = K_I
self._dt = dt
self._e_buffer = deque(maxlen=30)
<|end_body_0|>
<|body_start_1|>
current_speed = get_speed(self._vehicle)
if debug:
print('Current speed = ... | PIDLongitudinalController implements longitudinal control using a PID. | PIDLongitudinalController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIDLongitudinalController:
"""PIDLongitudinalController implements longitudinal control using a PID."""
def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03):
""":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differentia... | stack_v2_sparse_classes_36k_train_011859 | 13,383 | no_license | [
{
"docstring": ":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differential term :param K_I: Integral term :param dt: time differential in seconds",
"name": "__init__",
"signature": "def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03)"
... | 3 | stack_v2_sparse_classes_30k_train_000934 | Implement the Python class `PIDLongitudinalController` described below.
Class description:
PIDLongitudinalController implements longitudinal control using a PID.
Method signatures and docstrings:
- def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03): :param vehicle: actor to apply to local planner logic o... | Implement the Python class `PIDLongitudinalController` described below.
Class description:
PIDLongitudinalController implements longitudinal control using a PID.
Method signatures and docstrings:
- def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03): :param vehicle: actor to apply to local planner logic o... | da35bfec7d40708e4f76d08f54e04587bef1dd8b | <|skeleton|>
class PIDLongitudinalController:
"""PIDLongitudinalController implements longitudinal control using a PID."""
def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03):
""":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differentia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PIDLongitudinalController:
"""PIDLongitudinalController implements longitudinal control using a PID."""
def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03):
""":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differential term :param... | the_stack_v2_python_sparse | drive_interfaces/carla/comercial_cars/Navigation/controller.py | gy20073/CIL_modular | train | 2 |
392276cae4d281dbdbeaa2a3f71d89899570198d | [
"try:\n raise RuntimeError('foo')\nexcept Exception as e:\n error = e\nresult = catch(RuntimeError, lambda e: ('caught', e))(error)\nself.assertEqual(result, ('caught', error))",
"try:\n raise ZeroDivisionError('foo')\nexcept Exception as e:\n error = e\ne = self.assertRaises(ZeroDivisionError, lambda... | <|body_start_0|>
try:
raise RuntimeError('foo')
except Exception as e:
error = e
result = catch(RuntimeError, lambda e: ('caught', e))(error)
self.assertEqual(result, ('caught', error))
<|end_body_0|>
<|body_start_1|>
try:
raise ZeroDivisionEr... | Tests for :func:`catch`. | CatchTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatchTests:
"""Tests for :func:`catch`."""
def test_caught(self):
"""When the exception type matches the type of the raised exception, the callable is invoked and its result is returned."""
<|body_0|>
def test_missed(self):
"""When the exception type does not mat... | stack_v2_sparse_classes_36k_train_011860 | 10,308 | permissive | [
{
"docstring": "When the exception type matches the type of the raised exception, the callable is invoked and its result is returned.",
"name": "test_caught",
"signature": "def test_caught(self)"
},
{
"docstring": "When the exception type does not match the type of the raised exception, the call... | 2 | stack_v2_sparse_classes_30k_train_000326 | Implement the Python class `CatchTests` described below.
Class description:
Tests for :func:`catch`.
Method signatures and docstrings:
- def test_caught(self): When the exception type matches the type of the raised exception, the callable is invoked and its result is returned.
- def test_missed(self): When the except... | Implement the Python class `CatchTests` described below.
Class description:
Tests for :func:`catch`.
Method signatures and docstrings:
- def test_caught(self): When the exception type matches the type of the raised exception, the callable is invoked and its result is returned.
- def test_missed(self): When the except... | cd21859ad2babebcbf12fa372aef34b9cd25a10e | <|skeleton|>
class CatchTests:
"""Tests for :func:`catch`."""
def test_caught(self):
"""When the exception type matches the type of the raised exception, the callable is invoked and its result is returned."""
<|body_0|>
def test_missed(self):
"""When the exception type does not mat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CatchTests:
"""Tests for :func:`catch`."""
def test_caught(self):
"""When the exception type matches the type of the raised exception, the callable is invoked and its result is returned."""
try:
raise RuntimeError('foo')
except Exception as e:
error = e
... | the_stack_v2_python_sparse | effect/test_base.py | python-effect/effect | train | 289 |
283c28bc1bef0f0d4a6851ce8feed887180c31a8 | [
"mimetype = self.context.resource_mimetype()\nif mimetype:\n mime_parts = mimetype.split('/')\n for view_name in ['%s_%s' % tuple(mime_parts), mime_parts[0], 'default']:\n view = queryMultiAdapter((self.context, self.request), name='resource_%s' % view_name)\n if view:\n return view._... | <|body_start_0|>
mimetype = self.context.resource_mimetype()
if mimetype:
mime_parts = mimetype.split('/')
for view_name in ['%s_%s' % tuple(mime_parts), mime_parts[0], 'default']:
view = queryMultiAdapter((self.context, self.request), name='resource_%s' % view_na... | A view to display a resource. | ATResourceView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATResourceView:
"""A view to display a resource."""
def resource_view(self):
"""Returns the view for the resource based on its mimetype."""
<|body_0|>
def resource(self):
"""Renders the resource."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m... | stack_v2_sparse_classes_36k_train_011861 | 1,247 | no_license | [
{
"docstring": "Returns the view for the resource based on its mimetype.",
"name": "resource_view",
"signature": "def resource_view(self)"
},
{
"docstring": "Renders the resource.",
"name": "resource",
"signature": "def resource(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015657 | Implement the Python class `ATResourceView` described below.
Class description:
A view to display a resource.
Method signatures and docstrings:
- def resource_view(self): Returns the view for the resource based on its mimetype.
- def resource(self): Renders the resource. | Implement the Python class `ATResourceView` described below.
Class description:
A view to display a resource.
Method signatures and docstrings:
- def resource_view(self): Returns the view for the resource based on its mimetype.
- def resource(self): Renders the resource.
<|skeleton|>
class ATResourceView:
"""A v... | bd7ca0793d35bbdbc83200d27650fe024d1f432e | <|skeleton|>
class ATResourceView:
"""A view to display a resource."""
def resource_view(self):
"""Returns the view for the resource based on its mimetype."""
<|body_0|>
def resource(self):
"""Renders the resource."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ATResourceView:
"""A view to display a resource."""
def resource_view(self):
"""Returns the view for the resource based on its mimetype."""
mimetype = self.context.resource_mimetype()
if mimetype:
mime_parts = mimetype.split('/')
for view_name in ['%s_%s' %... | the_stack_v2_python_sparse | groundwire/atresources/browser/atresource.py | collective/groundwire.atresources | train | 0 |
1f1ce2c9c565816e0c806c3da2b884d1d71956e7 | [
"if len(nums) < k:\n return False\ntotal = sum(nums)\nif total % k != 0:\n return False\ntarget = total / k\nused = [0] * len(nums)\ns = self.backtrack(k, 0, nums, 0, used, target)\nreturn s",
"if k == 0:\n return True\nif cur_bucket_total == target:\n return self.backtrack(k - 1, 0, nums, 0, used, ta... | <|body_start_0|>
if len(nums) < k:
return False
total = sum(nums)
if total % k != 0:
return False
target = total / k
used = [0] * len(nums)
s = self.backtrack(k, 0, nums, 0, used, target)
return s
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_possible_divide(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def backtrack(self, k, cur_bucket_total, nums, start, used, target):
"""@param k: 待选择的桶编号 @param cur_bucket_total: 当前桶已经装的数字之和 @param nums: 待选择的数字列表 @par... | stack_v2_sparse_classes_36k_train_011862 | 2,042 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "is_possible_divide",
"signature": "def is_possible_divide(self, nums, k)"
},
{
"docstring": "@param k: 待选择的桶编号 @param cur_bucket_total: 当前桶已经装的数字之和 @param nums: 待选择的数字列表 @param used: 已经选择过的索引 @param start: 开始遍历的位置 @param ... | 2 | stack_v2_sparse_classes_30k_train_019299 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_possible_divide(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def backtrack(self, k, cur_bucket_total, nums, start, used, target): @param k: 待选择的桶编号 @p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_possible_divide(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def backtrack(self, k, cur_bucket_total, nums, start, used, target): @param k: 待选择的桶编号 @p... | 5ba3465ba9c85955eac188e1e3793a981de712e7 | <|skeleton|>
class Solution:
def is_possible_divide(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def backtrack(self, k, cur_bucket_total, nums, start, used, target):
"""@param k: 待选择的桶编号 @param cur_bucket_total: 当前桶已经装的数字之和 @param nums: 待选择的数字列表 @par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def is_possible_divide(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
if len(nums) < k:
return False
total = sum(nums)
if total % k != 0:
return False
target = total / k
used = [0] * len(nums)
s = ... | the_stack_v2_python_sparse | backtrack/698_划分为k个相等的子集.py | SilvesSun/learn-algorithm-in-python | train | 0 | |
980de806b394bb46849606d7e27fdf360354e87e | [
"super().setUpTestData()\ncls.acme = Company.objects.create(name='ACME', description='Supplier', is_customer=False, is_supplier=True)\nCompany.objects.create(name='Drippy Cup Co.', description='Customer', is_customer=True, is_supplier=False)\nCompany.objects.create(name='Sippy Cup Emporium', description='Another su... | <|body_start_0|>
super().setUpTestData()
cls.acme = Company.objects.create(name='ACME', description='Supplier', is_customer=False, is_supplier=True)
Company.objects.create(name='Drippy Cup Co.', description='Customer', is_customer=True, is_supplier=False)
Company.objects.create(name='Sip... | Series of tests for the Company DRF API. | CompanyTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyTest:
"""Series of tests for the Company DRF API."""
def setUpTestData(cls):
"""Perform initialization for the unit test class"""
<|body_0|>
def test_company_list(self):
"""Test the list API endpoint for the Company model"""
<|body_1|>
def tes... | stack_v2_sparse_classes_36k_train_011863 | 19,439 | permissive | [
{
"docstring": "Perform initialization for the unit test class",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Test the list API endpoint for the Company model",
"name": "test_company_list",
"signature": "def test_company_list(self)"
},
{
"docs... | 5 | stack_v2_sparse_classes_30k_train_013950 | Implement the Python class `CompanyTest` described below.
Class description:
Series of tests for the Company DRF API.
Method signatures and docstrings:
- def setUpTestData(cls): Perform initialization for the unit test class
- def test_company_list(self): Test the list API endpoint for the Company model
- def test_co... | Implement the Python class `CompanyTest` described below.
Class description:
Series of tests for the Company DRF API.
Method signatures and docstrings:
- def setUpTestData(cls): Perform initialization for the unit test class
- def test_company_list(self): Test the list API endpoint for the Company model
- def test_co... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CompanyTest:
"""Series of tests for the Company DRF API."""
def setUpTestData(cls):
"""Perform initialization for the unit test class"""
<|body_0|>
def test_company_list(self):
"""Test the list API endpoint for the Company model"""
<|body_1|>
def tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompanyTest:
"""Series of tests for the Company DRF API."""
def setUpTestData(cls):
"""Perform initialization for the unit test class"""
super().setUpTestData()
cls.acme = Company.objects.create(name='ACME', description='Supplier', is_customer=False, is_supplier=True)
Comp... | the_stack_v2_python_sparse | InvenTree/company/test_api.py | inventree/InvenTree | train | 3,077 |
2170a6771d53b47cd8e37244b64a00f93f8f27b9 | [
"def filter(d, max):\n \"\"\" filters dataset by max_len \"\"\"\n return tf.math.less(d, max)\nself.batch_size = batch_size\ntrain = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\nself.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(train)\nself.data_train = train.map(sel... | <|body_start_0|>
def filter(d, max):
""" filters dataset by max_len """
return tf.math.less(d, max)
self.batch_size = batch_size
train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.tokenizer_pt, self.tokenizer_en = self.tokeniz... | loads and preps a dataset for machine translation | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self, batch_size, max_len):
"""batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_... | stack_v2_sparse_classes_36k_train_011864 | 5,014 | no_license | [
{
"docstring": "batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervided data_valid, which contains the ted_hrlr_translate/pt to_en tf.dat... | 4 | stack_v2_sparse_classes_30k_train_011441 | Implement the Python class `Dataset` described below.
Class description:
loads and preps a dataset for machine translation
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sente... | Implement the Python class `Dataset` described below.
Class description:
loads and preps a dataset for machine translation
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sente... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self, batch_size, max_len):
"""batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self, batch_size, max_len):
"""batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_to en tf.data... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/3-dataset.py | icculp/holbertonschool-machine_learning | train | 0 |
0b905f18bd6c9ac36f682a9760e97a3783ef74bc | [
"for i in range(self.numFilters):\n self.position['filters'][i] += 1\n if self.position['filters'][i] < self.numFilterOutputs[i]:\n if not seeking:\n self.centerImage()\n return\n self.position['filters'][i] = 0\nself.position['image'] += 1\nif self.position['image'] == self.numIma... | <|body_start_0|>
for i in range(self.numFilters):
self.position['filters'][i] += 1
if self.position['filters'][i] < self.numFilterOutputs[i]:
if not seeking:
self.centerImage()
return
self.position['filters'][i] = 0
... | This explorer flashes each filtered image without sweeping. It centers each image, but does not resize them. If an image is larger than the sensor's size, only the center portion of it will be visible. Use this explorer for flash inference or any other time you want your images to be shown in order with no sweeping. Th... | Flash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flash:
"""This explorer flashes each filtered image without sweeping. It centers each image, but does not resize them. If an image is larger than the sensor's size, only the center portion of it will be visible. Use this explorer for flash inference or any other time you want your images to be sh... | stack_v2_sparse_classes_36k_train_011865 | 3,570 | no_license | [
{
"docstring": "Go to the next position (next iteration). Args: seeking: Boolean that indicates whether the explorer is calling next() from seek(). If True, the explorer should avoid unnecessary computation that would not affect the seek command. The last call to next() from seek() will be with seeking=False.",... | 3 | stack_v2_sparse_classes_30k_train_020749 | Implement the Python class `Flash` described below.
Class description:
This explorer flashes each filtered image without sweeping. It centers each image, but does not resize them. If an image is larger than the sensor's size, only the center portion of it will be visible. Use this explorer for flash inference or any o... | Implement the Python class `Flash` described below.
Class description:
This explorer flashes each filtered image without sweeping. It centers each image, but does not resize them. If an image is larger than the sensor's size, only the center portion of it will be visible. Use this explorer for flash inference or any o... | 1b52c77c49a32c3cfa9ae0a469f79457e3c03d6d | <|skeleton|>
class Flash:
"""This explorer flashes each filtered image without sweeping. It centers each image, but does not resize them. If an image is larger than the sensor's size, only the center portion of it will be visible. Use this explorer for flash inference or any other time you want your images to be sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Flash:
"""This explorer flashes each filtered image without sweeping. It centers each image, but does not resize them. If an image is larger than the sensor's size, only the center portion of it will be visible. Use this explorer for flash inference or any other time you want your images to be shown in order ... | the_stack_v2_python_sparse | pyhtm/nodes/ImageSensorExplorers/Flash.py | vankhoakmt/pyHTM | train | 0 |
987960badf80458cb3cde7066c2171e61b49b579 | [
"b_values = self._encoding(max_log_scale, embedding_size, num_inputs)\na_values = torch.ones(b_values.shape[1])\nsuper().__init__(num_inputs, num_outputs, a_values, b_values, [num_channels] * num_layers)",
"embedding_size = embedding_size // num_inputs\nfrequencies_matrix = 2.0 ** torch.linspace(0, max_log_scale,... | <|body_start_0|>
b_values = self._encoding(max_log_scale, embedding_size, num_inputs)
a_values = torch.ones(b_values.shape[1])
super().__init__(num_inputs, num_outputs, a_values, b_values, [num_channels] * num_layers)
<|end_body_0|>
<|body_start_1|>
embedding_size = embedding_size // nu... | Version of FFN with positional encoding. | PositionalFMLP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalFMLP:
"""Version of FFN with positional encoding."""
def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int):... | stack_v2_sparse_classes_36k_train_011866 | 8,060 | permissive | [
{
"docstring": "Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of dimensions in the output max_log_scale (float): Maximum log scale for embedding num_layers (int, optional): Number of layers in the MLP. Defaults to 4. num_channels (int, optional): Number of chan... | 2 | stack_v2_sparse_classes_30k_train_002635 | Implement the Python class `PositionalFMLP` described below.
Class description:
Version of FFN with positional encoding.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): Constructor. Args: num_inputs (i... | Implement the Python class `PositionalFMLP` described below.
Class description:
Version of FFN with positional encoding.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): Constructor. Args: num_inputs (i... | 94a402cab47a2bd6241608308371490079af4d53 | <|skeleton|>
class PositionalFMLP:
"""Version of FFN with positional encoding."""
def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalFMLP:
"""Version of FFN with positional encoding."""
def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of di... | the_stack_v2_python_sparse | draugr/torch_utilities/architectures/mlp_variants/fourier.py | cnheider/draugr | train | 4 |
b314ba76d2652c98bad9c2506019c5095f6e603f | [
"try:\n cls.abrir_conexion()\n sql = 'SELECT idValor, fecha, valor FROM valoresTipArt WHERE idTipoArticulo = {};'.format(id)\n cls.cursor.execute(sql)\n valores = cls.cursor.fetchall()\n max_date = valores[0]\n for v in valores:\n if v[1] > max_date[1... | <|body_start_0|>
try:
cls.abrir_conexion()
sql = 'SELECT idValor, fecha, valor FROM valoresTipArt WHERE idTipoArticulo = {};'.format(id)
cls.cursor.execute(sql)
valores = cls.cursor.fetchall()
max_date = valores[... | DatosValor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatosValor:
def get_from_TAid(cls, id, noClose=False):
"""Obtiene el valor de un tipo articulo de la BD"""
<|body_0|>
def add(cls, idArt, fecha, valor):
"""Da de alta un nuevo valor de un articulo en el sistema."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_011867 | 1,869 | no_license | [
{
"docstring": "Obtiene el valor de un tipo articulo de la BD",
"name": "get_from_TAid",
"signature": "def get_from_TAid(cls, id, noClose=False)"
},
{
"docstring": "Da de alta un nuevo valor de un articulo en el sistema.",
"name": "add",
"signature": "def add(cls, idArt, fecha, valor)"
... | 2 | stack_v2_sparse_classes_30k_train_010677 | Implement the Python class `DatosValor` described below.
Class description:
Implement the DatosValor class.
Method signatures and docstrings:
- def get_from_TAid(cls, id, noClose=False): Obtiene el valor de un tipo articulo de la BD
- def add(cls, idArt, fecha, valor): Da de alta un nuevo valor de un articulo en el s... | Implement the Python class `DatosValor` described below.
Class description:
Implement the DatosValor class.
Method signatures and docstrings:
- def get_from_TAid(cls, id, noClose=False): Obtiene el valor de un tipo articulo de la BD
- def add(cls, idArt, fecha, valor): Da de alta un nuevo valor de un articulo en el s... | 57ca674dba4dabd2526c450ba7210933240f19c5 | <|skeleton|>
class DatosValor:
def get_from_TAid(cls, id, noClose=False):
"""Obtiene el valor de un tipo articulo de la BD"""
<|body_0|>
def add(cls, idArt, fecha, valor):
"""Da de alta un nuevo valor de un articulo en el sistema."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatosValor:
def get_from_TAid(cls, id, noClose=False):
"""Obtiene el valor de un tipo articulo de la BD"""
try:
cls.abrir_conexion()
sql = 'SELECT idValor, fecha, valor FROM valoresTipArt WHERE idTipoArticulo = {};'.format(id)
... | the_stack_v2_python_sparse | data/data_valor.py | JoaquinCardonaRuiz/proyecto-final | train | 0 | |
3c4b114a9c3eed4783d30677fe874c8ddcefa2dc | [
"super().__init__(in_features, out_features, bias=bias)\nweights = torch.full((out_features, in_features), sigma_init)\nself.sigma_weight = nn.Parameter(weights)\nepsilon_weight = torch.zeros(out_features, in_features)\nself.register_buffer('epsilon_weight', epsilon_weight)\nif bias:\n bias = torch.full((out_fea... | <|body_start_0|>
super().__init__(in_features, out_features, bias=bias)
weights = torch.full((out_features, in_features), sigma_init)
self.sigma_weight = nn.Parameter(weights)
epsilon_weight = torch.zeros(out_features, in_features)
self.register_buffer('epsilon_weight', epsilon_w... | Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19 | NoisyLinear | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisyLinear:
"""Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19"""
def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: ... | stack_v2_sparse_classes_36k_train_011868 | 15,112 | permissive | [
{
"docstring": "Args: in_features: number of inputs out_features: number of outputs sigma_init: initial fill value of noisy weights bias: flag to include bias to linear layer",
"name": "__init__",
"signature": "def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: bool=T... | 3 | stack_v2_sparse_classes_30k_train_001581 | Implement the Python class `NoisyLinear` described below.
Class description:
Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19
Method signatures and docstrings:
- def __init__(self, ... | Implement the Python class `NoisyLinear` described below.
Class description:
Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19
Method signatures and docstrings:
- def __init__(self, ... | bdf311369b236c1e3d0336c7ed4ba249854f8606 | <|skeleton|>
class NoisyLinear:
"""Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19"""
def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoisyLinear:
"""Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19"""
def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: bool=True) ->... | the_stack_v2_python_sparse | src/pl_bolts/models/rl/common/networks.py | Lightning-Universe/lightning-bolts | train | 76 |
5f88fc41f2c324b042f3e5cb856b695f0d0c8fa0 | [
"tf.logging.info('Creating MultiHeadDQNAgent with following parameters:')\ntf.logging.info('\\t num_heads: %d', num_heads)\ntf.logging.info('\\t transform_strategy: %s', transform_strategy)\ntf.logging.info('\\t num_convex_combinations: %d', num_convex_combinations)\ntf.logging.info('\\t init_checkpoint_dir: %s', i... | <|body_start_0|>
tf.logging.info('Creating MultiHeadDQNAgent with following parameters:')
tf.logging.info('\t num_heads: %d', num_heads)
tf.logging.info('\t transform_strategy: %s', transform_strategy)
tf.logging.info('\t num_convex_combinations: %d', num_convex_combinations)
tf.... | DQN agent with multiple heads. | MultiHeadDQNAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadDQNAgent:
"""DQN agent with multiple heads."""
def __init__(self, sess, num_actions, num_heads=1, transform_strategy='IDENTITY', num_convex_combinations=1, network=atari_helpers.MultiHeadQNetwork, init_checkpoint_dir=None, **kwargs):
"""Initializes the agent and constructs t... | stack_v2_sparse_classes_36k_train_011869 | 5,707 | permissive | [
{
"docstring": "Initializes the agent and constructs the components of its graph. Args: sess: tf.Session, for executing ops. num_actions: int, number of actions the agent can take at any state. num_heads: int, Number of heads per action output of the Q function. transform_strategy: str, Possible options include... | 4 | stack_v2_sparse_classes_30k_train_008631 | Implement the Python class `MultiHeadDQNAgent` described below.
Class description:
DQN agent with multiple heads.
Method signatures and docstrings:
- def __init__(self, sess, num_actions, num_heads=1, transform_strategy='IDENTITY', num_convex_combinations=1, network=atari_helpers.MultiHeadQNetwork, init_checkpoint_di... | Implement the Python class `MultiHeadDQNAgent` described below.
Class description:
DQN agent with multiple heads.
Method signatures and docstrings:
- def __init__(self, sess, num_actions, num_heads=1, transform_strategy='IDENTITY', num_convex_combinations=1, network=atari_helpers.MultiHeadQNetwork, init_checkpoint_di... | 6f7f4d55af077b7f27648d8b970cf1558c3e791d | <|skeleton|>
class MultiHeadDQNAgent:
"""DQN agent with multiple heads."""
def __init__(self, sess, num_actions, num_heads=1, transform_strategy='IDENTITY', num_convex_combinations=1, network=atari_helpers.MultiHeadQNetwork, init_checkpoint_dir=None, **kwargs):
"""Initializes the agent and constructs t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadDQNAgent:
"""DQN agent with multiple heads."""
def __init__(self, sess, num_actions, num_heads=1, transform_strategy='IDENTITY', num_convex_combinations=1, network=atari_helpers.MultiHeadQNetwork, init_checkpoint_dir=None, **kwargs):
"""Initializes the agent and constructs the components... | the_stack_v2_python_sparse | batch_rl/multi_head/multi_head_dqn_agent.py | google-research/batch_rl | train | 484 |
fa37ee50699fa1c3252ece866cf83a4f1bfdb65e | [
"wordDict = set(wordDict)\nstack = [s]\nseen = {s}\nwhile stack:\n word = stack.pop()\n if not word:\n return True\n for next_word in [word[len(e):] for e in wordDict if word.startswith(e)]:\n if next_word not in seen:\n seen.add(next_word)\n stack.append(next_word)\nret... | <|body_start_0|>
wordDict = set(wordDict)
stack = [s]
seen = {s}
while stack:
word = stack.pop()
if not word:
return True
for next_word in [word[len(e):] for e in wordDict if word.startswith(e)]:
if next_word not in seen... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreakDp(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_011870 | 1,039 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreakDp",
"signature": "def wordBreakDp(self, s, wordDict)"
}... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreakDp(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreakDp(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
<... | 1bba7aadabd5d234a9482a661da84a6829adfb77 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreakDp(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
wordDict = set(wordDict)
stack = [s]
seen = {s}
while stack:
word = stack.pop()
if not word:
return True
for next_wo... | the_stack_v2_python_sparse | 139_Word_Break.py | nickciaravella/leetcode | train | 0 | |
c66cc9fea42ad994167af756ee7e645120cd5635 | [
"__excel_path = os.path.basename(excel_path)\n__excel_path_list = os.listdir(os.path.dirname(excel_path))\n__has_excel = False\nfor i in __excel_path_list:\n if __excel_path in i:\n __has_excel = True\n self.workbook = xlrd.open_workbook(os.path.join(os.path.dirname(excel_path), i))\n self.e... | <|body_start_0|>
__excel_path = os.path.basename(excel_path)
__excel_path_list = os.listdir(os.path.dirname(excel_path))
__has_excel = False
for i in __excel_path_list:
if __excel_path in i:
__has_excel = True
self.workbook = xlrd.open_workbook... | 读取支持xlsx,xls。写入更新支持xls | ExcelUntil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelUntil:
"""读取支持xlsx,xls。写入更新支持xls"""
def __init__(self, excel_path):
"""传入地址规则,不输入绝对路径,默认相对路径查找 传入文件名尽量加上后缀 传入不存在的文件名,则新建excel xlwt.Workbook.Workbook,xlrd.book.Book :param excel_path: :return:"""
<|body_0|>
def _checkout_sheet(self, sheetIndex, sheetName):
""... | stack_v2_sparse_classes_36k_train_011871 | 7,637 | no_license | [
{
"docstring": "传入地址规则,不输入绝对路径,默认相对路径查找 传入文件名尽量加上后缀 传入不存在的文件名,则新建excel xlwt.Workbook.Workbook,xlrd.book.Book :param excel_path: :return:",
"name": "__init__",
"signature": "def __init__(self, excel_path)"
},
{
"docstring": "默认是第一个sheet,内部方法,获取sheet用 读取专用切换",
"name": "_checkout_sheet",
"s... | 6 | stack_v2_sparse_classes_30k_test_000149 | Implement the Python class `ExcelUntil` described below.
Class description:
读取支持xlsx,xls。写入更新支持xls
Method signatures and docstrings:
- def __init__(self, excel_path): 传入地址规则,不输入绝对路径,默认相对路径查找 传入文件名尽量加上后缀 传入不存在的文件名,则新建excel xlwt.Workbook.Workbook,xlrd.book.Book :param excel_path: :return:
- def _checkout_sheet(self, sh... | Implement the Python class `ExcelUntil` described below.
Class description:
读取支持xlsx,xls。写入更新支持xls
Method signatures and docstrings:
- def __init__(self, excel_path): 传入地址规则,不输入绝对路径,默认相对路径查找 传入文件名尽量加上后缀 传入不存在的文件名,则新建excel xlwt.Workbook.Workbook,xlrd.book.Book :param excel_path: :return:
- def _checkout_sheet(self, sh... | a4e4f92fef4d02ddca055785b297fa191c940c08 | <|skeleton|>
class ExcelUntil:
"""读取支持xlsx,xls。写入更新支持xls"""
def __init__(self, excel_path):
"""传入地址规则,不输入绝对路径,默认相对路径查找 传入文件名尽量加上后缀 传入不存在的文件名,则新建excel xlwt.Workbook.Workbook,xlrd.book.Book :param excel_path: :return:"""
<|body_0|>
def _checkout_sheet(self, sheetIndex, sheetName):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcelUntil:
"""读取支持xlsx,xls。写入更新支持xls"""
def __init__(self, excel_path):
"""传入地址规则,不输入绝对路径,默认相对路径查找 传入文件名尽量加上后缀 传入不存在的文件名,则新建excel xlwt.Workbook.Workbook,xlrd.book.Book :param excel_path: :return:"""
__excel_path = os.path.basename(excel_path)
__excel_path_list = os.listdir(os.pat... | the_stack_v2_python_sparse | all_until_script/Excel.py | dangfuli/all_pro | train | 0 |
ae40776e845a584d88cee80180cb80d6cba9f4ce | [
"settings = self.settings\nignore = settings.get('ignore', '').strip()\ncmd = [config['exe_paths']['pycodestyle'], '--max-line-length=%s' % settings['max_line_length'], '--format=%(code)s:%(row)d:%(col)d:%(text)s']\nif ignore:\n cmd.append('--ignore=%s' % ignore)\nreturn cmd",
"output = execute(base_command + ... | <|body_start_0|>
settings = self.settings
ignore = settings.get('ignore', '').strip()
cmd = [config['exe_paths']['pycodestyle'], '--max-line-length=%s' % settings['max_line_length'], '--format=%(code)s:%(row)d:%(col)d:%(text)s']
if ignore:
cmd.append('--ignore=%s' % ignore)
... | Review Bot tool to run pycodestyle. | PycodestyleTool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PycodestyleTool:
"""Review Bot tool to run pycodestyle."""
def build_base_command(self, **kwargs):
"""Build the base command line used to review files. Args: **kwargs (dict, unused): Additional keyword arguments. Returns: list of unicode: The base command line."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_011872 | 3,322 | permissive | [
{
"docstring": "Build the base command line used to review files. Args: **kwargs (dict, unused): Additional keyword arguments. Returns: list of unicode: The base command line.",
"name": "build_base_command",
"signature": "def build_base_command(self, **kwargs)"
},
{
"docstring": "Perform a revie... | 2 | null | Implement the Python class `PycodestyleTool` described below.
Class description:
Review Bot tool to run pycodestyle.
Method signatures and docstrings:
- def build_base_command(self, **kwargs): Build the base command line used to review files. Args: **kwargs (dict, unused): Additional keyword arguments. Returns: list ... | Implement the Python class `PycodestyleTool` described below.
Class description:
Review Bot tool to run pycodestyle.
Method signatures and docstrings:
- def build_base_command(self, **kwargs): Build the base command line used to review files. Args: **kwargs (dict, unused): Additional keyword arguments. Returns: list ... | b59b566e127b5ef1b08f3189f1aa0194b7437d94 | <|skeleton|>
class PycodestyleTool:
"""Review Bot tool to run pycodestyle."""
def build_base_command(self, **kwargs):
"""Build the base command line used to review files. Args: **kwargs (dict, unused): Additional keyword arguments. Returns: list of unicode: The base command line."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PycodestyleTool:
"""Review Bot tool to run pycodestyle."""
def build_base_command(self, **kwargs):
"""Build the base command line used to review files. Args: **kwargs (dict, unused): Additional keyword arguments. Returns: list of unicode: The base command line."""
settings = self.settings... | the_stack_v2_python_sparse | bot/reviewbot/tools/pycodestyle.py | reviewboard/ReviewBot | train | 110 |
35c2c329f9664f6092506b419c767a8ce6da89ad | [
"self.dev = dev\nself.metadata = metadata\nself.fs_type = get_filesystem_type(fs_stream)\nif self.fs_type == 'FAT':\n self.metadata.set_module('fat-cluster-allocator')\n self.fs = FATAllocator(fs_stream)\nelif self.fs_type == 'NTFS':\n self.metadata.set_module('ntfs-cluster-allocator')\n self.fs = NTFSA... | <|body_start_0|>
self.dev = dev
self.metadata = metadata
self.fs_type = get_filesystem_type(fs_stream)
if self.fs_type == 'FAT':
self.metadata.set_module('fat-cluster-allocator')
self.fs = FATAllocator(fs_stream)
elif self.fs_type == 'NTFS':
se... | This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = ClusterAllocation(f) >>> m = Metadata("FileSlack") >>> filename = 'path/to/file/on/fs' to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m, filename) to read... | ClusterAllocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterAllocation:
"""This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = ClusterAllocation(f) >>> m = Metadata("FileSlack") >>> filename = 'path/to/file/on/fs' to write something from stdin into slack: >>> fs... | stack_v2_sparse_classes_36k_train_011873 | 5,289 | permissive | [
{
"docstring": ":param fs_stream: Stream of filesystem :param metadata: Metadata object",
"name": "__init__",
"signature": "def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None)"
},
{
"docstring": "writes data from instream into additional allocated clusters of given fil... | 5 | stack_v2_sparse_classes_30k_train_010042 | Implement the Python class `ClusterAllocation` described below.
Class description:
This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = ClusterAllocation(f) >>> m = Metadata("FileSlack") >>> filename = 'path/to/file/on/fs' to write ... | Implement the Python class `ClusterAllocation` described below.
Class description:
This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = ClusterAllocation(f) >>> m = Metadata("FileSlack") >>> filename = 'path/to/file/on/fs' to write ... | b602e90ddecb8e469a28e092da3ca7fec514e3dc | <|skeleton|>
class ClusterAllocation:
"""This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = ClusterAllocation(f) >>> m = Metadata("FileSlack") >>> filename = 'path/to/file/on/fs' to write something from stdin into slack: >>> fs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterAllocation:
"""This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = ClusterAllocation(f) >>> m = Metadata("FileSlack") >>> filename = 'path/to/file/on/fs' to write something from stdin into slack: >>> fs.write(sys.st... | the_stack_v2_python_sparse | src/wrapper/cluster_allocation.py | VanirLab/weever | train | 3 |
2eb0c0e123dd47ece3e80d85d120740c1320289d | [
"app = ReadGroupGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('read_group_genomic_file', kf_id))\nreturn ReadGroupGenomicFileSchema().jsonify(app)",
"app = ReadGroupGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('read_g... | <|body_start_0|>
app = ReadGroupGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.format('read_group_genomic_file', kf_id))
return ReadGroupGenomicFileSchema().jsonify(app)
<|end_body_0|>
<|body_start_1|>
app = ReadGroupGenomicFile.query.get(kf... | ReadGroupGenomicFile API | ReadGroupGenomicFileAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadGroupGenomicFileAPI:
"""ReadGroupGenomicFile API"""
def get(self, kf_id):
"""Get a read_group_genomic_file by id --- template: path: get_by_id.yml properties: resource: ReadGroupGenomicFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing read_grou... | stack_v2_sparse_classes_36k_train_011874 | 5,383 | permissive | [
{
"docstring": "Get a read_group_genomic_file by id --- template: path: get_by_id.yml properties: resource: ReadGroupGenomicFile",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing read_group_genomic_file. Allows partial update --- template: path: update_by... | 3 | null | Implement the Python class `ReadGroupGenomicFileAPI` described below.
Class description:
ReadGroupGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a read_group_genomic_file by id --- template: path: get_by_id.yml properties: resource: ReadGroupGenomicFile
- def patch(self, kf_id): Update ... | Implement the Python class `ReadGroupGenomicFileAPI` described below.
Class description:
ReadGroupGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a read_group_genomic_file by id --- template: path: get_by_id.yml properties: resource: ReadGroupGenomicFile
- def patch(self, kf_id): Update ... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class ReadGroupGenomicFileAPI:
"""ReadGroupGenomicFile API"""
def get(self, kf_id):
"""Get a read_group_genomic_file by id --- template: path: get_by_id.yml properties: resource: ReadGroupGenomicFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing read_grou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReadGroupGenomicFileAPI:
"""ReadGroupGenomicFile API"""
def get(self, kf_id):
"""Get a read_group_genomic_file by id --- template: path: get_by_id.yml properties: resource: ReadGroupGenomicFile"""
app = ReadGroupGenomicFile.query.get(kf_id)
if app is None:
abort(404, '... | the_stack_v2_python_sparse | dataservice/api/read_group_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
d73b6f6562be46bd81d441c08eb73cbe2720ea9f | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = EdgeLoadStatisticsResourceEventData()\nevent_data.last_update = self._GetWebKitDateTimeRowValue(query_hash, r... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = EdgeLoadStatisticsResourc... | SQLite parser plugin for Microsoft Edge load statistics database. | EdgeLoadStatisticsPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeLoadStatisticsPlugin:
"""SQLite parser plugin for Microsoft Edge load statistics database."""
def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identi... | stack_v2_sparse_classes_36k_train_011875 | 4,267 | permissive | [
{
"docstring": "Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.WebKitTime: date and time value or None if not available.",
... | 2 | stack_v2_sparse_classes_30k_train_009984 | Implement the Python class `EdgeLoadStatisticsPlugin` described below.
Class description:
SQLite parser plugin for Microsoft Edge load statistics database.
Method signatures and docstrings:
- def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name): Retrieves a WebKit date and time value from the row. Args: ... | Implement the Python class `EdgeLoadStatisticsPlugin` described below.
Class description:
SQLite parser plugin for Microsoft Edge load statistics database.
Method signatures and docstrings:
- def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name): Retrieves a WebKit date and time value from the row. Args: ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class EdgeLoadStatisticsPlugin:
"""SQLite parser plugin for Microsoft Edge load statistics database."""
def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeLoadStatisticsPlugin:
"""SQLite parser plugin for Microsoft Edge load statistics database."""
def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the quer... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/edge_load_statistics.py | log2timeline/plaso | train | 1,506 |
de8847e42af40839fc7bf4d0c550d4a922c508f3 | [
"if action.actor == self.tracked:\n return True\nif not self.actor_only and (self.tracked in action.targets.all() or self.tracked in action.related.all()):\n return True\nreturn False",
"if not TRACK_UNREAD:\n return set()\ntrackers = Tracker.objects.exclude(pk=self.pk).filter(user=self.user, last_update... | <|body_start_0|>
if action.actor == self.tracked:
return True
if not self.actor_only and (self.tracked in action.targets.all() or self.tracked in action.related.all()):
return True
return False
<|end_body_0|>
<|body_start_1|>
if not TRACK_UNREAD:
retu... | A base class for Tracker and TempTracker | TrackerBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrackerBase:
"""A base class for Tracker and TempTracker"""
def matches(self, action):
"""Returns true if an action is to be tracked by the Tracker object"""
<|body_0|>
def update_unread(self, already_fetched=()):
"""Retrieves the actions having occurred after th... | stack_v2_sparse_classes_36k_train_011876 | 12,849 | permissive | [
{
"docstring": "Returns true if an action is to be tracked by the Tracker object",
"name": "matches",
"signature": "def matches(self, action)"
},
{
"docstring": "Retrieves the actions having occurred after the last time the tracker was updated and mark them as unread (bulk-add to unread_actions)... | 2 | stack_v2_sparse_classes_30k_val_001135 | Implement the Python class `TrackerBase` described below.
Class description:
A base class for Tracker and TempTracker
Method signatures and docstrings:
- def matches(self, action): Returns true if an action is to be tracked by the Tracker object
- def update_unread(self, already_fetched=()): Retrieves the actions hav... | Implement the Python class `TrackerBase` described below.
Class description:
A base class for Tracker and TempTracker
Method signatures and docstrings:
- def matches(self, action): Returns true if an action is to be tracked by the Tracker object
- def update_unread(self, already_fetched=()): Retrieves the actions hav... | 014a6662b2d01673f17f8b8cb828570ad828650c | <|skeleton|>
class TrackerBase:
"""A base class for Tracker and TempTracker"""
def matches(self, action):
"""Returns true if an action is to be tracked by the Tracker object"""
<|body_0|>
def update_unread(self, already_fetched=()):
"""Retrieves the actions having occurred after th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrackerBase:
"""A base class for Tracker and TempTracker"""
def matches(self, action):
"""Returns true if an action is to be tracked by the Tracker object"""
if action.actor == self.tracked:
return True
if not self.actor_only and (self.tracked in action.targets.all() o... | the_stack_v2_python_sparse | actrack/models.py | tkhyn/django-actrack | train | 1 |
d91d1e36ee3b2c22c161d7bb3959f9907c07d2ff | [
"digits = [int(i) for i in str(n)]\nlength = len(digits)\nif length == 1:\n return -1\nfor i in range(length - 1, -1, -1):\n if i > 0 and digits[i] <= digits[i - 1]:\n continue\n break\nif i == 0:\n return -1\nj = length - 1\nwhile j > i:\n if digits[i - 1] >= digits[j]:\n j -= 1\n ... | <|body_start_0|>
digits = [int(i) for i in str(n)]
length = len(digits)
if length == 1:
return -1
for i in range(length - 1, -1, -1):
if i > 0 and digits[i] <= digits[i - 1]:
continue
break
if i == 0:
return -1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement_(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
digits = [int(i) for i in str(n)]
length = len... | stack_v2_sparse_classes_36k_train_011877 | 2,113 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement_",
"signature": "def nextGreaterElement_(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement_(self, n): :type n: int :rtype: int
- def nextGreaterElement(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement_(self, n): :type n: int :rtype: int
- def nextGreaterElement(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def nextGreaterElement_(... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class Solution:
def nextGreaterElement_(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElement_(self, n):
""":type n: int :rtype: int"""
digits = [int(i) for i in str(n)]
length = len(digits)
if length == 1:
return -1
for i in range(length - 1, -1, -1):
if i > 0 and digits[i] <= digits[i - 1]:
... | the_stack_v2_python_sparse | problems/N556_Next_Greater_Element_III.py | wan-catherine/Leetcode | train | 5 | |
714b519b3a3fdd456aaaddfedb503a50d8a175ef | [
"super().__init__(name, priority, **options)\nfilters = options.get('filters')\nfilter_map = options.get('filter_map')\nif filters is not None and (not isinstance(filters, list)):\n raise FiltersMustBeListError('The provided value for \"filters\" must be a list.')\nif filter_map is not None and (not isinstance(f... | <|body_start_0|>
super().__init__(name, priority, **options)
filters = options.get('filters')
filter_map = options.get('filter_map')
if filters is not None and (not isinstance(filters, list)):
raise FiltersMustBeListError('The provided value for "filters" must be a list.')
... | filter normalizer base class. this normalizer will filter provided values from string. | FilterNormalizerBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterNormalizerBase:
"""filter normalizer base class. this normalizer will filter provided values from string."""
def __init__(self, name, priority, **options):
"""initializes an instance of FilterNormalizerBase. :param str name: name of this normalizer. the normalizer will be regis... | stack_v2_sparse_classes_36k_train_011878 | 10,275 | permissive | [
{
"docstring": "initializes an instance of FilterNormalizerBase. :param str name: name of this normalizer. the normalizer will be registered by this name into available normalizers. it must be unique. :param int priority: priority of this normalizer. normalizers with higher priority will be executed sooner. :ke... | 4 | null | Implement the Python class `FilterNormalizerBase` described below.
Class description:
filter normalizer base class. this normalizer will filter provided values from string.
Method signatures and docstrings:
- def __init__(self, name, priority, **options): initializes an instance of FilterNormalizerBase. :param str na... | Implement the Python class `FilterNormalizerBase` described below.
Class description:
filter normalizer base class. this normalizer will filter provided values from string.
Method signatures and docstrings:
- def __init__(self, name, priority, **options): initializes an instance of FilterNormalizerBase. :param str na... | 9d4776498225de4f3d16a4600b5b19212abe8562 | <|skeleton|>
class FilterNormalizerBase:
"""filter normalizer base class. this normalizer will filter provided values from string."""
def __init__(self, name, priority, **options):
"""initializes an instance of FilterNormalizerBase. :param str name: name of this normalizer. the normalizer will be regis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterNormalizerBase:
"""filter normalizer base class. this normalizer will filter provided values from string."""
def __init__(self, name, priority, **options):
"""initializes an instance of FilterNormalizerBase. :param str name: name of this normalizer. the normalizer will be registered by this... | the_stack_v2_python_sparse | src/pyrin/utilities/string/normalizer/handlers/base.py | mononobi/pyrin | train | 20 |
6f675dfb5ced443a341560bdc8f4ed5b7552a312 | [
"super().__init__(*args, **kwargs)\nif self.instance.name:\n self.old_name = self.instance.name",
"form_data = super().clean()\nname = form_data.get('name')\nif not name:\n self.add_error('name', _('Name cannot be empty'))\n return form_data\nmsg = is_legal_name(form_data['name'])\nif msg:\n self.add_... | <|body_start_0|>
super().__init__(*args, **kwargs)
if self.instance.name:
self.old_name = self.instance.name
<|end_body_0|>
<|body_start_1|>
form_data = super().clean()
name = form_data.get('name')
if not name:
self.add_error('name', _('Name cannot be emp... | Form to read information about a condition. The same as the filter but we need to enforce that the name is a valid variable name | ConditionForm | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionForm:
"""Form to read information about a condition. The same as the filter but we need to enforce that the name is a valid variable name"""
def __init__(self, *args, **kwargs):
"""Remember the old name."""
<|body_0|>
def clean(self) -> Dict:
"""Check th... | stack_v2_sparse_classes_36k_train_011879 | 2,892 | permissive | [
{
"docstring": "Remember the old name.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check that data is not empty.",
"name": "clean",
"signature": "def clean(self) -> Dict"
}
] | 2 | stack_v2_sparse_classes_30k_train_016218 | Implement the Python class `ConditionForm` described below.
Class description:
Form to read information about a condition. The same as the filter but we need to enforce that the name is a valid variable name
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Remember the old name.
- def clean(se... | Implement the Python class `ConditionForm` described below.
Class description:
Form to read information about a condition. The same as the filter but we need to enforce that the name is a valid variable name
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Remember the old name.
- def clean(se... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class ConditionForm:
"""Form to read information about a condition. The same as the filter but we need to enforce that the name is a valid variable name"""
def __init__(self, *args, **kwargs):
"""Remember the old name."""
<|body_0|>
def clean(self) -> Dict:
"""Check th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionForm:
"""Form to read information about a condition. The same as the filter but we need to enforce that the name is a valid variable name"""
def __init__(self, *args, **kwargs):
"""Remember the old name."""
super().__init__(*args, **kwargs)
if self.instance.name:
... | the_stack_v2_python_sparse | ontask/condition/forms.py | abelardopardo/ontask_b | train | 43 |
1e2a4dbdff0c82b9a1e493ed65edabebe4986e4e | [
"if self.parent_:\n return Issue(self.parent_)\nreturn None",
"if self.subtasks_:\n return list(map(Issue, self.subtasks_))\nreturn None"
] | <|body_start_0|>
if self.parent_:
return Issue(self.parent_)
return None
<|end_body_0|>
<|body_start_1|>
if self.subtasks_:
return list(map(Issue, self.subtasks_))
return None
<|end_body_1|>
| Fields model for issue | Fields | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fields:
"""Fields model for issue"""
def parent(self):
"""Getter for parent issue"""
<|body_0|>
def subtasks(self):
"""Getter for subtasks"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.parent_:
return Issue(self.parent_)
... | stack_v2_sparse_classes_36k_train_011880 | 2,365 | no_license | [
{
"docstring": "Getter for parent issue",
"name": "parent",
"signature": "def parent(self)"
},
{
"docstring": "Getter for subtasks",
"name": "subtasks",
"signature": "def subtasks(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013620 | Implement the Python class `Fields` described below.
Class description:
Fields model for issue
Method signatures and docstrings:
- def parent(self): Getter for parent issue
- def subtasks(self): Getter for subtasks | Implement the Python class `Fields` described below.
Class description:
Fields model for issue
Method signatures and docstrings:
- def parent(self): Getter for parent issue
- def subtasks(self): Getter for subtasks
<|skeleton|>
class Fields:
"""Fields model for issue"""
def parent(self):
"""Getter f... | 7ca3ee6bc296aa897e8b04377950247408f83c16 | <|skeleton|>
class Fields:
"""Fields model for issue"""
def parent(self):
"""Getter for parent issue"""
<|body_0|>
def subtasks(self):
"""Getter for subtasks"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fields:
"""Fields model for issue"""
def parent(self):
"""Getter for parent issue"""
if self.parent_:
return Issue(self.parent_)
return None
def subtasks(self):
"""Getter for subtasks"""
if self.subtasks_:
return list(map(Issue, self.su... | the_stack_v2_python_sparse | atlassian_cli/atlassian/jira/models/issue.py | marksinkovics/atlassian-cli | train | 0 |
69d4aa993ddc8614d5719687aabb28f9fec24fd6 | [
"super().__init__(message)\nself.message = message\nself.context = context",
"message_repr = repr(self.message)\ncontext_repr = repr(self.context)\nreturn f'{self.__class__.__name__}({message_repr}, context={context_repr})'"
] | <|body_start_0|>
super().__init__(message)
self.message = message
self.context = context
<|end_body_0|>
<|body_start_1|>
message_repr = repr(self.message)
context_repr = repr(self.context)
return f'{self.__class__.__name__}({message_repr}, context={context_repr})'
<|end_... | A class representing a base attribute error. | BaseAttributeError | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseAttributeError:
"""A class representing a base attribute error."""
def __init__(self, message: str, context: Any):
"""Initialize the error. Args: message: a message context: a context in which the error occurred"""
<|body_0|>
def __repr__(self) -> str:
"""Is ... | stack_v2_sparse_classes_36k_train_011881 | 2,667 | no_license | [
{
"docstring": "Initialize the error. Args: message: a message context: a context in which the error occurred",
"name": "__init__",
"signature": "def __init__(self, message: str, context: Any)"
},
{
"docstring": "Is called by the `repr()` built-in function to compute the \"official\" string repr... | 2 | null | Implement the Python class `BaseAttributeError` described below.
Class description:
A class representing a base attribute error.
Method signatures and docstrings:
- def __init__(self, message: str, context: Any): Initialize the error. Args: message: a message context: a context in which the error occurred
- def __rep... | Implement the Python class `BaseAttributeError` described below.
Class description:
A class representing a base attribute error.
Method signatures and docstrings:
- def __init__(self, message: str, context: Any): Initialize the error. Args: message: a message context: a context in which the error occurred
- def __rep... | 3da2161c3c9e0652c2cfc78ab514359bcf2e436b | <|skeleton|>
class BaseAttributeError:
"""A class representing a base attribute error."""
def __init__(self, message: str, context: Any):
"""Initialize the error. Args: message: a message context: a context in which the error occurred"""
<|body_0|>
def __repr__(self) -> str:
"""Is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseAttributeError:
"""A class representing a base attribute error."""
def __init__(self, message: str, context: Any):
"""Initialize the error. Args: message: a message context: a context in which the error occurred"""
super().__init__(message)
self.message = message
self.... | the_stack_v2_python_sparse | ywh2bt/core/configuration/error.py | yeswehack/ywh2bugtracker | train | 10 |
178287d23c96c09c9a2d4c68d6f4547ab7cadaee | [
"magnitudes, edges = np.histogram(data, bins)\nbin_width = edges[1] - edges[0]\nbin_sizes = magnitudes.astype(np.float) / (magnitudes.sum() * resolution)\nvalid_indices = np.where(bin_sizes >= 1)[0]\nif valid_indices.size == 0:\n raise ValueError('Resolution is too low. Cumulative distribution array is empty.')\... | <|body_start_0|>
magnitudes, edges = np.histogram(data, bins)
bin_width = edges[1] - edges[0]
bin_sizes = magnitudes.astype(np.float) / (magnitudes.sum() * resolution)
valid_indices = np.where(bin_sizes >= 1)[0]
if valid_indices.size == 0:
raise ValueError('Resolution... | Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution. This sampler trades space for time by appro... | HistogramSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistogramSampler:
"""Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution.... | stack_v2_sparse_classes_36k_train_011882 | 5,295 | permissive | [
{
"docstring": "Construct a new sampler object. :param data: Observations for a single random variable. :type data: 1D ndarray :param bins: Number of bins to use when generating the histogram. :type bins: positive int :param resolution: Resolution of each element of the cum-dist array. For example, a resolution... | 2 | stack_v2_sparse_classes_30k_train_001475 | Implement the Python class `HistogramSampler` described below.
Class description:
Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new v... | Implement the Python class `HistogramSampler` described below.
Class description:
Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new v... | 8b98390850351385acfda5be3088cd4db4cc4a09 | <|skeleton|>
class HistogramSampler:
"""Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HistogramSampler:
"""Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution. This sampler... | the_stack_v2_python_sparse | glimpse/util/grandom.py | mthomure/glimpse-project | train | 1 |
16f9664f34326755cc256a0606a3f32728fae5f3 | [
"if not tf.executing_eagerly():\n self.skipTest('Skipping test due to NUFFT segfault.')\nimage_shape = [256, 256]\nimage = image_ops.phantom(shape=image_shape)\nimage = tf.expand_dims(image, -1)\nlayer = preproc_layers.KSpaceResampling(image_shape=image_shape, traj_type='radial', views=403, angle_range='half', d... | <|body_start_0|>
if not tf.executing_eagerly():
self.skipTest('Skipping test due to NUFFT segfault.')
image_shape = [256, 256]
image = image_ops.phantom(shape=image_shape)
image = tf.expand_dims(image, -1)
layer = preproc_layers.KSpaceResampling(image_shape=image_shap... | Tests for layer `KSpaceResampling`. | KSpaceResamplingTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KSpaceResamplingTest:
"""Tests for layer `KSpaceResampling`."""
def test_radial_2d(self, dens_algo):
"""Test radial 2D configuration."""
<|body_0|>
def test_radial_2d_impulse(self, dens_algo):
"""Test radial 2D with impulse function."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_011883 | 6,474 | permissive | [
{
"docstring": "Test radial 2D configuration.",
"name": "test_radial_2d",
"signature": "def test_radial_2d(self, dens_algo)"
},
{
"docstring": "Test radial 2D with impulse function.",
"name": "test_radial_2d_impulse",
"signature": "def test_radial_2d_impulse(self, dens_algo)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001833 | Implement the Python class `KSpaceResamplingTest` described below.
Class description:
Tests for layer `KSpaceResampling`.
Method signatures and docstrings:
- def test_radial_2d(self, dens_algo): Test radial 2D configuration.
- def test_radial_2d_impulse(self, dens_algo): Test radial 2D with impulse function. | Implement the Python class `KSpaceResamplingTest` described below.
Class description:
Tests for layer `KSpaceResampling`.
Method signatures and docstrings:
- def test_radial_2d(self, dens_algo): Test radial 2D configuration.
- def test_radial_2d_impulse(self, dens_algo): Test radial 2D with impulse function.
<|skele... | cfd8930ee5281e7f6dceb17c4a5acaf625fd3243 | <|skeleton|>
class KSpaceResamplingTest:
"""Tests for layer `KSpaceResampling`."""
def test_radial_2d(self, dens_algo):
"""Test radial 2D configuration."""
<|body_0|>
def test_radial_2d_impulse(self, dens_algo):
"""Test radial 2D with impulse function."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KSpaceResamplingTest:
"""Tests for layer `KSpaceResampling`."""
def test_radial_2d(self, dens_algo):
"""Test radial 2D configuration."""
if not tf.executing_eagerly():
self.skipTest('Skipping test due to NUFFT segfault.')
image_shape = [256, 256]
image = image_... | the_stack_v2_python_sparse | tensorflow_mri/python/layers/preproc_layers_test.py | mrphys/tensorflow-mri | train | 29 |
3b8c14b1c911048b737599c27dc773218fc4b61a | [
"super(EncoderCNN, self).__init__()\nresnet = models.resnet50(pretrained=True)\nmodules = list(resnet.children())[:-1]\nself.resnet = nn.Sequential(*modules)\nself.embed = nn.Linear(resnet.fc.in_features, embed_size)\nself.bn = nn.BatchNorm1d(embed_size, momentum=0.01)",
"with torch.no_grad():\n features = sel... | <|body_start_0|>
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.embed = nn.Linear(resnet.fc.in_features, embed_size)
self.bn = nn.BatchNorm1d(embed_size, moment... | EncoderCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderCNN:
def __init__(self, embed_size):
"""Load the pretrained ResNet-50 and replace top fc layer."""
<|body_0|>
def forward(self, images):
"""Extract feature vectors from input images."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Encod... | stack_v2_sparse_classes_36k_train_011884 | 4,303 | permissive | [
{
"docstring": "Load the pretrained ResNet-50 and replace top fc layer.",
"name": "__init__",
"signature": "def __init__(self, embed_size)"
},
{
"docstring": "Extract feature vectors from input images.",
"name": "forward",
"signature": "def forward(self, images)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011469 | Implement the Python class `EncoderCNN` described below.
Class description:
Implement the EncoderCNN class.
Method signatures and docstrings:
- def __init__(self, embed_size): Load the pretrained ResNet-50 and replace top fc layer.
- def forward(self, images): Extract feature vectors from input images. | Implement the Python class `EncoderCNN` described below.
Class description:
Implement the EncoderCNN class.
Method signatures and docstrings:
- def __init__(self, embed_size): Load the pretrained ResNet-50 and replace top fc layer.
- def forward(self, images): Extract feature vectors from input images.
<|skeleton|>
... | 2b558076dd7467acc2bcaf4c7480d48b129688a3 | <|skeleton|>
class EncoderCNN:
def __init__(self, embed_size):
"""Load the pretrained ResNet-50 and replace top fc layer."""
<|body_0|>
def forward(self, images):
"""Extract feature vectors from input images."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderCNN:
def __init__(self, embed_size):
"""Load the pretrained ResNet-50 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
se... | the_stack_v2_python_sparse | NIC/image_captioning/model.py | jomycs/Book-KnowledgeGraph-Recommendation | train | 1 | |
3a18ca32dc96b1ea69f3709aed799ba66060d60e | [
"self.itineraries = {}\nself.final_itenary = []\nfor itinerary in tickets:\n if not itinerary[0] in self.itineraries.keys():\n self.itineraries[itinerary[0]] = Q.PriorityQueue()\n self.itineraries.get(itinerary[0]).put(itinerary[1])\nself.travel('JFK')\nreturn self.final_itenary",
"pqueue = self.itin... | <|body_start_0|>
self.itineraries = {}
self.final_itenary = []
for itinerary in tickets:
if not itinerary[0] in self.itineraries.keys():
self.itineraries[itinerary[0]] = Q.PriorityQueue()
self.itineraries.get(itinerary[0]).put(itinerary[1])
self.tr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findItinerary(self, tickets):
""":type tickets: List[List[str]] :rtype: List[str]"""
<|body_0|>
def travel(self, root):
"""Takes the first destination and travels by retrieving the root of the heap. :param root:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_011885 | 1,297 | no_license | [
{
"docstring": ":type tickets: List[List[str]] :rtype: List[str]",
"name": "findItinerary",
"signature": "def findItinerary(self, tickets)"
},
{
"docstring": "Takes the first destination and travels by retrieving the root of the heap. :param root:",
"name": "travel",
"signature": "def tr... | 2 | stack_v2_sparse_classes_30k_train_009311 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findItinerary(self, tickets): :type tickets: List[List[str]] :rtype: List[str]
- def travel(self, root): Takes the first destination and travels by retrieving the root of the... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findItinerary(self, tickets): :type tickets: List[List[str]] :rtype: List[str]
- def travel(self, root): Takes the first destination and travels by retrieving the root of the... | 6c32a295f5e2b8c1959f73fad006273204734481 | <|skeleton|>
class Solution:
def findItinerary(self, tickets):
""":type tickets: List[List[str]] :rtype: List[str]"""
<|body_0|>
def travel(self, root):
"""Takes the first destination and travels by retrieving the root of the heap. :param root:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findItinerary(self, tickets):
""":type tickets: List[List[str]] :rtype: List[str]"""
self.itineraries = {}
self.final_itenary = []
for itinerary in tickets:
if not itinerary[0] in self.itineraries.keys():
self.itineraries[itinerary[0]] ... | the_stack_v2_python_sparse | Graph_Itenary.py | shahamish150294/LeetCode | train | 0 | |
47fb4c913f61d692ce968acc74768d7d9093aef7 | [
"a = tf.linalg.LinearOperatorFullMatrix([[13.0, 10.0], [10.0, 5.0]])\nb = tf.constant([3.0, 0.0])\nc = tf.constant(2.0)\nf = convex_ops.ConvexFunctionQuadratic(a, b, c, scale=1.0)\nx = tf.constant([-2.0, 1.0])\nself.assertAllClose(4.5, f(x))\nself.assertIsInstance(f.shape, tf.TensorShape)\nself.assertIsInstance(f.b... | <|body_start_0|>
a = tf.linalg.LinearOperatorFullMatrix([[13.0, 10.0], [10.0, 5.0]])
b = tf.constant([3.0, 0.0])
c = tf.constant(2.0)
f = convex_ops.ConvexFunctionQuadratic(a, b, c, scale=1.0)
x = tf.constant([-2.0, 1.0])
self.assertAllClose(4.5, f(x))
self.assert... | Tests for `ConvexFunctionQuadratic`. | ConvexFunctionQuadraticTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvexFunctionQuadraticTest:
"""Tests for `ConvexFunctionQuadratic`."""
def test_quadratic_simple(self):
"""Tests a simple `ConvexFunctionQuadratic`."""
<|body_0|>
def test_quadratic_batch(self):
"""Tests `ConvexFunctionQuadratic` with batch arguments."""
... | stack_v2_sparse_classes_36k_train_011886 | 17,079 | permissive | [
{
"docstring": "Tests a simple `ConvexFunctionQuadratic`.",
"name": "test_quadratic_simple",
"signature": "def test_quadratic_simple(self)"
},
{
"docstring": "Tests `ConvexFunctionQuadratic` with batch arguments.",
"name": "test_quadratic_batch",
"signature": "def test_quadratic_batch(se... | 5 | null | Implement the Python class `ConvexFunctionQuadraticTest` described below.
Class description:
Tests for `ConvexFunctionQuadratic`.
Method signatures and docstrings:
- def test_quadratic_simple(self): Tests a simple `ConvexFunctionQuadratic`.
- def test_quadratic_batch(self): Tests `ConvexFunctionQuadratic` with batch ... | Implement the Python class `ConvexFunctionQuadraticTest` described below.
Class description:
Tests for `ConvexFunctionQuadratic`.
Method signatures and docstrings:
- def test_quadratic_simple(self): Tests a simple `ConvexFunctionQuadratic`.
- def test_quadratic_batch(self): Tests `ConvexFunctionQuadratic` with batch ... | cfd8930ee5281e7f6dceb17c4a5acaf625fd3243 | <|skeleton|>
class ConvexFunctionQuadraticTest:
"""Tests for `ConvexFunctionQuadratic`."""
def test_quadratic_simple(self):
"""Tests a simple `ConvexFunctionQuadratic`."""
<|body_0|>
def test_quadratic_batch(self):
"""Tests `ConvexFunctionQuadratic` with batch arguments."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvexFunctionQuadraticTest:
"""Tests for `ConvexFunctionQuadratic`."""
def test_quadratic_simple(self):
"""Tests a simple `ConvexFunctionQuadratic`."""
a = tf.linalg.LinearOperatorFullMatrix([[13.0, 10.0], [10.0, 5.0]])
b = tf.constant([3.0, 0.0])
c = tf.constant(2.0)
... | the_stack_v2_python_sparse | tensorflow_mri/python/ops/convex_ops_test.py | mrphys/tensorflow-mri | train | 29 |
3f9bce83f9cf3f837bbf0a75f6725c9effe3a066 | [
"onnx_utils = import_module('mindinsight.mindconverter.graph_based_converter.third_party_graph.onnx_utils')\nconvert_tf_graph_to_onnx = getattr(onnx_utils, 'convert_tf_graph_to_onnx')\ntf_input_nodes = kwargs.get('input_nodes')\ntf_output_nodes = kwargs.get('output_nodes')\nif not os.path.exists(model_path):\n e... | <|body_start_0|>
onnx_utils = import_module('mindinsight.mindconverter.graph_based_converter.third_party_graph.onnx_utils')
convert_tf_graph_to_onnx = getattr(onnx_utils, 'convert_tf_graph_to_onnx')
tf_input_nodes = kwargs.get('input_nodes')
tf_output_nodes = kwargs.get('output_nodes')
... | Define TF graph parser. | TFGraphParser | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFGraphParser:
"""Define TF graph parser."""
def parse(cls, model_path: str, **kwargs):
"""Parse TF Computational Graph File (.pb) Args: model_path (str): Model file path. Returns: object, ONNX model."""
<|body_0|>
def invalid_nodes_name(input_str):
"""Check mode... | stack_v2_sparse_classes_36k_train_011887 | 3,266 | permissive | [
{
"docstring": "Parse TF Computational Graph File (.pb) Args: model_path (str): Model file path. Returns: object, ONNX model.",
"name": "parse",
"signature": "def parse(cls, model_path: str, **kwargs)"
},
{
"docstring": "Check model_inputs and model_outputs are correctly formatted. Args: input_s... | 2 | stack_v2_sparse_classes_30k_train_021346 | Implement the Python class `TFGraphParser` described below.
Class description:
Define TF graph parser.
Method signatures and docstrings:
- def parse(cls, model_path: str, **kwargs): Parse TF Computational Graph File (.pb) Args: model_path (str): Model file path. Returns: object, ONNX model.
- def invalid_nodes_name(i... | Implement the Python class `TFGraphParser` described below.
Class description:
Define TF graph parser.
Method signatures and docstrings:
- def parse(cls, model_path: str, **kwargs): Parse TF Computational Graph File (.pb) Args: model_path (str): Model file path. Returns: object, ONNX model.
- def invalid_nodes_name(i... | db5769eb80cbd13a2a9af7682c11f5667d8bf141 | <|skeleton|>
class TFGraphParser:
"""Define TF graph parser."""
def parse(cls, model_path: str, **kwargs):
"""Parse TF Computational Graph File (.pb) Args: model_path (str): Model file path. Returns: object, ONNX model."""
<|body_0|>
def invalid_nodes_name(input_str):
"""Check mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFGraphParser:
"""Define TF graph parser."""
def parse(cls, model_path: str, **kwargs):
"""Parse TF Computational Graph File (.pb) Args: model_path (str): Model file path. Returns: object, ONNX model."""
onnx_utils = import_module('mindinsight.mindconverter.graph_based_converter.third_par... | the_stack_v2_python_sparse | mindinsight/mindconverter/graph_based_converter/third_party_graph/tf_graph_parser.py | fapbatista/mindinsight | train | 0 |
9ceeaecd6eb28b8e2a803aeca3251367da63b365 | [
"StaticPanel.__init__(self, container, *args, **kwargs)\nself.attributes.append(wx.TextCtrl(self, wx.ID_ANY))\nself.attributes.append(wx.lib.intctrl.IntCtrl(self, wx.ID_ANY, min=0, limited=True, allow_none=False))\nself.attributes.append(wx.CheckBox(self, wx.ID_ANY))\nself._set_attributes(self.attributes)",
"attr... | <|body_start_0|>
StaticPanel.__init__(self, container, *args, **kwargs)
self.attributes.append(wx.TextCtrl(self, wx.ID_ANY))
self.attributes.append(wx.lib.intctrl.IntCtrl(self, wx.ID_ANY, min=0, limited=True, allow_none=False))
self.attributes.append(wx.CheckBox(self, wx.ID_ANY))
... | StaticEmploymentTypePanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticEmploymentTypePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
<|body_0|>
def get_attributes(self):
"""Return a list of all attributes. return: a list, that contains this panel's attribute v... | stack_v2_sparse_classes_36k_train_011888 | 11,497 | no_license | [
{
"docstring": "The default constructor container: a data container object",
"name": "__init__",
"signature": "def __init__(self, container, *args, **kwargs)"
},
{
"docstring": "Return a list of all attributes. return: a list, that contains this panel's attribute values.",
"name": "get_attri... | 3 | null | Implement the Python class `StaticEmploymentTypePanel` described below.
Class description:
Implement the StaticEmploymentTypePanel class.
Method signatures and docstrings:
- def __init__(self, container, *args, **kwargs): The default constructor container: a data container object
- def get_attributes(self): Return a ... | Implement the Python class `StaticEmploymentTypePanel` described below.
Class description:
Implement the StaticEmploymentTypePanel class.
Method signatures and docstrings:
- def __init__(self, container, *args, **kwargs): The default constructor container: a data container object
- def get_attributes(self): Return a ... | 781ce419b51b5bd99bbd1b155c03843cb434cb8c | <|skeleton|>
class StaticEmploymentTypePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
<|body_0|>
def get_attributes(self):
"""Return a list of all attributes. return: a list, that contains this panel's attribute v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaticEmploymentTypePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
StaticPanel.__init__(self, container, *args, **kwargs)
self.attributes.append(wx.TextCtrl(self, wx.ID_ANY))
self.attributes.append(wx.lib.... | the_stack_v2_python_sparse | gui/static_data.py | mcepar1/Scheduler | train | 0 | |
a29cfdd56d4ec6a9da8434e8d8d2c447dd39e4f9 | [
"from ..models import FacilityTransaction, DBSession\npayload = convert_request_to_sedm(request, method_value='new')\ncontent = json.dumps(payload)\nr = requests.post(cfg['app.sedm_endpoint'], files={'jsonfile': ('jsonfile', content)})\nif r.status_code == 200:\n request.status = 'submitted'\nelse:\n request.... | <|body_start_0|>
from ..models import FacilityTransaction, DBSession
payload = convert_request_to_sedm(request, method_value='new')
content = json.dumps(payload)
r = requests.post(cfg['app.sedm_endpoint'], files={'jsonfile': ('jsonfile', content)})
if r.status_code == 200:
... | SkyPortal interface to the Spectral Energy Distribution machine (SEDM). | SEDMAPI | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEDMAPI:
"""SkyPortal interface to the Spectral Energy Distribution machine (SEDM)."""
def submit(request):
"""Submit a follow-up request to SEDM. Parameters ---------- request: skyportal.models.FollowupRequest The request to submit."""
<|body_0|>
def delete(request):
... | stack_v2_sparse_classes_36k_train_011889 | 9,576 | permissive | [
{
"docstring": "Submit a follow-up request to SEDM. Parameters ---------- request: skyportal.models.FollowupRequest The request to submit.",
"name": "submit",
"signature": "def submit(request)"
},
{
"docstring": "Delete a follow-up request from SEDM queue. Parameters ---------- request: skyporta... | 3 | null | Implement the Python class `SEDMAPI` described below.
Class description:
SkyPortal interface to the Spectral Energy Distribution machine (SEDM).
Method signatures and docstrings:
- def submit(request): Submit a follow-up request to SEDM. Parameters ---------- request: skyportal.models.FollowupRequest The request to s... | Implement the Python class `SEDMAPI` described below.
Class description:
SkyPortal interface to the Spectral Energy Distribution machine (SEDM).
Method signatures and docstrings:
- def submit(request): Submit a follow-up request to SEDM. Parameters ---------- request: skyportal.models.FollowupRequest The request to s... | 2433d5ae0b2f41faac3c76ed4ae8d9a4da5522fb | <|skeleton|>
class SEDMAPI:
"""SkyPortal interface to the Spectral Energy Distribution machine (SEDM)."""
def submit(request):
"""Submit a follow-up request to SEDM. Parameters ---------- request: skyportal.models.FollowupRequest The request to submit."""
<|body_0|>
def delete(request):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEDMAPI:
"""SkyPortal interface to the Spectral Energy Distribution machine (SEDM)."""
def submit(request):
"""Submit a follow-up request to SEDM. Parameters ---------- request: skyportal.models.FollowupRequest The request to submit."""
from ..models import FacilityTransaction, DBSession
... | the_stack_v2_python_sparse | skyportal/facility_apis/sedm.py | dmitryduev/skyportal | train | 1 |
3eac9ed3b57657703b447998a7a773c37e02661e | [
"proxy = urllib.request.ProxyHandler({'http': proxy_addr})\nopener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)\nurllib.request.install_opener(opener)\ndata = urllib.request.urlopen(url).read()\nwith open('/home/fang/requestWithProxy.html', 'wb') as f:\n f.write(data)",
"httphd = urllib.req... | <|body_start_0|>
proxy = urllib.request.ProxyHandler({'http': proxy_addr})
opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
urllib.request.install_opener(opener)
data = urllib.request.urlopen(url).read()
with open('/home/fang/requestWithProxy.html', 'wb') a... | 这个类封装了一些对代理服务发送网络请求的实现 | MyRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyRequest:
"""这个类封装了一些对代理服务发送网络请求的实现"""
def requestWithProxy(self, proxy_addr, url):
"""通过代理服务器发送请求 :param proxy_addr 代理服务器的地址 下面是一些代理服务器的地址 <a href='http://www.xicidaili.com/'><a> :param url 请求的网址 :return: 函数会将创建的html网页的信息存放到/home/fang/requestWithProxy.html中"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_011890 | 7,420 | no_license | [
{
"docstring": "通过代理服务器发送请求 :param proxy_addr 代理服务器的地址 下面是一些代理服务器的地址 <a href='http://www.xicidaili.com/'><a> :param url 请求的网址 :return: 函数会将创建的html网页的信息存放到/home/fang/requestWithProxy.html中",
"name": "requestWithProxy",
"signature": "def requestWithProxy(self, proxy_addr, url)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_017680 | Implement the Python class `MyRequest` described below.
Class description:
这个类封装了一些对代理服务发送网络请求的实现
Method signatures and docstrings:
- def requestWithProxy(self, proxy_addr, url): 通过代理服务器发送请求 :param proxy_addr 代理服务器的地址 下面是一些代理服务器的地址 <a href='http://www.xicidaili.com/'><a> :param url 请求的网址 :return: 函数会将创建的html网页的信息存放到/... | Implement the Python class `MyRequest` described below.
Class description:
这个类封装了一些对代理服务发送网络请求的实现
Method signatures and docstrings:
- def requestWithProxy(self, proxy_addr, url): 通过代理服务器发送请求 :param proxy_addr 代理服务器的地址 下面是一些代理服务器的地址 <a href='http://www.xicidaili.com/'><a> :param url 请求的网址 :return: 函数会将创建的html网页的信息存放到/... | 3d88d76828daa78568654454e61da9c714ff671a | <|skeleton|>
class MyRequest:
"""这个类封装了一些对代理服务发送网络请求的实现"""
def requestWithProxy(self, proxy_addr, url):
"""通过代理服务器发送请求 :param proxy_addr 代理服务器的地址 下面是一些代理服务器的地址 <a href='http://www.xicidaili.com/'><a> :param url 请求的网址 :return: 函数会将创建的html网页的信息存放到/home/fang/requestWithProxy.html中"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyRequest:
"""这个类封装了一些对代理服务发送网络请求的实现"""
def requestWithProxy(self, proxy_addr, url):
"""通过代理服务器发送请求 :param proxy_addr 代理服务器的地址 下面是一些代理服务器的地址 <a href='http://www.xicidaili.com/'><a> :param url 请求的网址 :return: 函数会将创建的html网页的信息存放到/home/fang/requestWithProxy.html中"""
proxy = urllib.request.Pro... | the_stack_v2_python_sparse | 学习python笔记/demo2/first.py | 7973463/pythonPro | train | 0 |
2fa1d40dd1b9ac75816c7b9fd3aaab5657ace752 | [
"super().__init__()\nself.visual = visual\nself.hidden = hidden\nself.n_layers = n_layers\nself.attn_heads = attn_heads\nself.feed_forward_hidden = hidden * 2\nself.token_embedding = TokenEmbedding(vocab_size=vocab_size, embed_size=hidden)\nself.relation_embedding = RelationEmbedding(hidden, max_relative_1d_positio... | <|body_start_0|>
super().__init__()
self.visual = visual
self.hidden = hidden
self.n_layers = n_layers
self.attn_heads = attn_heads
self.feed_forward_hidden = hidden * 2
self.token_embedding = TokenEmbedding(vocab_size=vocab_size, embed_size=hidden)
self.r... | Language Model for proteins | ProEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProEncoder:
"""Language Model for proteins"""
def __init__(self, vocab_size, hidden=512, n_layers=5, attn_heads=1, dropout=0.0, max_relative_1d_positions=300, visual=False):
""":param vocab_size: vocab_size of total words :param hidden: BERT model hidden size :param n_layers: numbers... | stack_v2_sparse_classes_36k_train_011891 | 9,053 | no_license | [
{
"docstring": ":param vocab_size: vocab_size of total words :param hidden: BERT model hidden size :param n_layers: numbers of Transformer blocks(layers) :param attn_heads: number of attention heads :param dropout: dropout rate",
"name": "__init__",
"signature": "def __init__(self, vocab_size, hidden=51... | 2 | stack_v2_sparse_classes_30k_train_008714 | Implement the Python class `ProEncoder` described below.
Class description:
Language Model for proteins
Method signatures and docstrings:
- def __init__(self, vocab_size, hidden=512, n_layers=5, attn_heads=1, dropout=0.0, max_relative_1d_positions=300, visual=False): :param vocab_size: vocab_size of total words :para... | Implement the Python class `ProEncoder` described below.
Class description:
Language Model for proteins
Method signatures and docstrings:
- def __init__(self, vocab_size, hidden=512, n_layers=5, attn_heads=1, dropout=0.0, max_relative_1d_positions=300, visual=False): :param vocab_size: vocab_size of total words :para... | 51b03ad1426794704027e0bc6658aae5d55a6e90 | <|skeleton|>
class ProEncoder:
"""Language Model for proteins"""
def __init__(self, vocab_size, hidden=512, n_layers=5, attn_heads=1, dropout=0.0, max_relative_1d_positions=300, visual=False):
""":param vocab_size: vocab_size of total words :param hidden: BERT model hidden size :param n_layers: numbers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProEncoder:
"""Language Model for proteins"""
def __init__(self, vocab_size, hidden=512, n_layers=5, attn_heads=1, dropout=0.0, max_relative_1d_positions=300, visual=False):
""":param vocab_size: vocab_size of total words :param hidden: BERT model hidden size :param n_layers: numbers of Transform... | the_stack_v2_python_sparse | model/prolm_relative.py | lahplover/unippi | train | 1 |
e1285ea9c88422fc83ab296998e8070d6d129085 | [
"self.stack = []\nfor i in range(len(nestedList) - 1, -1, -1):\n self.stack.append(nestedList[i])",
"num = self.stack[-1].getInteger()\nself.stack.pop()\nreturn num",
"while self.stack and (not self.stack[-1].isInteger()):\n data = self.stack[-1].getList()\n self.stack.pop()\n for i in range(len(dat... | <|body_start_0|>
self.stack = []
for i in range(len(nestedList) - 1, -1, -1):
self.stack.append(nestedList[i])
<|end_body_0|>
<|body_start_1|>
num = self.stack[-1].getInteger()
self.stack.pop()
return num
<|end_body_1|>
<|body_start_2|>
while self.stack and ... | NestedIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_011892 | 2,133 | no_license | [
{
"docstring": "Initialize your data structure here. :type nestedList: List[NestedInteger]",
"name": "__init__",
"signature": "def __init__(self, nestedList)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"nam... | 3 | null | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | 9b38a7742a819ac3795ea295e371e26bb5bfc28c | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
self.stack = []
for i in range(len(nestedList) - 1, -1, -1):
self.stack.append(nestedList[i])
def next(self):
""":rtype: int"""
... | the_stack_v2_python_sparse | 341. Flatten Nested List Iterator.py | dundunmao/LeetCode2019 | train | 0 | |
a744487c92965c81657725718f8310d99898b5a5 | [
"query = {'query': {'match': {'profile.first_name': 'here'}}}\npercolate_query = PercolateQueryFactory.create(query=query, original_query='original')\npercolate_query_id = 123\npercolate_query.id = percolate_query_id\nwith self.assertRaises(NotFoundError):\n es.get_percolate_query(percolate_query_id)\nindex_perc... | <|body_start_0|>
query = {'query': {'match': {'profile.first_name': 'here'}}}
percolate_query = PercolateQueryFactory.create(query=query, original_query='original')
percolate_query_id = 123
percolate_query.id = percolate_query_id
with self.assertRaises(NotFoundError):
... | Tests for indexing of percolate queries | PercolateQueryTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PercolateQueryTests:
"""Tests for indexing of percolate queries"""
def test_index_percolate_query(self):
"""Test that we index the percolate query"""
<|body_0|>
def test_delete_percolate_queries(self):
"""Test that we delete the percolate query from the index"""
... | stack_v2_sparse_classes_36k_train_011893 | 42,701 | permissive | [
{
"docstring": "Test that we index the percolate query",
"name": "test_index_percolate_query",
"signature": "def test_index_percolate_query(self)"
},
{
"docstring": "Test that we delete the percolate query from the index",
"name": "test_delete_percolate_queries",
"signature": "def test_d... | 5 | null | Implement the Python class `PercolateQueryTests` described below.
Class description:
Tests for indexing of percolate queries
Method signatures and docstrings:
- def test_index_percolate_query(self): Test that we index the percolate query
- def test_delete_percolate_queries(self): Test that we delete the percolate que... | Implement the Python class `PercolateQueryTests` described below.
Class description:
Tests for indexing of percolate queries
Method signatures and docstrings:
- def test_index_percolate_query(self): Test that we index the percolate query
- def test_delete_percolate_queries(self): Test that we delete the percolate que... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class PercolateQueryTests:
"""Tests for indexing of percolate queries"""
def test_index_percolate_query(self):
"""Test that we index the percolate query"""
<|body_0|>
def test_delete_percolate_queries(self):
"""Test that we delete the percolate query from the index"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PercolateQueryTests:
"""Tests for indexing of percolate queries"""
def test_index_percolate_query(self):
"""Test that we index the percolate query"""
query = {'query': {'match': {'profile.first_name': 'here'}}}
percolate_query = PercolateQueryFactory.create(query=query, original_q... | the_stack_v2_python_sparse | search/indexing_api_test.py | mitodl/micromasters | train | 35 |
28d50c07ed843df1fb70e44b8e15dd06c7afebf2 | [
"arr = [0] * (len(s) + 1)\narr[-1] = 1\narr[-2] = 1 if s[-1] != '0' else 0\nfor i in reversed(range(0, len(s) - 1)):\n if s[i] == '1':\n arr[i] = arr[i + 1] + arr[i + 2]\n elif s[i] == '2':\n arr[i] = arr[i + 1]\n if s[i + 1] <= '6':\n arr[i] += arr[i + 2]\n elif s[i] == '0'... | <|body_start_0|>
arr = [0] * (len(s) + 1)
arr[-1] = 1
arr[-2] = 1 if s[-1] != '0' else 0
for i in reversed(range(0, len(s) - 1)):
if s[i] == '1':
arr[i] = arr[i + 1] + arr[i + 2]
elif s[i] == '2':
arr[i] = arr[i + 1]
... | Runtime: 36 ms, faster than 99.97% of Python3 online submissions for Decode Ways. Memory Usage: 13.2 MB, less than 18.18% of Python3 online submissions for Decode Ways. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Runtime: 36 ms, faster than 99.97% of Python3 online submissions for Decode Ways. Memory Usage: 13.2 MB, less than 18.18% of Python3 online submissions for Decode Ways."""
def numDecodings(self, s):
"""A message containing letters from A-Z is being encoded to numbers usi... | stack_v2_sparse_classes_36k_train_011894 | 3,747 | no_license | [
{
"docstring": "A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: \"12\" Output: 2 Explanation: It could be decoded as ... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Runtime: 36 ms, faster than 99.97% of Python3 online submissions for Decode Ways. Memory Usage: 13.2 MB, less than 18.18% of Python3 online submissions for Decode Ways.
Method signatures and docstrings:
- def numDecodings(self, s): A message co... | Implement the Python class `Solution` described below.
Class description:
Runtime: 36 ms, faster than 99.97% of Python3 online submissions for Decode Ways. Memory Usage: 13.2 MB, less than 18.18% of Python3 online submissions for Decode Ways.
Method signatures and docstrings:
- def numDecodings(self, s): A message co... | 01fe893ba2e37c9bda79e3081c556698f0b6d2f0 | <|skeleton|>
class Solution:
"""Runtime: 36 ms, faster than 99.97% of Python3 online submissions for Decode Ways. Memory Usage: 13.2 MB, less than 18.18% of Python3 online submissions for Decode Ways."""
def numDecodings(self, s):
"""A message containing letters from A-Z is being encoded to numbers usi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Runtime: 36 ms, faster than 99.97% of Python3 online submissions for Decode Ways. Memory Usage: 13.2 MB, less than 18.18% of Python3 online submissions for Decode Ways."""
def numDecodings(self, s):
"""A message containing letters from A-Z is being encoded to numbers using the follow... | the_stack_v2_python_sparse | LeetCode/91_decode_ways.py | KKosukeee/CodingQuestions | train | 1 |
51019c8e5eb37ed3e8b0f73594552db4f74852af | [
"c = Client()\nresp = c.get('/')\nself.assertIn(b'<div class=\"container-fluid\">', resp.content)",
"c = Client()\nresponse = c.get('/publishers/new/')\nself.assertIsNotNone(re.search('<input type=\"hidden\" name=\"csrfmiddlewaretoken\" value=\"\\\\w+\">', response.content.decode('utf8')))\nself.assertIn(b'<label... | <|body_start_0|>
c = Client()
resp = c.get('/')
self.assertIn(b'<div class="container-fluid">', resp.content)
<|end_body_0|>
<|body_start_1|>
c = Client()
response = c.get('/publishers/new/')
self.assertIsNotNone(re.search('<input type="hidden" name="csrfmiddlewaretoken"... | Activity1Test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Activity1Test:
def test_container_wrapper(self):
"""The <div class="container-fluid"> should have been added."""
<|body_0|>
def test_fields_in_view(self):
"""" Test that fields exist in the rendered template."""
<|body_1|>
def test_publisher_create(self)... | stack_v2_sparse_classes_36k_train_011895 | 5,762 | permissive | [
{
"docstring": "The <div class=\"container-fluid\"> should have been added.",
"name": "test_container_wrapper",
"signature": "def test_container_wrapper(self)"
},
{
"docstring": "\" Test that fields exist in the rendered template.",
"name": "test_fields_in_view",
"signature": "def test_f... | 6 | stack_v2_sparse_classes_30k_train_004658 | Implement the Python class `Activity1Test` described below.
Class description:
Implement the Activity1Test class.
Method signatures and docstrings:
- def test_container_wrapper(self): The <div class="container-fluid"> should have been added.
- def test_fields_in_view(self): " Test that fields exist in the rendered te... | Implement the Python class `Activity1Test` described below.
Class description:
Implement the Activity1Test class.
Method signatures and docstrings:
- def test_container_wrapper(self): The <div class="container-fluid"> should have been added.
- def test_fields_in_view(self): " Test that fields exist in the rendered te... | 52e86a8f93cb38bf70d50e9b8d2c6d7dac416f62 | <|skeleton|>
class Activity1Test:
def test_container_wrapper(self):
"""The <div class="container-fluid"> should have been added."""
<|body_0|>
def test_fields_in_view(self):
"""" Test that fields exist in the rendered template."""
<|body_1|>
def test_publisher_create(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Activity1Test:
def test_container_wrapper(self):
"""The <div class="container-fluid"> should have been added."""
c = Client()
resp = c.get('/')
self.assertIn(b'<div class="container-fluid">', resp.content)
def test_fields_in_view(self):
"""" Test that fields exist ... | the_stack_v2_python_sparse | Chapter07/Activity7.01/bookr/reviews/tests.py | lmoshood/The-Django-Workshop | train | 0 | |
3eb25e37fc03744017719d8338ab0aabcc17639a | [
"if isinstance(key, int):\n return HIAlgorithm(key)\nif key not in HIAlgorithm._member_map_:\n return extend_enum(HIAlgorithm, key, default)\nreturn HIAlgorithm[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 10 <= va... | <|body_start_0|>
if isinstance(key, int):
return HIAlgorithm(key)
if key not in HIAlgorithm._member_map_:
return extend_enum(HIAlgorithm, key, default)
return HIAlgorithm[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535)... | [HIAlgorithm] HI Algorithm | HIAlgorithm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HIAlgorithm:
"""[HIAlgorithm] HI Algorithm"""
def get(key: 'int | str', default: 'int'=-1) -> 'HIAlgorithm':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, valu... | stack_v2_sparse_classes_36k_train_011896 | 2,103 | 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) -> 'HIAlgorithm'"
},
{
"docstring": "Lookup function used when value is not found.... | 2 | null | Implement the Python class `HIAlgorithm` described below.
Class description:
[HIAlgorithm] HI Algorithm
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HIAlgorithm': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta pr... | Implement the Python class `HIAlgorithm` described below.
Class description:
[HIAlgorithm] HI Algorithm
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HIAlgorithm': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta pr... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class HIAlgorithm:
"""[HIAlgorithm] HI Algorithm"""
def get(key: 'int | str', default: 'int'=-1) -> 'HIAlgorithm':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HIAlgorithm:
"""[HIAlgorithm] HI Algorithm"""
def get(key: 'int | str', default: 'int'=-1) -> 'HIAlgorithm':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return HIAlgori... | the_stack_v2_python_sparse | pcapkit/const/hip/hi_algorithm.py | JarryShaw/PyPCAPKit | train | 204 |
9245b9f54f18328b88d63656b8b44722411a113d | [
"check_application(application_name)\nfacade = RouteManagement(huskar_client, application_name, None)\ndefault_route = facade.get_default_route()\nreturn api_response({'default_route': default_route, 'global_default_route': settings.ROUTE_DEFAULT_POLICY})",
"check_application_auth(application_name, Authority.WRIT... | <|body_start_0|>
check_application(application_name)
facade = RouteManagement(huskar_client, application_name, None)
default_route = facade.get_default_route()
return api_response({'default_route': default_route, 'global_default_route': settings.ROUTE_DEFAULT_POLICY})
<|end_body_0|>
<|b... | ServiceDefaultRouteView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceDefaultRouteView:
def get(self, application_name):
"""Gets the default route policy of specific application. Example of response:: { "status": "SUCCESS", "message": "", "data": { "default_route": { "overall": { "direct": "channel-stable-2" }, "altb1": { "direct": "channel-stable-1... | stack_v2_sparse_classes_36k_train_011897 | 10,027 | permissive | [
{
"docstring": "Gets the default route policy of specific application. Example of response:: { \"status\": \"SUCCESS\", \"message\": \"\", \"data\": { \"default_route\": { \"overall\": { \"direct\": \"channel-stable-2\" }, \"altb1\": { \"direct\": \"channel-stable-1\" } }, \"global_default_route\": { \"direct\"... | 3 | null | Implement the Python class `ServiceDefaultRouteView` described below.
Class description:
Implement the ServiceDefaultRouteView class.
Method signatures and docstrings:
- def get(self, application_name): Gets the default route policy of specific application. Example of response:: { "status": "SUCCESS", "message": "", ... | Implement the Python class `ServiceDefaultRouteView` described below.
Class description:
Implement the ServiceDefaultRouteView class.
Method signatures and docstrings:
- def get(self, application_name): Gets the default route policy of specific application. Example of response:: { "status": "SUCCESS", "message": "", ... | 395775c59c7da97c46efe9756365cad028b7c95a | <|skeleton|>
class ServiceDefaultRouteView:
def get(self, application_name):
"""Gets the default route policy of specific application. Example of response:: { "status": "SUCCESS", "message": "", "data": { "default_route": { "overall": { "direct": "channel-stable-2" }, "altb1": { "direct": "channel-stable-1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceDefaultRouteView:
def get(self, application_name):
"""Gets the default route policy of specific application. Example of response:: { "status": "SUCCESS", "message": "", "data": { "default_route": { "overall": { "direct": "channel-stable-2" }, "altb1": { "direct": "channel-stable-1" } }, "global... | the_stack_v2_python_sparse | huskar_api/api/service_route.py | Zheaoli/huskar | train | 0 | |
4f5035bc59f08dea5d56e6be7dfc16663cf5338b | [
"errors = {}\ninfo = None\nif user_input is not None:\n try:\n info = await validate_input(self.hass, user_input)\n except CannotConnect:\n errors['base'] = 'cannot_connect'\n except Exception:\n _LOGGER.exception('Unexpected exception')\n errors['base'] = 'unknown'\n if 'bas... | <|body_start_0|>
errors = {}
info = None
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors['base'] = 'cannot_connect'
except Exception:
_LOGGER.except... | Handle a config flow for Griddy Power. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Griddy Power."""
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_0|>
async def async_step_import(self, user_input):
"""Handle import."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_011898 | 2,514 | permissive | [
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Handle import.",
"name": "async_step_import",
"signature": "async def async_step_import(self, user_input)"
}
] | 2 | null | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Griddy Power.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_import(self, user_input): Handle import. | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Griddy Power.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_import(self, user_input): Handle import.
<|skeleton|>
class ConfigFl... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Griddy Power."""
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_0|>
async def async_step_import(self, user_input):
"""Handle import."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle a config flow for Griddy Power."""
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
info = None
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
... | the_stack_v2_python_sparse | homeassistant/components/griddy/config_flow.py | tchellomello/home-assistant | train | 8 |
f8cf9eeb033e5f1c1c88fbf2eb4afb0f38333559 | [
"active_ids = self._context.get('active_ids', False)\nproductions = self.env['mrp.production'].browse(active_ids)\nfor production in productions:\n production.action_cancel()\nreturn True",
"if any((workorder.state == 'progress' for workorder in self.mapped('workorder_ids'))):\n raise UserError(_('You can n... | <|body_start_0|>
active_ids = self._context.get('active_ids', False)
productions = self.env['mrp.production'].browse(active_ids)
for production in productions:
production.action_cancel()
return True
<|end_body_0|>
<|body_start_1|>
if any((workorder.state == 'progress... | mrp_cancel_more | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mrp_cancel_more:
def cancel_mrp_order(self):
"""Cancels the production order and related stock moves. @return: True"""
<|body_0|>
def action_cancel(self):
"""Cancels production order, unfinished stock moves and set procurement orders in exception"""
<|body_1|... | stack_v2_sparse_classes_36k_train_011899 | 2,560 | no_license | [
{
"docstring": "Cancels the production order and related stock moves. @return: True",
"name": "cancel_mrp_order",
"signature": "def cancel_mrp_order(self)"
},
{
"docstring": "Cancels production order, unfinished stock moves and set procurement orders in exception",
"name": "action_cancel",
... | 2 | stack_v2_sparse_classes_30k_train_005007 | Implement the Python class `mrp_cancel_more` described below.
Class description:
Implement the mrp_cancel_more class.
Method signatures and docstrings:
- def cancel_mrp_order(self): Cancels the production order and related stock moves. @return: True
- def action_cancel(self): Cancels production order, unfinished stoc... | Implement the Python class `mrp_cancel_more` described below.
Class description:
Implement the mrp_cancel_more class.
Method signatures and docstrings:
- def cancel_mrp_order(self): Cancels the production order and related stock moves. @return: True
- def action_cancel(self): Cancels production order, unfinished stoc... | c04e2b9730db07848c153d8245d2df65ec4e2c8f | <|skeleton|>
class mrp_cancel_more:
def cancel_mrp_order(self):
"""Cancels the production order and related stock moves. @return: True"""
<|body_0|>
def action_cancel(self):
"""Cancels production order, unfinished stock moves and set procurement orders in exception"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mrp_cancel_more:
def cancel_mrp_order(self):
"""Cancels the production order and related stock moves. @return: True"""
active_ids = self._context.get('active_ids', False)
productions = self.env['mrp.production'].browse(active_ids)
for production in productions:
prod... | the_stack_v2_python_sparse | altinkaya_mrp/wizard/mrp_cancel_wizard.py | aaltinisik/customaddons | train | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.