blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d7c333de72cbb393524dc0e496fdafabeecdbbe | [
"bit_string = list(params.keys())[0]\nself.num_qubits = len(bit_string)\nif not isclose(sum(np.absolute(list(params.values())) ** 2), 1.0, abs_tol=1e-10):\n Exception('Sum of amplitudes-squared does not equal one.')",
"if isinstance(parameter, tuple):\n if not match('([01])+', parameter[0]):\n raise ... | <|body_start_0|>
bit_string = list(params.keys())[0]
self.num_qubits = len(bit_string)
if not isclose(sum(np.absolute(list(params.values())) ** 2), 1.0, abs_tol=1e-10):
Exception('Sum of amplitudes-squared does not equal one.')
<|end_body_0|>
<|body_start_1|>
if isinstance(p... | Superclass dedicated for state preparation algorithms for initializing sparse states. | InitializeSparse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitializeSparse:
"""Superclass dedicated for state preparation algorithms for initializing sparse states."""
def _get_num_qubits(self, params):
"""Computes the number of qubits, based on the number of 0 or 1 characters in the dictionary key."""
<|body_0|>
def validate_p... | stack_v2_sparse_classes_75kplus_train_066000 | 2,039 | permissive | [
{
"docstring": "Computes the number of qubits, based on the number of 0 or 1 characters in the dictionary key.",
"name": "_get_num_qubits",
"signature": "def _get_num_qubits(self, params)"
},
{
"docstring": "Sparse preparation params are converted to a list of tuples when being validated, where ... | 2 | stack_v2_sparse_classes_30k_train_008178 | Implement the Python class `InitializeSparse` described below.
Class description:
Superclass dedicated for state preparation algorithms for initializing sparse states.
Method signatures and docstrings:
- def _get_num_qubits(self, params): Computes the number of qubits, based on the number of 0 or 1 characters in the ... | Implement the Python class `InitializeSparse` described below.
Class description:
Superclass dedicated for state preparation algorithms for initializing sparse states.
Method signatures and docstrings:
- def _get_num_qubits(self, params): Computes the number of qubits, based on the number of 0 or 1 characters in the ... | 8281ccc418e47b3525956badd00724ba12c054be | <|skeleton|>
class InitializeSparse:
"""Superclass dedicated for state preparation algorithms for initializing sparse states."""
def _get_num_qubits(self, params):
"""Computes the number of qubits, based on the number of 0 or 1 characters in the dictionary key."""
<|body_0|>
def validate_p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InitializeSparse:
"""Superclass dedicated for state preparation algorithms for initializing sparse states."""
def _get_num_qubits(self, params):
"""Computes the number of qubits, based on the number of 0 or 1 characters in the dictionary key."""
bit_string = list(params.keys())[0]
... | the_stack_v2_python_sparse | qclib/gates/initialize_sparse.py | IsmaelCesar/qclib | train | 1 |
b224eac4dfb3aa0ace048e9a1a177cba9b8e55c1 | [
"self._cr.execute('SELECT complete_name FROM stock_location WHERE complete_name = %s', (self.complete_name,))\nres = self._cr.fetchall()\nif res:\n raise ValidationError('Please use another Location Name. The Name already exists: ' + self.complete_name)",
"if default is None:\n default = {}\nif 'name' not i... | <|body_start_0|>
self._cr.execute('SELECT complete_name FROM stock_location WHERE complete_name = %s', (self.complete_name,))
res = self._cr.fetchall()
if res:
raise ValidationError('Please use another Location Name. The Name already exists: ' + self.complete_name)
<|end_body_0|>
<|... | flspStockLocation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class flspStockLocation:
def _constraint_only_unique_complete_name(self):
"""Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete ... | stack_v2_sparse_classes_75kplus_train_066001 | 1,591 | no_license | [
{
"docstring": "Date: Mar/16th/2021/Tuesday Purpose: To create only unique \"complete name\" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete names existing in database, so _sql_constraints would not work Author: Perry ... | 2 | stack_v2_sparse_classes_30k_train_049844 | Implement the Python class `flspStockLocation` described below.
Class description:
Implement the flspStockLocation class.
Method signatures and docstrings:
- def _constraint_only_unique_complete_name(self): Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / L... | Implement the Python class `flspStockLocation` described below.
Class description:
Implement the flspStockLocation class.
Method signatures and docstrings:
- def _constraint_only_unique_complete_name(self): Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / L... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class flspStockLocation:
def _constraint_only_unique_complete_name(self):
"""Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class flspStockLocation:
def _constraint_only_unique_complete_name(self):
"""Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete names existing... | the_stack_v2_python_sparse | flspstock/models/flsp_stock_location.py | odoo-smg/firstlight | train | 3 | |
2489a9599a1cd22997e71711d6caaab848f69e44 | [
"if value is not None:\n value = json.dumps(value)\nreturn value",
"if value is not None:\n value = json.loads(value)\nreturn value"
] | <|body_start_0|>
if value is not None:
value = json.dumps(value)
return value
<|end_body_0|>
<|body_start_1|>
if value is not None:
value = json.loads(value)
return value
<|end_body_1|>
| Stores and retrieves JSON as TEXT for SQLite. From https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy. .. note :: The associated field is immutable. That is, changes to the data (typically, changing the value of a dict field) will not trigger an update on the SQL side upon ``commit`` as... | StringyJSON | [
"MIT",
"ODbL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringyJSON:
"""Stores and retrieves JSON as TEXT for SQLite. From https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy. .. note :: The associated field is immutable. That is, changes to the data (typically, changing the value of a dict field) will not trigger an up... | stack_v2_sparse_classes_75kplus_train_066002 | 1,921 | permissive | [
{
"docstring": "Process the bound param, serialize the object to JSON before saving into database.",
"name": "process_bind_param",
"signature": "def process_bind_param(self, value, dialect)"
},
{
"docstring": "Process the value fetched from the database, deserialize the JSON string before return... | 2 | stack_v2_sparse_classes_30k_train_004105 | Implement the Python class `StringyJSON` described below.
Class description:
Stores and retrieves JSON as TEXT for SQLite. From https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy. .. note :: The associated field is immutable. That is, changes to the data (typically, changing the value ... | Implement the Python class `StringyJSON` described below.
Class description:
Stores and retrieves JSON as TEXT for SQLite. From https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy. .. note :: The associated field is immutable. That is, changes to the data (typically, changing the value ... | 9e495bb63ec32686e6dc6be566da9672ad014880 | <|skeleton|>
class StringyJSON:
"""Stores and retrieves JSON as TEXT for SQLite. From https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy. .. note :: The associated field is immutable. That is, changes to the data (typically, changing the value of a dict field) will not trigger an up... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringyJSON:
"""Stores and retrieves JSON as TEXT for SQLite. From https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy. .. note :: The associated field is immutable. That is, changes to the data (typically, changing the value of a dict field) will not trigger an update on the S... | the_stack_v2_python_sparse | migrations/versions/d21933db9ad8_add_flat_position_column.py | Phyks/Flatisfy | train | 16 |
d613a2fb4ab71976554ee1b751cff97770b0c8f7 | [
"self.index = index\nprint(rv.data)\nreturn super(SelectableLabel, self).refresh_view_attrs(rv, index, data)",
"if super(SelectableLabel, self).on_touch_down(touch):\n return True\nif self.collide_point(*touch.pos) and self.selectable:\n return self.parent.select_with_touch(self.index, touch)",
"self.sele... | <|body_start_0|>
self.index = index
print(rv.data)
return super(SelectableLabel, self).refresh_view_attrs(rv, index, data)
<|end_body_0|>
<|body_start_1|>
if super(SelectableLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.sel... | Add selection support to the Label | SelectableLabel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectableLabel:
"""Add selection support to the Label"""
def refresh_view_attrs(self, rv, index, data):
"""Catch and handle the view changes"""
<|body_0|>
def on_touch_down(self, touch):
"""Add selection on touch down"""
<|body_1|>
def apply_selecti... | stack_v2_sparse_classes_75kplus_train_066003 | 4,481 | no_license | [
{
"docstring": "Catch and handle the view changes",
"name": "refresh_view_attrs",
"signature": "def refresh_view_attrs(self, rv, index, data)"
},
{
"docstring": "Add selection on touch down",
"name": "on_touch_down",
"signature": "def on_touch_down(self, touch)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_041967 | Implement the Python class `SelectableLabel` described below.
Class description:
Add selection support to the Label
Method signatures and docstrings:
- def refresh_view_attrs(self, rv, index, data): Catch and handle the view changes
- def on_touch_down(self, touch): Add selection on touch down
- def apply_selection(s... | Implement the Python class `SelectableLabel` described below.
Class description:
Add selection support to the Label
Method signatures and docstrings:
- def refresh_view_attrs(self, rv, index, data): Catch and handle the view changes
- def on_touch_down(self, touch): Add selection on touch down
- def apply_selection(s... | 30b5448ae35803572171269038a5ab0fd22e9b13 | <|skeleton|>
class SelectableLabel:
"""Add selection support to the Label"""
def refresh_view_attrs(self, rv, index, data):
"""Catch and handle the view changes"""
<|body_0|>
def on_touch_down(self, touch):
"""Add selection on touch down"""
<|body_1|>
def apply_selecti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelectableLabel:
"""Add selection support to the Label"""
def refresh_view_attrs(self, rv, index, data):
"""Catch and handle the view changes"""
self.index = index
print(rv.data)
return super(SelectableLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down... | the_stack_v2_python_sparse | Raspberry Pi/GUI/RV.py | nguyenmthien/VGUServer_archive | train | 0 |
101b8bc58d9ba35ec826ced5469e6b1b782b8611 | [
"logging.getLogger(__name__).addHandler(logging.NullHandler())\nif scraper:\n self._s = scraper\nelse:\n self._s = Scraper(cache_name=cache_name)\nif parser:\n self._p = parser\nelse:\n self._p = Parser()",
"projections = []\nlogging.info('getting projections for %s Week %s', season_year, week)\nplaye... | <|body_start_0|>
logging.getLogger(__name__).addHandler(logging.NullHandler())
if scraper:
self._s = scraper
else:
self._s = Scraper(cache_name=cache_name)
if parser:
self._p = parser
else:
self._p = Parser()
<|end_body_0|>
<|body_... | Combines common scraping/parsing tasks Usage: a = Agent() | Agent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agent:
"""Combines common scraping/parsing tasks Usage: a = Agent()"""
def __init__(self, scraper=None, parser=None, cache_name='espn-agent'):
"""Creates Agent object Args: scraper(espn.Scraper): default None parser(espn.Parser): default None cache_name(str): default 'espn-agent'"""
... | stack_v2_sparse_classes_75kplus_train_066004 | 6,001 | permissive | [
{
"docstring": "Creates Agent object Args: scraper(espn.Scraper): default None parser(espn.Parser): default None cache_name(str): default 'espn-agent'",
"name": "__init__",
"signature": "def __init__(self, scraper=None, parser=None, cache_name='espn-agent')"
},
{
"docstring": "Gets weekly watson... | 2 | stack_v2_sparse_classes_30k_train_027979 | Implement the Python class `Agent` described below.
Class description:
Combines common scraping/parsing tasks Usage: a = Agent()
Method signatures and docstrings:
- def __init__(self, scraper=None, parser=None, cache_name='espn-agent'): Creates Agent object Args: scraper(espn.Scraper): default None parser(espn.Parser... | Implement the Python class `Agent` described below.
Class description:
Combines common scraping/parsing tasks Usage: a = Agent()
Method signatures and docstrings:
- def __init__(self, scraper=None, parser=None, cache_name='espn-agent'): Creates Agent object Args: scraper(espn.Scraper): default None parser(espn.Parser... | 11605b1a7725cce062ce0d7f15ebcf0a2f91a86e | <|skeleton|>
class Agent:
"""Combines common scraping/parsing tasks Usage: a = Agent()"""
def __init__(self, scraper=None, parser=None, cache_name='espn-agent'):
"""Creates Agent object Args: scraper(espn.Scraper): default None parser(espn.Parser): default None cache_name(str): default 'espn-agent'"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Agent:
"""Combines common scraping/parsing tasks Usage: a = Agent()"""
def __init__(self, scraper=None, parser=None, cache_name='espn-agent'):
"""Creates Agent object Args: scraper(espn.Scraper): default None parser(espn.Parser): default None cache_name(str): default 'espn-agent'"""
loggi... | the_stack_v2_python_sparse | nfl/watson.py | sansbacon/nfl | train | 2 |
875c3acb9b521924c09ab3c2f06815aebaf398ef | [
"hearing_list = response.css('.field-item ul')[1]\nfor item in hearing_list.css('li'):\n item_text = ' '.join(item.css('*::text').extract())\n meeting = Meeting(title='Public Hearing', description='', classification=FORUM, start=self._parse_start(item_text), end=None, all_day=False, time_notes='', location=se... | <|body_start_0|>
hearing_list = response.css('.field-item ul')[1]
for item in hearing_list.css('li'):
item_text = ' '.join(item.css('*::text').extract())
meeting = Meeting(title='Public Hearing', description='', classification=FORUM, start=self._parse_start(item_text), end=None, ... | CookZoningSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CookZoningSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, text):
"""Parse start datetime as a naive datetime obj... | stack_v2_sparse_classes_75kplus_train_066005 | 2,526 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse start datetime as a naive datetime object.",
"name": "_parse_st... | 3 | stack_v2_sparse_classes_30k_train_019072 | Implement the Python class `CookZoningSpider` described below.
Class description:
Implement the CookZoningSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _... | Implement the Python class `CookZoningSpider` described below.
Class description:
Implement the CookZoningSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class CookZoningSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, text):
"""Parse start datetime as a naive datetime obj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CookZoningSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
hearing_list = response.css('.field-item ul')[1]
for item in hearing_list.css('li'):
item_text ... | the_stack_v2_python_sparse | city_scrapers/spiders/cook_zoning.py | City-Bureau/city-scrapers | train | 308 | |
0a098ae22ec0c0459c3c2fa43c07d543730ee066 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AnalyzedMessageEvidence()",
"from .alert_evidence import AlertEvidence\nfrom .email_sender import EmailSender\nfrom .alert_evidence import AlertEvidence\nfrom .email_sender import EmailSender\nfields: Dict[str, Callable[[Any], None]] =... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AnalyzedMessageEvidence()
<|end_body_0|>
<|body_start_1|>
from .alert_evidence import AlertEvidence
from .email_sender import EmailSender
from .alert_evidence import AlertEvidenc... | AnalyzedMessageEvidence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyzedMessageEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AnalyzedMessageEvidence:
"""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 creat... | stack_v2_sparse_classes_75kplus_train_066006 | 7,115 | 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: AnalyzedMessageEvidence",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | null | Implement the Python class `AnalyzedMessageEvidence` described below.
Class description:
Implement the AnalyzedMessageEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AnalyzedMessageEvidence: Creates a new instance of the appropriate clas... | Implement the Python class `AnalyzedMessageEvidence` described below.
Class description:
Implement the AnalyzedMessageEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AnalyzedMessageEvidence: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AnalyzedMessageEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AnalyzedMessageEvidence:
"""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 creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalyzedMessageEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AnalyzedMessageEvidence:
"""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 R... | the_stack_v2_python_sparse | msgraph/generated/models/security/analyzed_message_evidence.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b05c89fdba66c10dbccbcac279ac924066219267 | [
"query = g.db.query(MatchTeam)\nquery = query.filter(MatchTeam.match_id == match_id)\nrows = query.all()\nret = []\nfor row in rows:\n record = row.as_dict()\n record['url'] = url_for('matches.team', match_id=match_id, team_id=row.team_id, _external=True)\n ret.append(record)\nreturn jsonify(ret)",
"args... | <|body_start_0|>
query = g.db.query(MatchTeam)
query = query.filter(MatchTeam.match_id == match_id)
rows = query.all()
ret = []
for row in rows:
record = row.as_dict()
record['url'] = url_for('matches.team', match_id=match_id, team_id=row.team_id, _externa... | All teams in a match | MatchTeamsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchTeamsAPI:
"""All teams in a match"""
def get(self, match_id):
"""Find teams by match"""
<|body_0|>
def post(self, match_id):
"""Add a team to a match"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = g.db.query(MatchTeam)
quer... | stack_v2_sparse_classes_75kplus_train_066007 | 24,829 | permissive | [
{
"docstring": "Find teams by match",
"name": "get",
"signature": "def get(self, match_id)"
},
{
"docstring": "Add a team to a match",
"name": "post",
"signature": "def post(self, match_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020413 | Implement the Python class `MatchTeamsAPI` described below.
Class description:
All teams in a match
Method signatures and docstrings:
- def get(self, match_id): Find teams by match
- def post(self, match_id): Add a team to a match | Implement the Python class `MatchTeamsAPI` described below.
Class description:
All teams in a match
Method signatures and docstrings:
- def get(self, match_id): Find teams by match
- def post(self, match_id): Add a team to a match
<|skeleton|>
class MatchTeamsAPI:
"""All teams in a match"""
def get(self, ma... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class MatchTeamsAPI:
"""All teams in a match"""
def get(self, match_id):
"""Find teams by match"""
<|body_0|>
def post(self, match_id):
"""Add a team to a match"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatchTeamsAPI:
"""All teams in a match"""
def get(self, match_id):
"""Find teams by match"""
query = g.db.query(MatchTeam)
query = query.filter(MatchTeam.match_id == match_id)
rows = query.all()
ret = []
for row in rows:
record = row.as_dict()
... | the_stack_v2_python_sparse | driftbase/api/matches.py | dgnorth/drift-base | train | 1 |
5c2ea34c6f1331fdbfeee9669b94540446661d59 | [
"from .service import send_gift_code\npurchase = Purchase()\npurchase.book = Book.objects.all()[0]\npurchase.buyer_user = User.objects.all()[0]\npurchase.recipient_email = 'friend@example.com'\npurchase.generate_gift_code()\nrequest = self.create_request()\nsend_gift_code(request, purchase)",
"from .service impor... | <|body_start_0|>
from .service import send_gift_code
purchase = Purchase()
purchase.book = Book.objects.all()[0]
purchase.buyer_user = User.objects.all()[0]
purchase.recipient_email = 'friend@example.com'
purchase.generate_gift_code()
request = self.create_request... | Service Test. | ServiceTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceTest:
"""Service Test."""
def test_send_gift_code(self):
"""Docstring."""
<|body_0|>
def test_send_invoice(self):
"""Docstring."""
<|body_1|>
def test_create_payment(self):
"""Docstring."""
<|body_2|>
def create_request(se... | stack_v2_sparse_classes_75kplus_train_066008 | 11,842 | no_license | [
{
"docstring": "Docstring.",
"name": "test_send_gift_code",
"signature": "def test_send_gift_code(self)"
},
{
"docstring": "Docstring.",
"name": "test_send_invoice",
"signature": "def test_send_invoice(self)"
},
{
"docstring": "Docstring.",
"name": "test_create_payment",
... | 4 | null | Implement the Python class `ServiceTest` described below.
Class description:
Service Test.
Method signatures and docstrings:
- def test_send_gift_code(self): Docstring.
- def test_send_invoice(self): Docstring.
- def test_create_payment(self): Docstring.
- def create_request(self): Docstring. | Implement the Python class `ServiceTest` described below.
Class description:
Service Test.
Method signatures and docstrings:
- def test_send_gift_code(self): Docstring.
- def test_send_invoice(self): Docstring.
- def test_create_payment(self): Docstring.
- def create_request(self): Docstring.
<|skeleton|>
class Serv... | ee6c8ec70e99c10b1056b28a3a219d7cda5faf06 | <|skeleton|>
class ServiceTest:
"""Service Test."""
def test_send_gift_code(self):
"""Docstring."""
<|body_0|>
def test_send_invoice(self):
"""Docstring."""
<|body_1|>
def test_create_payment(self):
"""Docstring."""
<|body_2|>
def create_request(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServiceTest:
"""Service Test."""
def test_send_gift_code(self):
"""Docstring."""
from .service import send_gift_code
purchase = Purchase()
purchase.book = Book.objects.all()[0]
purchase.buyer_user = User.objects.all()[0]
purchase.recipient_email = 'friend@e... | the_stack_v2_python_sparse | dwb_store/tests.py | ksbek/discleship | train | 0 |
3b5266a4acee04ad6a39a2efb0e8516bdc6c0a55 | [
"mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt, stddev_types)\nif imt == PGA():\n freq = 50.0\nelif imt == PGV():\n freq = 2.0\nelse:\n freq = 1.0 / imt.period\nx1 = np.min([-0.18 + 0.17 * np.log10(freq), 0])\nif rup.hypo_depth < 20.0:\n x0 = np.max([0.217 - 0.321 * np.log10(freq),... | <|body_start_0|>
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt, stddev_types)
if imt == PGA():
freq = 50.0
elif imt == PGV():
freq = 2.0
else:
freq = 1.0 / imt.period
x1 = np.min([-0.18 + 0.17 * np.log10(freq), 0])
... | Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No. 2, pp. 751–761 | Atkinson2010Hawaii | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Atkinson2010Hawaii:
"""Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No... | stack_v2_sparse_classes_75kplus_train_066009 | 18,299 | permissive | [
{
"docstring": "Using a frequency dependent correction for the mean ground motion. Standard deviation is fixed.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Return total standard deviation.",
"name": ... | 2 | stack_v2_sparse_classes_30k_test_001776 | Implement the Python class `Atkinson2010Hawaii` described below.
Class description:
Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismol... | Implement the Python class `Atkinson2010Hawaii` described below.
Class description:
Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismol... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Atkinson2010Hawaii:
"""Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Atkinson2010Hawaii:
"""Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No. 2, pp. 751–... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/boore_atkinson_2008.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
7a6a7c1f0a525445982c0b45ad78f07dc73118e3 | [
"name = f'GeneticAlgorithm_pop_size={population_size}_parents={parent_selection_strategy}'\nsuper().__init__(model, name, rounds, sequences_batch_size, model_queries_per_batch, starting_sequence, log_file)\nself.alphabet = alphabet\nself.population_size = population_size\nvalid_parent_selection_strategies = ['top-p... | <|body_start_0|>
name = f'GeneticAlgorithm_pop_size={population_size}_parents={parent_selection_strategy}'
super().__init__(model, name, rounds, sequences_batch_size, model_queries_per_batch, starting_sequence, log_file)
self.alphabet = alphabet
self.population_size = population_size
... | A genetic algorithm explorer with single point mutations and recombination. Based on the `parent_selection_strategy`, this class implements one of three genetic algorithms: 1. If `parent_selection_strategy == 'top-k'`, we have a traditional genetic algorithm where the top-k scoring sequences in the population become pa... | GeneticAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneticAlgorithm:
"""A genetic algorithm explorer with single point mutations and recombination. Based on the `parent_selection_strategy`, this class implements one of three genetic algorithms: 1. If `parent_selection_strategy == 'top-k'`, we have a traditional genetic algorithm where the top-k s... | stack_v2_sparse_classes_75kplus_train_066010 | 6,041 | permissive | [
{
"docstring": "Create genetic algorithm.",
"name": "__init__",
"signature": "def __init__(self, model: flexs.Model, rounds: int, starting_sequence: str, sequences_batch_size: int, model_queries_per_batch: int, alphabet: str, population_size: int, parent_selection_strategy: str, children_proportion: flo... | 3 | stack_v2_sparse_classes_30k_train_036487 | Implement the Python class `GeneticAlgorithm` described below.
Class description:
A genetic algorithm explorer with single point mutations and recombination. Based on the `parent_selection_strategy`, this class implements one of three genetic algorithms: 1. If `parent_selection_strategy == 'top-k'`, we have a traditio... | Implement the Python class `GeneticAlgorithm` described below.
Class description:
A genetic algorithm explorer with single point mutations and recombination. Based on the `parent_selection_strategy`, this class implements one of three genetic algorithms: 1. If `parent_selection_strategy == 'top-k'`, we have a traditio... | 744e792456d93e8c48fc58220689c0b4cff6ded9 | <|skeleton|>
class GeneticAlgorithm:
"""A genetic algorithm explorer with single point mutations and recombination. Based on the `parent_selection_strategy`, this class implements one of three genetic algorithms: 1. If `parent_selection_strategy == 'top-k'`, we have a traditional genetic algorithm where the top-k s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeneticAlgorithm:
"""A genetic algorithm explorer with single point mutations and recombination. Based on the `parent_selection_strategy`, this class implements one of three genetic algorithms: 1. If `parent_selection_strategy == 'top-k'`, we have a traditional genetic algorithm where the top-k scoring sequen... | the_stack_v2_python_sparse | flexs/baselines/explorers/genetic_algorithm.py | jonshao/FLEXS | train | 0 |
c0da60ab1afd1564f6656834f0e87d6c83bed35d | [
"maxprofit = 0\nlength = len(prices)\nfor i in range(length - 1):\n for j in range(i + 1, length):\n maxprofit = max(maxprofit, prices[j] - prices[i])\nreturn maxprofit",
"minprice, maxprofit = (float('inf'), 0)\nlength = len(prices)\nfor i in range(length):\n if prices[i] < minprice:\n minpri... | <|body_start_0|>
maxprofit = 0
length = len(prices)
for i in range(length - 1):
for j in range(i + 1, length):
maxprofit = max(maxprofit, prices[j] - prices[i])
return maxprofit
<|end_body_0|>
<|body_start_1|>
minprice, maxprofit = (float('inf'), 0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices) -> int:
"""暴力穷举任意两个元素之间的差值以得到最大值。 时间复杂度 : O(N**2)。循环运行n(n-1)/2次。 空间复杂度 : O(1)。只使用了一个变量。 :param root: :return:"""
<|body_0|>
def maxProfit_ergodic_once(self, prices):
"""一次遍历法 时间复杂度:O(N),只遍历一次。 空间复杂度:O(1),只使用了两个变量。 :param prices: ... | stack_v2_sparse_classes_75kplus_train_066011 | 2,766 | no_license | [
{
"docstring": "暴力穷举任意两个元素之间的差值以得到最大值。 时间复杂度 : O(N**2)。循环运行n(n-1)/2次。 空间复杂度 : O(1)。只使用了一个变量。 :param root: :return:",
"name": "maxProfit",
"signature": "def maxProfit(self, prices) -> int"
},
{
"docstring": "一次遍历法 时间复杂度:O(N),只遍历一次。 空间复杂度:O(1),只使用了两个变量。 :param prices: :return:",
"name": "maxPr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices) -> int: 暴力穷举任意两个元素之间的差值以得到最大值。 时间复杂度 : O(N**2)。循环运行n(n-1)/2次。 空间复杂度 : O(1)。只使用了一个变量。 :param root: :return:
- def maxProfit_ergodic_once(self, prices):... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices) -> int: 暴力穷举任意两个元素之间的差值以得到最大值。 时间复杂度 : O(N**2)。循环运行n(n-1)/2次。 空间复杂度 : O(1)。只使用了一个变量。 :param root: :return:
- def maxProfit_ergodic_once(self, prices):... | 62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c | <|skeleton|>
class Solution:
def maxProfit(self, prices) -> int:
"""暴力穷举任意两个元素之间的差值以得到最大值。 时间复杂度 : O(N**2)。循环运行n(n-1)/2次。 空间复杂度 : O(1)。只使用了一个变量。 :param root: :return:"""
<|body_0|>
def maxProfit_ergodic_once(self, prices):
"""一次遍历法 时间复杂度:O(N),只遍历一次。 空间复杂度:O(1),只使用了两个变量。 :param prices: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices) -> int:
"""暴力穷举任意两个元素之间的差值以得到最大值。 时间复杂度 : O(N**2)。循环运行n(n-1)/2次。 空间复杂度 : O(1)。只使用了一个变量。 :param root: :return:"""
maxprofit = 0
length = len(prices)
for i in range(length - 1):
for j in range(i + 1, length):
maxpr... | the_stack_v2_python_sparse | leetcode/solved/121_.py | usnnu/python_foundation | train | 0 | |
0b6558fcca757036f620f315ca78302b4fcd7f2c | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif not timestamp:\n return None\nreturn dfdatetime_posix_time.PosixTimeInMicroseconds(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = AndroidHangoutsMessageData()\nevent_data.body = self._GetRowValue(query_hash, row, 'text')\nevent_dat... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if not timestamp:
return None
return dfdatetime_posix_time.PosixTimeInMicroseconds(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = AndroidHangoutsMe... | SQLite parser plugin for Google Hangouts conversations database files. The Google Hangouts conversations database file is typically stored in: /data/com.google.android.talk/databases/babel.db This SQLite database is the conversation database for conversations, participant names, messages, and information about the Goog... | AndroidHangoutsMessagePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidHangoutsMessagePlugin:
"""SQLite parser plugin for Google Hangouts conversations database files. The Google Hangouts conversations database file is typically stored in: /data/com.google.android.talk/databases/babel.db This SQLite database is the conversation database for conversations, par... | stack_v2_sparse_classes_75kplus_train_066012 | 16,836 | permissive | [
{
"docstring": "Retrieves a POSIX time in microseconds 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.PosixTimeInMicroseconds: date and time va... | 2 | null | Implement the Python class `AndroidHangoutsMessagePlugin` described below.
Class description:
SQLite parser plugin for Google Hangouts conversations database files. The Google Hangouts conversations database file is typically stored in: /data/com.google.android.talk/databases/babel.db This SQLite database is the conve... | Implement the Python class `AndroidHangoutsMessagePlugin` described below.
Class description:
SQLite parser plugin for Google Hangouts conversations database files. The Google Hangouts conversations database file is typically stored in: /data/com.google.android.talk/databases/babel.db This SQLite database is the conve... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class AndroidHangoutsMessagePlugin:
"""SQLite parser plugin for Google Hangouts conversations database files. The Google Hangouts conversations database file is typically stored in: /data/com.google.android.talk/databases/babel.db This SQLite database is the conversation database for conversations, par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AndroidHangoutsMessagePlugin:
"""SQLite parser plugin for Google Hangouts conversations database files. The Google Hangouts conversations database file is typically stored in: /data/com.google.android.talk/databases/babel.db This SQLite database is the conversation database for conversations, participant name... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/android_hangouts.py | log2timeline/plaso | train | 1,506 |
3c0ce2bf58aeabbcb17fa76c2d382917c302a445 | [
"super().__init__(template_fn='joint_calling.html')\nself.title = 'Joint Calling Report'\nself.vcf = data\nself.table_html, self.table_options = self.create_datatable()\nself.create_html('joint_calling.html')",
"datatable = DataTable(self.vcf.df, 'jc')\ndatatable.datatable.datatable_options = {'scrollX': 'true', ... | <|body_start_0|>
super().__init__(template_fn='joint_calling.html')
self.title = 'Joint Calling Report'
self.vcf = data
self.table_html, self.table_options = self.create_datatable()
self.create_html('joint_calling.html')
<|end_body_0|>
<|body_start_1|>
datatable = DataTa... | Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter. | JointCallingModule | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_v... | stack_v2_sparse_classes_75kplus_train_066013 | 2,093 | permissive | [
{
"docstring": ".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_vcf_filter.Filtered_freebayes` object.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Variants detected section.",
"n... | 2 | stack_v2_sparse_classes_30k_train_027870 | Implement the Python class `JointCallingModule` described below.
Class description:
Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter.
Method signatures and docstrings:
- def __init__(self, data): .. rubric:: constructor :param data: it can be a csv filename created... | Implement the Python class `JointCallingModule` described below.
Class description:
Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter.
Method signatures and docstrings:
- def __init__(self, data): .. rubric:: constructor :param data: it can be a csv filename created... | 8717094493d1993debd079f324c540541dece70f | <|skeleton|>
class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_vcf_filter.Fil... | the_stack_v2_python_sparse | sequana/modules_report/joint_calling.py | sequana/sequana | train | 155 |
0290bfc2a9c3814eacc8a6bbd691442db278c343 | [
"self.print_help()\nmsg = 'ERROR: %s\\n\\n' % message\nprint(msg)\nraise Exception(msg)",
"print('')\nif file is None:\n file = sys.stdout\nself._print_message(self.format_help(), file)\nprint('\\nexamples:\\n python dimorphite_dl.py --smiles_file sample_molecules.smi\\n python dimorphite_dl.py --smiles \"CC... | <|body_start_0|>
self.print_help()
msg = 'ERROR: %s\n\n' % message
print(msg)
raise Exception(msg)
<|end_body_0|>
<|body_start_1|>
print('')
if file is None:
file = sys.stdout
self._print_message(self.format_help(), file)
print('\nexamples:\n ... | Overwrite default parse so it displays help file on error. See https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu | MyParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyParser:
"""Overwrite default parse so it displays help file on error. See https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu"""
def error(self, message):
"""Overwrites the default error message. :param messag... | stack_v2_sparse_classes_75kplus_train_066014 | 46,667 | permissive | [
{
"docstring": "Overwrites the default error message. :param message: The default error message.",
"name": "error",
"signature": "def error(self, message)"
},
{
"docstring": "Overwrite the default print_help function :param file: Output file, defaults to None",
"name": "print_help",
"sig... | 2 | null | Implement the Python class `MyParser` described below.
Class description:
Overwrite default parse so it displays help file on error. See https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu
Method signatures and docstrings:
- def error(self, mess... | Implement the Python class `MyParser` described below.
Class description:
Overwrite default parse so it displays help file on error. See https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu
Method signatures and docstrings:
- def error(self, mess... | 9981e25b00de29ed881b2229a173a8c812ded9bb | <|skeleton|>
class MyParser:
"""Overwrite default parse so it displays help file on error. See https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu"""
def error(self, message):
"""Overwrites the default error message. :param messag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyParser:
"""Overwrite default parse so it displays help file on error. See https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu"""
def error(self, message):
"""Overwrites the default error message. :param message: The defaul... | the_stack_v2_python_sparse | chemicaltoolbox/rdkit/dimorphite_dl.py | bgruening/galaxytools | train | 100 |
58a8e4d004361a7e995ccba9e298e746356aa980 | [
"self.ttype = ttype\nself.params = params\nself.params_explicit = params_explicit",
"single = False\nif coords.ndim == 1:\n coords = np.array([coords])\n single = True\nresult = TFUNCS[self.ttype](coords, self.params, inverse=False)\nif single:\n return result[0]\nreturn result",
"single = False\nif co... | <|body_start_0|>
self.ttype = ttype
self.params = params
self.params_explicit = params_explicit
<|end_body_0|>
<|body_start_1|>
single = False
if coords.ndim == 1:
coords = np.array([coords])
single = True
result = TFUNCS[self.ttype](coords, self.... | Transformation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformation:
def __init__(self, ttype, params, params_explicit=None):
"""Create transformation which allows you to do forward and inverse transformation and view the transformation parameters. :param ttype: similarity, bilinear, projective, polynomial, affine transformation type :para... | stack_v2_sparse_classes_75kplus_train_066015 | 18,435 | permissive | [
{
"docstring": "Create transformation which allows you to do forward and inverse transformation and view the transformation parameters. :param ttype: similarity, bilinear, projective, polynomial, affine transformation type :param params: :class:`numpy.array` transformation parameters :param params: :class:`nump... | 3 | stack_v2_sparse_classes_30k_train_044882 | Implement the Python class `Transformation` described below.
Class description:
Implement the Transformation class.
Method signatures and docstrings:
- def __init__(self, ttype, params, params_explicit=None): Create transformation which allows you to do forward and inverse transformation and view the transformation p... | Implement the Python class `Transformation` described below.
Class description:
Implement the Transformation class.
Method signatures and docstrings:
- def __init__(self, ttype, params, params_explicit=None): Create transformation which allows you to do forward and inverse transformation and view the transformation p... | 5e62e0419968adeb5291eed7012e62d52af14c7f | <|skeleton|>
class Transformation:
def __init__(self, ttype, params, params_explicit=None):
"""Create transformation which allows you to do forward and inverse transformation and view the transformation parameters. :param ttype: similarity, bilinear, projective, polynomial, affine transformation type :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformation:
def __init__(self, ttype, params, params_explicit=None):
"""Create transformation which allows you to do forward and inverse transformation and view the transformation parameters. :param ttype: similarity, bilinear, projective, polynomial, affine transformation type :param params: :cla... | the_stack_v2_python_sparse | code/transformations.py | vacancy/posewarp-cvpr2018 | train | 1 | |
e8d69fea767187a015bf76b82bcbe1c1b3e012d7 | [
"sample_n, feature_n = X.shape\nunused_features = np.ones(feature_n) == 1\nunclass_samples = np.ones(sample_n) == 1\nself.node = self._train_tree(X, Y, unused_features, unclass_samples)\nreturn self",
"logger.debug('train node -> X : < {} > Y : < {} >'.format(str(train_data).replace('\\n', ''), str(train_la... | <|body_start_0|>
sample_n, feature_n = X.shape
unused_features = np.ones(feature_n) == 1
unclass_samples = np.ones(sample_n) == 1
self.node = self._train_tree(X, Y, unused_features, unclass_samples)
return self
<|end_body_0|>
<|body_start_1|>
logger.debug('train node -> ... | ID3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ID3:
def fit(self, X, Y):
"""训练函数,X为二维array,Y为一维array"""
<|body_0|>
def _train_tree(self, train_data, train_labels, unused_features, unclass_samples):
"""递归调用用以创建树"""
<|body_1|>
def _find_split_feature(self, X, Y, unused_features, unclass_samples):
... | stack_v2_sparse_classes_75kplus_train_066016 | 4,988 | no_license | [
{
"docstring": "训练函数,X为二维array,Y为一维array",
"name": "fit",
"signature": "def fit(self, X, Y)"
},
{
"docstring": "递归调用用以创建树",
"name": "_train_tree",
"signature": "def _train_tree(self, train_data, train_labels, unused_features, unclass_samples)"
},
{
"docstring": "'寻找最优的拆分feature",... | 4 | stack_v2_sparse_classes_30k_train_041587 | Implement the Python class `ID3` described below.
Class description:
Implement the ID3 class.
Method signatures and docstrings:
- def fit(self, X, Y): 训练函数,X为二维array,Y为一维array
- def _train_tree(self, train_data, train_labels, unused_features, unclass_samples): 递归调用用以创建树
- def _find_split_feature(self, X, Y, unused_fe... | Implement the Python class `ID3` described below.
Class description:
Implement the ID3 class.
Method signatures and docstrings:
- def fit(self, X, Y): 训练函数,X为二维array,Y为一维array
- def _train_tree(self, train_data, train_labels, unused_features, unclass_samples): 递归调用用以创建树
- def _find_split_feature(self, X, Y, unused_fe... | 266f613fe2d5df3c0762061eb119386a9f6ea644 | <|skeleton|>
class ID3:
def fit(self, X, Y):
"""训练函数,X为二维array,Y为一维array"""
<|body_0|>
def _train_tree(self, train_data, train_labels, unused_features, unclass_samples):
"""递归调用用以创建树"""
<|body_1|>
def _find_split_feature(self, X, Y, unused_features, unclass_samples):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ID3:
def fit(self, X, Y):
"""训练函数,X为二维array,Y为一维array"""
sample_n, feature_n = X.shape
unused_features = np.ones(feature_n) == 1
unclass_samples = np.ones(sample_n) == 1
self.node = self._train_tree(X, Y, unused_features, unclass_samples)
return self
def _t... | the_stack_v2_python_sparse | ID3/id3.py | hxsylzpf/codes | train | 0 | |
14521b48035a5061348ce2e57415a8450e12f8ae | [
"assert self._version is not None\nif not hostname or not username or (not password):\n raise ValueError('hostname, username, and password are required')\nkwargs['hostname'] = hostname\nkwargs['username'] = username\nkwargs['password'] = password\nkwargs['version'] = self._version\nself._kwargs = kwargs\nself.co... | <|body_start_0|>
assert self._version is not None
if not hostname or not username or (not password):
raise ValueError('hostname, username, and password are required')
kwargs['hostname'] = hostname
kwargs['username'] = username
kwargs['password'] = password
kwa... | Use this object to talk to the REST interface of a Datera cluster | _DateraBaseApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DateraBaseApi:
"""Use this object to talk to the REST interface of a Datera cluster"""
def __init__(self, hostname, username=None, password=None, **kwargs):
"""Parameters: hostname (str) - IP address or host name username (str) - Username to log in with, e.g. "admin" password (str) ... | stack_v2_sparse_classes_75kplus_train_066017 | 5,460 | permissive | [
{
"docstring": "Parameters: hostname (str) - IP address or host name username (str) - Username to log in with, e.g. \"admin\" password (str) - Password to use when logging in to the cluster",
"name": "__init__",
"signature": "def __init__(self, hostname, username=None, password=None, **kwargs)"
},
{... | 2 | null | Implement the Python class `_DateraBaseApi` described below.
Class description:
Use this object to talk to the REST interface of a Datera cluster
Method signatures and docstrings:
- def __init__(self, hostname, username=None, password=None, **kwargs): Parameters: hostname (str) - IP address or host name username (str... | Implement the Python class `_DateraBaseApi` described below.
Class description:
Use this object to talk to the REST interface of a Datera cluster
Method signatures and docstrings:
- def __init__(self, hostname, username=None, password=None, **kwargs): Parameters: hostname (str) - IP address or host name username (str... | d9e20bea605a9e756ae3afdd28d6c4624b466ce2 | <|skeleton|>
class _DateraBaseApi:
"""Use this object to talk to the REST interface of a Datera cluster"""
def __init__(self, hostname, username=None, password=None, **kwargs):
"""Parameters: hostname (str) - IP address or host name username (str) - Username to log in with, e.g. "admin" password (str) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _DateraBaseApi:
"""Use this object to talk to the REST interface of a Datera cluster"""
def __init__(self, hostname, username=None, password=None, **kwargs):
"""Parameters: hostname (str) - IP address or host name username (str) - Username to log in with, e.g. "admin" password (str) - Password to... | the_stack_v2_python_sparse | src/dfs_sdk/api.py | Datera/python-sdk | train | 3 |
8ecbf02039a0d00678f57d4a2e25a8e1e1985a12 | [
"if S == '':\n return 0\nif S == '()':\n return 1\nscore = 0\nif S[0] == '(' and S[1] == '(':\n i = self.findSplit(S)\n temp1 = S[1:i]\n temp2 = S[i + 1:]\n score = 2 * self.scoreOfParentheses(temp1) + self.scoreOfParentheses(temp2)\nif S[0] == '(' and S[1] == ')':\n temp = S[2:]\n score = 1... | <|body_start_0|>
if S == '':
return 0
if S == '()':
return 1
score = 0
if S[0] == '(' and S[1] == '(':
i = self.findSplit(S)
temp1 = S[1:i]
temp2 = S[i + 1:]
score = 2 * self.scoreOfParentheses(temp1) + self.scoreOfP... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S):
""":type S: str :rtype: int"""
<|body_0|>
def findSplit(self, S):
""":type: str :rtype: int for example: S = '(())()' return 3"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if S == '':
return ... | stack_v2_sparse_classes_75kplus_train_066018 | 1,031 | no_license | [
{
"docstring": ":type S: str :rtype: int",
"name": "scoreOfParentheses",
"signature": "def scoreOfParentheses(self, S)"
},
{
"docstring": ":type: str :rtype: int for example: S = '(())()' return 3",
"name": "findSplit",
"signature": "def findSplit(self, S)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043086 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S): :type S: str :rtype: int
- def findSplit(self, S): :type: str :rtype: int for example: S = '(())()' return 3 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S): :type S: str :rtype: int
- def findSplit(self, S): :type: str :rtype: int for example: S = '(())()' return 3
<|skeleton|>
class Solution:
d... | a6d0e392134afe19d1aed2dfe7914b674e05ecc6 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S):
""":type S: str :rtype: int"""
<|body_0|>
def findSplit(self, S):
""":type: str :rtype: int for example: S = '(())()' return 3"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def scoreOfParentheses(self, S):
""":type S: str :rtype: int"""
if S == '':
return 0
if S == '()':
return 1
score = 0
if S[0] == '(' and S[1] == '(':
i = self.findSplit(S)
temp1 = S[1:i]
temp2 = S[i +... | the_stack_v2_python_sparse | 856ScoreParentheses.py | Ting007/leetcodePractice | train | 0 | |
7c64d4561f21fef5d52f8ce7f41bcbed15594343 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries:\n if not all((type(x) is dict for x in list_dictionaries)):\n raise TypeError('list must contain only dictionaries')\n return json.dumps(list_dictionaries)\nreturn json.d... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries:
if not all((type(x) is dict for x in list_dictionaries)):
raise TypeErr... | Base class of shapes Attributes: __nb_objects (int): class total instance count id (object): id of object Raises: | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Base class of shapes Attributes: __nb_objects (int): class total instance count id (object): id of object Raises:"""
def __init__(self, id=None):
"""initializer Args: id (object)"""
<|body_0|>
def to_json_string(list_dictionaries):
"""JSON string Args: l... | stack_v2_sparse_classes_75kplus_train_066019 | 2,963 | no_license | [
{
"docstring": "initializer Args: id (object)",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "JSON string Args: list_dictionaries (list): list of dicts",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docst... | 6 | stack_v2_sparse_classes_30k_train_052628 | Implement the Python class `Base` described below.
Class description:
Base class of shapes Attributes: __nb_objects (int): class total instance count id (object): id of object Raises:
Method signatures and docstrings:
- def __init__(self, id=None): initializer Args: id (object)
- def to_json_string(list_dictionaries)... | Implement the Python class `Base` described below.
Class description:
Base class of shapes Attributes: __nb_objects (int): class total instance count id (object): id of object Raises:
Method signatures and docstrings:
- def __init__(self, id=None): initializer Args: id (object)
- def to_json_string(list_dictionaries)... | 55ca661795dbbee94cc9cd984121cd471a493124 | <|skeleton|>
class Base:
"""Base class of shapes Attributes: __nb_objects (int): class total instance count id (object): id of object Raises:"""
def __init__(self, id=None):
"""initializer Args: id (object)"""
<|body_0|>
def to_json_string(list_dictionaries):
"""JSON string Args: l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Base class of shapes Attributes: __nb_objects (int): class total instance count id (object): id of object Raises:"""
def __init__(self, id=None):
"""initializer Args: id (object)"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | talktobrent/holbertonschool-higher_level_programming | train | 0 |
bb51235d110d77f7ce0332cea791ba0d4779e3c6 | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['lightRule_inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = CarInOutHandle(sentryLogin).getCarInRecord(send_data['carNum'], send_data['parkName'])\nresult = re[0]\nAssertions().assert_in_... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['lightRule_inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = CarInOutHandle(sentryLogin).getCarInRecord(send_data['car... | pc查看进出场记录 | TestSentryRecordInOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSentryRecordInOut:
"""pc查看进出场记录"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_recordIn(self, sentryLogin, send_data, expect):
"""在pc端查看进场记录"""
<|body_1|>
def test_mockCarout(self, send_data, expect):
"""模拟... | stack_v2_sparse_classes_75kplus_train_066020 | 2,413 | no_license | [
{
"docstring": "模拟进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, send_data, expect)"
},
{
"docstring": "在pc端查看进场记录",
"name": "test_recordIn",
"signature": "def test_recordIn(self, sentryLogin, send_data, expect)"
},
{
"docstring": "模拟离场",
"name": "test_... | 5 | stack_v2_sparse_classes_30k_train_026145 | Implement the Python class `TestSentryRecordInOut` described below.
Class description:
pc查看进出场记录
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟进场
- def test_recordIn(self, sentryLogin, send_data, expect): 在pc端查看进场记录
- def test_mockCarout(self, send_data, expect): 模拟离场
- def test_c... | Implement the Python class `TestSentryRecordInOut` described below.
Class description:
pc查看进出场记录
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟进场
- def test_recordIn(self, sentryLogin, send_data, expect): 在pc端查看进场记录
- def test_mockCarout(self, send_data, expect): 模拟离场
- def test_c... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestSentryRecordInOut:
"""pc查看进出场记录"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_recordIn(self, sentryLogin, send_data, expect):
"""在pc端查看进场记录"""
<|body_1|>
def test_mockCarout(self, send_data, expect):
"""模拟... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSentryRecordInOut:
"""pc查看进出场记录"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['lightRule_inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
... | the_stack_v2_python_sparse | test_suite/sentryDutyRoom/carInOutHandle/test_recordInAndOut.py | oyebino/pomp_api | train | 1 |
0211c3646d2ba7888dfbaa11bf12d5a6f254d778 | [
"result = [0, 0]\nl = len(A)\nL = [0] * (l + 1)\nfor i, a in enumerate(A):\n if i - a >= 0:\n L[i - a] += 1\ns = 0\nmax_index = l - 1\nfor i in range(l):\n print(L)\n a = L.pop(0)\n L.append(0)\n s -= a\n if max_index - A[i] >= 0:\n L[max_index - A[i]] += 1\n s += 1\n if s ... | <|body_start_0|>
result = [0, 0]
l = len(A)
L = [0] * (l + 1)
for i, a in enumerate(A):
if i - a >= 0:
L[i - a] += 1
s = 0
max_index = l - 1
for i in range(l):
print(L)
a = L.pop(0)
L.append(0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bestRotation(self, A):
""":type A: List[int] :rtype: int 880ms"""
<|body_0|>
def bestRotation_1(self, A):
""":type A: List[int] :rtype: int 119ms"""
<|body_1|>
def bestRotation_2(self, A):
"""127ms :param A: :return:"""
<|bo... | stack_v2_sparse_classes_75kplus_train_066021 | 3,416 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int 880ms",
"name": "bestRotation",
"signature": "def bestRotation(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int 119ms",
"name": "bestRotation_1",
"signature": "def bestRotation_1(self, A)"
},
{
"docstring": "127ms :param A... | 3 | stack_v2_sparse_classes_30k_val_002005 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bestRotation(self, A): :type A: List[int] :rtype: int 880ms
- def bestRotation_1(self, A): :type A: List[int] :rtype: int 119ms
- def bestRotation_2(self, A): 127ms :param A:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bestRotation(self, A): :type A: List[int] :rtype: int 880ms
- def bestRotation_1(self, A): :type A: List[int] :rtype: int 119ms
- def bestRotation_2(self, A): 127ms :param A:... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def bestRotation(self, A):
""":type A: List[int] :rtype: int 880ms"""
<|body_0|>
def bestRotation_1(self, A):
""":type A: List[int] :rtype: int 119ms"""
<|body_1|>
def bestRotation_2(self, A):
"""127ms :param A: :return:"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def bestRotation(self, A):
""":type A: List[int] :rtype: int 880ms"""
result = [0, 0]
l = len(A)
L = [0] * (l + 1)
for i, a in enumerate(A):
if i - a >= 0:
L[i - a] += 1
s = 0
max_index = l - 1
for i in range... | the_stack_v2_python_sparse | SmallestRotationWithHighestScore_HARD_798.py | 953250587/leetcode-python | train | 2 | |
04ea0e54f21c04dfcfc6f7f6927b8fc97c66fda8 | [
"super(Slice, self).__init__()\nself.slice = slice\nself.decoder = decoder\nself.axis = axis",
"channels = tf.shape(inputs)[self.axis]\nx1, x2 = tf.split(inputs, [self.slice, channels - self.slice], self.axis)\nz = x1\nsample = self.decoder(z)\nldj = Normal(x2).log_prob(sample)\nreturn (z, ldj)",
"channels = tf... | <|body_start_0|>
super(Slice, self).__init__()
self.slice = slice
self.decoder = decoder
self.axis = axis
<|end_body_0|>
<|body_start_1|>
channels = tf.shape(inputs)[self.axis]
x1, x2 = tf.split(inputs, [self.slice, channels - self.slice], self.axis)
z = x1
... | Tensor slice for inference surjection. | Slice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slice:
"""Tensor slice for inference surjection."""
def __init__(self, slice, decoder, axis=-1):
"""Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator. axis: int, slice axis."""
<|body_0|>
def call(self, inputs):
"""Slice t... | stack_v2_sparse_classes_75kplus_train_066022 | 4,364 | permissive | [
{
"docstring": "Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator. axis: int, slice axis.",
"name": "__init__",
"signature": "def __init__(self, slice, decoder, axis=-1)"
},
{
"docstring": "Slice the input tensor. Args: inputs: tf.Tensor, [tf.float32; [B,... | 4 | null | Implement the Python class `Slice` described below.
Class description:
Tensor slice for inference surjection.
Method signatures and docstrings:
- def __init__(self, slice, decoder, axis=-1): Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator. axis: int, slice axis.
- def call(s... | Implement the Python class `Slice` described below.
Class description:
Tensor slice for inference surjection.
Method signatures and docstrings:
- def __init__(self, slice, decoder, axis=-1): Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator. axis: int, slice axis.
- def call(s... | 950a06c5e85ffedec6a024e81dc5fae557e2aae8 | <|skeleton|>
class Slice:
"""Tensor slice for inference surjection."""
def __init__(self, slice, decoder, axis=-1):
"""Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator. axis: int, slice axis."""
<|body_0|>
def call(self, inputs):
"""Slice t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Slice:
"""Tensor slice for inference surjection."""
def __init__(self, slice, decoder, axis=-1):
"""Initializer. Args: slice: int, slice size. decoder: tf.keras.Model, posterior approximator. axis: int, slice axis."""
super(Slice, self).__init__()
self.slice = slice
self.d... | the_stack_v2_python_sparse | survaeflow/transform/surjection/slice.py | revsic/tf-survae-flows | train | 2 |
3579c66892292d00d545b5b26c8bfebafd0d67db | [
"self.params = params_init.get_params_list('test_MonitoringSupervise')\ndatas = {'url': self.params['MessageInfo'][CASEID]['url'], 'json': self.params['MessageInfo'][CASEID]['json'], 'headers': self.params['MessageInfo'][CASEID]['header'], 'method': self.params['MessageInfo'][CASEID]['method']}\ndatas['json']['conn... | <|body_start_0|>
self.params = params_init.get_params_list('test_MonitoringSupervise')
datas = {'url': self.params['MessageInfo'][CASEID]['url'], 'json': self.params['MessageInfo'][CASEID]['json'], 'headers': self.params['MessageInfo'][CASEID]['header'], 'method': self.params['MessageInfo'][CASEID]['met... | Test_MapIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_MapIndex:
def test_getMonitorByMultipleMatching_pass(self, request_init, assert_init, params_init, connectStatus, runStatus, deviceStatus, enabled, target, type, searchName):
"""用例描述:监控中心和监测点管理下获取设备的卡片信息以及头部的建筑信息正向用例"""
<|body_0|>
def test_getMonitorByMultipleMatching_s... | stack_v2_sparse_classes_75kplus_train_066023 | 4,444 | no_license | [
{
"docstring": "用例描述:监控中心和监测点管理下获取设备的卡片信息以及头部的建筑信息正向用例",
"name": "test_getMonitorByMultipleMatching_pass",
"signature": "def test_getMonitorByMultipleMatching_pass(self, request_init, assert_init, params_init, connectStatus, runStatus, deviceStatus, enabled, target, type, searchName)"
},
{
"docs... | 2 | null | Implement the Python class `Test_MapIndex` described below.
Class description:
Implement the Test_MapIndex class.
Method signatures and docstrings:
- def test_getMonitorByMultipleMatching_pass(self, request_init, assert_init, params_init, connectStatus, runStatus, deviceStatus, enabled, target, type, searchName): 用例描... | Implement the Python class `Test_MapIndex` described below.
Class description:
Implement the Test_MapIndex class.
Method signatures and docstrings:
- def test_getMonitorByMultipleMatching_pass(self, request_init, assert_init, params_init, connectStatus, runStatus, deviceStatus, enabled, target, type, searchName): 用例描... | f0311b8b4ddd9e8194b973edac9a574d71285e15 | <|skeleton|>
class Test_MapIndex:
def test_getMonitorByMultipleMatching_pass(self, request_init, assert_init, params_init, connectStatus, runStatus, deviceStatus, enabled, target, type, searchName):
"""用例描述:监控中心和监测点管理下获取设备的卡片信息以及头部的建筑信息正向用例"""
<|body_0|>
def test_getMonitorByMultipleMatching_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_MapIndex:
def test_getMonitorByMultipleMatching_pass(self, request_init, assert_init, params_init, connectStatus, runStatus, deviceStatus, enabled, target, type, searchName):
"""用例描述:监控中心和监测点管理下获取设备的卡片信息以及头部的建筑信息正向用例"""
self.params = params_init.get_params_list('test_MonitoringSupervise')... | the_stack_v2_python_sparse | case/test_MonitoringSupervise/test_basicData_getMonitorByMultipleMatching.py | Mceng/FireSafetySystem | train | 0 | |
a1985af3fd7ab6331761630e066f5825900bbe66 | [
"ns_url = 'http://www.example.com/foo/namespace.txt'\nrelative_url = 'bar.txt'\nfinal_url = 'http://www.example.com/foo/bar.txt'\nx = lncore.basic_relative_url_handling_behavior(relative_url, ns_url)\nassert x == final_url",
"ns_url = 'http://www.example.com/foo/namespace.txt'\nabsolute_url = 'http://www.example.... | <|body_start_0|>
ns_url = 'http://www.example.com/foo/namespace.txt'
relative_url = 'bar.txt'
final_url = 'http://www.example.com/foo/bar.txt'
x = lncore.basic_relative_url_handling_behavior(relative_url, ns_url)
assert x == final_url
<|end_body_0|>
<|body_start_1|>
ns_u... | DOC DOC DOC | TestBasicRelativeURLHandlingBehavior | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBasicRelativeURLHandlingBehavior:
"""DOC DOC DOC"""
def testBasic(self):
"""Test that basic relative URL handling behavior works."""
<|body_0|>
def testPassingAnAbsolute(self):
"""Test that absolute URLs are not handled specially."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_066024 | 34,773 | no_license | [
{
"docstring": "Test that basic relative URL handling behavior works.",
"name": "testBasic",
"signature": "def testBasic(self)"
},
{
"docstring": "Test that absolute URLs are not handled specially.",
"name": "testPassingAnAbsolute",
"signature": "def testPassingAnAbsolute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023628 | Implement the Python class `TestBasicRelativeURLHandlingBehavior` described below.
Class description:
DOC DOC DOC
Method signatures and docstrings:
- def testBasic(self): Test that basic relative URL handling behavior works.
- def testPassingAnAbsolute(self): Test that absolute URLs are not handled specially. | Implement the Python class `TestBasicRelativeURLHandlingBehavior` described below.
Class description:
DOC DOC DOC
Method signatures and docstrings:
- def testBasic(self): Test that basic relative URL handling behavior works.
- def testPassingAnAbsolute(self): Test that absolute URLs are not handled specially.
<|skel... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class TestBasicRelativeURLHandlingBehavior:
"""DOC DOC DOC"""
def testBasic(self):
"""Test that basic relative URL handling behavior works."""
<|body_0|>
def testPassingAnAbsolute(self):
"""Test that absolute URLs are not handled specially."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestBasicRelativeURLHandlingBehavior:
"""DOC DOC DOC"""
def testBasic(self):
"""Test that basic relative URL handling behavior works."""
ns_url = 'http://www.example.com/foo/namespace.txt'
relative_url = 'bar.txt'
final_url = 'http://www.example.com/foo/bar.txt'
x ... | the_stack_v2_python_sparse | pre2007/lncore/test.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
4a1067d22edebd9066945a9626f60e6ec529575a | [
"super().__init__()\nself._subdags: List = []\nself.initial_layout = None\nself.gate = qiskit.circuit.library.CXGate\nself.decomposition = QuantumCircuit(2)\nif mode == 'ry':\n self.decomposition.ry(-np.pi / 2, 1)\n self.decomposition.cz(0, 1)\n self.decomposition.ry(np.pi / 2, 1)\nelse:\n self.decompos... | <|body_start_0|>
super().__init__()
self._subdags: List = []
self.initial_layout = None
self.gate = qiskit.circuit.library.CXGate
self.decomposition = QuantumCircuit(2)
if mode == 'ry':
self.decomposition.ry(-np.pi / 2, 1)
self.decomposition.cz(0, ... | Decompose CX into CZ and single qubit rotations | DecomposeCX | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecomposeCX:
"""Decompose CX into CZ and single qubit rotations"""
def __init__(self, mode: str='ry'):
"""Args:"""
<|body_0|>
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the Decompose pass on `dag`. Args: dag: input dag. Returns: output dag where ``CX`` ... | stack_v2_sparse_classes_75kplus_train_066025 | 14,382 | permissive | [
{
"docstring": "Args:",
"name": "__init__",
"signature": "def __init__(self, mode: str='ry')"
},
{
"docstring": "Run the Decompose pass on `dag`. Args: dag: input dag. Returns: output dag where ``CX`` was expanded.",
"name": "run",
"signature": "def run(self, dag: DAGCircuit) -> DAGCircu... | 2 | stack_v2_sparse_classes_30k_train_011248 | Implement the Python class `DecomposeCX` described below.
Class description:
Decompose CX into CZ and single qubit rotations
Method signatures and docstrings:
- def __init__(self, mode: str='ry'): Args:
- def run(self, dag: DAGCircuit) -> DAGCircuit: Run the Decompose pass on `dag`. Args: dag: input dag. Returns: out... | Implement the Python class `DecomposeCX` described below.
Class description:
Decompose CX into CZ and single qubit rotations
Method signatures and docstrings:
- def __init__(self, mode: str='ry'): Args:
- def run(self, dag: DAGCircuit) -> DAGCircuit: Run the Decompose pass on `dag`. Args: dag: input dag. Returns: out... | 208c9c53309e10484e9883d537b53282cb83a43d | <|skeleton|>
class DecomposeCX:
"""Decompose CX into CZ and single qubit rotations"""
def __init__(self, mode: str='ry'):
"""Args:"""
<|body_0|>
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the Decompose pass on `dag`. Args: dag: input dag. Returns: output dag where ``CX`` ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecomposeCX:
"""Decompose CX into CZ and single qubit rotations"""
def __init__(self, mode: str='ry'):
"""Args:"""
super().__init__()
self._subdags: List = []
self.initial_layout = None
self.gate = qiskit.circuit.library.CXGate
self.decomposition = QuantumC... | the_stack_v2_python_sparse | src/qtt/qiskit/passes.py | QuTech-Delft/qtt | train | 58 |
3206f79e4e1ce38fdd487c14f24c2bc59bbdac57 | [
"super(Glimmer, self).__init__(general_options)\nself.__glimmer_options = glimmer_options\nself.__preliminary_tools_dict = preliminary_tools",
"os.system('mkdir -p {}'.format(self.get_output_path()))\nos.chdir('{}'.format(self.get_output_path()))\nself.launch_preliminary_tools(self.PRELIMINARY_TOOLS, self.__preli... | <|body_start_0|>
super(Glimmer, self).__init__(general_options)
self.__glimmer_options = glimmer_options
self.__preliminary_tools_dict = preliminary_tools
<|end_body_0|>
<|body_start_1|>
os.system('mkdir -p {}'.format(self.get_output_path()))
os.chdir('{}'.format(self.get_output... | Check options and launch Glimmer software. Launch Glimmer with start(). Glimmer inherit from CDSFindingTool. Static variables for Glimmer class are: OPTIONS_PROPERTIES, NAME, PRELIMINARY_TOOLS. | Glimmer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Glimmer:
"""Check options and launch Glimmer software. Launch Glimmer with start(). Glimmer inherit from CDSFindingTool. Static variables for Glimmer class are: OPTIONS_PROPERTIES, NAME, PRELIMINARY_TOOLS."""
def __init__(self, general_options, glimmer_options, preliminary_tools):
""... | stack_v2_sparse_classes_75kplus_train_066026 | 7,197 | no_license | [
{
"docstring": "Initialize the glimmer_options and preliminary_tools_dict object. Private Attributes: glimmer_options is an OptionList which contain only Glimmer's options. preliminary-tools_dict is a dictionary which has glimmer's preliminary tools's names as keys and their options (OptionList) as values.",
... | 3 | stack_v2_sparse_classes_30k_train_014302 | Implement the Python class `Glimmer` described below.
Class description:
Check options and launch Glimmer software. Launch Glimmer with start(). Glimmer inherit from CDSFindingTool. Static variables for Glimmer class are: OPTIONS_PROPERTIES, NAME, PRELIMINARY_TOOLS.
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `Glimmer` described below.
Class description:
Check options and launch Glimmer software. Launch Glimmer with start(). Glimmer inherit from CDSFindingTool. Static variables for Glimmer class are: OPTIONS_PROPERTIES, NAME, PRELIMINARY_TOOLS.
Method signatures and docstrings:
- def __init__(se... | 0377235647a1139a33dc0bffca4c6aa5ef665f6b | <|skeleton|>
class Glimmer:
"""Check options and launch Glimmer software. Launch Glimmer with start(). Glimmer inherit from CDSFindingTool. Static variables for Glimmer class are: OPTIONS_PROPERTIES, NAME, PRELIMINARY_TOOLS."""
def __init__(self, general_options, glimmer_options, preliminary_tools):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Glimmer:
"""Check options and launch Glimmer software. Launch Glimmer with start(). Glimmer inherit from CDSFindingTool. Static variables for Glimmer class are: OPTIONS_PROPERTIES, NAME, PRELIMINARY_TOOLS."""
def __init__(self, general_options, glimmer_options, preliminary_tools):
"""Initialize t... | the_stack_v2_python_sparse | src/tool/Glimmer.py | lucgiffon/GASBI-PIB | train | 0 |
5476b9e64be080afca0bce081b12865b342192d7 | [
"self._remote_control_property = device_instance.remote_control_property[element_uid]\nsuper().__init__(homecontrol=homecontrol, device_instance=device_instance, element_uid=f'{element_uid}_{key}')\nself._key = key\nself._attr_is_on = False\nself._attr_name = f'Button {key}'",
"if message[0] == self._remote_contr... | <|body_start_0|>
self._remote_control_property = device_instance.remote_control_property[element_uid]
super().__init__(homecontrol=homecontrol, device_instance=device_instance, element_uid=f'{element_uid}_{key}')
self._key = key
self._attr_is_on = False
self._attr_name = f'Button... | Representation of a remote control within devolo Home Control. | DevoloRemoteControl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DevoloRemoteControl:
"""Representation of a remote control within devolo Home Control."""
def __init__(self, homecontrol: HomeControl, device_instance: Zwave, element_uid: str, key: int) -> None:
"""Initialize a devolo remote control."""
<|body_0|>
def _sync(self, messag... | stack_v2_sparse_classes_75kplus_train_066027 | 5,255 | permissive | [
{
"docstring": "Initialize a devolo remote control.",
"name": "__init__",
"signature": "def __init__(self, homecontrol: HomeControl, device_instance: Zwave, element_uid: str, key: int) -> None"
},
{
"docstring": "Update the binary sensor state.",
"name": "_sync",
"signature": "def _sync(... | 2 | null | Implement the Python class `DevoloRemoteControl` described below.
Class description:
Representation of a remote control within devolo Home Control.
Method signatures and docstrings:
- def __init__(self, homecontrol: HomeControl, device_instance: Zwave, element_uid: str, key: int) -> None: Initialize a devolo remote c... | Implement the Python class `DevoloRemoteControl` described below.
Class description:
Representation of a remote control within devolo Home Control.
Method signatures and docstrings:
- def __init__(self, homecontrol: HomeControl, device_instance: Zwave, element_uid: str, key: int) -> None: Initialize a devolo remote c... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DevoloRemoteControl:
"""Representation of a remote control within devolo Home Control."""
def __init__(self, homecontrol: HomeControl, device_instance: Zwave, element_uid: str, key: int) -> None:
"""Initialize a devolo remote control."""
<|body_0|>
def _sync(self, messag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DevoloRemoteControl:
"""Representation of a remote control within devolo Home Control."""
def __init__(self, homecontrol: HomeControl, device_instance: Zwave, element_uid: str, key: int) -> None:
"""Initialize a devolo remote control."""
self._remote_control_property = device_instance.rem... | the_stack_v2_python_sparse | homeassistant/components/devolo_home_control/binary_sensor.py | home-assistant/core | train | 35,501 |
2f585eb8c42befc50b6e401394555a5923a62649 | [
"super().__init__(name=name or 'mlp')\nnum_dense_layers = get_num_dense_layers(model_size, override=num_dense_layers)\ndense_hidden_units = get_dense_hidden_units(model_size, override=dense_hidden_units)\nself.dense_layers = []\nfor _ in range(num_dense_layers):\n self.dense_layers.append(tf.keras.layers.Dense(d... | <|body_start_0|>
super().__init__(name=name or 'mlp')
num_dense_layers = get_num_dense_layers(model_size, override=num_dense_layers)
dense_hidden_units = get_dense_hidden_units(model_size, override=dense_hidden_units)
self.dense_layers = []
for _ in range(num_dense_layers):
... | An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. MLP=multi-layer perceptron. See Appendix B in [1] for the MLP sizes depending on the given `model_size`. | MLP | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. MLP=multi-layer perceptron. See Appendix B in [1] for the MLP sizes depending on the given `model_size`."""
def __init__(self, *, model_size: Optional[str]='XS', num_dense_layers: Optional[int]=None, de... | stack_v2_sparse_classes_75kplus_train_066028 | 3,647 | permissive | [
{
"docstring": "Initializes an MLP instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Use None for manually setting the different network sizes. num_dense_layers: The number of hidden layers in the MLP. If None, will use `model_size` and appendix B to figure out this value. dense_... | 2 | null | Implement the Python class `MLP` described below.
Class description:
An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. MLP=multi-layer perceptron. See Appendix B in [1] for the MLP sizes depending on the given `model_size`.
Method signatures and docstrings:
- def __init__(self, *, mode... | Implement the Python class `MLP` described below.
Class description:
An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. MLP=multi-layer perceptron. See Appendix B in [1] for the MLP sizes depending on the given `model_size`.
Method signatures and docstrings:
- def __init__(self, *, mode... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class MLP:
"""An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. MLP=multi-layer perceptron. See Appendix B in [1] for the MLP sizes depending on the given `model_size`."""
def __init__(self, *, model_size: Optional[str]='XS', num_dense_layers: Optional[int]=None, de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
"""An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. MLP=multi-layer perceptron. See Appendix B in [1] for the MLP sizes depending on the given `model_size`."""
def __init__(self, *, model_size: Optional[str]='XS', num_dense_layers: Optional[int]=None, dense_hidden_un... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/mlp.py | ray-project/ray | train | 29,482 |
5e94d1c1b9cc3634fe69697102b1141a4621e536 | [
"try:\n build_ext.run(self)\nexcept errors.DistutilsPlatformError:\n raise BuildFailed()",
"try:\n build_ext.build_extension(self, ext)\nexcept ext_errors:\n raise BuildFailed()\nexcept ValueError:\n if \"'path'\" in str(sys.exc_info()[1]):\n raise BuildFailed()\n raise"
] | <|body_start_0|>
try:
build_ext.run(self)
except errors.DistutilsPlatformError:
raise BuildFailed()
<|end_body_0|>
<|body_start_1|>
try:
build_ext.build_extension(self, ext)
except ext_errors:
raise BuildFailed()
except ValueError:... | Build C extensions, but fail with a straightforward exception. | ve_build_ext | [
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ve_build_ext:
"""Build C extensions, but fail with a straightforward exception."""
def run(self):
"""Wrap `run` with `BuildFailed`."""
<|body_0|>
def build_extension(self, ext):
"""Wrap `build_extension` with `BuildFailed`."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_066029 | 6,151 | permissive | [
{
"docstring": "Wrap `run` with `BuildFailed`.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Wrap `build_extension` with `BuildFailed`.",
"name": "build_extension",
"signature": "def build_extension(self, ext)"
}
] | 2 | null | Implement the Python class `ve_build_ext` described below.
Class description:
Build C extensions, but fail with a straightforward exception.
Method signatures and docstrings:
- def run(self): Wrap `run` with `BuildFailed`.
- def build_extension(self, ext): Wrap `build_extension` with `BuildFailed`. | Implement the Python class `ve_build_ext` described below.
Class description:
Build C extensions, but fail with a straightforward exception.
Method signatures and docstrings:
- def run(self): Wrap `run` with `BuildFailed`.
- def build_extension(self, ext): Wrap `build_extension` with `BuildFailed`.
<|skeleton|>
clas... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class ve_build_ext:
"""Build C extensions, but fail with a straightforward exception."""
def run(self):
"""Wrap `run` with `BuildFailed`."""
<|body_0|>
def build_extension(self, ext):
"""Wrap `build_extension` with `BuildFailed`."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ve_build_ext:
"""Build C extensions, but fail with a straightforward exception."""
def run(self):
"""Wrap `run` with `BuildFailed`."""
try:
build_ext.run(self)
except errors.DistutilsPlatformError:
raise BuildFailed()
def build_extension(self, ext):
... | the_stack_v2_python_sparse | third_party/pycoverage/setup.py | chromium/chromium | train | 17,408 |
705b722c06b993b6d9034b17d6dd551b0b796a2c | [
"super().__init__(root, split=split, mode='fine', target_type=target_type)\nself._transforms = transforms\nself.load_license_plates = load_license_plates",
"for named_tup in Cityscapes.classes:\n if named_tup.name == name:\n return named_tup.id\nreturn None",
"for named_tup in Cityscapes.classes:\n ... | <|body_start_0|>
super().__init__(root, split=split, mode='fine', target_type=target_type)
self._transforms = transforms
self.load_license_plates = load_license_plates
<|end_body_0|>
<|body_start_1|>
for named_tup in Cityscapes.classes:
if named_tup.name == name:
... | Cityscapes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cityscapes:
def __init__(self, root, split='train', target_type='semantic', load_license_plates=False, transforms=None):
"""Supports only the "fine" quality mode of Cityscapes Arguments: root (string): Root directory of the Cityscapes Dataset split (string, optional): Options are train, ... | stack_v2_sparse_classes_75kplus_train_066030 | 4,856 | permissive | [
{
"docstring": "Supports only the \"fine\" quality mode of Cityscapes Arguments: root (string): Root directory of the Cityscapes Dataset split (string, optional): Options are train, test, val target_type (string or list, optional): Can be instance, semantic, polygon or color. Specify a list of these to load the... | 4 | stack_v2_sparse_classes_30k_train_045735 | Implement the Python class `Cityscapes` described below.
Class description:
Implement the Cityscapes class.
Method signatures and docstrings:
- def __init__(self, root, split='train', target_type='semantic', load_license_plates=False, transforms=None): Supports only the "fine" quality mode of Cityscapes Arguments: ro... | Implement the Python class `Cityscapes` described below.
Class description:
Implement the Cityscapes class.
Method signatures and docstrings:
- def __init__(self, root, split='train', target_type='semantic', load_license_plates=False, transforms=None): Supports only the "fine" quality mode of Cityscapes Arguments: ro... | 37d5b4c41a83f15554994bf7d19d8d274282ee61 | <|skeleton|>
class Cityscapes:
def __init__(self, root, split='train', target_type='semantic', load_license_plates=False, transforms=None):
"""Supports only the "fine" quality mode of Cityscapes Arguments: root (string): Root directory of the Cityscapes Dataset split (string, optional): Options are train, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cityscapes:
def __init__(self, root, split='train', target_type='semantic', load_license_plates=False, transforms=None):
"""Supports only the "fine" quality mode of Cityscapes Arguments: root (string): Root directory of the Cityscapes Dataset split (string, optional): Options are train, test, val targ... | the_stack_v2_python_sparse | vector_cv_tools/datasets/cityscapes.py | VectorInstitute/vector_cv_tools | train | 6 | |
2fbf04e6b6fa581501936f300a3f6246c575340f | [
"super(Feedback, self).__init__()\nn_top_modalities = len(bottom_modality_sizes)\nself.use_self = use_self\nif not use_self:\n n_top_modalities = n_top_modalities - 1\nself.feedback_units = nn.ModuleList([_make_feedback_unit(top_size, bottom_modality_sizes[i], n_top_modalities, mask_type=mask_type, **kwargs) for... | <|body_start_0|>
super(Feedback, self).__init__()
n_top_modalities = len(bottom_modality_sizes)
self.use_self = use_self
if not use_self:
n_top_modalities = n_top_modalities - 1
self.feedback_units = nn.ModuleList([_make_feedback_unit(top_size, bottom_modality_sizes[i... | Feedback | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Feedback:
def __init__(self, top_size: int, bottom_modality_sizes: List[int], use_self: bool=False, mask_type: str='rnn', **kwargs):
"""Feedback module Given a list of low-level features and top-level representations for n modalities: * Create top-down masks for each modality * Apply top... | stack_v2_sparse_classes_75kplus_train_066031 | 12,286 | permissive | [
{
"docstring": "Feedback module Given a list of low-level features and top-level representations for n modalities: * Create top-down masks for each modality * Apply top-down masks to the low level features * Return masked low-level features Args: top_size (int): Feature size for top-level representations (Commo... | 2 | null | Implement the Python class `Feedback` described below.
Class description:
Implement the Feedback class.
Method signatures and docstrings:
- def __init__(self, top_size: int, bottom_modality_sizes: List[int], use_self: bool=False, mask_type: str='rnn', **kwargs): Feedback module Given a list of low-level features and ... | Implement the Python class `Feedback` described below.
Class description:
Implement the Feedback class.
Method signatures and docstrings:
- def __init__(self, top_size: int, bottom_modality_sizes: List[int], use_self: bool=False, mask_type: str='rnn', **kwargs): Feedback module Given a list of low-level features and ... | e4987310ed277abdec19462bdd749e2e7a000bec | <|skeleton|>
class Feedback:
def __init__(self, top_size: int, bottom_modality_sizes: List[int], use_self: bool=False, mask_type: str='rnn', **kwargs):
"""Feedback module Given a list of low-level features and top-level representations for n modalities: * Create top-down masks for each modality * Apply top... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Feedback:
def __init__(self, top_size: int, bottom_modality_sizes: List[int], use_self: bool=False, mask_type: str='rnn', **kwargs):
"""Feedback module Given a list of low-level features and top-level representations for n modalities: * Create top-down masks for each modality * Apply top-down masks to... | the_stack_v2_python_sparse | slp/modules/feedback.py | georgepar/slp | train | 26 | |
d3a16e3c10229928852c92c48944f783d474906f | [
"action = 'document-request-decline'\npermissions = current_app.config['ILS_VIEWS_PERMISSIONS_FACTORY']\nview_permission = permissions(action)\nreturn view_permission(record)",
"data = self.loader()\ndecline_reason = data.get('decline_reason')\ndocument_pid = data.get('document_pid')\nif record['state'] != 'PENDI... | <|body_start_0|>
action = 'document-request-decline'
permissions = current_app.config['ILS_VIEWS_PERMISSIONS_FACTORY']
view_permission = permissions(action)
return view_permission(record)
<|end_body_0|>
<|body_start_1|>
data = self.loader()
decline_reason = data.get('dec... | Decline request resource. | DocumentRequestDeclineResource | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentRequestDeclineResource:
"""Decline request resource."""
def decline_permission_factory(self, record):
"""Decline permission factory."""
<|body_0|>
def post(self, pid, record, **kwargs):
"""Decline request post method."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_066032 | 9,544 | permissive | [
{
"docstring": "Decline permission factory.",
"name": "decline_permission_factory",
"signature": "def decline_permission_factory(self, record)"
},
{
"docstring": "Decline request post method.",
"name": "post",
"signature": "def post(self, pid, record, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002785 | Implement the Python class `DocumentRequestDeclineResource` described below.
Class description:
Decline request resource.
Method signatures and docstrings:
- def decline_permission_factory(self, record): Decline permission factory.
- def post(self, pid, record, **kwargs): Decline request post method. | Implement the Python class `DocumentRequestDeclineResource` described below.
Class description:
Decline request resource.
Method signatures and docstrings:
- def decline_permission_factory(self, record): Decline permission factory.
- def post(self, pid, record, **kwargs): Decline request post method.
<|skeleton|>
cl... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class DocumentRequestDeclineResource:
"""Decline request resource."""
def decline_permission_factory(self, record):
"""Decline permission factory."""
<|body_0|>
def post(self, pid, record, **kwargs):
"""Decline request post method."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentRequestDeclineResource:
"""Decline request resource."""
def decline_permission_factory(self, record):
"""Decline permission factory."""
action = 'document-request-decline'
permissions = current_app.config['ILS_VIEWS_PERMISSIONS_FACTORY']
view_permission = permissio... | the_stack_v2_python_sparse | invenio_app_ils/document_requests/views.py | inveniosoftware/invenio-app-ils | train | 64 |
44774604633720cffa1821f03c19e8806464237c | [
"pygame.sprite.Sprite.__init__(self)\nlog('Creating an actor with file format: %s' % file_path_format)\nself.game = game\nself._cur_angle = 0\nspritesheet_file = random.choice(settings.ZOMBIE_SPRITES)\nspritesheet_file = data.filepath(spritesheet_file_name)\nspritesheet = utilities.spritesheet(spritesheet_file)\nse... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
log('Creating an actor with file format: %s' % file_path_format)
self.game = game
self._cur_angle = 0
spritesheet_file = random.choice(settings.ZOMBIE_SPRITES)
spritesheet_file = data.filepath(spritesheet_file_name)
... | Actor in our game. A helper class to load the sprite sheet and handle degrees. | SpriteActor | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpriteActor:
"""Actor in our game. A helper class to load the sprite sheet and handle degrees."""
def __init__(self, game, spritesheet, start_position_func=None):
"""Load all the degree logic."""
<|body_0|>
def turn(self, towards_x, towards_y):
"""Turn the player... | stack_v2_sparse_classes_75kplus_train_066033 | 5,721 | permissive | [
{
"docstring": "Load all the degree logic.",
"name": "__init__",
"signature": "def __init__(self, game, spritesheet, start_position_func=None)"
},
{
"docstring": "Turn the player towards the point whose coordinates are given.",
"name": "turn",
"signature": "def turn(self, towards_x, towa... | 2 | stack_v2_sparse_classes_30k_train_050885 | Implement the Python class `SpriteActor` described below.
Class description:
Actor in our game. A helper class to load the sprite sheet and handle degrees.
Method signatures and docstrings:
- def __init__(self, game, spritesheet, start_position_func=None): Load all the degree logic.
- def turn(self, towards_x, toward... | Implement the Python class `SpriteActor` described below.
Class description:
Actor in our game. A helper class to load the sprite sheet and handle degrees.
Method signatures and docstrings:
- def __init__(self, game, spritesheet, start_position_func=None): Load all the degree logic.
- def turn(self, towards_x, toward... | 100dd6197962508a78172c0945b9c914040bda7b | <|skeleton|>
class SpriteActor:
"""Actor in our game. A helper class to load the sprite sheet and handle degrees."""
def __init__(self, game, spritesheet, start_position_func=None):
"""Load all the degree logic."""
<|body_0|>
def turn(self, towards_x, towards_y):
"""Turn the player... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpriteActor:
"""Actor in our game. A helper class to load the sprite sheet and handle degrees."""
def __init__(self, game, spritesheet, start_position_func=None):
"""Load all the degree logic."""
pygame.sprite.Sprite.__init__(self)
log('Creating an actor with file format: %s' % fi... | the_stack_v2_python_sparse | byte/byte/Actor.py | Sveder/pyweek_18_game | train | 1 |
19a13bdc2dd0ae4b90ebaba85f9ab28366ce1ffe | [
"last_kl = factor_object.past_today_kl(self.kl_pd_buy, self.past_day_cnt)\nif last_kl is None or last_kl.empty:\n precent_pos = self.pos_base\nelse:\n precent_pos = stats.percentileofscore(last_kl.close, self.bp)\n precent_pos = (1 + (self.mid_precent - precent_pos) / 100) * self.pos_base\nprecent_pos = se... | <|body_start_0|>
last_kl = factor_object.past_today_kl(self.kl_pd_buy, self.past_day_cnt)
if last_kl is None or last_kl.empty:
precent_pos = self.pos_base
else:
precent_pos = stats.percentileofscore(last_kl.close, self.bp)
precent_pos = (1 + (self.mid_precent ... | 示例价格位置仓位管理类: 根据买入价格在之前一段时间的价格位置来决策仓位大小 假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间) 如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小) | AbuPtPosition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbuPtPosition:
"""示例价格位置仓位管理类: 根据买入价格在之前一段时间的价格位置来决策仓位大小 假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间) 如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小)"""
def fit_position(self, factor_object):
"""针对均值回复类型策略的仓位管理: 根据当前买入价格在过去一段金融序列中的价格rank位置来决定仓位 fit_position计算... | stack_v2_sparse_classes_75kplus_train_066034 | 2,547 | permissive | [
{
"docstring": "针对均值回复类型策略的仓位管理: 根据当前买入价格在过去一段金融序列中的价格rank位置来决定仓位 fit_position计算的结果是买入多少个单位(股,手,顿,合约) :param factor_object: ABuFactorBuyBases子类实例对象 :return:买入多少个单位(股,手,顿,合约)",
"name": "fit_position",
"signature": "def fit_position(self, factor_object)"
},
{
"docstring": "价格位置仓位控制管理类初始化设置",
"... | 2 | stack_v2_sparse_classes_30k_train_029235 | Implement the Python class `AbuPtPosition` described below.
Class description:
示例价格位置仓位管理类: 根据买入价格在之前一段时间的价格位置来决策仓位大小 假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间) 如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小)
Method signatures and docstrings:
- def fit_position(self, factor_object): 针对均值回复类... | Implement the Python class `AbuPtPosition` described below.
Class description:
示例价格位置仓位管理类: 根据买入价格在之前一段时间的价格位置来决策仓位大小 假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间) 如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小)
Method signatures and docstrings:
- def fit_position(self, factor_object): 针对均值回复类... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class AbuPtPosition:
"""示例价格位置仓位管理类: 根据买入价格在之前一段时间的价格位置来决策仓位大小 假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间) 如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小)"""
def fit_position(self, factor_object):
"""针对均值回复类型策略的仓位管理: 根据当前买入价格在过去一段金融序列中的价格rank位置来决定仓位 fit_position计算... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbuPtPosition:
"""示例价格位置仓位管理类: 根据买入价格在之前一段时间的价格位置来决策仓位大小 假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间) 如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小)"""
def fit_position(self, factor_object):
"""针对均值回复类型策略的仓位管理: 根据当前买入价格在过去一段金融序列中的价格rank位置来决定仓位 fit_position计算的结果是买入多少个单位(股... | the_stack_v2_python_sparse | abupy/BetaBu/ABuPtPosition.py | luqin/firefly | train | 1 |
98d97723ad272be70750d1be87e674158f396564 | [
"self.prefix = [m[:] for m in matrix]\nself.m = len(matrix)\nself.n = len(matrix[0]) if matrix else 0\nif self.m == 0 or self.n == 0:\n return\nfor i in range(self.m):\n for j in range(1, self.n):\n self.prefix[i][j] += self.prefix[i][j - 1]\nfor j in range(self.n):\n for i in range(1, self.m):\n ... | <|body_start_0|>
self.prefix = [m[:] for m in matrix]
self.m = len(matrix)
self.n = len(matrix[0]) if matrix else 0
if self.m == 0 or self.n == 0:
return
for i in range(self.m):
for j in range(1, self.n):
self.prefix[i][j] += self.prefix[i]... | NumMatrix | [] | 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_75kplus_train_066035 | 1,360 | no_license | [
{
"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_009565 | 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:... | 0e35e4cc87bd41144b8e34302aafe776fec1b356 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.prefix = [m[:] for m in matrix]
self.m = len(matrix)
self.n = len(matrix[0]) if matrix else 0
if self.m == 0 or self.n == 0:
return
for i in range(self.m):
fo... | the_stack_v2_python_sparse | LeetCode/304-range_sum_query_2d_immutable.py | davll/practical-algorithms | train | 0 | |
e8f37e648f2c2b29e8fb524f3ff503a802783aaf | [
"s_list = []\nfor i in range(0, len(s), 2 * k):\n cut = s[i:i + k]\n s_list.append(cut[::-1])\n s_list.append(s[i + k:i + 2 * k])\nreturn ''.join(s_list)",
"s = list(s)\nfor i in range(0, len(s), 2 * k):\n s[i:i + k] = reversed(s[i:i + k])\nreturn ''.join(s)"
] | <|body_start_0|>
s_list = []
for i in range(0, len(s), 2 * k):
cut = s[i:i + k]
s_list.append(cut[::-1])
s_list.append(s[i + k:i + 2 * k])
return ''.join(s_list)
<|end_body_0|>
<|body_start_1|>
s = list(s)
for i in range(0, len(s), 2 * k):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_0|>
def reverseStr_other_solution(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s_list = []
for ... | stack_v2_sparse_classes_75kplus_train_066036 | 731 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: str",
"name": "reverseStr",
"signature": "def reverseStr(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: str",
"name": "reverseStr_other_solution",
"signature": "def reverseStr_other_solution(self, s, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052334 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseStr(self, s, k): :type s: str :type k: int :rtype: str
- def reverseStr_other_solution(self, s, k): :type s: str :type k: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseStr(self, s, k): :type s: str :type k: int :rtype: str
- def reverseStr_other_solution(self, s, k): :type s: str :type k: int :rtype: str
<|skeleton|>
class Solution:... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_0|>
def reverseStr_other_solution(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
s_list = []
for i in range(0, len(s), 2 * k):
cut = s[i:i + k]
s_list.append(cut[::-1])
s_list.append(s[i + k:i + 2 * k])
return ''.join(s_list)
def revers... | the_stack_v2_python_sparse | LeetCode/String/541_reverse_string_II.py | XyK0907/for_work | train | 0 | |
5b27f794883ed18b0c95360e6ea778cb50d750a2 | [
"preorder = []\n\ndef traverse(root):\n if root is None:\n preorder.append('#')\n return\n preorder.append(root.val)\n traverse(root.left)\n traverse(root.right)\ntraverse(root)\nreturn ','.join([str(val) for val in preorder])",
"if data == '':\n return None\npreorder = data.split(','... | <|body_start_0|>
preorder = []
def traverse(root):
if root is None:
preorder.append('#')
return
preorder.append(root.val)
traverse(root.left)
traverse(root.right)
traverse(root)
return ','.join([str(val) for... | 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_75kplus_train_066037 | 6,926 | 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_020736 | 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:... | 0821af55eca60084b503b5f751301048c55e4381 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
preorder = []
def traverse(root):
if root is None:
preorder.append('#')
return
preorder.append(root.val)
trav... | the_stack_v2_python_sparse | Hard/LC297.py | shuowenwei/LeetCodePython | train | 2 | |
b751186e072b41eaa4a4d57ebaa6fe20be4b4161 | [
"payload = self.create_object.copy()\nurl = reverse(self.create_url)\nresponse = self.client.post(url, data=payload)\nself.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\nself.assertIn('detail', response.data)\nself.assertEqual(response.data['detail'], STR_401_MESSAGE)",
"user = self.template_use... | <|body_start_0|>
payload = self.create_object.copy()
url = reverse(self.create_url)
response = self.client.post(url, data=payload)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertIn('detail', response.data)
self.assertEqual(response.data['d... | BasicCreateApiTestCaseRunMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicCreateApiTestCaseRunMixin:
def test_create_anonymous(self):
"""Anonymous user should NOT be able to create"""
<|body_0|>
def test_create_staff_user(self):
"""Staff user should be able to create objects"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_066038 | 9,174 | permissive | [
{
"docstring": "Anonymous user should NOT be able to create",
"name": "test_create_anonymous",
"signature": "def test_create_anonymous(self)"
},
{
"docstring": "Staff user should be able to create objects",
"name": "test_create_staff_user",
"signature": "def test_create_staff_user(self)"... | 2 | stack_v2_sparse_classes_30k_train_049259 | Implement the Python class `BasicCreateApiTestCaseRunMixin` described below.
Class description:
Implement the BasicCreateApiTestCaseRunMixin class.
Method signatures and docstrings:
- def test_create_anonymous(self): Anonymous user should NOT be able to create
- def test_create_staff_user(self): Staff user should be ... | Implement the Python class `BasicCreateApiTestCaseRunMixin` described below.
Class description:
Implement the BasicCreateApiTestCaseRunMixin class.
Method signatures and docstrings:
- def test_create_anonymous(self): Anonymous user should NOT be able to create
- def test_create_staff_user(self): Staff user should be ... | 9baa530f2f3405322f74ccc145641148f253341b | <|skeleton|>
class BasicCreateApiTestCaseRunMixin:
def test_create_anonymous(self):
"""Anonymous user should NOT be able to create"""
<|body_0|>
def test_create_staff_user(self):
"""Staff user should be able to create objects"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicCreateApiTestCaseRunMixin:
def test_create_anonymous(self):
"""Anonymous user should NOT be able to create"""
payload = self.create_object.copy()
url = reverse(self.create_url)
response = self.client.post(url, data=payload)
self.assertEqual(response.status_code, st... | the_stack_v2_python_sparse | palvelutori/test_mixins.py | City-of-Turku/munpalvelut_backend | train | 0 | |
001f73e9d51180d1b7846fc0a0d30b35af1dc76c | [
"super(SwallowDiscreteActor, self).__init__()\nself.device = device\nself.layer1 = torch.nn.Sequential(torch.nn.Linear(input_shape[0], 64), torch.nn.ReLU())\nself.layer2 = torch.nn.Sequential(torch.nn.Linear(64, 32), torch.nn.ReLU())\nself.actor_logits = torch.nn.Linear(32, output_shape)",
"x = x.to(self.device)\... | <|body_start_0|>
super(SwallowDiscreteActor, self).__init__()
self.device = device
self.layer1 = torch.nn.Sequential(torch.nn.Linear(input_shape[0], 64), torch.nn.ReLU())
self.layer2 = torch.nn.Sequential(torch.nn.Linear(64, 32), torch.nn.ReLU())
self.actor_logits = torch.nn.Line... | SwallowDiscreteActor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwallowDiscreteActor:
def __init__(self, input_shape, output_shape, device=torch.device('cpu')):
"""Una red neorunal que utilizará una función logística para discriminar la acción del espacio de acciones discreto. Se utiliza para representar el papel del actor en A2C. :param input_shape:... | stack_v2_sparse_classes_75kplus_train_066039 | 6,347 | permissive | [
{
"docstring": "Una red neorunal que utilizará una función logística para discriminar la acción del espacio de acciones discreto. Se utiliza para representar el papel del actor en A2C. :param input_shape: Forma de los datos de entrada (representan las observaciones del actor) :param output_shape: Forma de los d... | 2 | stack_v2_sparse_classes_30k_train_038097 | Implement the Python class `SwallowDiscreteActor` described below.
Class description:
Implement the SwallowDiscreteActor class.
Method signatures and docstrings:
- def __init__(self, input_shape, output_shape, device=torch.device('cpu')): Una red neorunal que utilizará una función logística para discriminar la acción... | Implement the Python class `SwallowDiscreteActor` described below.
Class description:
Implement the SwallowDiscreteActor class.
Method signatures and docstrings:
- def __init__(self, input_shape, output_shape, device=torch.device('cpu')): Una red neorunal que utilizará una función logística para discriminar la acción... | 5e987fac269afcb8f43aa9da1d07e34e1e036948 | <|skeleton|>
class SwallowDiscreteActor:
def __init__(self, input_shape, output_shape, device=torch.device('cpu')):
"""Una red neorunal que utilizará una función logística para discriminar la acción del espacio de acciones discreto. Se utiliza para representar el papel del actor en A2C. :param input_shape:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SwallowDiscreteActor:
def __init__(self, input_shape, output_shape, device=torch.device('cpu')):
"""Una red neorunal que utilizará una función logística para discriminar la acción del espacio de acciones discreto. Se utiliza para representar el papel del actor en A2C. :param input_shape: Forma de los ... | the_stack_v2_python_sparse | tema5/function_aproximator/swallow.py | dabamascodes/ia-course | train | 1 | |
98f4ab1830b06818a567f6079fa00ebf388aa802 | [
"self._io: IO = io\n'\\n The IO object.\\n '\nself._parent = parent\n'\\n The formatter for the parent node.\\n\\n :type: sdoc.sdoc2.formatter.Formatter.Formatter\\n '\nself._errors: int = 0\n'\\n The error count.\\n '",
"if self._parent:\n return self._parent.e... | <|body_start_0|>
self._io: IO = io
'\n The IO object.\n '
self._parent = parent
'\n The formatter for the parent node.\n\n :type: sdoc.sdoc2.formatter.Formatter.Formatter\n '
self._errors: int = 0
'\n The error count.\n '
<... | Abstract parent class for all formatters for generating the output of nodes in a requested format. | Formatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Formatter:
"""Abstract parent class for all formatters for generating the output of nodes in a requested format."""
def __init__(self, io: IO, parent):
"""Object constructor. :param OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter|None parent: The format... | stack_v2_sparse_classes_75kplus_train_066040 | 3,002 | permissive | [
{
"docstring": "Object constructor. :param OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter|None parent: The formatter for the parent node.",
"name": "__init__",
"signature": "def __init__(self, io: IO, parent)"
},
{
"docstring": "Getter for the error count. :rtype:... | 4 | stack_v2_sparse_classes_30k_train_013801 | Implement the Python class `Formatter` described below.
Class description:
Abstract parent class for all formatters for generating the output of nodes in a requested format.
Method signatures and docstrings:
- def __init__(self, io: IO, parent): Object constructor. :param OutputStyle io: The IO object. :param sdoc.sd... | Implement the Python class `Formatter` described below.
Class description:
Abstract parent class for all formatters for generating the output of nodes in a requested format.
Method signatures and docstrings:
- def __init__(self, io: IO, parent): Object constructor. :param OutputStyle io: The IO object. :param sdoc.sd... | 589c2a27eceebb7d96c14744c1632bdbdee9be52 | <|skeleton|>
class Formatter:
"""Abstract parent class for all formatters for generating the output of nodes in a requested format."""
def __init__(self, io: IO, parent):
"""Object constructor. :param OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter|None parent: The format... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Formatter:
"""Abstract parent class for all formatters for generating the output of nodes in a requested format."""
def __init__(self, io: IO, parent):
"""Object constructor. :param OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter|None parent: The formatter for the p... | the_stack_v2_python_sparse | sdoc/sdoc2/formatter/Formatter.py | SDoc/py-sdoc | train | 2 |
e8554fad1c7997a78c3e31e3a08ccda16f32c8e7 | [
"self.ground_filter_offset = config.ground_filter_offset\nself.offset_filter_distance = config.offset_filter_distance\nself.std_dev_multiplier = config.std_dev_multiplier\nself.kitti_utils = kitti_utils",
"slice_filter = self.kitti_utils.create_slice_filter(point_cloud, area_extents, ground_plane, self.ground_fil... | <|body_start_0|>
self.ground_filter_offset = config.ground_filter_offset
self.offset_filter_distance = config.offset_filter_distance
self.std_dev_multiplier = config.std_dev_multiplier
self.kitti_utils = kitti_utils
<|end_body_0|>
<|body_start_1|>
slice_filter = self.kitti_utils... | BevHeightPriors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
<|body_0|>
def generate_bev(self, source, point_cloud, ground_plane, area_extents, voxel_... | stack_v2_sparse_classes_75kplus_train_066041 | 4,840 | no_license | [
{
"docstring": "BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object",
"name": "__init__",
"signature": "def __init__(self, config, kitti_utils)"
},
{
"docstring": "Generates the BEV maps dictionary. One height map is created f... | 2 | stack_v2_sparse_classes_30k_train_020258 | Implement the Python class `BevHeightPriors` described below.
Class description:
Implement the BevHeightPriors class.
Method signatures and docstrings:
- def __init__(self, config, kitti_utils): BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object
-... | Implement the Python class `BevHeightPriors` described below.
Class description:
Implement the BevHeightPriors class.
Method signatures and docstrings:
- def __init__(self, config, kitti_utils): BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object
-... | ac8256bd76fe4b81cfc48dc4c0b9d9dc92bc61c6 | <|skeleton|>
class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
<|body_0|>
def generate_bev(self, source, point_cloud, ground_plane, area_extents, voxel_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
self.ground_filter_offset = config.ground_filter_offset
self.offset_filter_distance = config.offset_... | the_stack_v2_python_sparse | mlod/core/bev_generators/bev_height_priors.py | songsanling/MLOD | train | 0 | |
5b3fd235aa5fee6d8d90209c226fdf6f45968453 | [
"super().__init__(db, version, uuid)\nself.columns = get_table_columns(self.conn, 'ZDETECTEDFACE')\nself.table_name = 'ZDETECTEDFACE'",
"conn, cursor = self.db.get_db_connection()\nsql = f' SELECT ZDETECTEDFACE.*\\n FROM ZDETECTEDFACE\\n JOIN {self.asset_table} ON {self.asse... | <|body_start_0|>
super().__init__(db, version, uuid)
self.columns = get_table_columns(self.conn, 'ZDETECTEDFACE')
self.table_name = 'ZDETECTEDFACE'
<|end_body_0|>
<|body_start_1|>
conn, cursor = self.db.get_db_connection()
sql = f' SELECT ZDETECTEDFACE.*\n FR... | ZDETECTEDFACE table. | DetectedFaceTable | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetectedFaceTable:
"""ZDETECTEDFACE table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
<|body_0|>
def rows(self) -> list[tuple[Any]]:
"""Return rows for this photo from the ZDETECTEDFACE table."""
<... | stack_v2_sparse_classes_75kplus_train_066042 | 8,828 | permissive | [
{
"docstring": "Create a Table object.",
"name": "__init__",
"signature": "def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str)"
},
{
"docstring": "Return rows for this photo from the ZDETECTEDFACE table.",
"name": "rows",
"signature": "def rows(self) -> list[tuple[Any]]"
... | 3 | stack_v2_sparse_classes_30k_train_001041 | Implement the Python class `DetectedFaceTable` described below.
Class description:
ZDETECTEDFACE table.
Method signatures and docstrings:
- def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str): Create a Table object.
- def rows(self) -> list[tuple[Any]]: Return rows for this photo from the ZDETECTEDFAC... | Implement the Python class `DetectedFaceTable` described below.
Class description:
ZDETECTEDFACE table.
Method signatures and docstrings:
- def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str): Create a Table object.
- def rows(self) -> list[tuple[Any]]: Return rows for this photo from the ZDETECTEDFAC... | 2cb5a4d18a27be6ccf68f5f35abd39418d238016 | <|skeleton|>
class DetectedFaceTable:
"""ZDETECTEDFACE table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
<|body_0|>
def rows(self) -> list[tuple[Any]]:
"""Return rows for this photo from the ZDETECTEDFACE table."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DetectedFaceTable:
"""ZDETECTEDFACE table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
super().__init__(db, version, uuid)
self.columns = get_table_columns(self.conn, 'ZDETECTEDFACE')
self.table_name = 'ZDETECTEDFACE... | the_stack_v2_python_sparse | osxphotos/phototables.py | RhetTbull/osxphotos | train | 1,287 |
f8b6060b112a5c484c4b4189bda9bcbf483074f9 | [
"examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True)\nself.data_train, self.data_valid = (examples['train'], examples['validation'])\nself.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(self.data_train)",
"token_en = tfds.features.text.SubwordTextEncoder.buil... | <|body_start_0|>
examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True)
self.data_train, self.data_valid = (examples['train'], examples['validation'])
self.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(self.data_train)
<|end_body_0|>
<|body_s... | doc | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""doc"""
def __init__(self):
"""doc"""
<|body_0|>
def tokenize_dataset(self, data):
"""doc"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True... | stack_v2_sparse_classes_75kplus_train_066043 | 957 | no_license | [
{
"docstring": "doc",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "doc",
"name": "tokenize_dataset",
"signature": "def tokenize_dataset(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032088 | Implement the Python class `Dataset` described below.
Class description:
doc
Method signatures and docstrings:
- def __init__(self): doc
- def tokenize_dataset(self, data): doc | Implement the Python class `Dataset` described below.
Class description:
doc
Method signatures and docstrings:
- def __init__(self): doc
- def tokenize_dataset(self, data): doc
<|skeleton|>
class Dataset:
"""doc"""
def __init__(self):
"""doc"""
<|body_0|>
def tokenize_dataset(self, data... | 3bffd1391b3fc790f0137d0afbe90eb8e2f7d713 | <|skeleton|>
class Dataset:
"""doc"""
def __init__(self):
"""doc"""
<|body_0|>
def tokenize_dataset(self, data):
"""doc"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataset:
"""doc"""
def __init__(self):
"""doc"""
examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True)
self.data_train, self.data_valid = (examples['train'], examples['validation'])
self.tokenizer_pt, self.tokenizer_en = self.tok... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/0-dataset.py | pafuentess/holbertonschool-machine_learning | train | 0 |
8099d713ddfe3b87a55dae24e9181a76187e7a2b | [
"for cat, urlpart in category_mapping.items():\n self.category = cat\n url = '{}{}'.format(self.ROOT_CAT_URL, urlpart)\n yield scrapy.Request(url, meta={'_ours': {'category': cat}})",
"links = set(response.css('.mw-category ul li a::attr(href)').extract())\nmeta = response.meta['_ours']\nfor rellink in l... | <|body_start_0|>
for cat, urlpart in category_mapping.items():
self.category = cat
url = '{}{}'.format(self.ROOT_CAT_URL, urlpart)
yield scrapy.Request(url, meta={'_ours': {'category': cat}})
<|end_body_0|>
<|body_start_1|>
links = set(response.css('.mw-category ul l... | Scrapes any wikipedia category page. | WikipediaCategoryScraper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikipediaCategoryScraper:
"""Scrapes any wikipedia category page."""
def start_requests(self):
"""Determine which category starting url to run."""
<|body_0|>
def parse(self, response):
"""Parse the response of each list category."""
<|body_1|>
def pa... | stack_v2_sparse_classes_75kplus_train_066044 | 2,111 | permissive | [
{
"docstring": "Determine which category starting url to run.",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "Parse the response of each list category.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse a si... | 3 | stack_v2_sparse_classes_30k_train_007478 | Implement the Python class `WikipediaCategoryScraper` described below.
Class description:
Scrapes any wikipedia category page.
Method signatures and docstrings:
- def start_requests(self): Determine which category starting url to run.
- def parse(self, response): Parse the response of each list category.
- def parse_... | Implement the Python class `WikipediaCategoryScraper` described below.
Class description:
Scrapes any wikipedia category page.
Method signatures and docstrings:
- def start_requests(self): Determine which category starting url to run.
- def parse(self, response): Parse the response of each list category.
- def parse_... | 8515fcc4c86ef0a96f34278d90419e5fad2b48d3 | <|skeleton|>
class WikipediaCategoryScraper:
"""Scrapes any wikipedia category page."""
def start_requests(self):
"""Determine which category starting url to run."""
<|body_0|>
def parse(self, response):
"""Parse the response of each list category."""
<|body_1|>
def pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WikipediaCategoryScraper:
"""Scrapes any wikipedia category page."""
def start_requests(self):
"""Determine which category starting url to run."""
for cat, urlpart in category_mapping.items():
self.category = cat
url = '{}{}'.format(self.ROOT_CAT_URL, urlpart)
... | the_stack_v2_python_sparse | plantstuff/scraping/scrapers/spiders/wikipedia.py | christabor/plantstuff | train | 8 |
e05fb3fae0fc407cbcc50d16d80cf9f87a1a2766 | [
"self.inputfile = open(inputfile, 'r')\nself.config = config.parse_file(configfile)\nself.buildroot = config.eval_string(self.config['BUILDROOT'])\nself.kernpath = '/kernel/' + self.config['ARCH'] + '/' + self.config['SYSTEM'] + '/kernel'\nself.addr2line = self.config['CROSS_COMPILE'] + 'addr2line -p -f -e '",
"i... | <|body_start_0|>
self.inputfile = open(inputfile, 'r')
self.config = config.parse_file(configfile)
self.buildroot = config.eval_string(self.config['BUILDROOT'])
self.kernpath = '/kernel/' + self.config['ARCH'] + '/' + self.config['SYSTEM'] + '/kernel'
self.addr2line = self.config... | Basic performance profile analyzer | QemuProfAnalyzer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QemuProfAnalyzer:
"""Basic performance profile analyzer"""
def __init__(self, inputfile, configfile):
"""Constructor"""
<|body_0|>
def _resolve_symbol(self, program, addr):
"""Translate address inside the given program to symbol name"""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus_train_066045 | 3,642 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, inputfile, configfile)"
},
{
"docstring": "Translate address inside the given program to symbol name",
"name": "_resolve_symbol",
"signature": "def _resolve_symbol(self, program, addr)"
},
{
"docst... | 3 | null | Implement the Python class `QemuProfAnalyzer` described below.
Class description:
Basic performance profile analyzer
Method signatures and docstrings:
- def __init__(self, inputfile, configfile): Constructor
- def _resolve_symbol(self, program, addr): Translate address inside the given program to symbol name
- def an... | Implement the Python class `QemuProfAnalyzer` described below.
Class description:
Basic performance profile analyzer
Method signatures and docstrings:
- def __init__(self, inputfile, configfile): Constructor
- def _resolve_symbol(self, program, addr): Translate address inside the given program to symbol name
- def an... | 0967dc627a7a73a7ccead427e56ff193dece1248 | <|skeleton|>
class QemuProfAnalyzer:
"""Basic performance profile analyzer"""
def __init__(self, inputfile, configfile):
"""Constructor"""
<|body_0|>
def _resolve_symbol(self, program, addr):
"""Translate address inside the given program to symbol name"""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QemuProfAnalyzer:
"""Basic performance profile analyzer"""
def __init__(self, inputfile, configfile):
"""Constructor"""
self.inputfile = open(inputfile, 'r')
self.config = config.parse_file(configfile)
self.buildroot = config.eval_string(self.config['BUILDROOT'])
s... | the_stack_v2_python_sparse | support/qemu/perf-analyze | SpaceMonkeyClan/FreeNOS-1.0.3 | train | 0 |
6e497c951ed086f14669750ae8fd56dde3d351a6 | [
"inputs = [x for x in sys_stdin]\na = [self.cast(x) for x in inputs[0].strip('[]\\n').split(',')]\nl = int(inputs[1])\nr = int(inputs[2])\nreturn (a, l, r)",
"if x.lower() == 'null':\n return None\nelse:\n return int(x)"
] | <|body_start_0|>
inputs = [x for x in sys_stdin]
a = [self.cast(x) for x in inputs[0].strip('[]\n').split(',')]
l = int(inputs[1])
r = int(inputs[2])
return (a, l, r)
<|end_body_0|>
<|body_start_1|>
if x.lower() == 'null':
return None
else:
... | Input | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: characteristic factor for spiral matrix :rtype: int"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :param ... | stack_v2_sparse_classes_75kplus_train_066046 | 2,927 | permissive | [
{
"docstring": "Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: characteristic factor for spiral matrix :rtype: int",
"name": "stdin",
"signature": "def stdin(self, sys_stdin)"
},
{
"docstring": "Converts string values to integer or None values. :param str x: ... | 2 | stack_v2_sparse_classes_30k_train_034449 | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: characteristic factor for spiral matrix :rtype: int
- def cast(self, x):... | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: characteristic factor for spiral matrix :rtype: int
- def cast(self, x):... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: characteristic factor for spiral matrix :rtype: int"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: characteristic factor for spiral matrix :rtype: int"""
inputs = [x for x in sys_stdin]
a = [self.cast(x) for x in inputs[0].strip('[]\n').split(',')]
l = in... | the_stack_v2_python_sparse | 0938_range_sum_bst/python_source.py | arthurdysart/LeetCode | train | 0 | |
f0632cd51f5c004bbfe21f78392c071c8c8dc05f | [
"template_cfg = config_pb2.InstanceTemplateConfig.InstanceTemplate(base_name='base-name')\nexpected_active_key = parse.get_instance_template_revision_key(template_cfg)\ninstance_template = models.InstanceTemplate()\nself.failUnless(parse.ensure_instance_template_revision_active(template_cfg, instance_template))\nse... | <|body_start_0|>
template_cfg = config_pb2.InstanceTemplateConfig.InstanceTemplate(base_name='base-name')
expected_active_key = parse.get_instance_template_revision_key(template_cfg)
instance_template = models.InstanceTemplate()
self.failUnless(parse.ensure_instance_template_revision_act... | Tests for parse.ensure_instance_template_revision_active. | EnsureInstanceTemplateRevisionActiveTest | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnsureInstanceTemplateRevisionActiveTest:
"""Tests for parse.ensure_instance_template_revision_active."""
def test_activates(self):
"""Ensures that the instance template revision is activated."""
<|body_0|>
def test_drains_and_activates(self):
"""Ensures that the... | stack_v2_sparse_classes_75kplus_train_066047 | 26,754 | permissive | [
{
"docstring": "Ensures that the instance template revision is activated.",
"name": "test_activates",
"signature": "def test_activates(self)"
},
{
"docstring": "Ensures that the active instance template revision is drained.",
"name": "test_drains_and_activates",
"signature": "def test_dr... | 5 | stack_v2_sparse_classes_30k_test_001188 | Implement the Python class `EnsureInstanceTemplateRevisionActiveTest` described below.
Class description:
Tests for parse.ensure_instance_template_revision_active.
Method signatures and docstrings:
- def test_activates(self): Ensures that the instance template revision is activated.
- def test_drains_and_activates(se... | Implement the Python class `EnsureInstanceTemplateRevisionActiveTest` described below.
Class description:
Tests for parse.ensure_instance_template_revision_active.
Method signatures and docstrings:
- def test_activates(self): Ensures that the instance template revision is activated.
- def test_drains_and_activates(se... | 0a4fdfc25f89833026be6a8b29c0a27b8f3c5fc4 | <|skeleton|>
class EnsureInstanceTemplateRevisionActiveTest:
"""Tests for parse.ensure_instance_template_revision_active."""
def test_activates(self):
"""Ensures that the instance template revision is activated."""
<|body_0|>
def test_drains_and_activates(self):
"""Ensures that the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnsureInstanceTemplateRevisionActiveTest:
"""Tests for parse.ensure_instance_template_revision_active."""
def test_activates(self):
"""Ensures that the instance template revision is activated."""
template_cfg = config_pb2.InstanceTemplateConfig.InstanceTemplate(base_name='base-name')
... | the_stack_v2_python_sparse | appengine/gce-backend/parse_test.py | Swift1313/luci-py | train | 0 |
1565e838be733eb91a1cb3ae88165fad76beb591 | [
"phonon_energy_from_nr = self.energy_nr_to_detectable_energy_function()\nphonon_resolution = self._energy_parameters[self.detector_key]['sigma_phonon']\nreturn _get_nr_resolution(energies_in_kev, phonon_energy_from_nr, phonon_resolution)",
"bg_rate_nr = 300\nconv_units = 1000.0\nreturn self._flat_background(len(e... | <|body_start_0|>
phonon_energy_from_nr = self.energy_nr_to_detectable_energy_function()
phonon_resolution = self._energy_parameters[self.detector_key]['sigma_phonon']
return _get_nr_resolution(energies_in_kev, phonon_energy_from_nr, phonon_resolution)
<|end_body_0|>
<|body_start_1|>
bg_... | SuperCdmsHvSiNr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperCdmsHvSiNr:
def resolution(self, energies_in_kev):
"""Flat resolution"""
<|body_0|>
def background_function(self, energies_in_kev):
"""Flat bg rate"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
phonon_energy_from_nr = self.energy_nr_to_detect... | stack_v2_sparse_classes_75kplus_train_066048 | 12,973 | permissive | [
{
"docstring": "Flat resolution",
"name": "resolution",
"signature": "def resolution(self, energies_in_kev)"
},
{
"docstring": "Flat bg rate",
"name": "background_function",
"signature": "def background_function(self, energies_in_kev)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054158 | Implement the Python class `SuperCdmsHvSiNr` described below.
Class description:
Implement the SuperCdmsHvSiNr class.
Method signatures and docstrings:
- def resolution(self, energies_in_kev): Flat resolution
- def background_function(self, energies_in_kev): Flat bg rate | Implement the Python class `SuperCdmsHvSiNr` described below.
Class description:
Implement the SuperCdmsHvSiNr class.
Method signatures and docstrings:
- def resolution(self, energies_in_kev): Flat resolution
- def background_function(self, energies_in_kev): Flat bg rate
<|skeleton|>
class SuperCdmsHvSiNr:
def ... | f305b70229473de19178298b5ef4afa898f79fa0 | <|skeleton|>
class SuperCdmsHvSiNr:
def resolution(self, energies_in_kev):
"""Flat resolution"""
<|body_0|>
def background_function(self, energies_in_kev):
"""Flat bg rate"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperCdmsHvSiNr:
def resolution(self, energies_in_kev):
"""Flat resolution"""
phonon_energy_from_nr = self.energy_nr_to_detectable_energy_function()
phonon_resolution = self._energy_parameters[self.detector_key]['sigma_phonon']
return _get_nr_resolution(energies_in_kev, phonon_... | the_stack_v2_python_sparse | dddm/detectors/super_cdms.py | JoranAngevaare/dddm | train | 0 | |
139e4adc626e26fd2636040a7b4ccf223d3443cc | [
"self._logl = logl\nself._logp = logp\nself._beta = beta",
"lp = self._logp(x)\nif lp == float('-inf'):\n return (lp, lp)\nll = self._logl(x)\nreturn (self._beta * ll + lp, ll)"
] | <|body_start_0|>
self._logl = logl
self._logp = logp
self._beta = beta
<|end_body_0|>
<|body_start_1|>
lp = self._logp(x)
if lp == float('-inf'):
return (lp, lp)
ll = self._logl(x)
return (self._beta * ll + lp, ll)
<|end_body_1|>
| Wrapper for posterior used with the :class:`PTSampler` in emcee. | PTPost | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PTPost:
"""Wrapper for posterior used with the :class:`PTSampler` in emcee."""
def __init__(self, logl, logp, beta):
""":param logl: Function returning natural log of the likelihood. :param logp: Function returning natural log of the prior. :param beta: Inverse temperature of this ch... | stack_v2_sparse_classes_75kplus_train_066049 | 14,129 | permissive | [
{
"docstring": ":param logl: Function returning natural log of the likelihood. :param logp: Function returning natural log of the prior. :param beta: Inverse temperature of this chain: ``lnpost = beta*logl + logp``.",
"name": "__init__",
"signature": "def __init__(self, logl, logp, beta)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_010943 | Implement the Python class `PTPost` described below.
Class description:
Wrapper for posterior used with the :class:`PTSampler` in emcee.
Method signatures and docstrings:
- def __init__(self, logl, logp, beta): :param logl: Function returning natural log of the likelihood. :param logp: Function returning natural log ... | Implement the Python class `PTPost` described below.
Class description:
Wrapper for posterior used with the :class:`PTSampler` in emcee.
Method signatures and docstrings:
- def __init__(self, logl, logp, beta): :param logl: Function returning natural log of the likelihood. :param logp: Function returning natural log ... | a89ec59e14de0cbed73e9063472419fbe2ed3b11 | <|skeleton|>
class PTPost:
"""Wrapper for posterior used with the :class:`PTSampler` in emcee."""
def __init__(self, logl, logp, beta):
""":param logl: Function returning natural log of the likelihood. :param logp: Function returning natural log of the prior. :param beta: Inverse temperature of this ch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PTPost:
"""Wrapper for posterior used with the :class:`PTSampler` in emcee."""
def __init__(self, logl, logp, beta):
""":param logl: Function returning natural log of the likelihood. :param logp: Function returning natural log of the prior. :param beta: Inverse temperature of this chain: ``lnpost... | the_stack_v2_python_sparse | emcee/ptsampler.py | GabrielaCR/AGNfitter | train | 45 |
5be623644b6c108237c2a53528d5039cd3faa639 | [
"if len(element) > 1:\n raise IndexError\nStack.__init__(self, list(element), 1)",
"if len(self) >= 1:\n raise IndexError\nself.append(element)"
] | <|body_start_0|>
if len(element) > 1:
raise IndexError
Stack.__init__(self, list(element), 1)
<|end_body_0|>
<|body_start_1|>
if len(self) >= 1:
raise IndexError
self.append(element)
<|end_body_1|>
| A one-element Queue/Stack. IndexError will be raised if an element is put() or unget() when the Bucket already has an element (is full). | Bucket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bucket:
"""A one-element Queue/Stack. IndexError will be raised if an element is put() or unget() when the Bucket already has an element (is full)."""
def __init__(self, element=[]):
"""(Bucket, [list]) -> NoneType Initialize a bucket with the element. If element is not provided, the... | stack_v2_sparse_classes_75kplus_train_066050 | 3,006 | no_license | [
{
"docstring": "(Bucket, [list]) -> NoneType Initialize a bucket with the element. If element is not provided, the Bucket will be empty. If element is a list with more than one element, IndexError will be raised",
"name": "__init__",
"signature": "def __init__(self, element=[])"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_048979 | Implement the Python class `Bucket` described below.
Class description:
A one-element Queue/Stack. IndexError will be raised if an element is put() or unget() when the Bucket already has an element (is full).
Method signatures and docstrings:
- def __init__(self, element=[]): (Bucket, [list]) -> NoneType Initialize a... | Implement the Python class `Bucket` described below.
Class description:
A one-element Queue/Stack. IndexError will be raised if an element is put() or unget() when the Bucket already has an element (is full).
Method signatures and docstrings:
- def __init__(self, element=[]): (Bucket, [list]) -> NoneType Initialize a... | c3c5031046ddf1b361eae886577c1c9e51f460cb | <|skeleton|>
class Bucket:
"""A one-element Queue/Stack. IndexError will be raised if an element is put() or unget() when the Bucket already has an element (is full)."""
def __init__(self, element=[]):
"""(Bucket, [list]) -> NoneType Initialize a bucket with the element. If element is not provided, the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bucket:
"""A one-element Queue/Stack. IndexError will be raised if an element is put() or unget() when the Bucket already has an element (is full)."""
def __init__(self, element=[]):
"""(Bucket, [list]) -> NoneType Initialize a bucket with the element. If element is not provided, the Bucket will ... | the_stack_v2_python_sparse | ex1/Containers.py | AyushParikh/CSCA48_assignments | train | 0 |
925baeaed88d3d17922e332c79942d541b8f87db | [
"database.drop_data()\nself.assertEqual(database.show_available_products(), {})\nwith self.assertRaises(FileNotFoundError):\n result = database.import_data('data2', 'p.csv', 'c.csv', 'r.csv')\nresult = database.import_data('data', 'products.csv', 'customers.csv', 'rentals.csv')\nself.assertEqual(result[0][0], 5)... | <|body_start_0|>
database.drop_data()
self.assertEqual(database.show_available_products(), {})
with self.assertRaises(FileNotFoundError):
result = database.import_data('data2', 'p.csv', 'c.csv', 'r.csv')
result = database.import_data('data', 'products.csv', 'customers.csv', '... | Tests for population and data integrity of database. | RentalDbTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RentalDbTest:
"""Tests for population and data integrity of database."""
def test_1_import(self):
"""Test that the records are successfully imported."""
<|body_0|>
def test_2_show_available(self):
"""Test the integrity of the returned dictionary of available prod... | stack_v2_sparse_classes_75kplus_train_066051 | 4,281 | no_license | [
{
"docstring": "Test that the records are successfully imported.",
"name": "test_1_import",
"signature": "def test_1_import(self)"
},
{
"docstring": "Test the integrity of the returned dictionary of available products. We particularly want to validate that quantity_available is deducted to accou... | 3 | stack_v2_sparse_classes_30k_train_041110 | Implement the Python class `RentalDbTest` described below.
Class description:
Tests for population and data integrity of database.
Method signatures and docstrings:
- def test_1_import(self): Test that the records are successfully imported.
- def test_2_show_available(self): Test the integrity of the returned diction... | Implement the Python class `RentalDbTest` described below.
Class description:
Tests for population and data integrity of database.
Method signatures and docstrings:
- def test_1_import(self): Test that the records are successfully imported.
- def test_2_show_available(self): Test the integrity of the returned diction... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class RentalDbTest:
"""Tests for population and data integrity of database."""
def test_1_import(self):
"""Test that the records are successfully imported."""
<|body_0|>
def test_2_show_available(self):
"""Test the integrity of the returned dictionary of available prod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RentalDbTest:
"""Tests for population and data integrity of database."""
def test_1_import(self):
"""Test that the records are successfully imported."""
database.drop_data()
self.assertEqual(database.show_available_products(), {})
with self.assertRaises(FileNotFoundError):... | the_stack_v2_python_sparse | students/shodges/lesson10/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
89583538a29b38c97ca5d769ef8b17902833fb79 | [
"self.verify_mco_parameters(params)\ntfunc = partial(self.translated_function, func=func, params=params)\nx0, bounds = self.get_initial_and_bounds(params)\noptimization_result = scipy_optimize.minimize(tfunc, x0, method=self.algorithms, bounds=bounds)\noptimal_point = self.translate_array_to_mco(optimization_result... | <|body_start_0|>
self.verify_mco_parameters(params)
tfunc = partial(self.translated_function, func=func, params=params)
x0, bounds = self.get_initial_and_bounds(params)
optimization_result = scipy_optimize.minimize(tfunc, x0, method=self.algorithms, bounds=bounds)
optimal_point =... | Optimization of an objective function using scipy. | ScipyOptimizer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScipyOptimizer:
"""Optimization of an objective function using scipy."""
def optimize_function(self, func, params):
"""Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a ... | stack_v2_sparse_classes_75kplus_train_066052 | 9,020 | permissive | [
{
"docstring": "Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a single-objective). If not the return (objectives) will be summed. params: list of MCOParameter The MCO parameter objects correspond... | 6 | stack_v2_sparse_classes_30k_train_048068 | Implement the Python class `ScipyOptimizer` described below.
Class description:
Optimization of an objective function using scipy.
Method signatures and docstrings:
- def optimize_function(self, func, params): Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list... | Implement the Python class `ScipyOptimizer` described below.
Class description:
Optimization of an objective function using scipy.
Method signatures and docstrings:
- def optimize_function(self, func, params): Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list... | 6106bec35d6ad2383138a35205cea44fe529a229 | <|skeleton|>
class ScipyOptimizer:
"""Optimization of an objective function using scipy."""
def optimize_function(self, func, params):
"""Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScipyOptimizer:
"""Optimization of an objective function using scipy."""
def optimize_function(self, func, params):
"""Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a single-object... | the_stack_v2_python_sparse | force_bdss/mco/optimizers/scipy_optimizer.py | force-h2020/force-bdss | train | 2 |
578f25cf0f64c96b315aba529fc3c20b577734b6 | [
"if len(np.shape(x_t)) > 1 and np.shape(x_t)[1] > 1:\n raise NotImplementedError()\nelse:\n x_next_mean_precision = x_t * self.parameters.A * self.parameters.Qinv + self.y_next * self.parameters.C * self.parameters.Rinv\n x_next_precision = self.parameters.Qinv + self.parameters.C ** 2 * self.parameters.Ri... | <|body_start_0|>
if len(np.shape(x_t)) > 1 and np.shape(x_t)[1] > 1:
raise NotImplementedError()
else:
x_next_mean_precision = x_t * self.parameters.A * self.parameters.Qinv + self.y_next * self.parameters.C * self.parameters.Rinv
x_next_precision = self.parameters.Qi... | Optimal Instrumental Kernel for LGSSM K(x_{t+1} | x_t) = Pr(x_{t+1} | x_t, y_{t+1}, parameters) | LGSSMOptimalKernel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LGSSMOptimalKernel:
"""Optimal Instrumental Kernel for LGSSM K(x_{t+1} | x_t) = Pr(x_{t+1} | x_t, y_{t+1}, parameters)"""
def rv(self, x_t, **kwargs):
"""optimal Kernel for LGSSM Sample x_{t+1} ~ Pr(x_{t+1} | x_t, y_{t+1}, parameters) Args: x_t (ndarray): N by n, x_t Return: x_next (... | stack_v2_sparse_classes_75kplus_train_066053 | 7,345 | permissive | [
{
"docstring": "optimal Kernel for LGSSM Sample x_{t+1} ~ Pr(x_{t+1} | x_t, y_{t+1}, parameters) Args: x_t (ndarray): N by n, x_t Return: x_next (ndarray): N by n, x_{t+1}",
"name": "rv",
"signature": "def rv(self, x_t, **kwargs)"
},
{
"docstring": "Reweight function for Optimal Kernel for LGSSM... | 2 | stack_v2_sparse_classes_30k_val_003016 | Implement the Python class `LGSSMOptimalKernel` described below.
Class description:
Optimal Instrumental Kernel for LGSSM K(x_{t+1} | x_t) = Pr(x_{t+1} | x_t, y_{t+1}, parameters)
Method signatures and docstrings:
- def rv(self, x_t, **kwargs): optimal Kernel for LGSSM Sample x_{t+1} ~ Pr(x_{t+1} | x_t, y_{t+1}, para... | Implement the Python class `LGSSMOptimalKernel` described below.
Class description:
Optimal Instrumental Kernel for LGSSM K(x_{t+1} | x_t) = Pr(x_{t+1} | x_t, y_{t+1}, parameters)
Method signatures and docstrings:
- def rv(self, x_t, **kwargs): optimal Kernel for LGSSM Sample x_{t+1} ~ Pr(x_{t+1} | x_t, y_{t+1}, para... | b4f04637165c13fd7b3e042b36ad9b77d2528733 | <|skeleton|>
class LGSSMOptimalKernel:
"""Optimal Instrumental Kernel for LGSSM K(x_{t+1} | x_t) = Pr(x_{t+1} | x_t, y_{t+1}, parameters)"""
def rv(self, x_t, **kwargs):
"""optimal Kernel for LGSSM Sample x_{t+1} ~ Pr(x_{t+1} | x_t, y_{t+1}, parameters) Args: x_t (ndarray): N by n, x_t Return: x_next (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LGSSMOptimalKernel:
"""Optimal Instrumental Kernel for LGSSM K(x_{t+1} | x_t) = Pr(x_{t+1} | x_t, y_{t+1}, parameters)"""
def rv(self, x_t, **kwargs):
"""optimal Kernel for LGSSM Sample x_{t+1} ~ Pr(x_{t+1} | x_t, y_{t+1}, parameters) Args: x_t (ndarray): N by n, x_t Return: x_next (ndarray): N b... | the_stack_v2_python_sparse | sgmcmc_ssm/models/lgssm/kernels.py | PeiKaLunCi/sgmcmc_ssm_code | train | 0 |
a2bf34d587bc9ee2a087ceecdd383893f6feff67 | [
"super(LandmarkDataSource, self).__init__(id_dict_preprocessing=id_dict_preprocessing)\nself.point_list_file_name = point_list_file_name\nself.num_points = num_points\nself.dim = dim\nself.silent_not_found = silent_not_found\nself.load()",
"ext = os.path.splitext(self.point_list_file_name)[1]\nif ext == '.csv':\n... | <|body_start_0|>
super(LandmarkDataSource, self).__init__(id_dict_preprocessing=id_dict_preprocessing)
self.point_list_file_name = point_list_file_name
self.num_points = num_points
self.dim = dim
self.silent_not_found = silent_not_found
self.load()
<|end_body_0|>
<|body_... | Datasource used for loading landmarks. Uses id_dict['image_id'] as the landmark file key and returns a list of landmarks. | LandmarkDataSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LandmarkDataSource:
"""Datasource used for loading landmarks. Uses id_dict['image_id'] as the landmark file key and returns a list of landmarks."""
def __init__(self, point_list_file_name, num_points, dim, silent_not_found=False, id_dict_preprocessing=None):
"""Initializer. :param po... | stack_v2_sparse_classes_75kplus_train_066054 | 5,859 | no_license | [
{
"docstring": "Initializer. :param point_list_file_name: File that contains all the landmarks. Either a .csv file or a .idl file. :param num_points: Number of landmarks in the landmarks file. :param dim: Dimension of the landmarks. :param silent_not_found: If true, will return a list of invalid landmarks, in c... | 4 | stack_v2_sparse_classes_30k_train_016906 | Implement the Python class `LandmarkDataSource` described below.
Class description:
Datasource used for loading landmarks. Uses id_dict['image_id'] as the landmark file key and returns a list of landmarks.
Method signatures and docstrings:
- def __init__(self, point_list_file_name, num_points, dim, silent_not_found=F... | Implement the Python class `LandmarkDataSource` described below.
Class description:
Datasource used for loading landmarks. Uses id_dict['image_id'] as the landmark file key and returns a list of landmarks.
Method signatures and docstrings:
- def __init__(self, point_list_file_name, num_points, dim, silent_not_found=F... | ef6cee91264ba1fe6b40d9823a07647b95bcc2c4 | <|skeleton|>
class LandmarkDataSource:
"""Datasource used for loading landmarks. Uses id_dict['image_id'] as the landmark file key and returns a list of landmarks."""
def __init__(self, point_list_file_name, num_points, dim, silent_not_found=False, id_dict_preprocessing=None):
"""Initializer. :param po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LandmarkDataSource:
"""Datasource used for loading landmarks. Uses id_dict['image_id'] as the landmark file key and returns a list of landmarks."""
def __init__(self, point_list_file_name, num_points, dim, silent_not_found=False, id_dict_preprocessing=None):
"""Initializer. :param point_list_file... | the_stack_v2_python_sparse | datasources/landmark_datasource.py | XiaoweiXu/MedicalDataAugmentationTool | train | 1 |
e092232d2590065e5006df17a75f70e39d5a04ad | [
"Space.__init__(self, signalHandlers)\nself.size = size\nwidth, height, depth = size\nself.sectors = [[[sectorType() for i in xrange(width)] for j in xrange(height)] for k in xrange(depth)]",
"i, j, k = index\nif i < 0 or j < 0 or k < 0:\n raise KeyError\nreturn self.sectors[k][j][i]"
] | <|body_start_0|>
Space.__init__(self, signalHandlers)
self.size = size
width, height, depth = size
self.sectors = [[[sectorType() for i in xrange(width)] for j in xrange(height)] for k in xrange(depth)]
<|end_body_0|>
<|body_start_1|>
i, j, k = index
if i < 0 or j < 0 or... | A space with its sectors arranged as a 3-dimensional array. | Array3dSpace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array3dSpace:
"""A space with its sectors arranged as a 3-dimensional array."""
def __init__(self, signalHandlers, size, sectorType=Sector):
"""Create a space with the three dimensions given in size."""
<|body_0|>
def __getitem__(self, index):
"""Retrieve a secto... | stack_v2_sparse_classes_75kplus_train_066055 | 4,551 | no_license | [
{
"docstring": "Create a space with the three dimensions given in size.",
"name": "__init__",
"signature": "def __init__(self, signalHandlers, size, sectorType=Sector)"
},
{
"docstring": "Retrieve a sector by coordinate index.",
"name": "__getitem__",
"signature": "def __getitem__(self, ... | 2 | stack_v2_sparse_classes_30k_train_053612 | Implement the Python class `Array3dSpace` described below.
Class description:
A space with its sectors arranged as a 3-dimensional array.
Method signatures and docstrings:
- def __init__(self, signalHandlers, size, sectorType=Sector): Create a space with the three dimensions given in size.
- def __getitem__(self, ind... | Implement the Python class `Array3dSpace` described below.
Class description:
A space with its sectors arranged as a 3-dimensional array.
Method signatures and docstrings:
- def __init__(self, signalHandlers, size, sectorType=Sector): Create a space with the three dimensions given in size.
- def __getitem__(self, ind... | 1e68c771cf041a6951d1c853dd20f99a4b5e7eb5 | <|skeleton|>
class Array3dSpace:
"""A space with its sectors arranged as a 3-dimensional array."""
def __init__(self, signalHandlers, size, sectorType=Sector):
"""Create a space with the three dimensions given in size."""
<|body_0|>
def __getitem__(self, index):
"""Retrieve a secto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Array3dSpace:
"""A space with its sectors arranged as a 3-dimensional array."""
def __init__(self, signalHandlers, size, sectorType=Sector):
"""Create a space with the three dimensions given in size."""
Space.__init__(self, signalHandlers)
self.size = size
width, height, d... | the_stack_v2_python_sparse | simulation/space.py | gregr/uriel | train | 0 |
04c9db5252c3ebd00174b92e2603904182e33a68 | [
"if user_id == 'me':\n user = auth.get_current_user()\n if not user:\n return self.error('not authenticated', 401)\nelse:\n raise NotImplementedError\nuser.options = list(ItemOption.query.filter(ItemOption.item_id == user.id))\nreturn self.respond_with_schema(user_schema, user)",
"if user_id == 'm... | <|body_start_0|>
if user_id == 'me':
user = auth.get_current_user()
if not user:
return self.error('not authenticated', 401)
else:
raise NotImplementedError
user.options = list(ItemOption.query.filter(ItemOption.item_id == user.id))
ret... | UserDetailsResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetailsResource:
def get(self, user_id: str):
"""Return information on a user."""
<|body_0|>
def put(self, user_id: str):
"""Return information on a user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if user_id == 'me':
user = aut... | stack_v2_sparse_classes_75kplus_train_066056 | 1,582 | permissive | [
{
"docstring": "Return information on a user.",
"name": "get",
"signature": "def get(self, user_id: str)"
},
{
"docstring": "Return information on a user.",
"name": "put",
"signature": "def put(self, user_id: str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052551 | Implement the Python class `UserDetailsResource` described below.
Class description:
Implement the UserDetailsResource class.
Method signatures and docstrings:
- def get(self, user_id: str): Return information on a user.
- def put(self, user_id: str): Return information on a user. | Implement the Python class `UserDetailsResource` described below.
Class description:
Implement the UserDetailsResource class.
Method signatures and docstrings:
- def get(self, user_id: str): Return information on a user.
- def put(self, user_id: str): Return information on a user.
<|skeleton|>
class UserDetailsResou... | 6d4a490c19ebe406b551641a022ca08f26c21fcb | <|skeleton|>
class UserDetailsResource:
def get(self, user_id: str):
"""Return information on a user."""
<|body_0|>
def put(self, user_id: str):
"""Return information on a user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserDetailsResource:
def get(self, user_id: str):
"""Return information on a user."""
if user_id == 'me':
user = auth.get_current_user()
if not user:
return self.error('not authenticated', 401)
else:
raise NotImplementedError
... | the_stack_v2_python_sparse | zeus/api/resources/user_details.py | getsentry/zeus | train | 222 | |
03acc116a75eb60d6aaf99255d7478285674da1d | [
"self._state = VoidPointer()\nresult = raw_ofb_lib.OFB_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of())\nif result:\n raise ValueError('Error %d while instantiating the OFB mode' % result)\nself._state = SmartPointer(self._state.get(), raw_ofb_lib.OFB_stop_operati... | <|body_start_0|>
self._state = VoidPointer()
result = raw_ofb_lib.OFB_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of())
if result:
raise ValueError('Error %d while instantiating the OFB mode' % result)
self._state = SmartPointer... | *Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.4. .. _`NIST SP800-38A` : http://... | OfbMode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfbMode:
"""*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section ... | stack_v2_sparse_classes_75kplus_train_066057 | 10,281 | permissive | [
{
"docstring": "Create a new block cipher, configured in OFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : bytes/bytearray/memoryview The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be a no... | 3 | stack_v2_sparse_classes_30k_train_037568 | Implement the Python class `OfbMode` described below.
Class description:
*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is req... | Implement the Python class `OfbMode` described below.
Class description:
*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is req... | fa82044a2dc2f0f1f7454f5394e6d68fa923c289 | <|skeleton|>
class OfbMode:
"""*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfbMode:
"""*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.4. .. _`NIS... | the_stack_v2_python_sparse | venv/lib/python3.6/site-packages/Crypto/Cipher/_mode_ofb.py | masora1030/eigoyurusan | train | 11 |
a995c546e793835109f1e4e4ba4fee56df26ed3a | [
"N, C, H, W = features.size()\nF_l = features.view(1, C, H * W)\ngram = torch.mm(F_l[0, :, :], F_l[0, :, :].transpose(1, 0))\nif normalize:\n gram = gram / (H * W * C)\ngram = gram.unsqueeze(0)\nreturn gram",
"style_loss = torch.zeros(1)\nfor i in range(len(style_layers)):\n im_gram = self.gram_matrix(feats... | <|body_start_0|>
N, C, H, W = features.size()
F_l = features.view(1, C, H * W)
gram = torch.mm(F_l[0, :, :], F_l[0, :, :].transpose(1, 0))
if normalize:
gram = gram / (H * W * C)
gram = gram.unsqueeze(0)
return gram
<|end_body_0|>
<|body_start_1|>
sty... | StyleLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleLoss:
def gram_matrix(self, features, normalize=True):
"""Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch of N images. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram m... | stack_v2_sparse_classes_75kplus_train_066058 | 2,194 | no_license | [
{
"docstring": "Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch of N images. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by the number of neurons (H * W * C) Returns: - gram: PyTorch Var... | 2 | stack_v2_sparse_classes_30k_train_047641 | Implement the Python class `StyleLoss` described below.
Class description:
Implement the StyleLoss class.
Method signatures and docstrings:
- def gram_matrix(self, features, normalize=True): Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch o... | Implement the Python class `StyleLoss` described below.
Class description:
Implement the StyleLoss class.
Method signatures and docstrings:
- def gram_matrix(self, features, normalize=True): Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch o... | 9463299e76ee200518e1448fdaf518339d773238 | <|skeleton|>
class StyleLoss:
def gram_matrix(self, features, normalize=True):
"""Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch of N images. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StyleLoss:
def gram_matrix(self, features, normalize=True):
"""Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch of N images. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by the n... | the_stack_v2_python_sparse | Network_Visualization_and_Style_Transfer/style_modules/style_loss.py | jiani556/Deep-Learning | train | 0 | |
11c025c713f94d85e2e9c3cc80a4ccd676d0e582 | [
"if not root:\n return '#'\nreturn str(root.val) + '-' + self.serialize(root.left) + '-' + self.serialize(root.right)",
"data = data.split('-')\nself.count = 0\n\ndef traverse():\n if data[self.count] == '#':\n self.count += 1\n return None\n root = TreeNode(int(data[self.count]))\n self... | <|body_start_0|>
if not root:
return '#'
return str(root.val) + '-' + self.serialize(root.left) + '-' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
data = data.split('-')
self.count = 0
def traverse():
if data[self.count] == '#':
... | 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|>
if not root:
... | stack_v2_sparse_classes_75kplus_train_066059 | 1,877 | 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_005189 | 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... | 284fcd4b022a1441861c1a3a79fbab2fe9068c49 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return '#'
return str(root.val) + '-' + self.serialize(root.left) + '-' + self.serialize(root.right)
def deserialize(self, data: str) -> TreeNode:
"""Decode... | the_stack_v2_python_sparse | 30-Day LeetCoding Challenge/October/Medium/449. Serialize and Deserialize BST.py | khushboo1510/leetcode-solutions | train | 1 | |
ac323f8956ef9bf6174ad464ad7e5667b825c779 | [
"self.api_root = api_root\nself.review_request_id = review_request_id\nself.diff_revision = diff_revision\nself.max_comments = max_comments\nself.comments = []\nif logger is None:\n self.logger = logging.getLogger('batchreview')\nelse:\n self.logger = logger\nself._destfile_to_file = {}\nself._file_to_diffdat... | <|body_start_0|>
self.api_root = api_root
self.review_request_id = review_request_id
self.diff_revision = diff_revision
self.max_comments = max_comments
self.comments = []
if logger is None:
self.logger = logging.getLogger('batchreview')
else:
... | Create a review and comments with a single API call Using BatchReview is much faster than creating a review and comments with individual API calls. | BatchReview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchReview:
"""Create a review and comments with a single API call Using BatchReview is much faster than creating a review and comments with individual API calls."""
def __init__(self, api_root, review_request_id, diff_revision, max_comments=100, logger=None):
"""Initialize BatchRev... | stack_v2_sparse_classes_75kplus_train_066060 | 5,356 | no_license | [
{
"docstring": "Initialize BatchReview The ``api_root`` is the result of calling get_root on a Reviewboard client. The ``review_request_id`` is the integer identifier of the review request on which to leave the review. The ``diff_revision`` is the integer identifier of the diff revision for which to leave the r... | 6 | null | Implement the Python class `BatchReview` described below.
Class description:
Create a review and comments with a single API call Using BatchReview is much faster than creating a review and comments with individual API calls.
Method signatures and docstrings:
- def __init__(self, api_root, review_request_id, diff_revi... | Implement the Python class `BatchReview` described below.
Class description:
Create a review and comments with a single API call Using BatchReview is much faster than creating a review and comments with individual API calls.
Method signatures and docstrings:
- def __init__(self, api_root, review_request_id, diff_revi... | 8ef71a98892473434dbd903647a11b6903b3c92a | <|skeleton|>
class BatchReview:
"""Create a review and comments with a single API call Using BatchReview is much faster than creating a review and comments with individual API calls."""
def __init__(self, api_root, review_request_id, diff_revision, max_comments=100, logger=None):
"""Initialize BatchRev... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchReview:
"""Create a review and comments with a single API call Using BatchReview is much faster than creating a review and comments with individual API calls."""
def __init__(self, api_root, review_request_id, diff_revision, max_comments=100, logger=None):
"""Initialize BatchReview The ``api... | the_stack_v2_python_sparse | mozreviewpulse/mozreviewpulse/batchreview.py | mjzffr/version-control-tools | train | 1 |
639eaffb78e6988255a9c08e1d51840d6e98a772 | [
"if not data:\n error_message = error_message or \"Unable to fetch API response from endpoint '{}'.\".format(request.get_full_path())\n LOGGER.error(error_message)\n raise NotFound(error_message)",
"if 'no_page' in self.request.query_params:\n return None\nreturn super(EnterpriseViewSet, self).paginat... | <|body_start_0|>
if not data:
error_message = error_message or "Unable to fetch API response from endpoint '{}'.".format(request.get_full_path())
LOGGER.error(error_message)
raise NotFound(error_message)
<|end_body_0|>
<|body_start_1|>
if 'no_page' in self.request.qu... | Base class for all Enterprise view sets. | EnterpriseViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnterpriseViewSet:
"""Base class for all Enterprise view sets."""
def ensure_data_exists(self, request, data, error_message=None):
"""Ensure that the API response brings us valid data. If not, raise an error and log it."""
<|body_0|>
def paginate_queryset(self, queryset)... | stack_v2_sparse_classes_75kplus_train_066061 | 13,701 | no_license | [
{
"docstring": "Ensure that the API response brings us valid data. If not, raise an error and log it.",
"name": "ensure_data_exists",
"signature": "def ensure_data_exists(self, request, data, error_message=None)"
},
{
"docstring": "Allows no_page query param to skip pagination",
"name": "pag... | 2 | stack_v2_sparse_classes_30k_train_016248 | Implement the Python class `EnterpriseViewSet` described below.
Class description:
Base class for all Enterprise view sets.
Method signatures and docstrings:
- def ensure_data_exists(self, request, data, error_message=None): Ensure that the API response brings us valid data. If not, raise an error and log it.
- def p... | Implement the Python class `EnterpriseViewSet` described below.
Class description:
Base class for all Enterprise view sets.
Method signatures and docstrings:
- def ensure_data_exists(self, request, data, error_message=None): Ensure that the API response brings us valid data. If not, raise an error and log it.
- def p... | d16a25b035b2e810b8ab2b0a2ac032b216562e26 | <|skeleton|>
class EnterpriseViewSet:
"""Base class for all Enterprise view sets."""
def ensure_data_exists(self, request, data, error_message=None):
"""Ensure that the API response brings us valid data. If not, raise an error and log it."""
<|body_0|>
def paginate_queryset(self, queryset)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnterpriseViewSet:
"""Base class for all Enterprise view sets."""
def ensure_data_exists(self, request, data, error_message=None):
"""Ensure that the API response brings us valid data. If not, raise an error and log it."""
if not data:
error_message = error_message or "Unable ... | the_stack_v2_python_sparse | edx/app/analytics_api/venvs/analytics_api/lib/python2.7/site-packages/enterprise_data/api/v0/views.py | JosiahKennedy/openedx-branded | train | 0 |
df4123b16fbdb1afbca0951dd9a15373712b2aba | [
"self.typology = 'Point'\nself.source_id = identifier\nself.name = name\nself.tectonic_region_type = tectonic_region\nself.aspect_ratio = aspect_ratio\nself.mfd = None\nself.msr = None\nif upper_depth < 0.0:\n raise ValueError('Upper Depth Must be Non Negative')\nself.upper_depth = upper_depth\nif lower_depth an... | <|body_start_0|>
self.typology = 'Point'
self.source_id = identifier
self.name = name
self.tectonic_region_type = tectonic_region
self.aspect_ratio = aspect_ratio
self.mfd = None
self.msr = None
if upper_depth < 0.0:
raise ValueError('Upper Dep... | New class to describe the mtkPointsource object | mtkPointSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mtkPointSource:
"""New class to describe the mtkPointsource object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None):
"""Instantiate class with just the basic attributes :param identifier: Integer ID code for the... | stack_v2_sparse_classes_75kplus_train_066062 | 6,769 | no_license | [
{
"docstring": "Instantiate class with just the basic attributes :param identifier: Integer ID code for the source :param name: Source Name (string) :param tectonic_region: Tectonic Region Type (String) :param aspect_ratio: Ratio of along-strike length to down-dip width (float) :param input_geometry: Point geom... | 2 | null | Implement the Python class `mtkPointSource` described below.
Class description:
New class to describe the mtkPointsource object
Method signatures and docstrings:
- def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None): Instantiate class with just the ba... | Implement the Python class `mtkPointSource` described below.
Class description:
New class to describe the mtkPointsource object
Method signatures and docstrings:
- def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None): Instantiate class with just the ba... | cb98126555d54548f8e6ff8305eef15328930310 | <|skeleton|>
class mtkPointSource:
"""New class to describe the mtkPointsource object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None):
"""Instantiate class with just the basic attributes :param identifier: Integer ID code for the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class mtkPointSource:
"""New class to describe the mtkPointsource object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None):
"""Instantiate class with just the basic attributes :param identifier: Integer ID code for the source :para... | the_stack_v2_python_sparse | seismicity_modeller/mtk/sources/mtk_point.py | g-weatherill/prototype_code | train | 0 |
afc8f12ca5cb2413ab02a1ad642426712d6868f0 | [
"self.query_str = ''\nself.tree = TreeNode()\nfor word in words:\n current_node = self.tree\n for letter in word[::-1]:\n current_node = current_node.children[letter]\n current_node.final = True",
"self.query_str += letter\nif len(self.query_str) > 2000:\n self.query_str = self.query_str[1:]\nc... | <|body_start_0|>
self.query_str = ''
self.tree = TreeNode()
for word in words:
current_node = self.tree
for letter in word[::-1]:
current_node = current_node.children[letter]
current_node.final = True
<|end_body_0|>
<|body_start_1|>
se... | StreamChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.query_str = ''
self.tree = TreeNode()
f... | stack_v2_sparse_classes_75kplus_train_066063 | 1,262 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type letter: str :rtype: bool",
"name": "query",
"signature": "def query(self, letter)"
}
] | 2 | null | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool
<|skeleton|>
class StreamChecker:
def __init__(self, w... | c7964d1b921d9a4e821abec02212a69b12891c83 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
self.query_str = ''
self.tree = TreeNode()
for word in words:
current_node = self.tree
for letter in word[::-1]:
current_node = current_node.children[letter]
... | the_stack_v2_python_sparse | 1032-Stream_of_Characters.py | FomalhautA/Algs | train | 0 | |
60f550aaf0208eb42d44fdeeb0cfedac3faaca75 | [
"Cat.__init__(self, x, y)\nself.sprite_sheet = SpriteSheet(constants.NYAN_CAT_IMG)\nself.images = []\nimage = self.sprite_sheet.get_image(2, 4, 52, 20)\nself.images.append(image)\nimage = self.sprite_sheet.get_image(63, 4, 52, 20)\nself.images.append(image)\nimage = self.sprite_sheet.get_image(123, 4, 52, 20)\nself... | <|body_start_0|>
Cat.__init__(self, x, y)
self.sprite_sheet = SpriteSheet(constants.NYAN_CAT_IMG)
self.images = []
image = self.sprite_sheet.get_image(2, 4, 52, 20)
self.images.append(image)
image = self.sprite_sheet.get_image(63, 4, 52, 20)
self.images.append(ima... | A subclass of the Cat character. This NyanCat is used for the victory screen. Nyaaaa!!! Attributes: img_index (int): the current index in the list of images. | NyanCat | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NyanCat:
"""A subclass of the Cat character. This NyanCat is used for the victory screen. Nyaaaa!!! Attributes: img_index (int): the current index in the list of images."""
def __init__(self, x, y):
"""Initialize NyanCat. Arguments: x (int): x coordinate of this sprite. y (int): y co... | stack_v2_sparse_classes_75kplus_train_066064 | 8,124 | permissive | [
{
"docstring": "Initialize NyanCat. Arguments: x (int): x coordinate of this sprite. y (int): y coordinate of this sprite.",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "Update NyanCat accordingly. Returns: None",
"name": "update",
"signature": "def upda... | 2 | stack_v2_sparse_classes_30k_train_033557 | Implement the Python class `NyanCat` described below.
Class description:
A subclass of the Cat character. This NyanCat is used for the victory screen. Nyaaaa!!! Attributes: img_index (int): the current index in the list of images.
Method signatures and docstrings:
- def __init__(self, x, y): Initialize NyanCat. Argum... | Implement the Python class `NyanCat` described below.
Class description:
A subclass of the Cat character. This NyanCat is used for the victory screen. Nyaaaa!!! Attributes: img_index (int): the current index in the list of images.
Method signatures and docstrings:
- def __init__(self, x, y): Initialize NyanCat. Argum... | 2533fa0869e816769627d9759e96bccd03dfafb6 | <|skeleton|>
class NyanCat:
"""A subclass of the Cat character. This NyanCat is used for the victory screen. Nyaaaa!!! Attributes: img_index (int): the current index in the list of images."""
def __init__(self, x, y):
"""Initialize NyanCat. Arguments: x (int): x coordinate of this sprite. y (int): y co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NyanCat:
"""A subclass of the Cat character. This NyanCat is used for the victory screen. Nyaaaa!!! Attributes: img_index (int): the current index in the list of images."""
def __init__(self, x, y):
"""Initialize NyanCat. Arguments: x (int): x coordinate of this sprite. y (int): y coordinate of t... | the_stack_v2_python_sparse | characters/cat.py | j-cali/save-me-right-meow | train | 1 |
ff58c4d0f9d4b3f1e767dd917f41053e025e7339 | [
"self.type = t\nself.beg = beg\nself.end = end",
"if self.type == 'new':\n color = pg.Color('green')\nif self.type == 'glass':\n color = pg.Color('cyan')\nelse:\n color = pg.Color('darkred')\npg.draw.line(screen, color, self.beg, self.end)"
] | <|body_start_0|>
self.type = t
self.beg = beg
self.end = end
<|end_body_0|>
<|body_start_1|>
if self.type == 'new':
color = pg.Color('green')
if self.type == 'glass':
color = pg.Color('cyan')
else:
color = pg.Color('darkred')
p... | Class for walls and glasses | Wall | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wall:
"""Class for walls and glasses"""
def __init__(self, t, beg, end):
"""TODO: to be defined1."""
<|body_0|>
def draw(self, screen: pg.Surface):
"""TODO: Docstring for draw. :f: TODO :screen: pg.surface.: TODO :returns: TODO"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_066065 | 633 | no_license | [
{
"docstring": "TODO: to be defined1.",
"name": "__init__",
"signature": "def __init__(self, t, beg, end)"
},
{
"docstring": "TODO: Docstring for draw. :f: TODO :screen: pg.surface.: TODO :returns: TODO",
"name": "draw",
"signature": "def draw(self, screen: pg.Surface)"
}
] | 2 | null | Implement the Python class `Wall` described below.
Class description:
Class for walls and glasses
Method signatures and docstrings:
- def __init__(self, t, beg, end): TODO: to be defined1.
- def draw(self, screen: pg.Surface): TODO: Docstring for draw. :f: TODO :screen: pg.surface.: TODO :returns: TODO | Implement the Python class `Wall` described below.
Class description:
Class for walls and glasses
Method signatures and docstrings:
- def __init__(self, t, beg, end): TODO: to be defined1.
- def draw(self, screen: pg.Surface): TODO: Docstring for draw. :f: TODO :screen: pg.surface.: TODO :returns: TODO
<|skeleton|>
... | a7e60426cfd1f9f6812947846d0813c03ec6d63e | <|skeleton|>
class Wall:
"""Class for walls and glasses"""
def __init__(self, t, beg, end):
"""TODO: to be defined1."""
<|body_0|>
def draw(self, screen: pg.Surface):
"""TODO: Docstring for draw. :f: TODO :screen: pg.surface.: TODO :returns: TODO"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Wall:
"""Class for walls and glasses"""
def __init__(self, t, beg, end):
"""TODO: to be defined1."""
self.type = t
self.beg = beg
self.end = end
def draw(self, screen: pg.Surface):
"""TODO: Docstring for draw. :f: TODO :screen: pg.surface.: TODO :returns: TODO... | the_stack_v2_python_sparse | sem_2/ookp/proj/wall.py | anstadnik/univ | train | 0 |
047f80690a5099e9f1505b2dd7da347d7bd2adc1 | [
"lists_ = []\nfor row in matrix:\n lists_ += row\nlists_.sort()\nreturn lists_[k - 1]",
"n = len(matrix)\npointers = [0] * n\ncount = 0\nwhile True:\n min_, min_index = (float('inf'), -1)\n for index, point in enumerate(pointers):\n if point < n:\n tmp_min = matrix[index][point]\n ... | <|body_start_0|>
lists_ = []
for row in matrix:
lists_ += row
lists_.sort()
return lists_[k - 1]
<|end_body_0|>
<|body_start_1|>
n = len(matrix)
pointers = [0] * n
count = 0
while True:
min_, min_index = (float('inf'), -1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest2(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_066066 | 2,165 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSmallest(self, matrix, k)"
},
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest2",
"signature": "def kthSmallest2(self, matrix,... | 2 | stack_v2_sparse_classes_30k_train_033809 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest2(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest2(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: i... | cefa2f08667de4d2973274de3ff29a31a7d25eda | <|skeleton|>
class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest2(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
lists_ = []
for row in matrix:
lists_ += row
lists_.sort()
return lists_[k - 1]
def kthSmallest2(self, matrix, k):
""":type matrix: List[Lis... | the_stack_v2_python_sparse | 378/Solution.py | zhangruochi/leetcode | train | 14 | |
600b474162e535fa590fe388601d73e476261085 | [
"super().__init__()\nself.n_patches = int(np.prod([i / patch_size for i in img_size]))\nself.pos_embed = nn.Parameter(torch.zeros(1, self.n_patches, embed_size))\nself.patch_embed = Conv(in_channels=in_feats, out_channels=embed_size, kernel_size=patch_size, stride=patch_size)",
"x = self.patch_embed(x)\nx = x.fla... | <|body_start_0|>
super().__init__()
self.n_patches = int(np.prod([i / patch_size for i in img_size]))
self.pos_embed = nn.Parameter(torch.zeros(1, self.n_patches, embed_size))
self.patch_embed = Conv(in_channels=in_feats, out_channels=embed_size, kernel_size=patch_size, stride=patch_size... | _Embedding | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Embedding:
def __init__(self, img_size, patch_size, in_feats, embed_size, Conv):
"""A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided... | stack_v2_sparse_classes_75kplus_train_066067 | 24,719 | permissive | [
{
"docstring": "A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided into. in_feats (int): The number of input channels in the image tensor. embed_size (int): Th... | 2 | stack_v2_sparse_classes_30k_test_002584 | Implement the Python class `_Embedding` described below.
Class description:
Implement the _Embedding class.
Method signatures and docstrings:
- def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the inpu... | Implement the Python class `_Embedding` described below.
Class description:
Implement the _Embedding class.
Method signatures and docstrings:
- def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the inpu... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class _Embedding:
def __init__(self, img_size, patch_size, in_feats, embed_size, Conv):
"""A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Embedding:
def __init__(self, img_size, patch_size, in_feats, embed_size, Conv):
"""A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided into. in_feat... | the_stack_v2_python_sparse | GANDLF/models/unetr.py | mlcommons/GaNDLF | train | 45 | |
0f6283b4e3e3e57f2001b80c41e274299a984ae7 | [
"if node is None:\n return None\nwhile node.right:\n node = node.right\nreturn node",
"if node is None:\n return None\nwhile node.left:\n node = node.left\nreturn node",
"if root is None:\n return True\nresult = False\nif self.isValidBST(root.left) and self.isValidBST(root.right):\n max_left =... | <|body_start_0|>
if node is None:
return None
while node.right:
node = node.right
return node
<|end_body_0|>
<|body_start_1|>
if node is None:
return None
while node.left:
node = node.left
return node
<|end_body_1|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def right_most(self, node):
""">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2"""
<|body_0|>
def left... | stack_v2_sparse_classes_75kplus_train_066068 | 2,115 | no_license | [
{
"docstring": ">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2",
"name": "right_most",
"signature": "def right_most(self, node)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_023486 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def right_most(self, node): >>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>>... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def right_most(self, node): >>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>>... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def right_most(self, node):
""">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2"""
<|body_0|>
def left... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def right_most(self, node):
""">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2"""
if node is None:
return No... | the_stack_v2_python_sparse | validate_bst.py | gsy/leetcode | train | 1 | |
2b3d9dee1a08c017f17e621e995a8ecd1e8aed43 | [
"mol = Chem.MolFromSmiles(smiles)\nengine = ScaffoldGenerator(include_chirality=include_chirality)\nscaffold = engine.get_scaffold(mol)\nreturn scaffold",
"np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)\nscaffolds = {}\nlog('About to generate scaffolds', self.verbose)\ndata_len = len(dat... | <|body_start_0|>
mol = Chem.MolFromSmiles(smiles)
engine = ScaffoldGenerator(include_chirality=include_chirality)
scaffold = engine.get_scaffold(mol)
return scaffold
<|end_body_0|>
<|body_start_1|>
np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)
... | Class for doing data splits based on the scaffold of small molecules. | ScaffoldSplitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaffoldSplitter:
"""Class for doing data splits based on the scaffold of small molecules."""
def generate_scaffold(self, smiles, include_chirality=False):
"""Compute the Bemis-Murcko scaffold for a SMILES string."""
<|body_0|>
def split(self, dataset, frac_train=0.5, fr... | stack_v2_sparse_classes_75kplus_train_066069 | 3,303 | no_license | [
{
"docstring": "Compute the Bemis-Murcko scaffold for a SMILES string.",
"name": "generate_scaffold",
"signature": "def generate_scaffold(self, smiles, include_chirality=False)"
},
{
"docstring": "Splits internal compounds into train/validation/test by scaffold.",
"name": "split",
"signa... | 2 | stack_v2_sparse_classes_30k_train_009323 | Implement the Python class `ScaffoldSplitter` described below.
Class description:
Class for doing data splits based on the scaffold of small molecules.
Method signatures and docstrings:
- def generate_scaffold(self, smiles, include_chirality=False): Compute the Bemis-Murcko scaffold for a SMILES string.
- def split(s... | Implement the Python class `ScaffoldSplitter` described below.
Class description:
Class for doing data splits based on the scaffold of small molecules.
Method signatures and docstrings:
- def generate_scaffold(self, smiles, include_chirality=False): Compute the Bemis-Murcko scaffold for a SMILES string.
- def split(s... | 57e40d04181059ca39890d22361606edfadcc930 | <|skeleton|>
class ScaffoldSplitter:
"""Class for doing data splits based on the scaffold of small molecules."""
def generate_scaffold(self, smiles, include_chirality=False):
"""Compute the Bemis-Murcko scaffold for a SMILES string."""
<|body_0|>
def split(self, dataset, frac_train=0.5, fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScaffoldSplitter:
"""Class for doing data splits based on the scaffold of small molecules."""
def generate_scaffold(self, smiles, include_chirality=False):
"""Compute the Bemis-Murcko scaffold for a SMILES string."""
mol = Chem.MolFromSmiles(smiles)
engine = ScaffoldGenerator(incl... | the_stack_v2_python_sparse | utils/splitter/scaffoldsplitter.py | moguizhizi/Adaptive-Graph-Convolutional-Network | train | 0 |
1d6a1395cb5d1bb1c0de2d69f4908aaed6a15d2d | [
"phone_valid = user_service.check_phone_valid(phone)\nif phone_valid:\n code = captcha_service.get_captch(phone)\n response = {'phone': phone, 'captcha': code}\n return APIResponse(response)\nelse:\n return APIResponse(status_code=status.HTTP_400_BAD_REQUEST)",
"phone_valid = user_service.check_phone_... | <|body_start_0|>
phone_valid = user_service.check_phone_valid(phone)
if phone_valid:
code = captcha_service.get_captch(phone)
response = {'phone': phone, 'captcha': code}
return APIResponse(response)
else:
return APIResponse(status_code=status.HTTP... | CaptchaViewSet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaptchaViewSet:
def retrieve(self, request, phone):
"""获得某个手机号的验证码 用于测试,只获得验证码而不发送短信。 ### Example Request captcha/{phone}/ ### Response { 'phone': phone, 'captcha': code, }"""
<|body_0|>
def send(self, request, phone):
"""发送验证码 Does actions for captcha. captcha/{phon... | stack_v2_sparse_classes_75kplus_train_066070 | 9,704 | permissive | [
{
"docstring": "获得某个手机号的验证码 用于测试,只获得验证码而不发送短信。 ### Example Request captcha/{phone}/ ### Response { 'phone': phone, 'captcha': code, }",
"name": "retrieve",
"signature": "def retrieve(self, request, phone)"
},
{
"docstring": "发送验证码 Does actions for captcha. captcha/{phone}/send/ phone -- phone nu... | 2 | stack_v2_sparse_classes_30k_train_011695 | Implement the Python class `CaptchaViewSet` described below.
Class description:
Implement the CaptchaViewSet class.
Method signatures and docstrings:
- def retrieve(self, request, phone): 获得某个手机号的验证码 用于测试,只获得验证码而不发送短信。 ### Example Request captcha/{phone}/ ### Response { 'phone': phone, 'captcha': code, }
- def send(s... | Implement the Python class `CaptchaViewSet` described below.
Class description:
Implement the CaptchaViewSet class.
Method signatures and docstrings:
- def retrieve(self, request, phone): 获得某个手机号的验证码 用于测试,只获得验证码而不发送短信。 ### Example Request captcha/{phone}/ ### Response { 'phone': phone, 'captcha': code, }
- def send(s... | 31ac08148fbe67ab166faa897c0cbe72cd7f62db | <|skeleton|>
class CaptchaViewSet:
def retrieve(self, request, phone):
"""获得某个手机号的验证码 用于测试,只获得验证码而不发送短信。 ### Example Request captcha/{phone}/ ### Response { 'phone': phone, 'captcha': code, }"""
<|body_0|>
def send(self, request, phone):
"""发送验证码 Does actions for captcha. captcha/{phon... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaptchaViewSet:
def retrieve(self, request, phone):
"""获得某个手机号的验证码 用于测试,只获得验证码而不发送短信。 ### Example Request captcha/{phone}/ ### Response { 'phone': phone, 'captcha': code, }"""
phone_valid = user_service.check_phone_valid(phone)
if phone_valid:
code = captcha_service.get_cap... | the_stack_v2_python_sparse | wheat/apps/user/apis.py | fortyMiles/moment-note | train | 2 | |
01bc48ed390f6ab5ba16eb0a4249940853b27f48 | [
"if lazy_numer is None:\n self.lazy_numer = int(points_number / 10) + 1\nelse:\n self.lazy_numer = lazy_numer\nneighborhood_radius = 1\nsuper().__init__(points_number, neighborhood_radius, dim_network, dist_func_points, net_dist_to_lr, points_to_aprox, self.lazy_numer)",
"for pos_net, pos_space in self.neur... | <|body_start_0|>
if lazy_numer is None:
self.lazy_numer = int(points_number / 10) + 1
else:
self.lazy_numer = lazy_numer
neighborhood_radius = 1
super().__init__(points_number, neighborhood_radius, dim_network, dist_func_points, net_dist_to_lr, points_to_aprox, se... | Implementation neuron gas | Kohonen_network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kohonen_network:
"""Implementation neuron gas"""
def __init__(self, points_number, points_to_aprox, neighborhood_radius=1, net_dist_to_lr=GNF, dist_func_points=E_dist, lazy_numer=None, lr=0.2, dim_network=1):
"""Args: points_number: number of points to approximate dinm_network: numbe... | stack_v2_sparse_classes_75kplus_train_066071 | 2,416 | no_license | [
{
"docstring": "Args: points_number: number of points to approximate dinm_network: number of dimensions of network organization dist_func: callable object that takes two points of from points_to_aprox and returns distance between them net_dist_to_lr: callable object that takes poison of two neurons and returns ... | 2 | stack_v2_sparse_classes_30k_train_046316 | Implement the Python class `Kohonen_network` described below.
Class description:
Implementation neuron gas
Method signatures and docstrings:
- def __init__(self, points_number, points_to_aprox, neighborhood_radius=1, net_dist_to_lr=GNF, dist_func_points=E_dist, lazy_numer=None, lr=0.2, dim_network=1): Args: points_nu... | Implement the Python class `Kohonen_network` described below.
Class description:
Implementation neuron gas
Method signatures and docstrings:
- def __init__(self, points_number, points_to_aprox, neighborhood_radius=1, net_dist_to_lr=GNF, dist_func_points=E_dist, lazy_numer=None, lr=0.2, dim_network=1): Args: points_nu... | 2609bf83e00e1d8773f127e10d9c140341397554 | <|skeleton|>
class Kohonen_network:
"""Implementation neuron gas"""
def __init__(self, points_number, points_to_aprox, neighborhood_radius=1, net_dist_to_lr=GNF, dist_func_points=E_dist, lazy_numer=None, lr=0.2, dim_network=1):
"""Args: points_number: number of points to approximate dinm_network: numbe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Kohonen_network:
"""Implementation neuron gas"""
def __init__(self, points_number, points_to_aprox, neighborhood_radius=1, net_dist_to_lr=GNF, dist_func_points=E_dist, lazy_numer=None, lr=0.2, dim_network=1):
"""Args: points_number: number of points to approximate dinm_network: number of dimensio... | the_stack_v2_python_sparse | Zadanie2/SOM/Kohonen_network.py | PatrykLisik/iad | train | 0 |
a084d369655d9638372ec7be6c302df88fed8fe8 | [
"dp = [[0 for i in range(W + 1)] for j in range(N + 1)]\nfor i in range(1, N + 1):\n for w in range(1, W + 1):\n if w - wt[i - 1] < 0:\n dp[i][w] = dp[i - 1][w]\n else:\n dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - wt[i - 1]] + val[i - 1])\nreturn dp[N][W]",
"n = len(coins)\n... | <|body_start_0|>
dp = [[0 for i in range(W + 1)] for j in range(N + 1)]
for i in range(1, N + 1):
for w in range(1, W + 1):
if w - wt[i - 1] < 0:
dp[i][w] = dp[i - 1][w]
else:
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - w... | 背包问题 | PackageProblem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageProblem:
"""背包问题"""
def knapsack(self, W, N, wt, val):
"""0-1背包问题 描述: 给你一个可装载重量为 W 的背包和 N 个物品,每个物品有重量和价值两个属性。 其中第 `i` 个物品的重量为 `wt[i]`,价值为 `val[i]`,现在让你用这个背包装物品,最多能装的价值是多少? 状态和选择:**背包的容量 & 可选择的物品 明确dp数组的定义:**对于前`i`个物品,当前背包的容量为`w`,这种情况下可以装的最大价值是`dp[i][w]` 根据选择,思考状态转移的逻辑: - 没有把第i... | stack_v2_sparse_classes_75kplus_train_066072 | 2,535 | no_license | [
{
"docstring": "0-1背包问题 描述: 给你一个可装载重量为 W 的背包和 N 个物品,每个物品有重量和价值两个属性。 其中第 `i` 个物品的重量为 `wt[i]`,价值为 `val[i]`,现在让你用这个背包装物品,最多能装的价值是多少? 状态和选择:**背包的容量 & 可选择的物品 明确dp数组的定义:**对于前`i`个物品,当前背包的容量为`w`,这种情况下可以装的最大价值是`dp[i][w]` 根据选择,思考状态转移的逻辑: - 没有把第i个物品装入背包:dp[i][w] = dp[i-1][w] - 把第i个物品装入背包:dp[i][w] = dp[i-1][w-wt[i-1]] + va... | 2 | null | Implement the Python class `PackageProblem` described below.
Class description:
背包问题
Method signatures and docstrings:
- def knapsack(self, W, N, wt, val): 0-1背包问题 描述: 给你一个可装载重量为 W 的背包和 N 个物品,每个物品有重量和价值两个属性。 其中第 `i` 个物品的重量为 `wt[i]`,价值为 `val[i]`,现在让你用这个背包装物品,最多能装的价值是多少? 状态和选择:**背包的容量 & 可选择的物品 明确dp数组的定义:**对于前`i`个物品,当前背... | Implement the Python class `PackageProblem` described below.
Class description:
背包问题
Method signatures and docstrings:
- def knapsack(self, W, N, wt, val): 0-1背包问题 描述: 给你一个可装载重量为 W 的背包和 N 个物品,每个物品有重量和价值两个属性。 其中第 `i` 个物品的重量为 `wt[i]`,价值为 `val[i]`,现在让你用这个背包装物品,最多能装的价值是多少? 状态和选择:**背包的容量 & 可选择的物品 明确dp数组的定义:**对于前`i`个物品,当前背... | 70ca9c5ef5be291abbc6e48100ff638c4145eb58 | <|skeleton|>
class PackageProblem:
"""背包问题"""
def knapsack(self, W, N, wt, val):
"""0-1背包问题 描述: 给你一个可装载重量为 W 的背包和 N 个物品,每个物品有重量和价值两个属性。 其中第 `i` 个物品的重量为 `wt[i]`,价值为 `val[i]`,现在让你用这个背包装物品,最多能装的价值是多少? 状态和选择:**背包的容量 & 可选择的物品 明确dp数组的定义:**对于前`i`个物品,当前背包的容量为`w`,这种情况下可以装的最大价值是`dp[i][w]` 根据选择,思考状态转移的逻辑: - 没有把第i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PackageProblem:
"""背包问题"""
def knapsack(self, W, N, wt, val):
"""0-1背包问题 描述: 给你一个可装载重量为 W 的背包和 N 个物品,每个物品有重量和价值两个属性。 其中第 `i` 个物品的重量为 `wt[i]`,价值为 `val[i]`,现在让你用这个背包装物品,最多能装的价值是多少? 状态和选择:**背包的容量 & 可选择的物品 明确dp数组的定义:**对于前`i`个物品,当前背包的容量为`w`,这种情况下可以装的最大价值是`dp[i][w]` 根据选择,思考状态转移的逻辑: - 没有把第i个物品装入背包:dp[i]... | the_stack_v2_python_sparse | 3_dynamic_programming/package_problem.py | Step657/leetcode | train | 0 |
b02426f09e4c9a8b9fb5962d3e4dec3601109fda | [
"i, j = (0, num)\nwhile i <= j:\n mid = (i + j) // 2\n s = mid ** 2\n if s == num:\n return True\n elif s < num:\n i = mid + 1\n else:\n j = mid - 1\nreturn False",
"if num < 0:\n return False\nelif num == 1:\n return True\ni, j, last = (0, num, -1)\nwhile i <= j:\n mi... | <|body_start_0|>
i, j = (0, num)
while i <= j:
mid = (i + j) // 2
s = mid ** 2
if s == num:
return True
elif s < num:
i = mid + 1
else:
j = mid - 1
return False
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPerfectSquare(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def isPerfectSquare2(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i, j = (0, num)
while i <= j:
... | stack_v2_sparse_classes_75kplus_train_066073 | 1,736 | no_license | [
{
"docstring": ":type num: int :rtype: bool",
"name": "isPerfectSquare",
"signature": "def isPerfectSquare(self, num)"
},
{
"docstring": ":type num: int :rtype: bool",
"name": "isPerfectSquare2",
"signature": "def isPerfectSquare2(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036715 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPerfectSquare(self, num): :type num: int :rtype: bool
- def isPerfectSquare2(self, num): :type num: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPerfectSquare(self, num): :type num: int :rtype: bool
- def isPerfectSquare2(self, num): :type num: int :rtype: bool
<|skeleton|>
class Solution:
def isPerfectSquare(... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def isPerfectSquare(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def isPerfectSquare2(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPerfectSquare(self, num):
""":type num: int :rtype: bool"""
i, j = (0, num)
while i <= j:
mid = (i + j) // 2
s = mid ** 2
if s == num:
return True
elif s < num:
i = mid + 1
else:... | the_stack_v2_python_sparse | code367ValidPerfectSquare.py | cybelewang/leetcode-python | train | 0 | |
58fc98edb1e6fca22c80fabdb0744a0eab102f27 | [
"if isinstance(value, basestring):\n try:\n value = format.parse_decimal(value)\n except ValueError:\n pass\nreturn validators.Number.to_python(value, state)",
"dec_places = util.find_precision(value)\nif dec_places > 0:\n return format.format_decimal(value, dec_places)\nelse:\n return f... | <|body_start_0|>
if isinstance(value, basestring):
try:
value = format.parse_decimal(value)
except ValueError:
pass
return validators.Number.to_python(value, state)
<|end_body_0|>
<|body_start_1|>
dec_places = util.find_precision(value)
... | Number | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Number:
def _to_python(self, value, state):
"""parse a string and returns a float or integer"""
<|body_0|>
def _from_python(self, value, state):
"""returns a string using the correct grouping"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if isinst... | stack_v2_sparse_classes_75kplus_train_066074 | 8,823 | no_license | [
{
"docstring": "parse a string and returns a float or integer",
"name": "_to_python",
"signature": "def _to_python(self, value, state)"
},
{
"docstring": "returns a string using the correct grouping",
"name": "_from_python",
"signature": "def _from_python(self, value, state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008934 | Implement the Python class `Number` described below.
Class description:
Implement the Number class.
Method signatures and docstrings:
- def _to_python(self, value, state): parse a string and returns a float or integer
- def _from_python(self, value, state): returns a string using the correct grouping | Implement the Python class `Number` described below.
Class description:
Implement the Number class.
Method signatures and docstrings:
- def _to_python(self, value, state): parse a string and returns a float or integer
- def _from_python(self, value, state): returns a string using the correct grouping
<|skeleton|>
cl... | ca228848364edb204b15a7411fd6192379781c78 | <|skeleton|>
class Number:
def _to_python(self, value, state):
"""parse a string and returns a float or integer"""
<|body_0|>
def _from_python(self, value, state):
"""returns a string using the correct grouping"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Number:
def _to_python(self, value, state):
"""parse a string and returns a float or integer"""
if isinstance(value, basestring):
try:
value = format.parse_decimal(value)
except ValueError:
pass
return validators.Number.to_python(... | the_stack_v2_python_sparse | working-env/lib/python2.5/TurboGears-1.0.2.2-py2.5.egg/turbogears/validators.py | thraxil/gtreed | train | 1 | |
7c1e707daaacaa43e592c2c8d1d2a0b64e6401e0 | [
"for pin in self.pins:\n for dot in self.dots:\n distance = pin - dot\n if dot.distance == math.inf:\n dot.distance = distance\n else:\n dot.distance += distance",
"total = 0\nself.calc_sum_distances()\nfor dot in self.dots:\n if dot.distance < limit:\n tota... | <|body_start_0|>
for pin in self.pins:
for dot in self.dots:
distance = pin - dot
if dot.distance == math.inf:
dot.distance = distance
else:
dot.distance += distance
<|end_body_0|>
<|body_start_1|>
total... | A gird of time dots with pins. | Grid | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grid:
"""A gird of time dots with pins."""
def calc_sum_distances(self) -> None:
"""Get sum of pin distances for each dot."""
<|body_0|>
def closest_region_size(self, limit: int=10000) -> int:
"""Get number of dots with distance less than limit."""
<|body... | stack_v2_sparse_classes_75kplus_train_066075 | 1,033 | permissive | [
{
"docstring": "Get sum of pin distances for each dot.",
"name": "calc_sum_distances",
"signature": "def calc_sum_distances(self) -> None"
},
{
"docstring": "Get number of dots with distance less than limit.",
"name": "closest_region_size",
"signature": "def closest_region_size(self, lim... | 2 | stack_v2_sparse_classes_30k_train_021164 | Implement the Python class `Grid` described below.
Class description:
A gird of time dots with pins.
Method signatures and docstrings:
- def calc_sum_distances(self) -> None: Get sum of pin distances for each dot.
- def closest_region_size(self, limit: int=10000) -> int: Get number of dots with distance less than lim... | Implement the Python class `Grid` described below.
Class description:
A gird of time dots with pins.
Method signatures and docstrings:
- def calc_sum_distances(self) -> None: Get sum of pin distances for each dot.
- def closest_region_size(self, limit: int=10000) -> int: Get number of dots with distance less than lim... | 4b8ac6a97859b1320f77ba0ee91168b58db28cdb | <|skeleton|>
class Grid:
"""A gird of time dots with pins."""
def calc_sum_distances(self) -> None:
"""Get sum of pin distances for each dot."""
<|body_0|>
def closest_region_size(self, limit: int=10000) -> int:
"""Get number of dots with distance less than limit."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grid:
"""A gird of time dots with pins."""
def calc_sum_distances(self) -> None:
"""Get sum of pin distances for each dot."""
for pin in self.pins:
for dot in self.dots:
distance = pin - dot
if dot.distance == math.inf:
dot.d... | the_stack_v2_python_sparse | src/year2018/day06b.py | lancelote/advent_of_code | train | 11 |
c0776e6bc5b2f3ecb57a3a46234147c7d7405453 | [
"motion_gateway = MotionGateway(motor_board_adapter=socket_adapter_mock)\nawait motion_gateway.rotate(15)\nsocket_adapter_mock.send.assert_called_once_with(b'R\\x02\\x08\\x1e')",
"motion_gateway = MotionGateway(motor_board_adapter=socket_adapter_mock)\nawait motion_gateway.translate(15)\nsocket_adapter_mock.send.... | <|body_start_0|>
motion_gateway = MotionGateway(motor_board_adapter=socket_adapter_mock)
await motion_gateway.rotate(15)
socket_adapter_mock.send.assert_called_once_with(b'R\x02\x08\x1e')
<|end_body_0|>
<|body_start_1|>
motion_gateway = MotionGateway(motor_board_adapter=socket_adapter_m... | Tests for the motion gateway. | TestMotionGateway | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMotionGateway:
"""Tests for the motion gateway."""
async def test_rotate(socket_adapter_mock):
"""Test that the motion gateway calls the CAN adapter."""
<|body_0|>
async def test_translate(socket_adapter_mock):
"""Test that the motion gateway calls the CAN ad... | stack_v2_sparse_classes_75kplus_train_066076 | 936 | permissive | [
{
"docstring": "Test that the motion gateway calls the CAN adapter.",
"name": "test_rotate",
"signature": "async def test_rotate(socket_adapter_mock)"
},
{
"docstring": "Test that the motion gateway calls the CAN adapter.",
"name": "test_translate",
"signature": "async def test_translate... | 2 | null | Implement the Python class `TestMotionGateway` described below.
Class description:
Tests for the motion gateway.
Method signatures and docstrings:
- async def test_rotate(socket_adapter_mock): Test that the motion gateway calls the CAN adapter.
- async def test_translate(socket_adapter_mock): Test that the motion gat... | Implement the Python class `TestMotionGateway` described below.
Class description:
Tests for the motion gateway.
Method signatures and docstrings:
- async def test_rotate(socket_adapter_mock): Test that the motion gateway calls the CAN adapter.
- async def test_translate(socket_adapter_mock): Test that the motion gat... | b55d1ce6143ee7ef248fa7a9d6675c693b727d91 | <|skeleton|>
class TestMotionGateway:
"""Tests for the motion gateway."""
async def test_rotate(socket_adapter_mock):
"""Test that the motion gateway calls the CAN adapter."""
<|body_0|>
async def test_translate(socket_adapter_mock):
"""Test that the motion gateway calls the CAN ad... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMotionGateway:
"""Tests for the motion gateway."""
async def test_rotate(socket_adapter_mock):
"""Test that the motion gateway calls the CAN adapter."""
motion_gateway = MotionGateway(motor_board_adapter=socket_adapter_mock)
await motion_gateway.rotate(15)
socket_adapt... | the_stack_v2_python_sparse | highlevel/robot/gateway/motion/motion_test.py | outech-robotic/hl-flowing-clean-arch | train | 2 |
6f7df5c9b484cd3ae428083c4ec33156fa4b85db | [
"self.input_arr = [[1, 3, 4, 10], [2, 5, 9, 11], [6, 8, 12, 15], [7, 13, 14, 16]]\nself.output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\nreturn (self.input_arr, self.output)",
"input_arr, output_arr = self.setUp()\noutput = zigzagTraverse(input_arr)\nself.assertEqual(output, output_arr)"
] | <|body_start_0|>
self.input_arr = [[1, 3, 4, 10], [2, 5, 9, 11], [6, 8, 12, 15], [7, 13, 14, 16]]
self.output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
return (self.input_arr, self.output)
<|end_body_0|>
<|body_start_1|>
input_arr, output_arr = self.setUp()
outpu... | Class with unittests for ZigzagTraverse.py | test_ZigzagTraverse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_ZigzagTraverse:
"""Class with unittests for ZigzagTraverse.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_75kplus_train_066077 | 1,088 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022245 | Implement the Python class `test_ZigzagTraverse` described below.
Class description:
Class with unittests for ZigzagTraverse.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_ZigzagTraverse` described below.
Class description:
Class with unittests for ZigzagTraverse.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_ZigzagTraverse:
""... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_ZigzagTraverse:
"""Class with unittests for ZigzagTraverse.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_ZigzagTraverse:
"""Class with unittests for ZigzagTraverse.py"""
def setUp(self):
"""Sets up input."""
self.input_arr = [[1, 3, 4, 10], [2, 5, 9, 11], [6, 8, 12, 15], [7, 13, 14, 16]]
self.output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
return (self.i... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/ZigzagTraverse/test_ZigzagTraverse.py | JakubKazimierski/PythonPortfolio | train | 9 |
2b240565e8d891fd45f3853f3c87af73248f7457 | [
"self.factory = RequestFactory()\nself.temp_dir = tempfile.mkdtemp()\nsuper(ViewTestCase, self).setUp()",
"setattr(request, 'session', 'session')\nmessages = FallbackStorage(request)\nsetattr(request, '_messages', messages)",
"\"\"\"Annotate a request object with a session\"\"\"\nmiddleware = SessionMiddleware(... | <|body_start_0|>
self.factory = RequestFactory()
self.temp_dir = tempfile.mkdtemp()
super(ViewTestCase, self).setUp()
<|end_body_0|>
<|body_start_1|>
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
<|end_... | Test basic view functionality. | ViewTestCase | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewTestCase:
"""Test basic view functionality."""
def setUp(self):
"""Create request factory and set temp_dir for testing."""
<|body_0|>
def set_request_message_attributes(request):
"""Set session and _messages attributies on request."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_066078 | 40,377 | permissive | [
{
"docstring": "Create request factory and set temp_dir for testing.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Set session and _messages attributies on request.",
"name": "set_request_message_attributes",
"signature": "def set_request_message_attributes(request... | 3 | stack_v2_sparse_classes_30k_train_041119 | Implement the Python class `ViewTestCase` described below.
Class description:
Test basic view functionality.
Method signatures and docstrings:
- def setUp(self): Create request factory and set temp_dir for testing.
- def set_request_message_attributes(request): Set session and _messages attributies on request.
- def ... | Implement the Python class `ViewTestCase` described below.
Class description:
Test basic view functionality.
Method signatures and docstrings:
- def setUp(self): Create request factory and set temp_dir for testing.
- def set_request_message_attributes(request): Set session and _messages attributies on request.
- def ... | 69855813052243c702c9b0108d2eac3f4f1a768f | <|skeleton|>
class ViewTestCase:
"""Test basic view functionality."""
def setUp(self):
"""Create request factory and set temp_dir for testing."""
<|body_0|>
def set_request_message_attributes(request):
"""Set session and _messages attributies on request."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ViewTestCase:
"""Test basic view functionality."""
def setUp(self):
"""Create request factory and set temp_dir for testing."""
self.factory = RequestFactory()
self.temp_dir = tempfile.mkdtemp()
super(ViewTestCase, self).setUp()
def set_request_message_attributes(reque... | the_stack_v2_python_sparse | hs_core/testing.py | hydroshare/hydroshare | train | 207 |
14e5b466d4b5d3e6fe01d956793a48e31f80ebd3 | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_name = f'{name} {description.name}'\nuuid = self.coordinator.data.get_uuid()\nself._attr_unique_id = f'{uuid}-{description.key}'",
"if (metric_key := self.entity_description.metric_key) is None:\n return None\nreturn self.coordin... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_name = f'{name} {description.name}'
uuid = self.coordinator.data.get_uuid()
self._attr_unique_id = f'{uuid}-{description.key}'
<|end_body_0|>
<|body_start_1|>
if (metric_key :... | Representation of a Vallox sensor. | ValloxSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValloxSensor:
"""Representation of a Vallox sensor."""
def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None:
"""Initialize the Vallox sensor."""
<|body_0|>
def native_value(self) -> StateType | dateti... | stack_v2_sparse_classes_75kplus_train_066079 | 7,735 | permissive | [
{
"docstring": "Initialize the Vallox sensor.",
"name": "__init__",
"signature": "def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None"
},
{
"docstring": "Return the value reported by the sensor.",
"name": "native_value",... | 2 | stack_v2_sparse_classes_30k_test_001806 | Implement the Python class `ValloxSensor` described below.
Class description:
Representation of a Vallox sensor.
Method signatures and docstrings:
- def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None: Initialize the Vallox sensor.
- def native_v... | Implement the Python class `ValloxSensor` described below.
Class description:
Representation of a Vallox sensor.
Method signatures and docstrings:
- def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None: Initialize the Vallox sensor.
- def native_v... | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | <|skeleton|>
class ValloxSensor:
"""Representation of a Vallox sensor."""
def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None:
"""Initialize the Vallox sensor."""
<|body_0|>
def native_value(self) -> StateType | dateti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValloxSensor:
"""Representation of a Vallox sensor."""
def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None:
"""Initialize the Vallox sensor."""
super().__init__(coordinator)
self.entity_description = descripti... | the_stack_v2_python_sparse | homeassistant/components/vallox/sensor.py | JeffLIrion/home-assistant | train | 5 |
b4561dbdba21826420772d8d8607c2246d166925 | [
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ncheckpoint_path = 'VQMIVC-pretrained models/checkpoints/useCSMITrue_useCPMITrue_usePSMITrue_useAmpTrue/VQMIVC-model.ckpt-500.pt'\nmel_stats = np.load('./mel_stats/stats.npy')\nencoder = Encoder(in_channels=80, channels=512, n_embeddings=512, z_... | <|body_start_0|>
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
checkpoint_path = 'VQMIVC-pretrained models/checkpoints/useCSMITrue_useCPMITrue_usePSMITrue_useAmpTrue/VQMIVC-model.ckpt-500.pt'
mel_stats = np.load('./mel_stats/stats.npy')
encoder = Encoder(in_channe... | Predictor | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
def setup(self):
"""Load models"""
<|body_0|>
def predict(self, input_source: Path=Input(description='Source voice wav path'), input_reference: Path=Input(description='Reference voice wav path')) -> Path:
"""Compute prediction"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_066080 | 4,930 | permissive | [
{
"docstring": "Load models",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Compute prediction",
"name": "predict",
"signature": "def predict(self, input_source: Path=Input(description='Source voice wav path'), input_reference: Path=Input(description='Reference voice... | 2 | stack_v2_sparse_classes_30k_train_012335 | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def setup(self): Load models
- def predict(self, input_source: Path=Input(description='Source voice wav path'), input_reference: Path=Input(description='Reference voice wav pat... | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def setup(self): Load models
- def predict(self, input_source: Path=Input(description='Source voice wav path'), input_reference: Path=Input(description='Reference voice wav pat... | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | <|skeleton|>
class Predictor:
def setup(self):
"""Load models"""
<|body_0|>
def predict(self, input_source: Path=Input(description='Source voice wav path'), input_reference: Path=Input(description='Reference voice wav path')) -> Path:
"""Compute prediction"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predictor:
def setup(self):
"""Load models"""
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
checkpoint_path = 'VQMIVC-pretrained models/checkpoints/useCSMITrue_useCPMITrue_usePSMITrue_useAmpTrue/VQMIVC-model.ckpt-500.pt'
mel_stats = np.load('./mel_stats/... | the_stack_v2_python_sparse | speech/speech_synthesis/vqmivc/pytorch/predict.py | Deep-Spark/DeepSparkHub | train | 7 | |
2f4dd4f02594e253ce6b4fe7e1db686e5aed3c45 | [
"num_lines = int(lines)\nwith open(filename) as opened_file:\n content = opened_file.read().split(DataStoreUtilities.LINE_DELIMITER)\ncontent = [_f for _f in content if _f]\ncount = len(content)\nif num_lines >= count:\n num_lines = count\nlines = list()\ni = count - 1\nwhile i >= 0 and len(lines) < num_lines... | <|body_start_0|>
num_lines = int(lines)
with open(filename) as opened_file:
content = opened_file.read().split(DataStoreUtilities.LINE_DELIMITER)
content = [_f for _f in content if _f]
count = len(content)
if num_lines >= count:
num_lines = count
l... | Handy utilities that everyone needs. | DataStoreUtilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataStoreUtilities:
"""Handy utilities that everyone needs."""
def tail_file(filename, lines, formatter=None, log_filter=None):
"""Tries to emulate the function of tail on linux machines by retrieving the last x lines from a file. Allows for two functions, a formatter and lo_filter t... | stack_v2_sparse_classes_75kplus_train_066081 | 5,952 | permissive | [
{
"docstring": "Tries to emulate the function of tail on linux machines by retrieving the last x lines from a file. Allows for two functions, a formatter and lo_filter to be passed in for advanced usage. :param filename: :param lines: :param formatter: :param log_filter: :return:",
"name": "tail_file",
... | 2 | null | Implement the Python class `DataStoreUtilities` described below.
Class description:
Handy utilities that everyone needs.
Method signatures and docstrings:
- def tail_file(filename, lines, formatter=None, log_filter=None): Tries to emulate the function of tail on linux machines by retrieving the last x lines from a fi... | Implement the Python class `DataStoreUtilities` described below.
Class description:
Handy utilities that everyone needs.
Method signatures and docstrings:
- def tail_file(filename, lines, formatter=None, log_filter=None): Tries to emulate the function of tail on linux machines by retrieving the last x lines from a fi... | b0c88b877921dda20d0af4dab6497a50600d975d | <|skeleton|>
class DataStoreUtilities:
"""Handy utilities that everyone needs."""
def tail_file(filename, lines, formatter=None, log_filter=None):
"""Tries to emulate the function of tail on linux machines by retrieving the last x lines from a file. Allows for two functions, a formatter and lo_filter t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataStoreUtilities:
"""Handy utilities that everyone needs."""
def tail_file(filename, lines, formatter=None, log_filter=None):
"""Tries to emulate the function of tail on linux machines by retrieving the last x lines from a file. Allows for two functions, a formatter and lo_filter to be passed i... | the_stack_v2_python_sparse | datastore/datastore/utilities.py | intel-ctrlsys/actsys | train | 5 |
32436fda51618c7580b85df24372d10da94932ad | [
"query = Query(Ability.collection, service_id=self._client.service_id)\nquery.add_term(field=Ability.id_field, value=self.data.ability_id)\nreturn InstanceProxy(Ability, query, client=self._client)",
"query = Query(ZoneEffectType.collection, service_id=self._client.service_id)\nquery.add_term(field=ZoneEffectType... | <|body_start_0|>
query = Query(Ability.collection, service_id=self._client.service_id)
query.add_term(field=Ability.id_field, value=self.data.ability_id)
return InstanceProxy(Ability, query, client=self._client)
<|end_body_0|>
<|body_start_1|>
query = Query(ZoneEffectType.collection, se... | An effect or buff applied in an area. Zone effects are area-bound effects acting on a group of characters or entities. Access the corresponding :class:`ZoneEffectType` instance via the :meth:`type` method for information on generic parameters. .. note:: The relationship between :class:`ZoneEffect` and :class:`Effect` i... | ZoneEffect | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoneEffect:
"""An effect or buff applied in an area. Zone effects are area-bound effects acting on a group of characters or entities. Access the corresponding :class:`ZoneEffectType` instance via the :meth:`type` method for information on generic parameters. .. note:: The relationship between :cl... | stack_v2_sparse_classes_75kplus_train_066082 | 10,551 | permissive | [
{
"docstring": "Return the ability associated with this zone effect.",
"name": "ability",
"signature": "def ability(self) -> InstanceProxy[Ability]"
},
{
"docstring": "Return the type of this zone effect.",
"name": "type",
"signature": "def type(self) -> InstanceProxy[ZoneEffectType]"
... | 2 | stack_v2_sparse_classes_30k_train_011425 | Implement the Python class `ZoneEffect` described below.
Class description:
An effect or buff applied in an area. Zone effects are area-bound effects acting on a group of characters or entities. Access the corresponding :class:`ZoneEffectType` instance via the :meth:`type` method for information on generic parameters.... | Implement the Python class `ZoneEffect` described below.
Class description:
An effect or buff applied in an area. Zone effects are area-bound effects acting on a group of characters or entities. Access the corresponding :class:`ZoneEffectType` instance via the :meth:`type` method for information on generic parameters.... | 23dcf927a199c8d7c917d89fe96b470a34cf4bba | <|skeleton|>
class ZoneEffect:
"""An effect or buff applied in an area. Zone effects are area-bound effects acting on a group of characters or entities. Access the corresponding :class:`ZoneEffectType` instance via the :meth:`type` method for information on generic parameters. .. note:: The relationship between :cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZoneEffect:
"""An effect or buff applied in an area. Zone effects are area-bound effects acting on a group of characters or entities. Access the corresponding :class:`ZoneEffectType` instance via the :meth:`type` method for information on generic parameters. .. note:: The relationship between :class:`ZoneEffe... | the_stack_v2_python_sparse | auraxium/ps2/_effect.py | leonhard-s/auraxium | train | 29 |
331f7416945d6b97a1324bb0ba1a0fd076c18677 | [
"lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\nlookup = self.kwargs.get(lookup_url_kwarg, None)\nif lookup is not None:\n return Clip.objects.filter(video__hash_key=lookup).select_related('owner', 'video')\nreturn Clip.objects.none()",
"lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_f... | <|body_start_0|>
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
lookup = self.kwargs.get(lookup_url_kwarg, None)
if lookup is not None:
return Clip.objects.filter(video__hash_key=lookup).select_related('owner', 'video')
return Clip.objects.none()
<|end_body_0|>... | List all clips of a video and create new clips. ## Reading ### Permissions * Anyone can read this endpoint. ### Fields Reading this endpoint returns a list of [Clip objects](0/) ## Publishing ### Permissions * Only authenticated users can create using this endpoint. * Only associated users of a video can write to this ... | VideoClipList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoClipList:
"""List all clips of a video and create new clips. ## Reading ### Permissions * Anyone can read this endpoint. ### Fields Reading this endpoint returns a list of [Clip objects](0/) ## Publishing ### Permissions * Only authenticated users can create using this endpoint. * Only assoc... | stack_v2_sparse_classes_75kplus_train_066083 | 40,640 | no_license | [
{
"docstring": "This view should return a list of all clips for the video as determined by the lookup parameters of the view.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Create a new clip",
"name": "perform_create",
"signature": "def perform_create(... | 2 | stack_v2_sparse_classes_30k_train_040572 | Implement the Python class `VideoClipList` described below.
Class description:
List all clips of a video and create new clips. ## Reading ### Permissions * Anyone can read this endpoint. ### Fields Reading this endpoint returns a list of [Clip objects](0/) ## Publishing ### Permissions * Only authenticated users can c... | Implement the Python class `VideoClipList` described below.
Class description:
List all clips of a video and create new clips. ## Reading ### Permissions * Anyone can read this endpoint. ### Fields Reading this endpoint returns a list of [Clip objects](0/) ## Publishing ### Permissions * Only authenticated users can c... | 1f4b4cd74c9b4280437f73bdfef4491536194eeb | <|skeleton|>
class VideoClipList:
"""List all clips of a video and create new clips. ## Reading ### Permissions * Anyone can read this endpoint. ### Fields Reading this endpoint returns a list of [Clip objects](0/) ## Publishing ### Permissions * Only authenticated users can create using this endpoint. * Only assoc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoClipList:
"""List all clips of a video and create new clips. ## Reading ### Permissions * Anyone can read this endpoint. ### Fields Reading this endpoint returns a list of [Clip objects](0/) ## Publishing ### Permissions * Only authenticated users can create using this endpoint. * Only associated users o... | the_stack_v2_python_sparse | gravvy/apps/video/views.py | nceruchalu/gravvy-server | train | 1 |
c5afd837def6a6ec93ab77a5746a49b3d3ffd86d | [
"assert padding in ['SAME', 'VALID', 'REFLECT'], 'Error: unsupported padding'\nself._padding = padding\nwith tf.variable_scope(name):\n if isinstance(stride, int):\n stride = [1, stride, stride, 1]\n else:\n assert len(stride) == 0, 'stride is either an int or a 2-tuple'\n stride = [1, st... | <|body_start_0|>
assert padding in ['SAME', 'VALID', 'REFLECT'], 'Error: unsupported padding'
self._padding = padding
with tf.variable_scope(name):
if isinstance(stride, int):
stride = [1, stride, stride, 1]
else:
assert len(stride) == 0, '... | Convolution layer with support for equalized learning. | LayerConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerConv:
"""Convolution layer with support for equalized learning."""
def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0):
"""Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. w: int o... | stack_v2_sparse_classes_75kplus_train_066084 | 13,442 | permissive | [
{
"docstring": "Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. w: int or 2-tuple, width of the convolution kernel. n: 2-tuple of ints, input and output channel depths. padding: string, the padding method. {SAME, VALID, REFLECT}. use_scaling: bool, w... | 2 | stack_v2_sparse_classes_30k_train_018693 | Implement the Python class `LayerConv` described below.
Class description:
Convolution layer with support for equalized learning.
Method signatures and docstrings:
- def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0): Layer constructor. Args: name: string, layer name. stride: in... | Implement the Python class `LayerConv` described below.
Class description:
Convolution layer with support for equalized learning.
Method signatures and docstrings:
- def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0): Layer constructor. Args: name: string, layer name. stride: in... | 091d6ae9e087cf5a6e18b00bce7d8f7ede9d9d08 | <|skeleton|>
class LayerConv:
"""Convolution layer with support for equalized learning."""
def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0):
"""Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. w: int o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayerConv:
"""Convolution layer with support for equalized learning."""
def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0):
"""Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. w: int or 2-tuple, wi... | the_stack_v2_python_sparse | layers.py | MoustafaMeshry/StEP | train | 6 |
f9c1321e217783f89e0983c14623e997a8ee3a25 | [
"database = 'scratch/chr11_and_Tcf3.db'\ntry:\n subprocess.check_output(['talon_abundance', '--db', database, '-a', 'gencode_vM7', '-b', 'mm10', '--o', 'scratch/chr11_and_Tcf3_base'])\nexcept:\n pytest.fail('Talon abundance crashed on basic case')\nabd = 'scratch/chr11_and_Tcf3_base_talon_abundance.tsv'\ndata... | <|body_start_0|>
database = 'scratch/chr11_and_Tcf3.db'
try:
subprocess.check_output(['talon_abundance', '--db', database, '-a', 'gencode_vM7', '-b', 'mm10', '--o', 'scratch/chr11_and_Tcf3_base'])
except:
pytest.fail('Talon abundance crashed on basic case')
abd = ... | Make sure that the abundance utility is working correctly | TestAbundance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAbundance:
"""Make sure that the abundance utility is working correctly"""
def test_base_settings(self):
"""Test abundance utility without a datasets or whitelist file."""
<|body_0|>
def test_with_whitelist(self):
"""Test abundance utility with a transcript w... | stack_v2_sparse_classes_75kplus_train_066085 | 6,002 | permissive | [
{
"docstring": "Test abundance utility without a datasets or whitelist file.",
"name": "test_base_settings",
"signature": "def test_base_settings(self)"
},
{
"docstring": "Test abundance utility with a transcript whitelist",
"name": "test_with_whitelist",
"signature": "def test_with_whit... | 4 | stack_v2_sparse_classes_30k_train_001958 | Implement the Python class `TestAbundance` described below.
Class description:
Make sure that the abundance utility is working correctly
Method signatures and docstrings:
- def test_base_settings(self): Test abundance utility without a datasets or whitelist file.
- def test_with_whitelist(self): Test abundance utilit... | Implement the Python class `TestAbundance` described below.
Class description:
Make sure that the abundance utility is working correctly
Method signatures and docstrings:
- def test_base_settings(self): Test abundance utility without a datasets or whitelist file.
- def test_with_whitelist(self): Test abundance utilit... | 8014faed5f982e5e106ec05239e47d65878e76c3 | <|skeleton|>
class TestAbundance:
"""Make sure that the abundance utility is working correctly"""
def test_base_settings(self):
"""Test abundance utility without a datasets or whitelist file."""
<|body_0|>
def test_with_whitelist(self):
"""Test abundance utility with a transcript w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAbundance:
"""Make sure that the abundance utility is working correctly"""
def test_base_settings(self):
"""Test abundance utility without a datasets or whitelist file."""
database = 'scratch/chr11_and_Tcf3.db'
try:
subprocess.check_output(['talon_abundance', '--db... | the_stack_v2_python_sparse | testing_suite/test_abundance_utility.py | kopardev/TALON | train | 0 |
46b2195d1cc5a150a34b6d467f9948c0b2ab5d57 | [
"n = len(friends)\nqueue = deque([id])\nvisited = [False] * n\nvisited[id] = True\nc = Counter()\nk = 0\nwhile queue:\n q = deque()\n while queue:\n cur = queue.popleft()\n for i in friends[cur]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n ... | <|body_start_0|>
n = len(friends)
queue = deque([id])
visited = [False] * n
visited[id] = True
c = Counter()
k = 0
while queue:
q = deque()
while queue:
cur = queue.popleft()
for i in friends[cur]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def watchedVideosByFriends(self, watchedVideos, friends, id, level):
""":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]"""
<|body_0|>
def watchedVideosByFriendsFast(self, watchedVideos, friends, i... | stack_v2_sparse_classes_75kplus_train_066086 | 3,535 | no_license | [
{
"docstring": ":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]",
"name": "watchedVideosByFriends",
"signature": "def watchedVideosByFriends(self, watchedVideos, friends, id, level)"
},
{
"docstring": ":type watchedVideos: List... | 2 | stack_v2_sparse_classes_30k_train_012767 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def watchedVideosByFriends(self, watchedVideos, friends, id, level): :type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def watchedVideosByFriends(self, watchedVideos, friends, id, level): :type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: Li... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def watchedVideosByFriends(self, watchedVideos, friends, id, level):
""":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]"""
<|body_0|>
def watchedVideosByFriendsFast(self, watchedVideos, friends, i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def watchedVideosByFriends(self, watchedVideos, friends, id, level):
""":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]"""
n = len(friends)
queue = deque([id])
visited = [False] * n
visited[i... | the_stack_v2_python_sparse | G/GetWatchedVideosbyYourFriends.py | bssrdf/pyleet | train | 2 | |
afbbf63c70a588a0cf443d790ccecc8ec336f9a6 | [
"self.language = language\nself.available_languages = ['akkadian', 'arabic', 'french', 'greek', 'latin', 'middle_english', 'middle_french', 'middle_high_german', 'old_french', 'old_norse', 'sanskrit', 'multilingual']\nassert self.language in self.available_languages, \"Specific tokenizer not available for '{0}'. On... | <|body_start_0|>
self.language = language
self.available_languages = ['akkadian', 'arabic', 'french', 'greek', 'latin', 'middle_english', 'middle_french', 'middle_high_german', 'old_french', 'old_norse', 'sanskrit', 'multilingual']
assert self.language in self.available_languages, "Specific toke... | Tokenize according to rules specific to a given language. | WordTokenizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordTokenizer:
"""Tokenize according to rules specific to a given language."""
def __init__(self, language):
"""Take language as argument to the class. Check availability and setup class variables."""
<|body_0|>
def tokenize(self, text):
"""Tokenize incoming stri... | stack_v2_sparse_classes_75kplus_train_066087 | 7,425 | permissive | [
{
"docstring": "Take language as argument to the class. Check availability and setup class variables.",
"name": "__init__",
"signature": "def __init__(self, language)"
},
{
"docstring": "Tokenize incoming string.",
"name": "tokenize",
"signature": "def tokenize(self, text)"
},
{
... | 3 | null | Implement the Python class `WordTokenizer` described below.
Class description:
Tokenize according to rules specific to a given language.
Method signatures and docstrings:
- def __init__(self, language): Take language as argument to the class. Check availability and setup class variables.
- def tokenize(self, text): T... | Implement the Python class `WordTokenizer` described below.
Class description:
Tokenize according to rules specific to a given language.
Method signatures and docstrings:
- def __init__(self, language): Take language as argument to the class. Check availability and setup class variables.
- def tokenize(self, text): T... | 90c3daaafda242a1982b38c2b11c52aedab7ddf8 | <|skeleton|>
class WordTokenizer:
"""Tokenize according to rules specific to a given language."""
def __init__(self, language):
"""Take language as argument to the class. Check availability and setup class variables."""
<|body_0|>
def tokenize(self, text):
"""Tokenize incoming stri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordTokenizer:
"""Tokenize according to rules specific to a given language."""
def __init__(self, language):
"""Take language as argument to the class. Check availability and setup class variables."""
self.language = language
self.available_languages = ['akkadian', 'arabic', 'fren... | the_stack_v2_python_sparse | src/cltkv1/tokenize/word.py | todd-cook/cltkv1 | train | 0 |
8a221680bbf4a99a22364a4f81a47af3fd59c1fc | [
"self.lineNos = [callAstNode.lineNo, funcLineNo]\nself.astNodes = [callAstNode, funcAstNode]\nself.errorType = errorType\nself.valid = False\nself.argNos = None\nself.expected = None\nself.provided = None",
"if not self.valid:\n errPrint('\\nValidity check for FuncCallArgMatchError object failed.\\n')\n ass... | <|body_start_0|>
self.lineNos = [callAstNode.lineNo, funcLineNo]
self.astNodes = [callAstNode, funcAstNode]
self.errorType = errorType
self.valid = False
self.argNos = None
self.expected = None
self.provided = None
<|end_body_0|>
<|body_start_1|>
if not s... | Stores data used for error reporting when try to call a function but either have incorrect number of arguments or have mismatched arguments. It is good form to make a call to checkValid before trying to use internal fields, and after you think the object is completely constructed. See more documentation in init method'... | FuncCallArgMatchError | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuncCallArgMatchError:
"""Stores data used for error reporting when try to call a function but either have incorrect number of arguments or have mismatched arguments. It is good form to make a call to checkValid before trying to use internal fields, and after you think the object is completely co... | stack_v2_sparse_classes_75kplus_train_066088 | 34,359 | no_license | [
{
"docstring": "@param {int} funcLineNo -- line where the actual function signature is declared. @param {AstNode} funcAstNode -- ast node corresponding to actual function. @param {int} errorType -- FUNC_CALL_ARG_MATCH_ERROR_NUM_ARGS_MISMATCH if error is mismatched number of arguments (in which case, creator of ... | 4 | stack_v2_sparse_classes_30k_train_019975 | Implement the Python class `FuncCallArgMatchError` described below.
Class description:
Stores data used for error reporting when try to call a function but either have incorrect number of arguments or have mismatched arguments. It is good form to make a call to checkValid before trying to use internal fields, and afte... | Implement the Python class `FuncCallArgMatchError` described below.
Class description:
Stores data used for error reporting when try to call a function but either have incorrect number of arguments or have mismatched arguments. It is good form to make a call to checkValid before trying to use internal fields, and afte... | 729a51f04d540111af01c283b1c17ad1489b664a | <|skeleton|>
class FuncCallArgMatchError:
"""Stores data used for error reporting when try to call a function but either have incorrect number of arguments or have mismatched arguments. It is good form to make a call to checkValid before trying to use internal fields, and after you think the object is completely co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FuncCallArgMatchError:
"""Stores data used for error reporting when try to call a function but either have incorrect number of arguments or have mismatched arguments. It is good form to make a call to checkValid before trying to use internal fields, and after you think the object is completely constructed. Se... | the_stack_v2_python_sparse | waldo/parser/ast/typeCheck/astTypeCheckStack.py | bmistree/Waldo | train | 0 |
5224ea5c2e36ab1bd4e04a71338ca612c0c2d917 | [
"Thread.__init__(self)\ndbusCExtension.setCallback(cb)\nself.daemon = True",
"while True:\n dbusCExtension.infiniteEventLoop()\n logging.error('C extension loop has exited')"
] | <|body_start_0|>
Thread.__init__(self)
dbusCExtension.setCallback(cb)
self.daemon = True
<|end_body_0|>
<|body_start_1|>
while True:
dbusCExtension.infiniteEventLoop()
logging.error('C extension loop has exited')
<|end_body_1|>
| Dedicated Thread to manage DBUS messages signals in C The thread is created in Python world but its real execution is delegated to C through a Python C extension | DbusEventHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbusEventHandler:
"""Dedicated Thread to manage DBUS messages signals in C The thread is created in Python world but its real execution is delegated to C through a Python C extension"""
def __init__(self, cb):
"""Initialize the C module wrapper :param cb: Python Callback to call from... | stack_v2_sparse_classes_75kplus_train_066089 | 5,617 | permissive | [
{
"docstring": "Initialize the C module wrapper :param cb: Python Callback to call from C on packet reception",
"name": "__init__",
"signature": "def __init__(self, cb)"
},
{
"docstring": "Delegate the execution to C Extension :return: None, as it is an infinite loop in C",
"name": "run",
... | 2 | null | Implement the Python class `DbusEventHandler` described below.
Class description:
Dedicated Thread to manage DBUS messages signals in C The thread is created in Python world but its real execution is delegated to C through a Python C extension
Method signatures and docstrings:
- def __init__(self, cb): Initialize the... | Implement the Python class `DbusEventHandler` described below.
Class description:
Dedicated Thread to manage DBUS messages signals in C The thread is created in Python world but its real execution is delegated to C through a Python C extension
Method signatures and docstrings:
- def __init__(self, cb): Initialize the... | 3edf43900f201a44fbaa3086a6b8876d57ec7cb1 | <|skeleton|>
class DbusEventHandler:
"""Dedicated Thread to manage DBUS messages signals in C The thread is created in Python world but its real execution is delegated to C through a Python C extension"""
def __init__(self, cb):
"""Initialize the C module wrapper :param cb: Python Callback to call from... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DbusEventHandler:
"""Dedicated Thread to manage DBUS messages signals in C The thread is created in Python world but its real execution is delegated to C through a Python C extension"""
def __init__(self, cb):
"""Initialize the C module wrapper :param cb: Python Callback to call from C on packet ... | the_stack_v2_python_sparse | python_transport/wirepas_gateway/dbus/dbus_client.py | wirepas/gateway | train | 64 |
ce93af0c4a4c649840d3c82700548cdbad43d259 | [
"num_len = len(nums)\nfor i in range(num_len):\n for j in range(i + 1, num_len):\n if nums[i] + num[j] == target:\n return [i, j]",
"for i, n in enumerate(nums):\n second = target - n\n if second in nums[i + 1:]:\n return [i, nums[i + 1:].index(second) + i + 1]",
"pair_nums = {... | <|body_start_0|>
num_len = len(nums)
for i in range(num_len):
for j in range(i + 1, num_len):
if nums[i] + num[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
for i, n in enumerate(nums):
second = target - n
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums: List[int], target: int) -> List[int]:
"""Brute-Force"""
<|body_0|>
def twoSum_2(self, nums: List[int], target: int) -> List[int]:
"""In"""
<|body_1|>
def twoSum_3(self, nums: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_75kplus_train_066090 | 1,412 | no_license | [
{
"docstring": "Brute-Force",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "In",
"name": "twoSum_2",
"signature": "def twoSum_2(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Dictionary 2 ... | 4 | stack_v2_sparse_classes_30k_train_027370 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums: List[int], target: int) -> List[int]: Brute-Force
- def twoSum_2(self, nums: List[int], target: int) -> List[int]: In
- def twoSum_3(self, nums: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums: List[int], target: int) -> List[int]: Brute-Force
- def twoSum_2(self, nums: List[int], target: int) -> List[int]: In
- def twoSum_3(self, nums: List[int... | 8e1825e2b78c3897bde813520c1af5608a7c576c | <|skeleton|>
class Solution:
def twoSum_1(self, nums: List[int], target: int) -> List[int]:
"""Brute-Force"""
<|body_0|>
def twoSum_2(self, nums: List[int], target: int) -> List[int]:
"""In"""
<|body_1|>
def twoSum_3(self, nums: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_1(self, nums: List[int], target: int) -> List[int]:
"""Brute-Force"""
num_len = len(nums)
for i in range(num_len):
for j in range(i + 1, num_len):
if nums[i] + num[j] == target:
return [i, j]
def twoSum_2(self, n... | the_stack_v2_python_sparse | leetcode/linear/leetcode_1_two-sum.py | ecpark4545/algorithms | train | 0 | |
5ae84fcccbda78d095d76bc3a8c582fa17e68e84 | [
"slow = fast = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow is fast:\n break\nif not fast or not fast.next:\n return None\nwhile slow != head:\n slow = slow.next\n head = head.next\nreturn head",
"slow = fast = head\nwhile fast and fast.next:\n s... | <|body_start_0|>
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
break
if not fast or not fast.next:
return None
while slow != head:
slow = slow.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head):
"""Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list)."""
<|body_0|>
def detectCycle(self, head):
"""More concise code versio... | stack_v2_sparse_classes_75kplus_train_066091 | 1,728 | no_license | [
{
"docstring": "Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list).",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
},
{
"docstring": "More concise code version. Returns nod... | 2 | stack_v2_sparse_classes_30k_train_031340 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked l... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def detectCycle(self, head):
"""Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list)."""
<|body_0|>
def detectCycle(self, head):
"""More concise code versio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def detectCycle(self, head):
"""Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list)."""
slow = fast = head
while fast and fast.next:
slow = slow.next
... | the_stack_v2_python_sparse | Linked_Lists/linked_list_cycle_2.py | vladn90/Algorithms | train | 0 | |
b16a71641f631761491eb83b8a6a51ffbb5e5077 | [
"n = len(nums)\nself.m = int(sqrt(2 * n))\nself.buckets = [[] for _ in range(m)]\nself.cums = [0] * m\nfor i, n in enumerate(nums):\n bucket = self.buckets[i / m]\n bucket.append(n)\n self.cums[i / m] += n",
"bucket_idx = i / self.m\nbucket = self.buckets[bucket_idx]\nidx = i % self.m\nself.cums[bucket_i... | <|body_start_0|>
n = len(nums)
self.m = int(sqrt(2 * n))
self.buckets = [[] for _ in range(m)]
self.cums = [0] * m
for i, n in enumerate(nums):
bucket = self.buckets[i / m]
bucket.append(n)
self.cums[i / m] += n
<|end_body_0|>
<|body_start_1|>... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_066092 | 1,142 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_050807 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 9f6ccf8a8fd8eaaeae2f11557b73be4e5e7adba8 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
n = len(nums)
self.m = int(sqrt(2 * n))
self.buckets = [[] for _ in range(m)]
self.cums = [0] * m
for i, n in enumerate(nums):
bucket = self.buckets[i / m]
bucket.append(n)
... | the_stack_v2_python_sparse | python/307.py | MrRabbit0o0/LeetCode | train | 0 | |
d5a6b6a8a8df0ae39b7386884723d6489b5e9c55 | [
"transactions = get_all_transactions()\nif not transactions:\n api.abort(417)\nelse:\n return (transactions, 200)",
"data = request.json\nfeedback = save_new_transaction(data=data)\nif not feedback.get('error', None):\n response_object = {'status': 'success', 'message': 'Transaction Successfully', 'body'... | <|body_start_0|>
transactions = get_all_transactions()
if not transactions:
api.abort(417)
else:
return (transactions, 200)
<|end_body_0|>
<|body_start_1|>
data = request.json
feedback = save_new_transaction(data=data)
if not feedback.get('error',... | TransactionList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionList:
def get(self):
"""get all transaction history"""
<|body_0|>
def post(self):
"""transfer funds from one wallet to another"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
transactions = get_all_transactions()
if not transactio... | stack_v2_sparse_classes_75kplus_train_066093 | 1,841 | no_license | [
{
"docstring": "get all transaction history",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "transfer funds from one wallet to another",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005244 | Implement the Python class `TransactionList` described below.
Class description:
Implement the TransactionList class.
Method signatures and docstrings:
- def get(self): get all transaction history
- def post(self): transfer funds from one wallet to another | Implement the Python class `TransactionList` described below.
Class description:
Implement the TransactionList class.
Method signatures and docstrings:
- def get(self): get all transaction history
- def post(self): transfer funds from one wallet to another
<|skeleton|>
class TransactionList:
def get(self):
... | 8ff4a78856f187f6ff975a4a8a312f28a1d3e361 | <|skeleton|>
class TransactionList:
def get(self):
"""get all transaction history"""
<|body_0|>
def post(self):
"""transfer funds from one wallet to another"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransactionList:
def get(self):
"""get all transaction history"""
transactions = get_all_transactions()
if not transactions:
api.abort(417)
else:
return (transactions, 200)
def post(self):
"""transfer funds from one wallet to another"""
... | the_stack_v2_python_sparse | app/main/controller/transaction_controller.py | Greyacey/RichVest | train | 0 | |
8175412021b9c9e9437d09dbdd7f83b282992114 | [
"user = kwargs.pop('user')\nsuper().__init__(*args, **kwargs)\nif self.instance.pk is None:\n self.fields['password'] = forms.CharField(widget=forms.widgets.PasswordInput)\nif user.pk == self.instance.pk:\n self.fields.pop('is_active')\n self.fields.pop('is_staff')\nif not user.is_staff:\n self.fields.p... | <|body_start_0|>
user = kwargs.pop('user')
super().__init__(*args, **kwargs)
if self.instance.pk is None:
self.fields['password'] = forms.CharField(widget=forms.widgets.PasswordInput)
if user.pk == self.instance.pk:
self.fields.pop('is_active')
self.fi... | UserForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserForm:
def __init__(self, *args, **kwargs):
"""`user` is the person using the form, not the person the form is actually going edit"""
<|body_0|>
def save(self, *args, **kwargs):
"""Save the form, and set the password, if it has been set"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_066094 | 3,241 | no_license | [
{
"docstring": "`user` is the person using the form, not the person the form is actually going edit",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Save the form, and set the password, if it has been set",
"name": "save",
"signature": "def save... | 2 | null | Implement the Python class `UserForm` described below.
Class description:
Implement the UserForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): `user` is the person using the form, not the person the form is actually going edit
- def save(self, *args, **kwargs): Save the form, and set... | Implement the Python class `UserForm` described below.
Class description:
Implement the UserForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): `user` is the person using the form, not the person the form is actually going edit
- def save(self, *args, **kwargs): Save the form, and set... | 86f237b1b1e7a476ad86d0c59571036b1183d92c | <|skeleton|>
class UserForm:
def __init__(self, *args, **kwargs):
"""`user` is the person using the form, not the person the form is actually going edit"""
<|body_0|>
def save(self, *args, **kwargs):
"""Save the form, and set the password, if it has been set"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserForm:
def __init__(self, *args, **kwargs):
"""`user` is the person using the form, not the person the form is actually going edit"""
user = kwargs.pop('user')
super().__init__(*args, **kwargs)
if self.instance.pk is None:
self.fields['password'] = forms.CharFiel... | the_stack_v2_python_sparse | oregoninvasiveshotline/users/forms.py | PSU-OIT-ARC/oregoninvasiveshotline | train | 2 | |
49c45741466bbd7a085d745bd6605840b1415573 | [
"sampling = sampling.lower()\npool_method = pool_method.lower()\nassert sampling in ('healpix', 'equiangular')\nassert pool_method in ('max', 'avg')\npooling, unpool = ALL_POOL[sampling][pool_method]\nreturn (pooling(**kwargs), unpool(**kwargs))",
"if src_graph.n_vertices < dst_graph.n_vertices:\n src_graph, d... | <|body_start_0|>
sampling = sampling.lower()
pool_method = pool_method.lower()
assert sampling in ('healpix', 'equiangular')
assert pool_method in ('max', 'avg')
pooling, unpool = ALL_POOL[sampling][pool_method]
return (pooling(**kwargs), unpool(**kwargs))
<|end_body_0|>
... | Define Pooling and Unpooling Layers. | PoolUnpoolBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoolUnpoolBlock:
"""Define Pooling and Unpooling Layers."""
def getPoolUnpoolLayer(sampling: str, pool_method: str, **kwargs):
"""Retrieve ad-hoc pooling and unpooling layers for healpix and equiangular."""
<|body_0|>
def getGeneralPoolUnpoolLayer(src_graph, dst_graph, p... | stack_v2_sparse_classes_75kplus_train_066095 | 42,132 | permissive | [
{
"docstring": "Retrieve ad-hoc pooling and unpooling layers for healpix and equiangular.",
"name": "getPoolUnpoolLayer",
"signature": "def getPoolUnpoolLayer(sampling: str, pool_method: str, **kwargs)"
},
{
"docstring": "Retrieve general pooling and unpooling layers.",
"name": "getGeneralPo... | 2 | stack_v2_sparse_classes_30k_train_047227 | Implement the Python class `PoolUnpoolBlock` described below.
Class description:
Define Pooling and Unpooling Layers.
Method signatures and docstrings:
- def getPoolUnpoolLayer(sampling: str, pool_method: str, **kwargs): Retrieve ad-hoc pooling and unpooling layers for healpix and equiangular.
- def getGeneralPoolUnp... | Implement the Python class `PoolUnpoolBlock` described below.
Class description:
Define Pooling and Unpooling Layers.
Method signatures and docstrings:
- def getPoolUnpoolLayer(sampling: str, pool_method: str, **kwargs): Retrieve ad-hoc pooling and unpooling layers for healpix and equiangular.
- def getGeneralPoolUnp... | a9c75de9c9852a2832883cd998efd16d6542b083 | <|skeleton|>
class PoolUnpoolBlock:
"""Define Pooling and Unpooling Layers."""
def getPoolUnpoolLayer(sampling: str, pool_method: str, **kwargs):
"""Retrieve ad-hoc pooling and unpooling layers for healpix and equiangular."""
<|body_0|>
def getGeneralPoolUnpoolLayer(src_graph, dst_graph, p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PoolUnpoolBlock:
"""Define Pooling and Unpooling Layers."""
def getPoolUnpoolLayer(sampling: str, pool_method: str, **kwargs):
"""Retrieve ad-hoc pooling and unpooling layers for healpix and equiangular."""
sampling = sampling.lower()
pool_method = pool_method.lower()
asse... | the_stack_v2_python_sparse | modules/layers.py | ghiggi/deepsphere-weather | train | 0 |
53ab89a3d82577ba0dc3f69e6177ddd14742d162 | [
"left = 0\nright = x + 1\nwhile True:\n p = (left + right) // 2\n if p ** 2 <= x < (p + 1) ** 2:\n return p\n elif p ** 2 > x:\n right = p\n else:\n left = p",
"import math\nif x == 0:\n return 0\nans = int(math.exp(0.5 * math.log(x)))\nreturn ans + 1 if (ans + 1) ** 2 <= x els... | <|body_start_0|>
left = 0
right = x + 1
while True:
p = (left + right) // 2
if p ** 2 <= x < (p + 1) ** 2:
return p
elif p ** 2 > x:
right = p
else:
left = p
<|end_body_0|>
<|body_start_1|>
i... | 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。"""
def mySqrt(self, x: int) -> int:
"""对于任意整数,有a^2 <= x <= (a+1)^2,通过这个进行二分查找,快速找到目标值 :param x: :return:"""
... | stack_v2_sparse_classes_75kplus_train_066096 | 1,710 | no_license | [
{
"docstring": "对于任意整数,有a^2 <= x <= (a+1)^2,通过这个进行二分查找,快速找到目标值 :param x: :return:",
"name": "mySqrt",
"signature": "def mySqrt(self, x: int) -> int"
},
{
"docstring": "公式转换法,sqrt(x)= x^(1/2) = (e^(ln x))^(1/2) = e^(0.5*ln x) :param x: :return:",
"name": "my_sqrt",
"signature": "def my_sq... | 2 | stack_v2_sparse_classes_30k_train_038121 | Implement the Python class `Solution` described below.
Class description:
实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 对于任意整数,有a^2 <= x... | Implement the Python class `Solution` described below.
Class description:
实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 对于任意整数,有a^2 <= x... | de86b04b1f874c50613c33e969ec7a7590cceaff | <|skeleton|>
class Solution:
"""实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。"""
def mySqrt(self, x: int) -> int:
"""对于任意整数,有a^2 <= x <= (a+1)^2,通过这个进行二分查找,快速找到目标值 :param x: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。"""
def mySqrt(self, x: int) -> int:
"""对于任意整数,有a^2 <= x <= (a+1)^2,通过这个进行二分查找,快速找到目标值 :param x: :return:"""
left = 0
... | the_stack_v2_python_sparse | 069_Normal_SqrtX.py | CGump/leetcode-everyday | train | 0 |
1ccc6b3c837d06beaade1866b8bc0760385d92dd | [
"if n > 0:\n sum = x\n for i in range(n - 1):\n sum *= x\nelif n < 0:\n sum = 1 / x\n for i in range(n + 1, 0):\n sum *= 1 / x\nelse:\n sum = 1\nreturn sum",
"if not x:\n return 1\nif n < 0:\n return 1 / self.myPow3(x, -n)\nif n % 2:\n return x * self.myPow3(x, n - 1)\nreturn... | <|body_start_0|>
if n > 0:
sum = x
for i in range(n - 1):
sum *= x
elif n < 0:
sum = 1 / x
for i in range(n + 1, 0):
sum *= 1 / x
else:
sum = 1
return sum
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow2(self, x: float, n: int) -> float:
"""暴力. 使用循环。 leetcode说超过时间限制 Args: x: n: Returns:"""
<|body_0|>
def myPow3(self, x: float, n: int) -> float:
"""分而治之的方法。 x * x * x = y 1. 如果n的个数是偶数 y = x^(n/2) sum = y * y = (x * x)^(n/2) 2. 如果n的个数是奇数 y = x^(x//2... | stack_v2_sparse_classes_75kplus_train_066097 | 1,987 | no_license | [
{
"docstring": "暴力. 使用循环。 leetcode说超过时间限制 Args: x: n: Returns:",
"name": "myPow2",
"signature": "def myPow2(self, x: float, n: int) -> float"
},
{
"docstring": "分而治之的方法。 x * x * x = y 1. 如果n的个数是偶数 y = x^(n/2) sum = y * y = (x * x)^(n/2) 2. 如果n的个数是奇数 y = x^(x//2) sum = y * y * x = x * (x * x)^((n... | 3 | stack_v2_sparse_classes_30k_train_044436 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow2(self, x: float, n: int) -> float: 暴力. 使用循环。 leetcode说超过时间限制 Args: x: n: Returns:
- def myPow3(self, x: float, n: int) -> float: 分而治之的方法。 x * x * x = y 1. 如果n的个数是偶数 y =... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow2(self, x: float, n: int) -> float: 暴力. 使用循环。 leetcode说超过时间限制 Args: x: n: Returns:
- def myPow3(self, x: float, n: int) -> float: 分而治之的方法。 x * x * x = y 1. 如果n的个数是偶数 y =... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def myPow2(self, x: float, n: int) -> float:
"""暴力. 使用循环。 leetcode说超过时间限制 Args: x: n: Returns:"""
<|body_0|>
def myPow3(self, x: float, n: int) -> float:
"""分而治之的方法。 x * x * x = y 1. 如果n的个数是偶数 y = x^(n/2) sum = y * y = (x * x)^(n/2) 2. 如果n的个数是奇数 y = x^(x//2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def myPow2(self, x: float, n: int) -> float:
"""暴力. 使用循环。 leetcode说超过时间限制 Args: x: n: Returns:"""
if n > 0:
sum = x
for i in range(n - 1):
sum *= x
elif n < 0:
sum = 1 / x
for i in range(n + 1, 0):
... | the_stack_v2_python_sparse | leetcode/50_POW(x, n).py | tenqaz/crazy_arithmetic | train | 0 | |
b1ce38513fa29a3f798ad2eb817977500f41db31 | [
"input_should_stop = abs(x_delta) <= abs(x_delta) / 2 * cls.EPSILON_RELATIVE + cls.EPSILON_ABSOLUTE and abs(y_delta) <= abs(y_delta) / 2 * cls.EPSILON_RELATIVE + cls.EPSILON_ABSOLUTE\noutput_should_stop = abs(f_delta) <= abs(f_delta) / 2 * cls.EPSILON_RELATIVE + cls.EPSILON_ABSOLUTE\nreturn input_should_stop or out... | <|body_start_0|>
input_should_stop = abs(x_delta) <= abs(x_delta) / 2 * cls.EPSILON_RELATIVE + cls.EPSILON_ABSOLUTE and abs(y_delta) <= abs(y_delta) / 2 * cls.EPSILON_RELATIVE + cls.EPSILON_ABSOLUTE
output_should_stop = abs(f_delta) <= abs(f_delta) / 2 * cls.EPSILON_RELATIVE + cls.EPSILON_ABSOLUTE
... | Optimizer2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Optimizer2D:
def should_stop(cls, x_delta, y_delta, f_delta):
"""Stopping criteria for 2D optimizer. Check delta for input and output and compare to relative machine epsilon. :param x_delta: :param y_delta: :param f_delta: :return:"""
<|body_0|>
def coordinate_descent(cls, f... | stack_v2_sparse_classes_75kplus_train_066098 | 3,099 | no_license | [
{
"docstring": "Stopping criteria for 2D optimizer. Check delta for input and output and compare to relative machine epsilon. :param x_delta: :param y_delta: :param f_delta: :return:",
"name": "should_stop",
"signature": "def should_stop(cls, x_delta, y_delta, f_delta)"
},
{
"docstring": "Coordi... | 2 | stack_v2_sparse_classes_30k_train_017196 | Implement the Python class `Optimizer2D` described below.
Class description:
Implement the Optimizer2D class.
Method signatures and docstrings:
- def should_stop(cls, x_delta, y_delta, f_delta): Stopping criteria for 2D optimizer. Check delta for input and output and compare to relative machine epsilon. :param x_delt... | Implement the Python class `Optimizer2D` described below.
Class description:
Implement the Optimizer2D class.
Method signatures and docstrings:
- def should_stop(cls, x_delta, y_delta, f_delta): Stopping criteria for 2D optimizer. Check delta for input and output and compare to relative machine epsilon. :param x_delt... | 5917aa6c2fb9921c66f8da89058ed8386e9f6718 | <|skeleton|>
class Optimizer2D:
def should_stop(cls, x_delta, y_delta, f_delta):
"""Stopping criteria for 2D optimizer. Check delta for input and output and compare to relative machine epsilon. :param x_delta: :param y_delta: :param f_delta: :return:"""
<|body_0|>
def coordinate_descent(cls, f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Optimizer2D:
def should_stop(cls, x_delta, y_delta, f_delta):
"""Stopping criteria for 2D optimizer. Check delta for input and output and compare to relative machine epsilon. :param x_delta: :param y_delta: :param f_delta: :return:"""
input_should_stop = abs(x_delta) <= abs(x_delta) / 2 * cls.... | the_stack_v2_python_sparse | HW1/optimizer_2d.py | matt-dees/optimization-algs | train | 0 | |
a3cd96a44fd7390abd469390a5651162a4fe4e62 | [
"self.X = X\nself.y = y\nself.iterator = 0\nself.batchsize = batchsize",
"start = self.iterator\nend = self.iterator + self.batchsize\nself.iterator = end if end < len(self.X) else 0\nreturn (self.X[start:end], self.y[start:end])",
"r = []\nfor i in xrange(0, len(l), n):\n r.append(l[i:i + n])\nreturn r"
] | <|body_start_0|>
self.X = X
self.y = y
self.iterator = 0
self.batchsize = batchsize
<|end_body_0|>
<|body_start_1|>
start = self.iterator
end = self.iterator + self.batchsize
self.iterator = end if end < len(self.X) else 0
return (self.X[start:end], self.... | a helper class to create batches given a dataset | Batcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Batcher:
"""a helper class to create batches given a dataset"""
def __init__(self, X, y, batchsize=50):
""":param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self"""
... | stack_v2_sparse_classes_75kplus_train_066099 | 8,798 | permissive | [
{
"docstring": ":param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self",
"name": "__init__",
"signature": "def __init__(self, X, y, batchsize=50)"
},
{
"docstring": "return the next tra... | 3 | stack_v2_sparse_classes_30k_test_000846 | Implement the Python class `Batcher` described below.
Class description:
a helper class to create batches given a dataset
Method signatures and docstrings:
- def __init__(self, X, y, batchsize=50): :param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param bat... | Implement the Python class `Batcher` described below.
Class description:
a helper class to create batches given a dataset
Method signatures and docstrings:
- def __init__(self, X, y, batchsize=50): :param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param bat... | 544e843c5430abdd58138cdf1c79dcf240168a5f | <|skeleton|>
class Batcher:
"""a helper class to create batches given a dataset"""
def __init__(self, X, y, batchsize=50):
""":param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Batcher:
"""a helper class to create batches given a dataset"""
def __init__(self, X, y, batchsize=50):
""":param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self"""
self.X = X
... | the_stack_v2_python_sparse | scripts/study_case/ID_44/CNN_grist.py | Liang813/GRIST | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.