blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b89c75304acd181b0450298f1db8195a55deec3d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RequestorManager()",
"from .subject_set import SubjectSet\nfrom .subject_set import SubjectSet\nfields: Dict[str, Callable[[Any], None]] = {'managerLevel': lambda n: setattr(self, 'manager_level', n.get_int_value())}\nsuper_fields = su... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RequestorManager()
<|end_body_0|>
<|body_start_1|>
from .subject_set import SubjectSet
from .subject_set import SubjectSet
fields: Dict[str, Callable[[Any], None]] = {'managerLev... | RequestorManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestorManager:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequestorManager:
"""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... | stack_v2_sparse_classes_36k_train_031900 | 2,338 | 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: RequestorManager",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_020505 | Implement the Python class `RequestorManager` described below.
Class description:
Implement the RequestorManager class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequestorManager: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `RequestorManager` described below.
Class description:
Implement the RequestorManager class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequestorManager: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RequestorManager:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequestorManager:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestorManager:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequestorManager:
"""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: Reques... | the_stack_v2_python_sparse | msgraph/generated/models/requestor_manager.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
77de5a3aed7ec053ed54d484048dbb3edf7cf91a | [
"description = ' '.join(response.css('.mainRail .block p:nth-child(1) *::text').extract())\nif '321 N' not in description and 'teleconference' not in description:\n raise ValueError('Meeting location has changed')\nfor item in response.css('.days'):\n meeting = Meeting(title=self._parse_title(item), descripti... | <|body_start_0|>
description = ' '.join(response.css('.mainRail .block p:nth-child(1) *::text').extract())
if '321 N' not in description and 'teleconference' not in description:
raise ValueError('Meeting location has changed')
for item in response.css('.days'):
meeting = ... | ChiLaborRetirementFundSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiLaborRetirementFundSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_title(self, item):
"""Parse or generate meeting title."""
... | stack_v2_sparse_classes_36k_train_031901 | 2,731 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse or generate meeting title.",
"name": "_parse_title",
"signature... | 4 | null | Implement the Python class `ChiLaborRetirementFundSpider` described below.
Class description:
Implement the ChiLaborRetirementFundSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scr... | Implement the Python class `ChiLaborRetirementFundSpider` described below.
Class description:
Implement the ChiLaborRetirementFundSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scr... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class ChiLaborRetirementFundSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_title(self, item):
"""Parse or generate meeting title."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChiLaborRetirementFundSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs."""
description = ' '.join(response.css('.mainRail .block p:nth-child(1) *::text').extract())
if '321 N... | the_stack_v2_python_sparse | city_scrapers/spiders/chi_labor_retirement_fund.py | City-Bureau/city-scrapers | train | 308 | |
3cabec7d5448934ad8919166e547f59932a907e4 | [
"from ggrc.snapshotter import rules as snapshot_rules\nparent, child = (None, None)\nif src['source']['type'] in snapshot_rules.Types.parents:\n parent, child = (src['source'], src['destination'])\nelif src['destination']['type'] in snapshot_rules.Types.parents:\n parent, child = (src['destination'], src['sou... | <|body_start_0|>
from ggrc.snapshotter import rules as snapshot_rules
parent, child = (None, None)
if src['source']['type'] in snapshot_rules.Types.parents:
parent, child = (src['source'], src['destination'])
elif src['destination']['type'] in snapshot_rules.Types.parents:
... | Custom Resource that transforms Relationships to Snapshots on un-json. | RelationshipResource | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelationshipResource:
"""Custom Resource that transforms Relationships to Snapshots on un-json."""
def _parse_snapshot_data(src):
"""Try to find parent-child pair from src. Args: src: source JSON from which a Relationship would have been created. Returns: (parent, child, is_snapshot)... | stack_v2_sparse_classes_36k_train_031902 | 2,510 | permissive | [
{
"docstring": "Try to find parent-child pair from src. Args: src: source JSON from which a Relationship would have been created. Returns: (parent, child, is_snapshot): (source, destination, True) if source is a Parent and destination is a Snapshottable; (destination, source, True) if source is a Snapshottable ... | 3 | null | Implement the Python class `RelationshipResource` described below.
Class description:
Custom Resource that transforms Relationships to Snapshots on un-json.
Method signatures and docstrings:
- def _parse_snapshot_data(src): Try to find parent-child pair from src. Args: src: source JSON from which a Relationship would... | Implement the Python class `RelationshipResource` described below.
Class description:
Custom Resource that transforms Relationships to Snapshots on un-json.
Method signatures and docstrings:
- def _parse_snapshot_data(src): Try to find parent-child pair from src. Args: src: source JSON from which a Relationship would... | 9bdc0fc6ca9e252f4919db682d80e360d5581eb4 | <|skeleton|>
class RelationshipResource:
"""Custom Resource that transforms Relationships to Snapshots on un-json."""
def _parse_snapshot_data(src):
"""Try to find parent-child pair from src. Args: src: source JSON from which a Relationship would have been created. Returns: (parent, child, is_snapshot)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelationshipResource:
"""Custom Resource that transforms Relationships to Snapshots on un-json."""
def _parse_snapshot_data(src):
"""Try to find parent-child pair from src. Args: src: source JSON from which a Relationship would have been created. Returns: (parent, child, is_snapshot): (source, de... | the_stack_v2_python_sparse | src/ggrc/services/relationship_resource.py | HLD/ggrc-core | train | 0 |
f5d078121353f9dd3853bde1c9a9f8f151c46654 | [
"cls.__name__ = str(name + 'Spec')\ncls.name = name\ncls.xmlType = xmlType\ncls.needGenerating = True\ncls.enumList = enumList",
"simpleType = ET.SubElement(xsdNode, 'xsd:simpleType')\nsimpleType.set('name', cls.getXMLType())\nrestriction = ET.SubElement(simpleType, 'xsd:restriction')\nrestriction.set('base', 'xs... | <|body_start_0|>
cls.__name__ = str(name + 'Spec')
cls.name = name
cls.xmlType = xmlType
cls.needGenerating = True
cls.enumList = enumList
<|end_body_0|>
<|body_start_1|>
simpleType = ET.SubElement(xsdNode, 'xsd:simpleType')
simpleType.set('name', cls.getXMLType(... | A type that allows a set list of strings | EnumBaseType | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumBaseType:
"""A type that allows a set list of strings"""
def createClass(cls, name, xmlType, enumList):
"""creates a new enumeration type. @ In, name, string, the name of the type @ In, xmlType, string, the name used for the xml type. @ In, enumList, [string], a list of allowable... | stack_v2_sparse_classes_36k_train_031903 | 16,966 | permissive | [
{
"docstring": "creates a new enumeration type. @ In, name, string, the name of the type @ In, xmlType, string, the name used for the xml type. @ In, enumList, [string], a list of allowable strings. @ Out, None",
"name": "createClass",
"signature": "def createClass(cls, name, xmlType, enumList)"
},
... | 2 | stack_v2_sparse_classes_30k_train_009039 | Implement the Python class `EnumBaseType` described below.
Class description:
A type that allows a set list of strings
Method signatures and docstrings:
- def createClass(cls, name, xmlType, enumList): creates a new enumeration type. @ In, name, string, the name of the type @ In, xmlType, string, the name used for th... | Implement the Python class `EnumBaseType` described below.
Class description:
A type that allows a set list of strings
Method signatures and docstrings:
- def createClass(cls, name, xmlType, enumList): creates a new enumeration type. @ In, name, string, the name of the type @ In, xmlType, string, the name used for th... | fbee9e3def3c1ee576d1af85f3258cc816ceaaaf | <|skeleton|>
class EnumBaseType:
"""A type that allows a set list of strings"""
def createClass(cls, name, xmlType, enumList):
"""creates a new enumeration type. @ In, name, string, the name of the type @ In, xmlType, string, the name used for the xml type. @ In, enumList, [string], a list of allowable... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnumBaseType:
"""A type that allows a set list of strings"""
def createClass(cls, name, xmlType, enumList):
"""creates a new enumeration type. @ In, name, string, the name of the type @ In, xmlType, string, the name used for the xml type. @ In, enumList, [string], a list of allowable strings. @ O... | the_stack_v2_python_sparse | framework/utils/InputData.py | jbae11/raven | train | 0 |
665023f36d147a4073ff942a84f0fa7fbfa3e30b | [
"data = {'uid': uid, 'last_type': 1, 'last_time': 0}\nmodel_create(UserLastTime, data, commit=is_commit)\ndata = {'uid': uid, 'funds': 0, 'add_time': current_time, 'update_time': current_time}\nmodel_create(Funds, data, commit=is_commit)\nreturn True",
"ult = UserLastTime.query.filter(UserLastTime.uid == uid).fil... | <|body_start_0|>
data = {'uid': uid, 'last_type': 1, 'last_time': 0}
model_create(UserLastTime, data, commit=is_commit)
data = {'uid': uid, 'funds': 0, 'add_time': current_time, 'update_time': current_time}
model_create(Funds, data, commit=is_commit)
return True
<|end_body_0|>
<... | 用户静态方法Service | UserStaticMethodsService | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserStaticMethodsService:
"""用户静态方法Service"""
def create_account(uid, current_time, is_commit=False):
"""创建帐户"""
<|body_0|>
def unread_count(uid):
"""未读消息数"""
<|body_1|>
def reset_last_time(uid, last_type):
"""重置最新时间"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k_train_031904 | 2,890 | permissive | [
{
"docstring": "创建帐户",
"name": "create_account",
"signature": "def create_account(uid, current_time, is_commit=False)"
},
{
"docstring": "未读消息数",
"name": "unread_count",
"signature": "def unread_count(uid)"
},
{
"docstring": "重置最新时间",
"name": "reset_last_time",
"signature... | 3 | null | Implement the Python class `UserStaticMethodsService` described below.
Class description:
用户静态方法Service
Method signatures and docstrings:
- def create_account(uid, current_time, is_commit=False): 创建帐户
- def unread_count(uid): 未读消息数
- def reset_last_time(uid, last_type): 重置最新时间 | Implement the Python class `UserStaticMethodsService` described below.
Class description:
用户静态方法Service
Method signatures and docstrings:
- def create_account(uid, current_time, is_commit=False): 创建帐户
- def unread_count(uid): 未读消息数
- def reset_last_time(uid, last_type): 重置最新时间
<|skeleton|>
class UserStaticMethodsSer... | 469444e33ef8a57d024e02c76040b1a7a6df983d | <|skeleton|>
class UserStaticMethodsService:
"""用户静态方法Service"""
def create_account(uid, current_time, is_commit=False):
"""创建帐户"""
<|body_0|>
def unread_count(uid):
"""未读消息数"""
<|body_1|>
def reset_last_time(uid, last_type):
"""重置最新时间"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserStaticMethodsService:
"""用户静态方法Service"""
def create_account(uid, current_time, is_commit=False):
"""创建帐户"""
data = {'uid': uid, 'last_type': 1, 'last_time': 0}
model_create(UserLastTime, data, commit=is_commit)
data = {'uid': uid, 'funds': 0, 'add_time': current_time,... | the_stack_v2_python_sparse | app/services/api/user.py | lanshizhen/theonestore | train | 0 |
6de916fb17caf7136b22033461b2ececfa2bfcdf | [
"if key == 'is_verified' and value is False and (self.is_primary is True):\n raise PrimaryElementViolation(\"Can't remove verified status of primary element\")\nsuper().__setattr__(key, value)",
"data = super()._from_dict_transform(data)\nif 'primary' in data:\n data['is_primary'] = data.pop('primary')\nret... | <|body_start_0|>
if key == 'is_verified' and value is False and (self.is_primary is True):
raise PrimaryElementViolation("Can't remove verified status of primary element")
super().__setattr__(key, value)
<|end_body_0|>
<|body_start_1|>
data = super()._from_dict_transform(data)
... | Elements that can be either primary or not. | PrimaryElement | [
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrimaryElement:
"""Elements that can be either primary or not."""
def __setattr__(self, key: str, value: Any):
"""raise PrimaryElementViolation when trying to set a primary element as unverified"""
<|body_0|>
def _from_dict_transform(cls: Type[TPrimaryElementSubclass], d... | stack_v2_sparse_classes_36k_train_031905 | 18,109 | permissive | [
{
"docstring": "raise PrimaryElementViolation when trying to set a primary element as unverified",
"name": "__setattr__",
"signature": "def __setattr__(self, key: str, value: Any)"
},
{
"docstring": "Transform data received in eduid format into pythonic format.",
"name": "_from_dict_transfor... | 3 | stack_v2_sparse_classes_30k_train_007739 | Implement the Python class `PrimaryElement` described below.
Class description:
Elements that can be either primary or not.
Method signatures and docstrings:
- def __setattr__(self, key: str, value: Any): raise PrimaryElementViolation when trying to set a primary element as unverified
- def _from_dict_transform(cls: ... | Implement the Python class `PrimaryElement` described below.
Class description:
Elements that can be either primary or not.
Method signatures and docstrings:
- def __setattr__(self, key: str, value: Any): raise PrimaryElementViolation when trying to set a primary element as unverified
- def _from_dict_transform(cls: ... | 5970880caf0b0e2bdee6c23869ef287acc87af2a | <|skeleton|>
class PrimaryElement:
"""Elements that can be either primary or not."""
def __setattr__(self, key: str, value: Any):
"""raise PrimaryElementViolation when trying to set a primary element as unverified"""
<|body_0|>
def _from_dict_transform(cls: Type[TPrimaryElementSubclass], d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrimaryElement:
"""Elements that can be either primary or not."""
def __setattr__(self, key: str, value: Any):
"""raise PrimaryElementViolation when trying to set a primary element as unverified"""
if key == 'is_verified' and value is False and (self.is_primary is True):
raise... | the_stack_v2_python_sparse | src/eduid_userdb/element.py | SUNET/eduid-userdb | train | 0 |
74e7d22fba18875c289e3f217632b8e459bf4229 | [
"self.unknownVal = 'arbitraryValue'\nself.dataFrame = dataFrame\nself.dataClass = dataClass\nself.separatedClasses = self.seperateDataByClass()\nself.classPriors = self.calculateClassPriors()\nself.d = len(next(iter(self.separatedClasses.values())).columns)\nself.trainedCalculation = self.train()",
"classProbs = ... | <|body_start_0|>
self.unknownVal = 'arbitraryValue'
self.dataFrame = dataFrame
self.dataClass = dataClass
self.separatedClasses = self.seperateDataByClass()
self.classPriors = self.calculateClassPriors()
self.d = len(next(iter(self.separatedClasses.values())).columns)
... | NaiveBayes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveBayes:
def __init__(self, dataFrame, dataClass):
"""Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set"""
<|body_0|>
def test(self, tes... | stack_v2_sparse_classes_36k_train_031906 | 3,359 | no_license | [
{
"docstring": "Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set",
"name": "__init__",
"signature": "def __init__(self, dataFrame, dataClass)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_009906 | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def __init__(self, dataFrame, dataClass): Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataCla... | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def __init__(self, dataFrame, dataClass): Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataCla... | ee1dd50f2d01fe3b651d095a9dd25b1e0d3047a5 | <|skeleton|>
class NaiveBayes:
def __init__(self, dataFrame, dataClass):
"""Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set"""
<|body_0|>
def test(self, tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NaiveBayes:
def __init__(self, dataFrame, dataClass):
"""Creates an instance of a trained NaiveBayes Algorithm Args: dataFrame (DataFrame): The dataset that will train the algorithm dataClass (String): The class attribute for a given data set"""
self.unknownVal = 'arbitraryValue'
self.... | the_stack_v2_python_sparse | MLAlgorithms/NaiveBayes/naiveBayes.py | lineranch/CSCI-447 | train | 0 | |
c085289f31151cb3b8ae782250141b9d4c00732e | [
"request = self.request.GET\nqueryset = get_objects_for_user(self.request.user, 'studies.can_view_study').exclude(state='archived')\nqueryset = queryset.select_related('creator')\nqueryset = queryset.annotate(completed_responses_count=Count(Case(When(responses__completed=True, then=1))))\nqueryset = queryset.annota... | <|body_start_0|>
request = self.request.GET
queryset = get_objects_for_user(self.request.user, 'studies.can_view_study').exclude(state='archived')
queryset = queryset.select_related('creator')
queryset = queryset.annotate(completed_responses_count=Count(Case(When(responses__completed=Tru... | StudyListView shows a list of studies that a user has permission to. | StudyListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudyListView:
"""StudyListView shows a list of studies that a user has permission to."""
def get_queryset(self, *args, **kwargs):
"""Returns paginated list of items for the StudyListView - handles filtering on state, match, and sort."""
<|body_0|>
def get_context_data(s... | stack_v2_sparse_classes_36k_train_031907 | 34,217 | permissive | [
{
"docstring": "Returns paginated list of items for the StudyListView - handles filtering on state, match, and sort.",
"name": "get_queryset",
"signature": "def get_queryset(self, *args, **kwargs)"
},
{
"docstring": "Gets the context for the StudyListView and supplements with the state, match, a... | 2 | stack_v2_sparse_classes_30k_train_020487 | Implement the Python class `StudyListView` described below.
Class description:
StudyListView shows a list of studies that a user has permission to.
Method signatures and docstrings:
- def get_queryset(self, *args, **kwargs): Returns paginated list of items for the StudyListView - handles filtering on state, match, an... | Implement the Python class `StudyListView` described below.
Class description:
StudyListView shows a list of studies that a user has permission to.
Method signatures and docstrings:
- def get_queryset(self, *args, **kwargs): Returns paginated list of items for the StudyListView - handles filtering on state, match, an... | 621fbb8b25100a21fd94721d39003b5d4f651dc5 | <|skeleton|>
class StudyListView:
"""StudyListView shows a list of studies that a user has permission to."""
def get_queryset(self, *args, **kwargs):
"""Returns paginated list of items for the StudyListView - handles filtering on state, match, and sort."""
<|body_0|>
def get_context_data(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudyListView:
"""StudyListView shows a list of studies that a user has permission to."""
def get_queryset(self, *args, **kwargs):
"""Returns paginated list of items for the StudyListView - handles filtering on state, match, and sort."""
request = self.request.GET
queryset = get_o... | the_stack_v2_python_sparse | exp/views/study.py | enrobyn/lookit-api | train | 0 |
abc4e4ef09fd4da1cc6df66a3f00982d0f022ea4 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')\nself.independent_set = dict(((node, False) for node in self.graph.iternodes()))\nself.cardinality = 0\nse... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target:
raise ValueError('a loop detected')
self.independent_set = dict(((node, False) ... | Find a maximal independent set. | UnorderedSequentialIndependentSet3 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031908 | 3,887 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011645 | Implement the Python class `UnorderedSequentialIndependentSet3` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode. | Implement the Python class `UnorderedSequentialIndependentSet3` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.
<|skeleton|>
class UnorderedSequentialI... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
... | the_stack_v2_python_sparse | graphtheory/independentsets/isetus.py | kgashok/graphs-dict | train | 0 |
8c79d7fe29e8dd77452545909dff6a1e0d9d07fd | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RecurrencePattern()",
"from .day_of_week import DayOfWeek\nfrom .recurrence_pattern_type import RecurrencePatternType\nfrom .week_index import WeekIndex\nfrom .day_of_week import DayOfWeek\nfrom .recurrence_pattern_type import Recurren... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RecurrencePattern()
<|end_body_0|>
<|body_start_1|>
from .day_of_week import DayOfWeek
from .recurrence_pattern_type import RecurrencePatternType
from .week_index import WeekInde... | RecurrencePattern | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurrencePattern:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecurrencePattern:
"""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... | stack_v2_sparse_classes_36k_train_031909 | 5,400 | 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: RecurrencePattern",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_011531 | Implement the Python class `RecurrencePattern` described below.
Class description:
Implement the RecurrencePattern class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecurrencePattern: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `RecurrencePattern` described below.
Class description:
Implement the RecurrencePattern class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecurrencePattern: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RecurrencePattern:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecurrencePattern:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecurrencePattern:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecurrencePattern:
"""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: Recu... | the_stack_v2_python_sparse | msgraph/generated/models/recurrence_pattern.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
7518ec57cee1db9011db43c2edee61b1aaee2e03 | [
"if registration_enabled():\n return super().is_open_for_signup(request, *args, **kwargs)\nreturn False",
"mail_restriction = InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_RESTRICTION', None)\nif not mail_restriction:\n return super().clean_email(email)\nsplit_email = email.split('@')\nif len(split_email)... | <|body_start_0|>
if registration_enabled():
return super().is_open_for_signup(request, *args, **kwargs)
return False
<|end_body_0|>
<|body_start_1|>
mail_restriction = InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_RESTRICTION', None)
if not mail_restriction:
re... | Mixin to check if registration should be enabled. | RegistratonMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistratonMixin:
"""Mixin to check if registration should be enabled."""
def is_open_for_signup(self, request, *args, **kwargs):
"""Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to set which setting should be used, default: `LOGIN_ENABLE... | stack_v2_sparse_classes_36k_train_031910 | 12,546 | permissive | [
{
"docstring": "Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to set which setting should be used, default: `LOGIN_ENABLE_REG`.",
"name": "is_open_for_signup",
"signature": "def is_open_for_signup(self, request, *args, **kwargs)"
},
{
"docstring": "C... | 3 | stack_v2_sparse_classes_30k_val_000734 | Implement the Python class `RegistratonMixin` described below.
Class description:
Mixin to check if registration should be enabled.
Method signatures and docstrings:
- def is_open_for_signup(self, request, *args, **kwargs): Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to... | Implement the Python class `RegistratonMixin` described below.
Class description:
Mixin to check if registration should be enabled.
Method signatures and docstrings:
- def is_open_for_signup(self, request, *args, **kwargs): Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class RegistratonMixin:
"""Mixin to check if registration should be enabled."""
def is_open_for_signup(self, request, *args, **kwargs):
"""Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to set which setting should be used, default: `LOGIN_ENABLE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistratonMixin:
"""Mixin to check if registration should be enabled."""
def is_open_for_signup(self, request, *args, **kwargs):
"""Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to set which setting should be used, default: `LOGIN_ENABLE_REG`."""
... | the_stack_v2_python_sparse | InvenTree/InvenTree/forms.py | inventree/InvenTree | train | 3,077 |
afeddccb09a188c2a205c033162be27db599bcf4 | [
"super(FeaturesAndAttrAttention, self).__init__()\nself.encoder_att = nn.Linear(encoder_dim + 1, attention_dim)\nself.decoder_att = nn.Linear(decoder_dim, attention_dim)\nself.attr_att = nn.Linear(512, 512)\nself.full_att = nn.Linear(attention_dim, 1)\nself.relu = nn.ReLU()\nself.softmax = nn.Softmax(dim=1)\nself.e... | <|body_start_0|>
super(FeaturesAndAttrAttention, self).__init__()
self.encoder_att = nn.Linear(encoder_dim + 1, attention_dim)
self.decoder_att = nn.Linear(decoder_dim, attention_dim)
self.attr_att = nn.Linear(512, 512)
self.full_att = nn.Linear(attention_dim, 1)
self.rel... | Attention Network. | FeaturesAndAttrAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeaturesAndAttrAttention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim, embedding_attr):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
... | stack_v2_sparse_classes_36k_train_031911 | 13,865 | no_license | [
{
"docstring": ":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network",
"name": "__init__",
"signature": "def __init__(self, encoder_dim, decoder_dim, attention_dim, embedding_attr)"
},
{
"docstring": "For... | 2 | stack_v2_sparse_classes_30k_train_011363 | Implement the Python class `FeaturesAndAttrAttention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, encoder_dim, decoder_dim, attention_dim, embedding_attr): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :pa... | Implement the Python class `FeaturesAndAttrAttention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, encoder_dim, decoder_dim, attention_dim, embedding_attr): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :pa... | 426d97b5d3688f6c52c51ef6e33872554d55751a | <|skeleton|>
class FeaturesAndAttrAttention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim, embedding_attr):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeaturesAndAttrAttention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim, embedding_attr):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
super(Feat... | the_stack_v2_python_sparse | src/models/continuous_encoder_decoder_models/encoder_decoder_variants/attention_attribute_embedding_scorecat_image.py | RitaRamo/remote-sensing-images-caption | train | 3 |
00e109356af20195309c532a97446bc65f37e24c | [
"whatsappid = '+27820001001'\nwith patch('ada.tasks.rapidpro') as p:\n start_prototype_survey_flow(whatsappid)\np.create_flow_start.assert_called_once_with(extra={}, flow='test-flow-uuid', urns=['whatsapp:27820001001'])",
"whatsappid = '+27820001001'\nwith patch('ada.tasks.rapidpro') as p:\n start_topup_flo... | <|body_start_0|>
whatsappid = '+27820001001'
with patch('ada.tasks.rapidpro') as p:
start_prototype_survey_flow(whatsappid)
p.create_flow_start.assert_called_once_with(extra={}, flow='test-flow-uuid', urns=['whatsapp:27820001001'])
<|end_body_0|>
<|body_start_1|>
whatsappid ... | HandleSubmitShatsappidToRapidpro | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandleSubmitShatsappidToRapidpro:
def test_start_prototype_survey_flow(self):
"""Triggers the correct flow with the correct details"""
<|body_0|>
def test_start_topup_flow(self):
"""Triggers the topup flow with the correct details"""
<|body_1|>
def test_... | stack_v2_sparse_classes_36k_train_031912 | 2,373 | permissive | [
{
"docstring": "Triggers the correct flow with the correct details",
"name": "test_start_prototype_survey_flow",
"signature": "def test_start_prototype_survey_flow(self)"
},
{
"docstring": "Triggers the topup flow with the correct details",
"name": "test_start_topup_flow",
"signature": "... | 4 | null | Implement the Python class `HandleSubmitShatsappidToRapidpro` described below.
Class description:
Implement the HandleSubmitShatsappidToRapidpro class.
Method signatures and docstrings:
- def test_start_prototype_survey_flow(self): Triggers the correct flow with the correct details
- def test_start_topup_flow(self): ... | Implement the Python class `HandleSubmitShatsappidToRapidpro` described below.
Class description:
Implement the HandleSubmitShatsappidToRapidpro class.
Method signatures and docstrings:
- def test_start_prototype_survey_flow(self): Triggers the correct flow with the correct details
- def test_start_topup_flow(self): ... | e1ea0beaf079f4f4d5f9562fb9d9a4f0670f459f | <|skeleton|>
class HandleSubmitShatsappidToRapidpro:
def test_start_prototype_survey_flow(self):
"""Triggers the correct flow with the correct details"""
<|body_0|>
def test_start_topup_flow(self):
"""Triggers the topup flow with the correct details"""
<|body_1|>
def test_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HandleSubmitShatsappidToRapidpro:
def test_start_prototype_survey_flow(self):
"""Triggers the correct flow with the correct details"""
whatsappid = '+27820001001'
with patch('ada.tasks.rapidpro') as p:
start_prototype_survey_flow(whatsappid)
p.create_flow_start.asse... | the_stack_v2_python_sparse | ada/test_tasks.py | praekeltfoundation/ndoh-hub | train | 0 | |
8e45f56662c629348994dec01d3040ced336de24 | [
"if categorical:\n raise ValueError('This model does not support categorical action spaces.')\nsuper().__init__()\nself.action_dim = action_size\nself.feature_extractor = _ImpalaCNN(observation_shape.img, observation_shape.vector[0])\nn_feats = self.feature_extractor.n_outputs\nmlp_activation = nn.ReLU()\nmlp_hi... | <|body_start_0|>
if categorical:
raise ValueError('This model does not support categorical action spaces.')
super().__init__()
self.action_dim = action_size
self.feature_extractor = _ImpalaCNN(observation_shape.img, observation_shape.vector[0])
n_feats = self.feature_... | ImpalaSacModel | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImpalaSacModel:
def __init__(self, observation_shape, action_size: int, categorical: bool=False, sym_extractor=None):
""":param action_dim: The number of actions if `categorical` otherwise the number of dimensions in the continuous action space."""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k_train_031913 | 20,237 | permissive | [
{
"docstring": ":param action_dim: The number of actions if `categorical` otherwise the number of dimensions in the continuous action space.",
"name": "__init__",
"signature": "def __init__(self, observation_shape, action_size: int, categorical: bool=False, sym_extractor=None)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_005144 | Implement the Python class `ImpalaSacModel` described below.
Class description:
Implement the ImpalaSacModel class.
Method signatures and docstrings:
- def __init__(self, observation_shape, action_size: int, categorical: bool=False, sym_extractor=None): :param action_dim: The number of actions if `categorical` otherw... | Implement the Python class `ImpalaSacModel` described below.
Class description:
Implement the ImpalaSacModel class.
Method signatures and docstrings:
- def __init__(self, observation_shape, action_size: int, categorical: bool=False, sym_extractor=None): :param action_dim: The number of actions if `categorical` otherw... | c778824b3285e3e994a4c5846c7b1c2ac03c669b | <|skeleton|>
class ImpalaSacModel:
def __init__(self, observation_shape, action_size: int, categorical: bool=False, sym_extractor=None):
""":param action_dim: The number of actions if `categorical` otherwise the number of dimensions in the continuous action space."""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImpalaSacModel:
def __init__(self, observation_shape, action_size: int, categorical: bool=False, sym_extractor=None):
""":param action_dim: The number of actions if `categorical` otherwise the number of dimensions in the continuous action space."""
if categorical:
raise ValueError(... | the_stack_v2_python_sparse | vsrl/rl/rlpyt/models.py | nrfulton/vsrl-framework | train | 1 | |
f0705818a7412546cba0482f9f4776a7da68fc10 | [
"counter = Counter(nums)\nn = max(counter.values())\nreturn n * K <= len(nums)",
"counter = Counter(nums)\nn = max(counter.values())\nif n * K > len(nums):\n return False\nwhile n > 0:\n m = K\n for c in counter:\n if counter[c] > 0:\n counter[c] -= 1\n m -= 1\n if m =... | <|body_start_0|>
counter = Counter(nums)
n = max(counter.values())
return n * K <= len(nums)
<|end_body_0|>
<|body_start_1|>
counter = Counter(nums)
n = max(counter.values())
if n * K > len(nums):
return False
while n > 0:
m = K
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canDivideIntoSubsequencesMath(self, nums, K):
""":type nums: List[int] :type K: int :rtype: bool"""
<|body_0|>
def canDivideIntoSubsequences(self, nums, K):
""":type nums: List[int] :type K: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_031914 | 2,085 | no_license | [
{
"docstring": ":type nums: List[int] :type K: int :rtype: bool",
"name": "canDivideIntoSubsequencesMath",
"signature": "def canDivideIntoSubsequencesMath(self, nums, K)"
},
{
"docstring": ":type nums: List[int] :type K: int :rtype: bool",
"name": "canDivideIntoSubsequences",
"signature"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canDivideIntoSubsequencesMath(self, nums, K): :type nums: List[int] :type K: int :rtype: bool
- def canDivideIntoSubsequences(self, nums, K): :type nums: List[int] :type K: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canDivideIntoSubsequencesMath(self, nums, K): :type nums: List[int] :type K: int :rtype: bool
- def canDivideIntoSubsequences(self, nums, K): :type nums: List[int] :type K: i... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def canDivideIntoSubsequencesMath(self, nums, K):
""":type nums: List[int] :type K: int :rtype: bool"""
<|body_0|>
def canDivideIntoSubsequences(self, nums, K):
""":type nums: List[int] :type K: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canDivideIntoSubsequencesMath(self, nums, K):
""":type nums: List[int] :type K: int :rtype: bool"""
counter = Counter(nums)
n = max(counter.values())
return n * K <= len(nums)
def canDivideIntoSubsequences(self, nums, K):
""":type nums: List[int] :typ... | the_stack_v2_python_sparse | D/DivideArrayIntoIncreasingSequences.py | bssrdf/pyleet | train | 2 | |
0cd01d4da8a9e28c5896a1e2b072fcace47bc687 | [
"lst = []\nQ = [root] if root else []\nwhile len(Q) > 0:\n p = Q.pop()\n if not p:\n lst.append(None)\n continue\n Q.append(p.left)\n Q.append(p.right)\nwhile len(lst) > 0 and lst[-1] == None:\n lst.pop()\nreturn str(lst)",
"data = data[1:-1]\nif len(data) == 0:\n return None\nlst ... | <|body_start_0|>
lst = []
Q = [root] if root else []
while len(Q) > 0:
p = Q.pop()
if not p:
lst.append(None)
continue
Q.append(p.left)
Q.append(p.right)
while len(lst) > 0 and lst[-1] == None:
ls... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031915 | 1,480 | 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_012890 | 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:... | a95b871578aae0103066962c33b8c0f4ec22d0f2 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
lst = []
Q = [root] if root else []
while len(Q) > 0:
p = Q.pop()
if not p:
lst.append(None)
continue
... | the_stack_v2_python_sparse | Offer037.py | Jane11111/Leetcode2021 | train | 2 | |
f8b9acfc4f5541e964330df331eb979f41f5d8d1 | [
"insurance_requirement = get_object_or_404(InsuranceRequirement, pk=pk)\nself.check_object_permissions(request, insurance_requirement)\nserializer = InsuranceRequirementRetrieveUpdateDestroySerializer(insurance_requirement, many=False)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)",
"insurance... | <|body_start_0|>
insurance_requirement = get_object_or_404(InsuranceRequirement, pk=pk)
self.check_object_permissions(request, insurance_requirement)
serializer = InsuranceRequirementRetrieveUpdateDestroySerializer(insurance_requirement, many=False)
return Response(data=serializer.data, ... | InsuranceRequirementRetrieveUpdateDestroyAPIView | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsuranceRequirementRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
def delete(self, request, pk=None):
"""Delete"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k_train_031916 | 3,452 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, pk=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, pk=None)"
},
{
"docstring": "Delete",
"name": "delete",
"signature": "def delete(self, request, pk=None... | 3 | stack_v2_sparse_classes_30k_train_016054 | Implement the Python class `InsuranceRequirementRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the InsuranceRequirementRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, pk=None): Retrieve
- def put(self, request, pk=None): Update
- def delete(s... | Implement the Python class `InsuranceRequirementRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the InsuranceRequirementRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, pk=None): Retrieve
- def put(self, request, pk=None): Update
- def delete(s... | 289318b0333d830c089f4492716c38d409c365ed | <|skeleton|>
class InsuranceRequirementRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
def delete(self, request, pk=None):
"""Delete"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsuranceRequirementRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
insurance_requirement = get_object_or_404(InsuranceRequirement, pk=pk)
self.check_object_permissions(request, insurance_requirement)
serializer = InsuranceRequirementRetrieveUpdate... | the_stack_v2_python_sparse | workery/tenant_api/views/insurance_requirement.py | wahello/workery-django | train | 0 | |
ed3c47753361bdaa131a5db33bfd4b0b8aeee9d2 | [
"if population_response is None:\n return None\npopulation = population_response['population']\nunpack_obj.generation = population_response['generation_count']\nevaluation_stats = population_response['evaluation_stats']\nunpack_obj.checkpoint_id = population_response['checkpoint_id']\nif evaluation_stats is not ... | <|body_start_0|>
if population_response is None:
return None
population = population_response['population']
unpack_obj.generation = population_response['generation_count']
evaluation_stats = population_response['evaluation_stats']
unpack_obj.checkpoint_id = population... | Utility class with stateless methods that assist in packing and unpacking population responses that go over the wire. | PopulationResponseUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopulationResponseUtil:
"""Utility class with stateless methods that assist in packing and unpacking population responses that go over the wire."""
def unpack_response(self, population_response, unpack_obj):
""":param population_response: The population response to unpack :param unpa... | stack_v2_sparse_classes_36k_train_031917 | 3,085 | no_license | [
{
"docstring": ":param population_response: The population response to unpack :param unpack_obj: The object onto which unpacked data is assigned It is expected this object has the following fields: * persistor.advanced_stats * server_stats * seen_checkpoint_ids * generation * checkpoint_id :return: The populati... | 2 | null | Implement the Python class `PopulationResponseUtil` described below.
Class description:
Utility class with stateless methods that assist in packing and unpacking population responses that go over the wire.
Method signatures and docstrings:
- def unpack_response(self, population_response, unpack_obj): :param populatio... | Implement the Python class `PopulationResponseUtil` described below.
Class description:
Utility class with stateless methods that assist in packing and unpacking population responses that go over the wire.
Method signatures and docstrings:
- def unpack_response(self, population_response, unpack_obj): :param populatio... | 99c2f401d6c4b203ee439ed607985a918d0c3c7e | <|skeleton|>
class PopulationResponseUtil:
"""Utility class with stateless methods that assist in packing and unpacking population responses that go over the wire."""
def unpack_response(self, population_response, unpack_obj):
""":param population_response: The population response to unpack :param unpa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PopulationResponseUtil:
"""Utility class with stateless methods that assist in packing and unpacking population responses that go over the wire."""
def unpack_response(self, population_response, unpack_obj):
""":param population_response: The population response to unpack :param unpack_obj: The o... | the_stack_v2_python_sparse | experimenthost/tasks/population_response_util.py | Cognizant-CDB-AIA-BAI-AI-OI/LEAF-ENN-Training-V2 | train | 0 |
921d95720ff1d27689bd0efd940ee1dc1391b5ac | [
"self.dnaSeq = dnaSeq\nself.peptide = peptide\nself.peptideSeqs = []",
"thisPeptide = ''\nif len(seq) % 3 == 0 and len(self.peptide) * 3 == len(seq):\n for i in range(0, len(seq), 3):\n thisPeptide += self.dnaCodonTable[seq[i:i + 3]]\n if thisPeptide == self.peptide:\n self.peptideSeqs.append(... | <|body_start_0|>
self.dnaSeq = dnaSeq
self.peptide = peptide
self.peptideSeqs = []
<|end_body_0|>
<|body_start_1|>
thisPeptide = ''
if len(seq) % 3 == 0 and len(self.peptide) * 3 == len(seq):
for i in range(0, len(seq), 3):
thisPeptide += self.dnaCodo... | Class containing a DNA sequence, a peptide sequence, and finds the DNA subsequences coding for the peptide sequence. 3 Attributes: self.dnaSeq self.peptide self.peptideSeqs 4 methods: self.__init__() self.translation() self.findPeptideSeqs() self.printPeptideSeqs() NOTE: There is one other variable, dnaCodonTable, that... | Peptide | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Peptide:
"""Class containing a DNA sequence, a peptide sequence, and finds the DNA subsequences coding for the peptide sequence. 3 Attributes: self.dnaSeq self.peptide self.peptideSeqs 4 methods: self.__init__() self.translation() self.findPeptideSeqs() self.printPeptideSeqs() NOTE: There is one ... | stack_v2_sparse_classes_36k_train_031918 | 5,421 | no_license | [
{
"docstring": "Constructor for the Peptide class. Takes two parameters: :param dnaSeq: a DNA sequence :param peptide: a peptide sequence Contains the following attributes: self.dnaSeq # (str) the DNA sequence provided by the user self.peptide # (str) the peptide sequence provided by the user self.peptideSeqs #... | 4 | stack_v2_sparse_classes_30k_train_009991 | Implement the Python class `Peptide` described below.
Class description:
Class containing a DNA sequence, a peptide sequence, and finds the DNA subsequences coding for the peptide sequence. 3 Attributes: self.dnaSeq self.peptide self.peptideSeqs 4 methods: self.__init__() self.translation() self.findPeptideSeqs() self... | Implement the Python class `Peptide` described below.
Class description:
Class containing a DNA sequence, a peptide sequence, and finds the DNA subsequences coding for the peptide sequence. 3 Attributes: self.dnaSeq self.peptide self.peptideSeqs 4 methods: self.__init__() self.translation() self.findPeptideSeqs() self... | 205e38dccf95d4be43ed542e46c2265689ca2cdf | <|skeleton|>
class Peptide:
"""Class containing a DNA sequence, a peptide sequence, and finds the DNA subsequences coding for the peptide sequence. 3 Attributes: self.dnaSeq self.peptide self.peptideSeqs 4 methods: self.__init__() self.translation() self.findPeptideSeqs() self.printPeptideSeqs() NOTE: There is one ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Peptide:
"""Class containing a DNA sequence, a peptide sequence, and finds the DNA subsequences coding for the peptide sequence. 3 Attributes: self.dnaSeq self.peptide self.peptideSeqs 4 methods: self.__init__() self.translation() self.findPeptideSeqs() self.printPeptideSeqs() NOTE: There is one other variabl... | the_stack_v2_python_sparse | problem15.py | tianap/bme-205 | train | 0 |
365071cfa5d5a15884a78dbe5c6a49e5b9c9f609 | [
"feature_mapping = {'Nearest_Color': {'black': 0, 'white': 1, 'red': 2, 'blue': 3, 'grey': 4, 'yellow': 5, 'orange': 6, 'green': 7, 'purple': 8}, 'Nearest_Bg_Color': {'black': 0, 'white': 1, 'red': 2, 'blue': 3, 'grey': 4, 'yellow': 5, 'orange': 6, 'green': 7, 'purple': 8}, 'Class': {'None': 0, 'LabelCandidate': 1,... | <|body_start_0|>
feature_mapping = {'Nearest_Color': {'black': 0, 'white': 1, 'red': 2, 'blue': 3, 'grey': 4, 'yellow': 5, 'orange': 6, 'green': 7, 'purple': 8}, 'Nearest_Bg_Color': {'black': 0, 'white': 1, 'red': 2, 'blue': 3, 'grey': 4, 'yellow': 5, 'orange': 6, 'green': 7, 'purple': 8}, 'Class': {'None': 0, ... | Pre-processes a data frame for training purposes. | FrameMapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrameMapper:
"""Pre-processes a data frame for training purposes."""
def map_label_candidates(data_frame):
"""Performs label encoding and removes noisy columns for the label candidate classification problem. :param data_frame: The data frame extracted using the ConcreteStateFeaturize... | stack_v2_sparse_classes_36k_train_031919 | 3,057 | permissive | [
{
"docstring": "Performs label encoding and removes noisy columns for the label candidate classification problem. :param data_frame: The data frame extracted using the ConcreteStateFeaturizer class. :return: A data frame that is ready to be input into a training function.",
"name": "map_label_candidates",
... | 2 | stack_v2_sparse_classes_30k_train_017347 | Implement the Python class `FrameMapper` described below.
Class description:
Pre-processes a data frame for training purposes.
Method signatures and docstrings:
- def map_label_candidates(data_frame): Performs label encoding and removes noisy columns for the label candidate classification problem. :param data_frame: ... | Implement the Python class `FrameMapper` described below.
Class description:
Pre-processes a data frame for training purposes.
Method signatures and docstrings:
- def map_label_candidates(data_frame): Performs label encoding and removes noisy columns for the label candidate classification problem. :param data_frame: ... | b9b4db6af024ea9e075e345066547e9c4fc4766f | <|skeleton|>
class FrameMapper:
"""Pre-processes a data frame for training purposes."""
def map_label_candidates(data_frame):
"""Performs label encoding and removes noisy columns for the label candidate classification problem. :param data_frame: The data frame extracted using the ConcreteStateFeaturize... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrameMapper:
"""Pre-processes a data frame for training purposes."""
def map_label_candidates(data_frame):
"""Performs label encoding and removes noisy columns for the label candidate classification problem. :param data_frame: The data frame extracted using the ConcreteStateFeaturizer class. :ret... | the_stack_v2_python_sparse | components/page-analyzer/src/services/frame_mapper.py | BrentGTR/AGENT | train | 1 |
18514ca2fcf4527abe68f379b5901562fd800737 | [
"self.input_arr = [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]\nself.output = [3, 9]\nreturn (self.input_arr, self.output)",
"input_arr, output_arr = self.setUp()\noutput = subarraySort(input_arr)\nself.assertEqual(output, output_arr)"
] | <|body_start_0|>
self.input_arr = [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]
self.output = [3, 9]
return (self.input_arr, self.output)
<|end_body_0|>
<|body_start_1|>
input_arr, output_arr = self.setUp()
output = subarraySort(input_arr)
self.assertEqual(output, output... | Class with unittests for SubarraySort.py | test_SubarraySort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_SubarraySort:
"""Class with unittests for SubarraySort.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|>
self.i... | stack_v2_sparse_classes_36k_train_031920 | 861 | 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 | null | Implement the Python class `test_SubarraySort` described below.
Class description:
Class with unittests for SubarraySort.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_SubarraySort` described below.
Class description:
Class with unittests for SubarraySort.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_SubarraySort:
"""Class... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_SubarraySort:
"""Class with unittests for SubarraySort.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_36k | data/stack_v2_sparse_classes_30k | class test_SubarraySort:
"""Class with unittests for SubarraySort.py"""
def setUp(self):
"""Sets up input."""
self.input_arr = [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]
self.output = [3, 9]
return (self.input_arr, self.output)
def test_ExpectedOutput(self):
"""C... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/SubarraySort/test_SubarraySort.py | JakubKazimierski/PythonPortfolio | train | 9 |
b4c9e801b142ee0efa5887ebe2015a3098fa8947 | [
"logging.info('Received a message from: ' + mail_message.sender)\nlogging.info(self.getBody(mail_message))\nself.sendEmailByTask(mail_message)",
"html_bodies = mail_message.bodies('text/html')\nfor content_type, body in html_bodies:\n decoded_html = body.decode()\n return decoded_html",
"subject = 'Messag... | <|body_start_0|>
logging.info('Received a message from: ' + mail_message.sender)
logging.info(self.getBody(mail_message))
self.sendEmailByTask(mail_message)
<|end_body_0|>
<|body_start_1|>
html_bodies = mail_message.bodies('text/html')
for content_type, body in html_bodies:
... | General class to recived messages. by now, it just records them in the log | LogSenderHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogSenderHandler:
"""General class to recived messages. by now, it just records them in the log"""
def receive(self, mail_message):
"""receives an email and log it"""
<|body_0|>
def getBody(self, mail_message):
"""Return the html body of a message."""
<|b... | stack_v2_sparse_classes_36k_train_031921 | 2,562 | no_license | [
{
"docstring": "receives an email and log it",
"name": "receive",
"signature": "def receive(self, mail_message)"
},
{
"docstring": "Return the html body of a message.",
"name": "getBody",
"signature": "def getBody(self, mail_message)"
},
{
"docstring": "Uses the message received ... | 3 | stack_v2_sparse_classes_30k_train_008106 | Implement the Python class `LogSenderHandler` described below.
Class description:
General class to recived messages. by now, it just records them in the log
Method signatures and docstrings:
- def receive(self, mail_message): receives an email and log it
- def getBody(self, mail_message): Return the html body of a me... | Implement the Python class `LogSenderHandler` described below.
Class description:
General class to recived messages. by now, it just records them in the log
Method signatures and docstrings:
- def receive(self, mail_message): receives an email and log it
- def getBody(self, mail_message): Return the html body of a me... | 088db8f6cc85ad0430b5d7d501bc4a4c34fad24b | <|skeleton|>
class LogSenderHandler:
"""General class to recived messages. by now, it just records them in the log"""
def receive(self, mail_message):
"""receives an email and log it"""
<|body_0|>
def getBody(self, mail_message):
"""Return the html body of a message."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogSenderHandler:
"""General class to recived messages. by now, it just records them in the log"""
def receive(self, mail_message):
"""receives an email and log it"""
logging.info('Received a message from: ' + mail_message.sender)
logging.info(self.getBody(mail_message))
s... | the_stack_v2_python_sparse | handlers/email_incoming.py | wakaru44/capitulizer | train | 0 |
c9b30968eb734c1293e40b9ee90a0f7358e64abe | [
"super(PolyInterp, self).__init__(diff_order)\nself.cheb_width = width\nself.cheb_degree = degree",
"diff_terms = {}\ndifferentiated_terms = self.PolyDiff(dvar.data, ivar.data)\nfor i in range(differentiated_terms.shape[1]):\n diff_data = differentiated_terms[:, i].flatten()\n diff_data = np.pad(diff_data, ... | <|body_start_0|>
super(PolyInterp, self).__init__(diff_order)
self.cheb_width = width
self.cheb_degree = degree
<|end_body_0|>
<|body_start_1|>
diff_terms = {}
differentiated_terms = self.PolyDiff(dvar.data, ivar.data)
for i in range(differentiated_terms.shape[1]):
... | Differentiator that implements Chebychev polynomial interpolation. | PolyInterp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolyInterp:
"""Differentiator that implements Chebychev polynomial interpolation."""
def __init__(self, diff_order: int=3, width: int=5, degree: int=3):
"""Store diff_order and other polynomial interpolation attributes. Keyword arguments: diff_order -- max order differential to compu... | stack_v2_sparse_classes_36k_train_031922 | 3,952 | permissive | [
{
"docstring": "Store diff_order and other polynomial interpolation attributes. Keyword arguments: diff_order -- max order differential to compute (e.g. 2 is u_xx) cheb_width -- Width of window on which to interpolate polynomial cheb_degree -- Polynomial degree for Chebychev polynomial fitting",
"name": "__... | 3 | stack_v2_sparse_classes_30k_train_001302 | Implement the Python class `PolyInterp` described below.
Class description:
Differentiator that implements Chebychev polynomial interpolation.
Method signatures and docstrings:
- def __init__(self, diff_order: int=3, width: int=5, degree: int=3): Store diff_order and other polynomial interpolation attributes. Keyword... | Implement the Python class `PolyInterp` described below.
Class description:
Differentiator that implements Chebychev polynomial interpolation.
Method signatures and docstrings:
- def __init__(self, diff_order: int=3, width: int=5, degree: int=3): Store diff_order and other polynomial interpolation attributes. Keyword... | ac5b2bb4854bb311e4f6f26b180dde87cc10c13d | <|skeleton|>
class PolyInterp:
"""Differentiator that implements Chebychev polynomial interpolation."""
def __init__(self, diff_order: int=3, width: int=5, degree: int=3):
"""Store diff_order and other polynomial interpolation attributes. Keyword arguments: diff_order -- max order differential to compu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolyInterp:
"""Differentiator that implements Chebychev polynomial interpolation."""
def __init__(self, diff_order: int=3, width: int=5, degree: int=3):
"""Store diff_order and other polynomial interpolation attributes. Keyword arguments: diff_order -- max order differential to compute (e.g. 2 is... | the_stack_v2_python_sparse | sindy_bvp/differentiators/poly_interp.py | AI-and-ML/SINDy-BVP | train | 0 |
f0df91748f61ac1f7625c90c394626a388631130 | [
"User = apps.get_model('auth', 'User')\ntry:\n user = User.objects.get(username=USERNAME, email=OLD_EMAIL)\nexcept User.DoesNotExist:\n return\nuser.email = NEW_EMAIL\nuser.save()",
"User = apps.get_model('auth', 'User')\ntry:\n user = User.objects.get(username=USERNAME, email=NEW_EMAIL)\nexcept User.Doe... | <|body_start_0|>
User = apps.get_model('auth', 'User')
try:
user = User.objects.get(username=USERNAME, email=OLD_EMAIL)
except User.DoesNotExist:
return
user.email = NEW_EMAIL
user.save()
<|end_body_0|>
<|body_start_1|>
User = apps.get_model('auth... | Migration | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(apps, schema_editor):
"""Update the email of the service user."""
<|body_0|>
def backwards(apps, schema_editor):
"""Replaces new email with old email for the service user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
User ... | stack_v2_sparse_classes_36k_train_031923 | 1,271 | permissive | [
{
"docstring": "Update the email of the service user.",
"name": "forwards",
"signature": "def forwards(apps, schema_editor)"
},
{
"docstring": "Replaces new email with old email for the service user.",
"name": "backwards",
"signature": "def backwards(apps, schema_editor)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000704 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(apps, schema_editor): Update the email of the service user.
- def backwards(apps, schema_editor): Replaces new email with old email for the service user. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(apps, schema_editor): Update the email of the service user.
- def backwards(apps, schema_editor): Replaces new email with old email for the service user.
<|skelet... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class Migration:
def forwards(apps, schema_editor):
"""Update the email of the service user."""
<|body_0|>
def backwards(apps, schema_editor):
"""Replaces new email with old email for the service user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(apps, schema_editor):
"""Update the email of the service user."""
User = apps.get_model('auth', 'User')
try:
user = User.objects.get(username=USERNAME, email=OLD_EMAIL)
except User.DoesNotExist:
return
user.email = NEW_EMA... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/commerce/migrations/0008_auto_20191024_2048.py | luque/better-ways-of-thinking-about-software | train | 3 | |
a39cbcb7848a40c5147dce1db2bf7cc52efac26a | [
"self.constr = constr\nself.conerr = 'Fetcher: Cannot connect with the supplied Connection String.'\nself.sqlerr = 'Fetcher: Error executing the supplied SQL.'",
"try:\n con = pyodbc.connect(self.constr)\nexcept:\n raise self.FetcherError(self.conerr)\ncur = con.cursor()\ncur.execute('SET QUERY_GOVERNOR_COS... | <|body_start_0|>
self.constr = constr
self.conerr = 'Fetcher: Cannot connect with the supplied Connection String.'
self.sqlerr = 'Fetcher: Error executing the supplied SQL.'
<|end_body_0|>
<|body_start_1|>
try:
con = pyodbc.connect(self.constr)
except:
ra... | Simple pyodbc-based SQL Server data grabber. Based off of fetchdata.py, except much simpler. | Fetcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fetcher:
"""Simple pyodbc-based SQL Server data grabber. Based off of fetchdata.py, except much simpler."""
def __init__(self, constr):
"""Initializes the Fetcher Class. constr is the connection string to the db of interest."""
<|body_0|>
def fetch(self, fetchsql):
... | stack_v2_sparse_classes_36k_train_031924 | 1,634 | permissive | [
{
"docstring": "Initializes the Fetcher Class. constr is the connection string to the db of interest.",
"name": "__init__",
"signature": "def __init__(self, constr)"
},
{
"docstring": "Fetches data from the connected database. fetchsql is the SQL to execute. returns a list of ordered dicts of th... | 2 | stack_v2_sparse_classes_30k_test_000452 | Implement the Python class `Fetcher` described below.
Class description:
Simple pyodbc-based SQL Server data grabber. Based off of fetchdata.py, except much simpler.
Method signatures and docstrings:
- def __init__(self, constr): Initializes the Fetcher Class. constr is the connection string to the db of interest.
- ... | Implement the Python class `Fetcher` described below.
Class description:
Simple pyodbc-based SQL Server data grabber. Based off of fetchdata.py, except much simpler.
Method signatures and docstrings:
- def __init__(self, constr): Initializes the Fetcher Class. constr is the connection string to the db of interest.
- ... | 931cc4ff0dd955f314e17f6e0d68b514cb854402 | <|skeleton|>
class Fetcher:
"""Simple pyodbc-based SQL Server data grabber. Based off of fetchdata.py, except much simpler."""
def __init__(self, constr):
"""Initializes the Fetcher Class. constr is the connection string to the db of interest."""
<|body_0|>
def fetch(self, fetchsql):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fetcher:
"""Simple pyodbc-based SQL Server data grabber. Based off of fetchdata.py, except much simpler."""
def __init__(self, constr):
"""Initializes the Fetcher Class. constr is the connection string to the db of interest."""
self.constr = constr
self.conerr = 'Fetcher: Cannot c... | the_stack_v2_python_sparse | Backend/fetcher.py | CityOfNewOrleans/NoticeMe | train | 5 |
f1ba654e2459649e83ca75d6a4ae75e0c2b6a6f9 | [
"super().__init__()\nif rotate:\n self.rotate = nn.Linear(embedding_size, embedding_size, bias=False)\nelse:\n self.rotate = lambda x: x\nself.softmax = nn.Softmax(dim=1)",
"attn = torch.bmm(query_embs.unsqueeze(1), in_mem_embs).squeeze(1)\nif pad_mask is not None:\n attn[pad_mask] = neginf(attn.dtype)\n... | <|body_start_0|>
super().__init__()
if rotate:
self.rotate = nn.Linear(embedding_size, embedding_size, bias=False)
else:
self.rotate = lambda x: x
self.softmax = nn.Softmax(dim=1)
<|end_body_0|>
<|body_start_1|>
attn = torch.bmm(query_embs.unsqueeze(1), i... | Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the probabilities 4) add the query embe... | Hop | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hop:
"""Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the prob... | stack_v2_sparse_classes_36k_train_031925 | 7,626 | permissive | [
{
"docstring": "Initialize linear rotation.",
"name": "__init__",
"signature": "def __init__(self, embedding_size, rotate=True)"
},
{
"docstring": "Compute MemNN Hop step. :param query_embs: (bsz x esz) embedding of queries :param in_mem_embs: bsz list of (num_mems x esz) embedding of memories f... | 2 | null | Implement the Python class `Hop` described below.
Class description:
Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum ... | Implement the Python class `Hop` described below.
Class description:
Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum ... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class Hop:
"""Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the prob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hop:
"""Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the probabilities 4) ... | the_stack_v2_python_sparse | parlai/agents/memnn/modules.py | facebookresearch/ParlAI | train | 10,943 |
76100de9ac0db45aec0dfc53424fdfe0048bb8ad | [
"self.logger = logging.getLogger(self.__class__.__name__)\nself.username = username\nself.password = password\nself.command_config = command_config\nif self.COMMAND_SETTINGS not in self.command_config:\n raise Exception('The command config was failed.\\n{}'.format(self.command_config))\nself.command_config_setti... | <|body_start_0|>
self.logger = logging.getLogger(self.__class__.__name__)
self.username = username
self.password = password
self.command_config = command_config
if self.COMMAND_SETTINGS not in self.command_config:
raise Exception('The command config was failed.\n{}'.f... | Push MetaTask into Pulse. | HasalPulsePublisher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HasalPulsePublisher:
"""Push MetaTask into Pulse."""
def __init__(self, username, password, command_config):
"""Hasal Pulse Publisher. @param username: the username of Pulse. @param password: the password of Pulse. @param command_config: the dict object loaded from cmd_config.json.""... | stack_v2_sparse_classes_36k_train_031926 | 7,582 | no_license | [
{
"docstring": "Hasal Pulse Publisher. @param username: the username of Pulse. @param password: the password of Pulse. @param command_config: the dict object loaded from cmd_config.json.",
"name": "__init__",
"signature": "def __init__(self, username, password, command_config)"
},
{
"docstring":... | 5 | null | Implement the Python class `HasalPulsePublisher` described below.
Class description:
Push MetaTask into Pulse.
Method signatures and docstrings:
- def __init__(self, username, password, command_config): Hasal Pulse Publisher. @param username: the username of Pulse. @param password: the password of Pulse. @param comma... | Implement the Python class `HasalPulsePublisher` described below.
Class description:
Push MetaTask into Pulse.
Method signatures and docstrings:
- def __init__(self, username, password, command_config): Hasal Pulse Publisher. @param username: the username of Pulse. @param password: the password of Pulse. @param comma... | 678f9a2984a3c359b9f0a107726f0143b9db5531 | <|skeleton|>
class HasalPulsePublisher:
"""Push MetaTask into Pulse."""
def __init__(self, username, password, command_config):
"""Hasal Pulse Publisher. @param username: the username of Pulse. @param password: the password of Pulse. @param command_config: the dict object loaded from cmd_config.json.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HasalPulsePublisher:
"""Push MetaTask into Pulse."""
def __init__(self, username, password, command_config):
"""Hasal Pulse Publisher. @param username: the username of Pulse. @param password: the password of Pulse. @param command_config: the dict object loaded from cmd_config.json."""
sel... | the_stack_v2_python_sparse | ejenti/pulse_modules/hasalPulsePublisher.py | Mozilla-TWQA/Hasal | train | 35 |
3f0895d61a88bf95f9a735b81ae22a28666e2003 | [
"self.agents = {'creator': User(1234, 'foo@bar.baz', endorsements=[('astro-ph', 'GA')]), 'client': Client(5678), 'proxy': None}\nself.token = 'asdf1234'\nself.headers = {}",
"preserve_exceptions_and_events(mock_events)\nurl_for.return_value = '/foo/'\nuser = User(1234, 'foo@bar.baz')\nmock_events.save.return_valu... | <|body_start_0|>
self.agents = {'creator': User(1234, 'foo@bar.baz', endorsements=[('astro-ph', 'GA')]), 'client': Client(5678), 'proxy': None}
self.token = 'asdf1234'
self.headers = {}
<|end_body_0|>
<|body_start_1|>
preserve_exceptions_and_events(mock_events)
url_for.return_va... | Tests for :func:`.submission.create_submission`. | TestCreateSubmission | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreateSubmission:
"""Tests for :func:`.submission.create_submission`."""
def setUp(self):
"""Create some fake request data."""
<|body_0|>
def test_create_submission_with_valid_data(self, mock_events, url_for):
"""Create a submission with valid data."""
... | stack_v2_sparse_classes_36k_train_031927 | 11,936 | permissive | [
{
"docstring": "Create some fake request data.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Create a submission with valid data.",
"name": "test_create_submission_with_valid_data",
"signature": "def test_create_submission_with_valid_data(self, mock_events, url_for... | 5 | stack_v2_sparse_classes_30k_train_015007 | Implement the Python class `TestCreateSubmission` described below.
Class description:
Tests for :func:`.submission.create_submission`.
Method signatures and docstrings:
- def setUp(self): Create some fake request data.
- def test_create_submission_with_valid_data(self, mock_events, url_for): Create a submission with ... | Implement the Python class `TestCreateSubmission` described below.
Class description:
Tests for :func:`.submission.create_submission`.
Method signatures and docstrings:
- def setUp(self): Create some fake request data.
- def test_create_submission_with_valid_data(self, mock_events, url_for): Create a submission with ... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class TestCreateSubmission:
"""Tests for :func:`.submission.create_submission`."""
def setUp(self):
"""Create some fake request data."""
<|body_0|>
def test_create_submission_with_valid_data(self, mock_events, url_for):
"""Create a submission with valid data."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCreateSubmission:
"""Tests for :func:`.submission.create_submission`."""
def setUp(self):
"""Create some fake request data."""
self.agents = {'creator': User(1234, 'foo@bar.baz', endorsements=[('astro-ph', 'GA')]), 'client': Client(5678), 'proxy': None}
self.token = 'asdf1234'... | the_stack_v2_python_sparse | metadata/metadata/controllers/submission/tests.py | arXiv/arxiv-submission-core | train | 14 |
8f429a0287307f1780503d984f1fb61d48938f27 | [
"super().__init__(*args, **kwargs)\nself.OUT_QUESTION_MUL = OUT_QUESTION_MUL\nself.outQuestion = Linear(CMD_DIM, CMD_DIM)\nself.in_dim = 3 * self.in_dim if OUT_QUESTION_MUL else 2 * self.in_dim\nself.classifier_layer = nn.Sequential(nn.Dropout(1 - outputDropout), Linear(self.in_dim, CMD_DIM), nn.ELU(), nn.Dropout(1... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.OUT_QUESTION_MUL = OUT_QUESTION_MUL
self.outQuestion = Linear(CMD_DIM, CMD_DIM)
self.in_dim = 3 * self.in_dim if OUT_QUESTION_MUL else 2 * self.in_dim
self.classifier_layer = nn.Sequential(nn.Dropout(1 - outputDropout), Line... | LCGNClassiferHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCGNClassiferHead:
def __init__(self, OUT_QUESTION_MUL: bool, CMD_DIM: int, outputDropout: float, *args, **kwargs) -> None:
"""initialization of LCGNClassiferHead. Args: OUT_QUESTION_MUL: bool to identify if do the multiplication opearation based on features CMD_DIM: command vector's dim... | stack_v2_sparse_classes_36k_train_031928 | 8,420 | permissive | [
{
"docstring": "initialization of LCGNClassiferHead. Args: OUT_QUESTION_MUL: bool to identify if do the multiplication opearation based on features CMD_DIM: command vector's dimension outputDropout: dropout rate in output layer *args: optional **kwargs: optional",
"name": "__init__",
"signature": "def _... | 2 | null | Implement the Python class `LCGNClassiferHead` described below.
Class description:
Implement the LCGNClassiferHead class.
Method signatures and docstrings:
- def __init__(self, OUT_QUESTION_MUL: bool, CMD_DIM: int, outputDropout: float, *args, **kwargs) -> None: initialization of LCGNClassiferHead. Args: OUT_QUESTION... | Implement the Python class `LCGNClassiferHead` described below.
Class description:
Implement the LCGNClassiferHead class.
Method signatures and docstrings:
- def __init__(self, OUT_QUESTION_MUL: bool, CMD_DIM: int, outputDropout: float, *args, **kwargs) -> None: initialization of LCGNClassiferHead. Args: OUT_QUESTION... | af87a17275f02c94932bb2e29f132a84db812002 | <|skeleton|>
class LCGNClassiferHead:
def __init__(self, OUT_QUESTION_MUL: bool, CMD_DIM: int, outputDropout: float, *args, **kwargs) -> None:
"""initialization of LCGNClassiferHead. Args: OUT_QUESTION_MUL: bool to identify if do the multiplication opearation based on features CMD_DIM: command vector's dim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LCGNClassiferHead:
def __init__(self, OUT_QUESTION_MUL: bool, CMD_DIM: int, outputDropout: float, *args, **kwargs) -> None:
"""initialization of LCGNClassiferHead. Args: OUT_QUESTION_MUL: bool to identify if do the multiplication opearation based on features CMD_DIM: command vector's dimension outputD... | the_stack_v2_python_sparse | imix/models/heads/classifier_mix.py | linxi1158/iMIX | train | 0 | |
c389b1c27dacbd2abfa06685f1fece2cacede9be | [
"super().__init__(data, device)\nself._sensor_type = sensor_type\nself._attr_name = f'{device.name} {SENSOR_TYPES[sensor_type][0]}'\nself._attr_device_class = SENSOR_TYPES[self._sensor_type][1]\nself._attr_unique_id = f'{device.device_uuid}-{sensor_type}'\nif self._sensor_type == CONST.TEMP_STATUS_KEY:\n self._a... | <|body_start_0|>
super().__init__(data, device)
self._sensor_type = sensor_type
self._attr_name = f'{device.name} {SENSOR_TYPES[sensor_type][0]}'
self._attr_device_class = SENSOR_TYPES[self._sensor_type][1]
self._attr_unique_id = f'{device.device_uuid}-{sensor_type}'
if s... | A sensor implementation for Abode devices. | AbodeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data, device, sensor_type):
"""Initialize a sensor for an Abode device."""
<|body_0|>
def state(self):
"""Return the state of the sensor."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_031929 | 2,256 | permissive | [
{
"docstring": "Initialize a sensor for an Abode device.",
"name": "__init__",
"signature": "def __init__(self, data, device, sensor_type)"
},
{
"docstring": "Return the state of the sensor.",
"name": "state",
"signature": "def state(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016405 | Implement the Python class `AbodeSensor` described below.
Class description:
A sensor implementation for Abode devices.
Method signatures and docstrings:
- def __init__(self, data, device, sensor_type): Initialize a sensor for an Abode device.
- def state(self): Return the state of the sensor. | Implement the Python class `AbodeSensor` described below.
Class description:
A sensor implementation for Abode devices.
Method signatures and docstrings:
- def __init__(self, data, device, sensor_type): Initialize a sensor for an Abode device.
- def state(self): Return the state of the sensor.
<|skeleton|>
class Abo... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data, device, sensor_type):
"""Initialize a sensor for an Abode device."""
<|body_0|>
def state(self):
"""Return the state of the sensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data, device, sensor_type):
"""Initialize a sensor for an Abode device."""
super().__init__(data, device)
self._sensor_type = sensor_type
self._attr_name = f'{device.name} {SENSOR_TYPES[sensor... | the_stack_v2_python_sparse | homeassistant/components/abode/sensor.py | BenWoodford/home-assistant | train | 11 |
7bd4b1ed058a3cdb04528af6aee4074a2a74281c | [
"df_tmp = df[cols + [target]].copy(deep=True)\ndf_tmp = df_tmp.fillna(0)\ndf_tmp[cols] = df_tmp[cols].apply(lambda col: (col - col.min()) / (col.max() - col.min()))\nreturn df_tmp",
"df_tmp = self.max_min_df(df_all.loc[df_all[target].isin(view_label), :], call_cols, target)\ndf_view = df_tmp.groupby(by=target)[ca... | <|body_start_0|>
df_tmp = df[cols + [target]].copy(deep=True)
df_tmp = df_tmp.fillna(0)
df_tmp[cols] = df_tmp[cols].apply(lambda col: (col - col.min()) / (col.max() - col.min()))
return df_tmp
<|end_body_0|>
<|body_start_1|>
df_tmp = self.max_min_df(df_all.loc[df_all[target].isi... | cat_target_Radar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cat_target_Radar:
def max_min_df(self, df, cols, target):
"""maxmin标准化"""
<|body_0|>
def get_view_dt(self, df_all, target, view_label, call_cols, dct=None):
"""获取目标变量两类特征(view_label)对应的call_cols 的均值,并求出差值 param df_all: 数据集 pd.DataFrame param target: object 目标变量 param... | stack_v2_sparse_classes_36k_train_031930 | 31,053 | no_license | [
{
"docstring": "maxmin标准化",
"name": "max_min_df",
"signature": "def max_min_df(self, df, cols, target)"
},
{
"docstring": "获取目标变量两类特征(view_label)对应的call_cols 的均值,并求出差值 param df_all: 数据集 pd.DataFrame param target: object 目标变量 param view_label: list 要观察的目标变量的两个类型 param call_cols: list 要进行比对的特征 par... | 3 | stack_v2_sparse_classes_30k_train_006516 | Implement the Python class `cat_target_Radar` described below.
Class description:
Implement the cat_target_Radar class.
Method signatures and docstrings:
- def max_min_df(self, df, cols, target): maxmin标准化
- def get_view_dt(self, df_all, target, view_label, call_cols, dct=None): 获取目标变量两类特征(view_label)对应的call_cols 的均值... | Implement the Python class `cat_target_Radar` described below.
Class description:
Implement the cat_target_Radar class.
Method signatures and docstrings:
- def max_min_df(self, df, cols, target): maxmin标准化
- def get_view_dt(self, df_all, target, view_label, call_cols, dct=None): 获取目标变量两类特征(view_label)对应的call_cols 的均值... | aed839a0b264d2618551482116160a3c83db3e81 | <|skeleton|>
class cat_target_Radar:
def max_min_df(self, df, cols, target):
"""maxmin标准化"""
<|body_0|>
def get_view_dt(self, df_all, target, view_label, call_cols, dct=None):
"""获取目标变量两类特征(view_label)对应的call_cols 的均值,并求出差值 param df_all: 数据集 pd.DataFrame param target: object 目标变量 param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cat_target_Radar:
def max_min_df(self, df, cols, target):
"""maxmin标准化"""
df_tmp = df[cols + [target]].copy(deep=True)
df_tmp = df_tmp.fillna(0)
df_tmp[cols] = df_tmp[cols].apply(lambda col: (col - col.min()) / (col.max() - col.min()))
return df_tmp
def get_view_dt... | the_stack_v2_python_sparse | Comp_funcs/EDA_func.py | scchy/scc_function | train | 0 | |
f9615308d4d8333a4c4ac01256e5124605a0f3f0 | [
"name = 'WTARULDDTDQWMU-UHFFFAOYAW'\ninchi = 'InChI=1/C10H16/c1-7-4-5-8-6-9(7)10(8,2)3/h8-9H,1,4-6H2,2-3H3'\ndirectory = os.path.join(os.path.dirname(__file__), 'data', 'QMfiles', '3DMolfiles')\ntarget_file = os.path.join(directory, name + '.mop')\nif os.path.exists(target_file):\n os.remove(target_file)\nmolecu... | <|body_start_0|>
name = 'WTARULDDTDQWMU-UHFFFAOYAW'
inchi = 'InChI=1/C10H16/c1-7-4-5-8-6-9(7)10(8,2)3/h8-9H,1,4-6H2,2-3H3'
directory = os.path.join(os.path.dirname(__file__), 'data', 'QMfiles', '3DMolfiles')
target_file = os.path.join(directory, name + '.mop')
if os.path.exists(t... | Test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def testMOPACInputWriter(self):
"""Checks whether the .mop output file has been written based on the 3D coords file (.mol)"""
<|body_0|>
def testG03InputWriter(self):
"""Checks whether the .gjf output file has been written based on the 3D coords file (.mol)"""
... | stack_v2_sparse_classes_36k_train_031931 | 2,020 | permissive | [
{
"docstring": "Checks whether the .mop output file has been written based on the 3D coords file (.mol)",
"name": "testMOPACInputWriter",
"signature": "def testMOPACInputWriter(self)"
},
{
"docstring": "Checks whether the .gjf output file has been written based on the 3D coords file (.mol)",
... | 2 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def testMOPACInputWriter(self): Checks whether the .mop output file has been written based on the 3D coords file (.mol)
- def testG03InputWriter(self): Checks whether the .gjf output fil... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def testMOPACInputWriter(self): Checks whether the .mop output file has been written based on the 3D coords file (.mol)
- def testG03InputWriter(self): Checks whether the .gjf output fil... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class Test:
def testMOPACInputWriter(self):
"""Checks whether the .mop output file has been written based on the 3D coords file (.mol)"""
<|body_0|>
def testG03InputWriter(self):
"""Checks whether the .gjf output file has been written based on the 3D coords file (.mol)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def testMOPACInputWriter(self):
"""Checks whether the .mop output file has been written based on the 3D coords file (.mol)"""
name = 'WTARULDDTDQWMU-UHFFFAOYAW'
inchi = 'InChI=1/C10H16/c1-7-4-5-8-6-9(7)10(8,2)3/h8-9H,1,4-6H2,2-3H3'
directory = os.path.join(os.path.dirname... | the_stack_v2_python_sparse | unittest/qm/inputWriterTest.py | vrlambert/RMG-Py | train | 1 | |
ae4cd0b6d93eddad531cff9fb0c25cea5962bd9e | [
"self.poly_degree = params.poly_degree\nself.ciph_modulus = params.ciph_modulus\nself.plain_modulus = params.plain_modulus\nself.scaling_factor = params.scaling_factor\nself.secret_key = secret_key",
"c0, c1 = (ciphertext.c0, ciphertext.c1)\nintermed_message = c0.add(c1.multiply(self.secret_key.s, self.ciph_modul... | <|body_start_0|>
self.poly_degree = params.poly_degree
self.ciph_modulus = params.ciph_modulus
self.plain_modulus = params.plain_modulus
self.scaling_factor = params.scaling_factor
self.secret_key = secret_key
<|end_body_0|>
<|body_start_1|>
c0, c1 = (ciphertext.c0, ciph... | An object that can decrypt data using BFV given a secret key. Attributes: poly_degree: Degree of polynomial in quotient ring. ciph_modulus: Coefficient modulus in ciphertext space. plain_modulus: Coefficient modulus in plaintext space. secret_key (SecretKey): Secret key used for encryption. | BFVDecryptor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BFVDecryptor:
"""An object that can decrypt data using BFV given a secret key. Attributes: poly_degree: Degree of polynomial in quotient ring. ciph_modulus: Coefficient modulus in ciphertext space. plain_modulus: Coefficient modulus in plaintext space. secret_key (SecretKey): Secret key used for ... | stack_v2_sparse_classes_36k_train_031932 | 2,037 | permissive | [
{
"docstring": "Generates private/public key pair for BFV scheme. Args: params (Parameters): Parameters including polynomial degree, plaintext modulus, and ciphertext modulus. secret_key (SecretKey): Secret key used for decryption.",
"name": "__init__",
"signature": "def __init__(self, params, secret_ke... | 2 | stack_v2_sparse_classes_30k_train_002884 | Implement the Python class `BFVDecryptor` described below.
Class description:
An object that can decrypt data using BFV given a secret key. Attributes: poly_degree: Degree of polynomial in quotient ring. ciph_modulus: Coefficient modulus in ciphertext space. plain_modulus: Coefficient modulus in plaintext space. secre... | Implement the Python class `BFVDecryptor` described below.
Class description:
An object that can decrypt data using BFV given a secret key. Attributes: poly_degree: Degree of polynomial in quotient ring. ciph_modulus: Coefficient modulus in ciphertext space. plain_modulus: Coefficient modulus in plaintext space. secre... | be700505547b81671c37026e55c4eefbd44dcaae | <|skeleton|>
class BFVDecryptor:
"""An object that can decrypt data using BFV given a secret key. Attributes: poly_degree: Degree of polynomial in quotient ring. ciph_modulus: Coefficient modulus in ciphertext space. plain_modulus: Coefficient modulus in plaintext space. secret_key (SecretKey): Secret key used for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BFVDecryptor:
"""An object that can decrypt data using BFV given a secret key. Attributes: poly_degree: Degree of polynomial in quotient ring. ciph_modulus: Coefficient modulus in ciphertext space. plain_modulus: Coefficient modulus in plaintext space. secret_key (SecretKey): Secret key used for encryption.""... | the_stack_v2_python_sparse | bfv/bfv_decryptor.py | seounghwan-oh/py_FHE_for_homomorphic_encryption | train | 3 |
0fa583a4cb055a58c158366a27c68a494f3d98ec | [
"t = Timex()\nif node.hasAttribute('SET'):\n if node.getAttribute('SET').lower() == 'yes':\n t.type = 'set'\n if node.hasAttribute('PERIODICITY'):\n t.value = 'P' + node.getAttribute('PERIODICITY')[1:]\nif node.hasAttribute('VAL'):\n t.value = node.getAttribute('VAL')\nif node.hasAttr... | <|body_start_0|>
t = Timex()
if node.hasAttribute('SET'):
if node.getAttribute('SET').lower() == 'yes':
t.type = 'set'
if node.hasAttribute('PERIODICITY'):
t.value = 'P' + node.getAttribute('PERIODICITY')[1:]
if node.hasAttribute('V... | A class which takes any random XML document and adds TIMEX2 tags to it. | Timex2XmlDocument | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timex2XmlDocument:
"""A class which takes any random XML document and adds TIMEX2 tags to it."""
def _timex_from_node(self, node):
"""Given a TIMEX2 node, create a timex object with the values of that node"""
<|body_0|>
def _annotate_node_from_timex(self, timex, node):
... | stack_v2_sparse_classes_36k_train_031933 | 1,985 | permissive | [
{
"docstring": "Given a TIMEX2 node, create a timex object with the values of that node",
"name": "_timex_from_node",
"signature": "def _timex_from_node(self, node)"
},
{
"docstring": "Add attributes to this TIMEX2 node",
"name": "_annotate_node_from_timex",
"signature": "def _annotate_n... | 2 | stack_v2_sparse_classes_30k_train_017418 | Implement the Python class `Timex2XmlDocument` described below.
Class description:
A class which takes any random XML document and adds TIMEX2 tags to it.
Method signatures and docstrings:
- def _timex_from_node(self, node): Given a TIMEX2 node, create a timex object with the values of that node
- def _annotate_node_... | Implement the Python class `Timex2XmlDocument` described below.
Class description:
A class which takes any random XML document and adds TIMEX2 tags to it.
Method signatures and docstrings:
- def _timex_from_node(self, node): Given a TIMEX2 node, create a timex object with the values of that node
- def _annotate_node_... | e2e1fd101e230951e17431dff3af4cdb6c1270d1 | <|skeleton|>
class Timex2XmlDocument:
"""A class which takes any random XML document and adds TIMEX2 tags to it."""
def _timex_from_node(self, node):
"""Given a TIMEX2 node, create a timex object with the values of that node"""
<|body_0|>
def _annotate_node_from_timex(self, timex, node):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Timex2XmlDocument:
"""A class which takes any random XML document and adds TIMEX2 tags to it."""
def _timex_from_node(self, node):
"""Given a TIMEX2 node, create a timex object with the values of that node"""
t = Timex()
if node.hasAttribute('SET'):
if node.getAttribut... | the_stack_v2_python_sparse | ternip/formats/timex2.py | jo-fu/TimeLineCurator | train | 63 |
e35296fdfba9054950bdc5af8628adc9e619d210 | [
"assert cv_iters > 2, 'Cross validation folds must be more than 2 folds'\nself.cv_iters = cv_iters\ndatapath = './Data'\nself.dataset = [[os.path.join(os.path.join(os.path.join(datapath, folder), label), image), int(label)] for folder in os.listdir(datapath) for label in os.listdir(os.path.join(datapath, folder)) f... | <|body_start_0|>
assert cv_iters > 2, 'Cross validation folds must be more than 2 folds'
self.cv_iters = cv_iters
datapath = './Data'
self.dataset = [[os.path.join(os.path.join(os.path.join(datapath, folder), label), image), int(label)] for folder in os.listdir(datapath) for label in os.... | A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__. | __DatasetWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class __DatasetWrapper:
"""A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__."""
def __init__(self, cv_iters):
"""create df for features and labels remove samples that are not shared between the two tables"""
<|body_0|>
def shuffle(se... | stack_v2_sparse_classes_36k_train_031934 | 5,905 | no_license | [
{
"docstring": "create df for features and labels remove samples that are not shared between the two tables",
"name": "__init__",
"signature": "def __init__(self, cv_iters)"
},
{
"docstring": "categorize sample ID by label",
"name": "shuffle",
"signature": "def shuffle(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_019565 | Implement the Python class `__DatasetWrapper` described below.
Class description:
A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__.
Method signatures and docstrings:
- def __init__(self, cv_iters): create df for features and labels remove samples that are not shared between... | Implement the Python class `__DatasetWrapper` described below.
Class description:
A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__.
Method signatures and docstrings:
- def __init__(self, cv_iters): create df for features and labels remove samples that are not shared between... | 9a959ceeaa44c6d5a4d051e76862f5f7ab65e54b | <|skeleton|>
class __DatasetWrapper:
"""A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__."""
def __init__(self, cv_iters):
"""create df for features and labels remove samples that are not shared between the two tables"""
<|body_0|>
def shuffle(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class __DatasetWrapper:
"""A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__."""
def __init__(self, cv_iters):
"""create df for features and labels remove samples that are not shared between the two tables"""
assert cv_iters > 2, 'Cross validation fold... | the_stack_v2_python_sparse | data_loader.py | Bozhao-Liu/Kaggle-breast-cancer-autoencoder | train | 1 |
2ef03609f94ef0f3e850fed7ac7b0cceb7bb2c05 | [
"if type(style_image) is not np.ndarray or style_image.ndim != 3 or style_image.shape[2] != 3:\n raise TypeError('style_image must be a' + ' numpy.ndarray with shape (h, w, 3)')\nif type(content_image) is not np.ndarray or content_image.ndim != 3 or content_image.shape[2] != 3:\n raise TypeError('content_imag... | <|body_start_0|>
if type(style_image) is not np.ndarray or style_image.ndim != 3 or style_image.shape[2] != 3:
raise TypeError('style_image must be a' + ' numpy.ndarray with shape (h, w, 3)')
if type(content_image) is not np.ndarray or content_image.ndim != 3 or content_image.shape[2] != 3:
... | Neural style transfer class | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""Neural style transfer class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""class constructor"""
<|body_0|>
def scale_image(image):
"""scales image dimensions and values to 0-1"""
<|body_1|>
def load_model(self):
... | stack_v2_sparse_classes_36k_train_031935 | 4,555 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"
},
{
"docstring": "scales image dimensions and values to 0-1",
"name": "scale_image",
"signature": "def scale_image(image)"
},
{
"docstring... | 4 | null | Implement the Python class `NST` described below.
Class description:
Neural style transfer class
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): class constructor
- def scale_image(image): scales image dimensions and values to 0-1
- def load_model(self): load... | Implement the Python class `NST` described below.
Class description:
Neural style transfer class
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): class constructor
- def scale_image(image): scales image dimensions and values to 0-1
- def load_model(self): load... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class NST:
"""Neural style transfer class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""class constructor"""
<|body_0|>
def scale_image(image):
"""scales image dimensions and values to 0-1"""
<|body_1|>
def load_model(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NST:
"""Neural style transfer class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""class constructor"""
if type(style_image) is not np.ndarray or style_image.ndim != 3 or style_image.shape[2] != 3:
raise TypeError('style_image must be a' + ' numpy... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/2-neural_style.py | icculp/holbertonschool-machine_learning | train | 0 |
b007283f380c9b5451804fbd6c1a5fd7e902a943 | [
"super().__init__(self.PROBLEM_NAME)\nself.values = values\nself.weights = weights\nself.capacity = capacity",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nnumber_values = len(self.values)\nsack_matrix = [[0 for x in range(self.capacity + 1)] for x in range(number_values + 1)]\nfor i in range(numbe... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.values = values
self.weights = weights
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
number_values = len(self.values)
sack_matrix = [[0 ... | Zero One Knapsack | ZeroOneKnapsack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZeroOneKnapsack:
"""Zero One Knapsack"""
def __init__(self, values, weights, capacity):
"""ZeroOneKnapsack Args: values: Value of the items weights: Weights of the items capacity: Maximum capacity of the knapsack Returns: None Raises: None"""
<|body_0|>
def solve(self):
... | stack_v2_sparse_classes_36k_train_031936 | 2,246 | no_license | [
{
"docstring": "ZeroOneKnapsack Args: values: Value of the items weights: Weights of the items capacity: Maximum capacity of the knapsack Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, values, weights, capacity)"
},
{
"docstring": "Solve the problem Note: Args:... | 2 | stack_v2_sparse_classes_30k_train_015881 | Implement the Python class `ZeroOneKnapsack` described below.
Class description:
Zero One Knapsack
Method signatures and docstrings:
- def __init__(self, values, weights, capacity): ZeroOneKnapsack Args: values: Value of the items weights: Weights of the items capacity: Maximum capacity of the knapsack Returns: None ... | Implement the Python class `ZeroOneKnapsack` described below.
Class description:
Zero One Knapsack
Method signatures and docstrings:
- def __init__(self, values, weights, capacity): ZeroOneKnapsack Args: values: Value of the items weights: Weights of the items capacity: Maximum capacity of the knapsack Returns: None ... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class ZeroOneKnapsack:
"""Zero One Knapsack"""
def __init__(self, values, weights, capacity):
"""ZeroOneKnapsack Args: values: Value of the items weights: Weights of the items capacity: Maximum capacity of the knapsack Returns: None Raises: None"""
<|body_0|>
def solve(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZeroOneKnapsack:
"""Zero One Knapsack"""
def __init__(self, values, weights, capacity):
"""ZeroOneKnapsack Args: values: Value of the items weights: Weights of the items capacity: Maximum capacity of the knapsack Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
se... | the_stack_v2_python_sparse | python/problems/dynamic_programming/zero_one_knapsack.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
12dcd5f7096e4684a91a188a73df5dbe52febc66 | [
"self.name = name\nself.desired_species = desired_species\nself.considered_species = considered_species",
"adopter_score = float(adoption_center.get_number_of_species(self.desired_species))\nnum_other = 0\nfor a in self.considered_species:\n num_other += float(adoption_center.get_number_of_species(a))\nreturn ... | <|body_start_0|>
self.name = name
self.desired_species = desired_species
self.considered_species = considered_species
<|end_body_0|>
<|body_start_1|>
adopter_score = float(adoption_center.get_number_of_species(self.desired_species))
num_other = 0
for a in self.considered... | A FlexibleAdopter still has one type of species that they desire, but they are also alright with considering other types of species. considered_species is a list containing the other species the adopter will consider Their score should be 1x their desired species + .3x all of their desired species | FlexibleAdopter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexibleAdopter:
"""A FlexibleAdopter still has one type of species that they desire, but they are also alright with considering other types of species. considered_species is a list containing the other species the adopter will consider Their score should be 1x their desired species + .3x all of ... | stack_v2_sparse_classes_36k_train_031937 | 4,359 | no_license | [
{
"docstring": "Initializes FlexibleAdopter, a subclass of Adopter object class considered_species - a list of strings of alternative species that the person is interested in adopting. All of the inputs are the same as the Adopter",
"name": "__init__",
"signature": "def __init__(self, name, desired_spec... | 2 | stack_v2_sparse_classes_30k_train_010336 | Implement the Python class `FlexibleAdopter` described below.
Class description:
A FlexibleAdopter still has one type of species that they desire, but they are also alright with considering other types of species. considered_species is a list containing the other species the adopter will consider Their score should be... | Implement the Python class `FlexibleAdopter` described below.
Class description:
A FlexibleAdopter still has one type of species that they desire, but they are also alright with considering other types of species. considered_species is a list containing the other species the adopter will consider Their score should be... | d8750a5d78f042477f6577af67cc46d584f4aede | <|skeleton|>
class FlexibleAdopter:
"""A FlexibleAdopter still has one type of species that they desire, but they are also alright with considering other types of species. considered_species is a list containing the other species the adopter will consider Their score should be 1x their desired species + .3x all of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlexibleAdopter:
"""A FlexibleAdopter still has one type of species that they desire, but they are also alright with considering other types of species. considered_species is a list containing the other species the adopter will consider Their score should be 1x their desired species + .3x all of their desired... | the_stack_v2_python_sparse | ProblemSets/ProblemSet07c.py | Greatdane/MITx-6.00.1x | train | 0 |
89a228e893e87b20035e03a43537bcf5d1fcf929 | [
"super(RNNEnc, self).__init__()\nself._input_dim = input_dim\nself._con_len = context_length\nself.gru_enc = GRU(input_size=self._input_dim, hidden_size=self._input_dim, num_layers=1, bias=True, batch_first=True, bidirectional=True)\nself.initialize_encoder()",
"xavier_normal_(self.gru_enc.weight_ih_l0)\northogon... | <|body_start_0|>
super(RNNEnc, self).__init__()
self._input_dim = input_dim
self._con_len = context_length
self.gru_enc = GRU(input_size=self._input_dim, hidden_size=self._input_dim, num_layers=1, bias=True, batch_first=True, bidirectional=True)
self.initialize_encoder()
<|end_bo... | RNNEnc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEnc:
def __init__(self, input_dim, context_length):
"""The RNN encoder of the Masker. :param input_dim: The input dimensionality. :type input_dim: int :param context_length: The context length. :type context_length: int"""
<|body_0|>
def initialize_encoder(self):
... | stack_v2_sparse_classes_36k_train_031938 | 16,858 | no_license | [
{
"docstring": "The RNN encoder of the Masker. :param input_dim: The input dimensionality. :type input_dim: int :param context_length: The context length. :type context_length: int",
"name": "__init__",
"signature": "def __init__(self, input_dim, context_length)"
},
{
"docstring": "Manual weight... | 3 | null | Implement the Python class `RNNEnc` described below.
Class description:
Implement the RNNEnc class.
Method signatures and docstrings:
- def __init__(self, input_dim, context_length): The RNN encoder of the Masker. :param input_dim: The input dimensionality. :type input_dim: int :param context_length: The context leng... | Implement the Python class `RNNEnc` described below.
Class description:
Implement the RNNEnc class.
Method signatures and docstrings:
- def __init__(self, input_dim, context_length): The RNN encoder of the Masker. :param input_dim: The input dimensionality. :type input_dim: int :param context_length: The context leng... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class RNNEnc:
def __init__(self, input_dim, context_length):
"""The RNN encoder of the Masker. :param input_dim: The input dimensionality. :type input_dim: int :param context_length: The context length. :type context_length: int"""
<|body_0|>
def initialize_encoder(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEnc:
def __init__(self, input_dim, context_length):
"""The RNN encoder of the Masker. :param input_dim: The input dimensionality. :type input_dim: int :param context_length: The context length. :type context_length: int"""
super(RNNEnc, self).__init__()
self._input_dim = input_dim
... | the_stack_v2_python_sparse | generated/test_dr_costas_mad_twinnet.py | jansel/pytorch-jit-paritybench | train | 35 | |
62873a50a8fc5975c816332290a10add9cd62446 | [
"pairs = self.make_pairs(nums)\nif not pairs:\n return 0\nmost_freq = self.get_max_freq(pairs, nums)\nreturn len([num for num in nums if num in most_freq])",
"pairs = []\nfor num1 in nums:\n for num2 in nums:\n if abs(num1 - num2) == 1:\n pairs.append(tuple(sorted([num1, num2])))\nreturn l... | <|body_start_0|>
pairs = self.make_pairs(nums)
if not pairs:
return 0
most_freq = self.get_max_freq(pairs, nums)
return len([num for num in nums if num in most_freq])
<|end_body_0|>
<|body_start_1|>
pairs = []
for num1 in nums:
for num2 in nums:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLHS(self, nums):
"""Find longest harmonious subsequence (where diff btwn max/min is 1) :type nums: List[int] :rtype: int"""
<|body_0|>
def make_pairs(self, nums):
"""Breaks list of numbers into harmonious pairs (diff of 1) :type: nums: List[int] :rt... | stack_v2_sparse_classes_36k_train_031939 | 2,040 | no_license | [
{
"docstring": "Find longest harmonious subsequence (where diff btwn max/min is 1) :type nums: List[int] :rtype: int",
"name": "findLHS",
"signature": "def findLHS(self, nums)"
},
{
"docstring": "Breaks list of numbers into harmonious pairs (diff of 1) :type: nums: List[int] :rtype: List[tuple(i... | 3 | stack_v2_sparse_classes_30k_train_003263 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLHS(self, nums): Find longest harmonious subsequence (where diff btwn max/min is 1) :type nums: List[int] :rtype: int
- def make_pairs(self, nums): Breaks list of numbers... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLHS(self, nums): Find longest harmonious subsequence (where diff btwn max/min is 1) :type nums: List[int] :rtype: int
- def make_pairs(self, nums): Breaks list of numbers... | 308889e57e71c369aa8516fba8a2064f6a26abee | <|skeleton|>
class Solution:
def findLHS(self, nums):
"""Find longest harmonious subsequence (where diff btwn max/min is 1) :type nums: List[int] :rtype: int"""
<|body_0|>
def make_pairs(self, nums):
"""Breaks list of numbers into harmonious pairs (diff of 1) :type: nums: List[int] :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLHS(self, nums):
"""Find longest harmonious subsequence (where diff btwn max/min is 1) :type nums: List[int] :rtype: int"""
pairs = self.make_pairs(nums)
if not pairs:
return 0
most_freq = self.get_max_freq(pairs, nums)
return len([num for ... | the_stack_v2_python_sparse | leet_594.py | mike-jolliffe/Learning | train | 0 | |
b857f4095cf36042baa38810ad2a0995c717e324 | [
"warnings.warn('SequentialDTNNGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)\nself.graph = tf.Graph()\nwith self.graph.as_default():\n self.graph_topology = DTNNGraphTopology(n_distance, distance_min=distance_min, distance_max=distance_max)\n self.output = self.graph_topology.get_... | <|body_start_0|>
warnings.warn('SequentialDTNNGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)
self.graph = tf.Graph()
with self.graph.as_default():
self.graph_topology = DTNNGraphTopology(n_distance, distance_min=distance_min, distance_max=distance_max)
... | An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer. | SequentialDTNNGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialDTNNGraph:
"""An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer."""
def __init__(self, n_distance=100, distance_min=-1.0, distance_max=18.0):
"""Parameters ---------- n_distance: int, optional... | stack_v2_sparse_classes_36k_train_031940 | 11,824 | permissive | [
{
"docstring": "Parameters ---------- n_distance: int, optional granularity of distance matrix step size will be (distance_max-distance_min)/n_distance distance_min: float, optional minimum distance of atom pairs, default = -1 Angstorm distance_max: float, optional maximum distance of atom pairs, default = 18 A... | 2 | stack_v2_sparse_classes_30k_test_000361 | Implement the Python class `SequentialDTNNGraph` described below.
Class description:
An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer.
Method signatures and docstrings:
- def __init__(self, n_distance=100, distance_min=-1.0, distance_m... | Implement the Python class `SequentialDTNNGraph` described below.
Class description:
An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer.
Method signatures and docstrings:
- def __init__(self, n_distance=100, distance_min=-1.0, distance_m... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class SequentialDTNNGraph:
"""An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer."""
def __init__(self, n_distance=100, distance_min=-1.0, distance_max=18.0):
"""Parameters ---------- n_distance: int, optional... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequentialDTNNGraph:
"""An analog of Keras Sequential class for Coulomb Matrix data. automatically generates and passes topology placeholders to each layer."""
def __init__(self, n_distance=100, distance_min=-1.0, distance_max=18.0):
"""Parameters ---------- n_distance: int, optional granularity ... | the_stack_v2_python_sparse | contrib/one_shot_models/graph_models.py | deepchem/deepchem | train | 4,876 |
dffce24720881545e7ac6afb12fafbf93e1949b2 | [
"child1 = Candidate(parent1.originalPuzzle)\nchild2 = Candidate(parent2.originalPuzzle)\nchild1.values = np.copy(parent1.values)\nchild2.values = np.copy(parent2.values)\nr = random.uniform(0, 1.1)\nwhile r > 1:\n r = random.uniform(0, 1.1)\nif r < crossoverRate:\n crossoverPoint1 = random.randint(0, 7)\n ... | <|body_start_0|>
child1 = Candidate(parent1.originalPuzzle)
child2 = Candidate(parent2.originalPuzzle)
child1.values = np.copy(parent1.values)
child2.values = np.copy(parent2.values)
r = random.uniform(0, 1.1)
while r > 1:
r = random.uniform(0, 1.1)
if... | Crossover | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crossover:
def crossover(self, parent1, parent2, crossoverRate):
"""Takes 2 parents and a crossover rate and returns 2 new child Candidates created by swapping sections of the parents with each other"""
<|body_0|>
def crossoverBoxes(self, parent1, parent2, boxNum):
"... | stack_v2_sparse_classes_36k_train_031941 | 14,555 | no_license | [
{
"docstring": "Takes 2 parents and a crossover rate and returns 2 new child Candidates created by swapping sections of the parents with each other",
"name": "crossover",
"signature": "def crossover(self, parent1, parent2, crossoverRate)"
},
{
"docstring": "Takes 2 parents and a box number for e... | 2 | stack_v2_sparse_classes_30k_train_016663 | Implement the Python class `Crossover` described below.
Class description:
Implement the Crossover class.
Method signatures and docstrings:
- def crossover(self, parent1, parent2, crossoverRate): Takes 2 parents and a crossover rate and returns 2 new child Candidates created by swapping sections of the parents with e... | Implement the Python class `Crossover` described below.
Class description:
Implement the Crossover class.
Method signatures and docstrings:
- def crossover(self, parent1, parent2, crossoverRate): Takes 2 parents and a crossover rate and returns 2 new child Candidates created by swapping sections of the parents with e... | d1c8021cb1621d3bf10c369843eda3ac29fb802f | <|skeleton|>
class Crossover:
def crossover(self, parent1, parent2, crossoverRate):
"""Takes 2 parents and a crossover rate and returns 2 new child Candidates created by swapping sections of the parents with each other"""
<|body_0|>
def crossoverBoxes(self, parent1, parent2, boxNum):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Crossover:
def crossover(self, parent1, parent2, crossoverRate):
"""Takes 2 parents and a crossover rate and returns 2 new child Candidates created by swapping sections of the parents with each other"""
child1 = Candidate(parent1.originalPuzzle)
child2 = Candidate(parent2.originalPuzzl... | the_stack_v2_python_sparse | algorithms/geneticAttempt2.py | CalumHarvey/sudoku-solving-algorithms | train | 0 | |
3286204220c37223eb62a65ec767687a674e632c | [
"response = None\nheaders.setdefault('Accept', 'multipart/mixed, application/json, */*;q=0.5')\nif self._client._credentials:\n self._security_auth_headers(self._client._credentials.username, self._client._credentials.password, headers)\ntry:\n self._connection.request(method, uri, body, headers)\n try:\n ... | <|body_start_0|>
response = None
headers.setdefault('Accept', 'multipart/mixed, application/json, */*;q=0.5')
if self._client._credentials:
self._security_auth_headers(self._client._credentials.username, self._client._credentials.password, headers)
try:
self._conn... | Connection and low-level request methods for HttpTransport. | HttpConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpConnection:
"""Connection and low-level request methods for HttpTransport."""
def _request(self, method, uri, headers={}, body='', stream=False):
"""Given a Method, URL, Headers, and Body, perform and HTTP request, and return a 3-tuple containing the response status, response hea... | stack_v2_sparse_classes_36k_train_031942 | 3,972 | permissive | [
{
"docstring": "Given a Method, URL, Headers, and Body, perform and HTTP request, and return a 3-tuple containing the response status, response headers (as httplib.HTTPMessage), and response body.",
"name": "_request",
"signature": "def _request(self, method, uri, headers={}, body='', stream=False)"
}... | 4 | stack_v2_sparse_classes_30k_train_012474 | Implement the Python class `HttpConnection` described below.
Class description:
Connection and low-level request methods for HttpTransport.
Method signatures and docstrings:
- def _request(self, method, uri, headers={}, body='', stream=False): Given a Method, URL, Headers, and Body, perform and HTTP request, and retu... | Implement the Python class `HttpConnection` described below.
Class description:
Connection and low-level request methods for HttpTransport.
Method signatures and docstrings:
- def _request(self, method, uri, headers={}, body='', stream=False): Given a Method, URL, Headers, and Body, perform and HTTP request, and retu... | 91de13a16607cdf553d1a194e762734e3bec4231 | <|skeleton|>
class HttpConnection:
"""Connection and low-level request methods for HttpTransport."""
def _request(self, method, uri, headers={}, body='', stream=False):
"""Given a Method, URL, Headers, and Body, perform and HTTP request, and return a 3-tuple containing the response status, response hea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpConnection:
"""Connection and low-level request methods for HttpTransport."""
def _request(self, method, uri, headers={}, body='', stream=False):
"""Given a Method, URL, Headers, and Body, perform and HTTP request, and return a 3-tuple containing the response status, response headers (as http... | the_stack_v2_python_sparse | riak/transports/http/connection.py | EDITD/riak-python-client | train | 0 |
70e6aa40625d1c5e50f4500565e4491ca859ddc7 | [
"super(State, self).__init__(methodName)\nskip = ['test_load_state_no_gui']\nif wx.version() == '2.9.4.1 gtk2 (classic)' and methodName in skip:\n status.skipped_tests.append([methodName, 'wxPython 2.9.4.1 gtk2 bugs', self._skip_type])",
"file = status.install_path + sep + 'test_suite' + sep + 'shared_data' + ... | <|body_start_0|>
super(State, self).__init__(methodName)
skip = ['test_load_state_no_gui']
if wx.version() == '2.9.4.1 gtk2 (classic)' and methodName in skip:
status.skipped_tests.append([methodName, 'wxPython 2.9.4.1 gtk2 bugs', self._skip_type])
<|end_body_0|>
<|body_start_1|>
... | Class for testing various aspects specific to saved states. | State | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
"""Class for testing various aspects specific to saved states."""
def __init__(self, methodName='runTest'):
"""Skip certain tests due to wxPython bugs. @keyword methodName: The name of the test. @type methodName: str"""
<|body_0|>
def test_bug_20480(self):
... | stack_v2_sparse_classes_36k_train_031943 | 7,570 | no_license | [
{
"docstring": "Skip certain tests due to wxPython bugs. @keyword methodName: The name of the test. @type methodName: str",
"name": "__init__",
"signature": "def __init__(self, methodName='runTest')"
},
{
"docstring": "Catch U{bug #20480<https://gna.org/bugs/?20480>}, the failure to load a relax... | 4 | stack_v2_sparse_classes_30k_train_007574 | Implement the Python class `State` described below.
Class description:
Class for testing various aspects specific to saved states.
Method signatures and docstrings:
- def __init__(self, methodName='runTest'): Skip certain tests due to wxPython bugs. @keyword methodName: The name of the test. @type methodName: str
- d... | Implement the Python class `State` described below.
Class description:
Class for testing various aspects specific to saved states.
Method signatures and docstrings:
- def __init__(self, methodName='runTest'): Skip certain tests due to wxPython bugs. @keyword methodName: The name of the test. @type methodName: str
- d... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class State:
"""Class for testing various aspects specific to saved states."""
def __init__(self, methodName='runTest'):
"""Skip certain tests due to wxPython bugs. @keyword methodName: The name of the test. @type methodName: str"""
<|body_0|>
def test_bug_20480(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
"""Class for testing various aspects specific to saved states."""
def __init__(self, methodName='runTest'):
"""Skip certain tests due to wxPython bugs. @keyword methodName: The name of the test. @type methodName: str"""
super(State, self).__init__(methodName)
skip = ['test_... | the_stack_v2_python_sparse | test_suite/gui_tests/state.py | jlec/relax | train | 4 |
e504670b4f25f2b1219a1a723351effacc8f2eb1 | [
"_url_path = '/tokens/{id}?appId={public_key}'\n_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'id': id, 'public_key': public_key})\n_query_builder = Configuration.base_uri\n_query_builder += _url_path\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json'... | <|body_start_0|>
_url_path = '/tokens/{id}?appId={public_key}'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'id': id, 'public_key': public_key})
_query_builder = Configuration.base_uri
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_bu... | A Controller to access Endpoints in the mundiapi API. | TokensController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokensController:
"""A Controller to access Endpoints in the mundiapi API."""
def get_token(self, id, public_key):
"""Does a GET request to /tokens/{id}?appId={public_key}. Gets a token from its id Args: id (string): Token id public_key (string): Public key Returns: GetTokenResponse:... | stack_v2_sparse_classes_36k_train_031944 | 3,792 | permissive | [
{
"docstring": "Does a GET request to /tokens/{id}?appId={public_key}. Gets a token from its id Args: id (string): Token id public_key (string): Public key Returns: GetTokenResponse: Response from the API. Raises: APIException: When an error occurs while fetching the data from the remote API. This exception inc... | 2 | stack_v2_sparse_classes_30k_train_012665 | Implement the Python class `TokensController` described below.
Class description:
A Controller to access Endpoints in the mundiapi API.
Method signatures and docstrings:
- def get_token(self, id, public_key): Does a GET request to /tokens/{id}?appId={public_key}. Gets a token from its id Args: id (string): Token id p... | Implement the Python class `TokensController` described below.
Class description:
A Controller to access Endpoints in the mundiapi API.
Method signatures and docstrings:
- def get_token(self, id, public_key): Does a GET request to /tokens/{id}?appId={public_key}. Gets a token from its id Args: id (string): Token id p... | f0c67e1f92471a7a0e2d0b0cb1765105f07fb8cb | <|skeleton|>
class TokensController:
"""A Controller to access Endpoints in the mundiapi API."""
def get_token(self, id, public_key):
"""Does a GET request to /tokens/{id}?appId={public_key}. Gets a token from its id Args: id (string): Token id public_key (string): Public key Returns: GetTokenResponse:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokensController:
"""A Controller to access Endpoints in the mundiapi API."""
def get_token(self, id, public_key):
"""Does a GET request to /tokens/{id}?appId={public_key}. Gets a token from its id Args: id (string): Token id public_key (string): Public key Returns: GetTokenResponse: Response fro... | the_stack_v2_python_sparse | mundiapi/controllers/tokens_controller.py | mundipagg/MundiApi-NodeJS | train | 9 |
028d80b24867f09946d11df436e66ed39985cbb7 | [
"super(BceLoss, self).__init__()\nif weight is not None:\n if isinstance(weight, (list, tuple)) and len(weight) == 2:\n weight = weight[1]\n weight = torch.tensor(weight).float()\nself.weight = weight",
"num_class = logits.shape[1]\nassert num_class <= 2, 'For class num larger than 2, use CrossEntrop... | <|body_start_0|>
super(BceLoss, self).__init__()
if weight is not None:
if isinstance(weight, (list, tuple)) and len(weight) == 2:
weight = weight[1]
weight = torch.tensor(weight).float()
self.weight = weight
<|end_body_0|>
<|body_start_1|>
num_cl... | BceLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BceLoss:
def __init__(self, weight=None):
"""Computes the weighted binary cross-entropy loss. :param weight: a scalar representing the weight attributed to the positive class. This is especially useful for an imbalanced dataset."""
<|body_0|>
def forward(self, gt, logits, re... | stack_v2_sparse_classes_36k_train_031945 | 12,362 | no_license | [
{
"docstring": "Computes the weighted binary cross-entropy loss. :param weight: a scalar representing the weight attributed to the positive class. This is especially useful for an imbalanced dataset.",
"name": "__init__",
"signature": "def __init__(self, weight=None)"
},
{
"docstring": "Computes... | 2 | stack_v2_sparse_classes_30k_train_021279 | Implement the Python class `BceLoss` described below.
Class description:
Implement the BceLoss class.
Method signatures and docstrings:
- def __init__(self, weight=None): Computes the weighted binary cross-entropy loss. :param weight: a scalar representing the weight attributed to the positive class. This is especial... | Implement the Python class `BceLoss` described below.
Class description:
Implement the BceLoss class.
Method signatures and docstrings:
- def __init__(self, weight=None): Computes the weighted binary cross-entropy loss. :param weight: a scalar representing the weight attributed to the positive class. This is especial... | 8e6f42e3a0cbc87c66b148fb61fcb44af287619e | <|skeleton|>
class BceLoss:
def __init__(self, weight=None):
"""Computes the weighted binary cross-entropy loss. :param weight: a scalar representing the weight attributed to the positive class. This is especially useful for an imbalanced dataset."""
<|body_0|>
def forward(self, gt, logits, re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BceLoss:
def __init__(self, weight=None):
"""Computes the weighted binary cross-entropy loss. :param weight: a scalar representing the weight attributed to the positive class. This is especially useful for an imbalanced dataset."""
super(BceLoss, self).__init__()
if weight is not None:... | the_stack_v2_python_sparse | lib/loss/loss.py | yangsenwxy/colonoscopy_tissue_screen_and_segmentation | train | 0 | |
0b2813686d01fd6f967ef19d005078e500c1dfb9 | [
"self.table = dict()\nfor pair in pairs:\n self.put(pair[0], pair[1])",
"if k in self.table:\n self.table[k].append(v)\nelse:\n self.table[k] = [v]",
"try:\n return self.table[k]\nexcept KeyError:\n return []"
] | <|body_start_0|>
self.table = dict()
for pair in pairs:
self.put(pair[0], pair[1])
<|end_body_0|>
<|body_start_1|>
if k in self.table:
self.table[k].append(v)
else:
self.table[k] = [v]
<|end_body_1|>
<|body_start_2|>
try:
return s... | Create a multidict from several seuqences. | Multidict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Multidict:
"""Create a multidict from several seuqences."""
def __init__(self, pairs=[]):
"""Initialize the self with a list of pairs."""
<|body_0|>
def put(self, k, v):
"""Put key k and value v in the table or append it to an existing entry."""
<|body_1|... | stack_v2_sparse_classes_36k_train_031946 | 4,545 | no_license | [
{
"docstring": "Initialize the self with a list of pairs.",
"name": "__init__",
"signature": "def __init__(self, pairs=[])"
},
{
"docstring": "Put key k and value v in the table or append it to an existing entry.",
"name": "put",
"signature": "def put(self, k, v)"
},
{
"docstring... | 3 | null | Implement the Python class `Multidict` described below.
Class description:
Create a multidict from several seuqences.
Method signatures and docstrings:
- def __init__(self, pairs=[]): Initialize the self with a list of pairs.
- def put(self, k, v): Put key k and value v in the table or append it to an existing entry.... | Implement the Python class `Multidict` described below.
Class description:
Create a multidict from several seuqences.
Method signatures and docstrings:
- def __init__(self, pairs=[]): Initialize the self with a list of pairs.
- def put(self, k, v): Put key k and value v in the table or append it to an existing entry.... | ff77118fe81d82c835f71a41e70e3f7f303028bf | <|skeleton|>
class Multidict:
"""Create a multidict from several seuqences."""
def __init__(self, pairs=[]):
"""Initialize the self with a list of pairs."""
<|body_0|>
def put(self, k, v):
"""Put key k and value v in the table or append it to an existing entry."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Multidict:
"""Create a multidict from several seuqences."""
def __init__(self, pairs=[]):
"""Initialize the self with a list of pairs."""
self.table = dict()
for pair in pairs:
self.put(pair[0], pair[1])
def put(self, k, v):
"""Put key k and value v in the... | the_stack_v2_python_sparse | biotech/dnamatch.py | HussainAther/biology | train | 11 |
ba259b78397e660501b0cddcc54cdcee3b9b80e6 | [
"super().__init__(*args, **kwargs)\nself.max_pe_iterations = max_pe_iterations\nself.bellman_updates = 0\nself.logger.info('Max PE Iterations:\\t%d' % self.max_pe_iterations)\nif not self.is_tabular():\n raise ValueError('Policy Iteration works only with a tabular representation.')",
"converged = False\npolicy... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.max_pe_iterations = max_pe_iterations
self.bellman_updates = 0
self.logger.info('Max PE Iterations:\t%d' % self.max_pe_iterations)
if not self.is_tabular():
raise ValueError('Policy Iteration works only with a ta... | Policy Iteration MDP Solver. | PolicyIteration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolicyIteration:
"""Policy Iteration MDP Solver."""
def __init__(self, *args, max_pe_iterations=10, **kwargs):
""":param max_pe_iterations: Maximum number of Policy evaluation iterations to run."""
<|body_0|>
def policy_evaluation(self, policy):
"""Evaluate a giv... | stack_v2_sparse_classes_36k_train_031947 | 6,952 | permissive | [
{
"docstring": ":param max_pe_iterations: Maximum number of Policy evaluation iterations to run.",
"name": "__init__",
"signature": "def __init__(self, *args, max_pe_iterations=10, **kwargs)"
},
{
"docstring": "Evaluate a given policy: this is done by applying the Bellman backup over all states ... | 4 | null | Implement the Python class `PolicyIteration` described below.
Class description:
Policy Iteration MDP Solver.
Method signatures and docstrings:
- def __init__(self, *args, max_pe_iterations=10, **kwargs): :param max_pe_iterations: Maximum number of Policy evaluation iterations to run.
- def policy_evaluation(self, po... | Implement the Python class `PolicyIteration` described below.
Class description:
Policy Iteration MDP Solver.
Method signatures and docstrings:
- def __init__(self, *args, max_pe_iterations=10, **kwargs): :param max_pe_iterations: Maximum number of Policy evaluation iterations to run.
- def policy_evaluation(self, po... | 329166de28d311d8f87358a62c38f40a7318fe07 | <|skeleton|>
class PolicyIteration:
"""Policy Iteration MDP Solver."""
def __init__(self, *args, max_pe_iterations=10, **kwargs):
""":param max_pe_iterations: Maximum number of Policy evaluation iterations to run."""
<|body_0|>
def policy_evaluation(self, policy):
"""Evaluate a giv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolicyIteration:
"""Policy Iteration MDP Solver."""
def __init__(self, *args, max_pe_iterations=10, **kwargs):
""":param max_pe_iterations: Maximum number of Policy evaluation iterations to run."""
super().__init__(*args, **kwargs)
self.max_pe_iterations = max_pe_iterations
... | the_stack_v2_python_sparse | rlpy/mdp_solvers/policy_iteration.py | kngwyu/rlpy3 | train | 4 |
31ddae5b426974b91acf6cfbe555864b0391cae9 | [
"super().__init__(structure, sort_structure=False, **kwargs)\nself.structure = structure\nself.num_perturb = num_perturb",
"if self.num_perturb > 0 and self.num_perturb <= len(self.structure):\n syms = [site.specie.symbol for site in self.structure[self.num_perturb:]]\n syms = [a[0] for a in itertools.group... | <|body_start_0|>
super().__init__(structure, sort_structure=False, **kwargs)
self.structure = structure
self.num_perturb = num_perturb
<|end_body_0|>
<|body_start_1|>
if self.num_perturb > 0 and self.num_perturb <= len(self.structure):
syms = [site.specie.symbol for site in ... | Derived Poscar class that allows the distinction of individual sites in the Structure | PoscarPerturb | [
"LicenseRef-scancode-hdf5",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoscarPerturb:
"""Derived Poscar class that allows the distinction of individual sites in the Structure"""
def __init__(self, structure: Structure, num_perturb: int=1, **kwargs):
"""Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as "separate" sp... | stack_v2_sparse_classes_36k_train_031948 | 25,948 | permissive | [
{
"docstring": "Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as \"separate\" species **kwargs:",
"name": "__init__",
"signature": "def __init__(self, structure: Structure, num_perturb: int=1, **kwargs)"
},
{
"docstring": "Sequence of symbols associated wi... | 3 | null | Implement the Python class `PoscarPerturb` described below.
Class description:
Derived Poscar class that allows the distinction of individual sites in the Structure
Method signatures and docstrings:
- def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): Args: structure: num_perturb: Number of sites... | Implement the Python class `PoscarPerturb` described below.
Class description:
Derived Poscar class that allows the distinction of individual sites in the Structure
Method signatures and docstrings:
- def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): Args: structure: num_perturb: Number of sites... | f4060e55ae3a22289fde9516ff0e8e4ac1d22190 | <|skeleton|>
class PoscarPerturb:
"""Derived Poscar class that allows the distinction of individual sites in the Structure"""
def __init__(self, structure: Structure, num_perturb: int=1, **kwargs):
"""Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as "separate" sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoscarPerturb:
"""Derived Poscar class that allows the distinction of individual sites in the Structure"""
def __init__(self, structure: Structure, num_perturb: int=1, **kwargs):
"""Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as "separate" species **kwarg... | the_stack_v2_python_sparse | atomate/vasp/workflows/base/hubbard_hund_linresp.py | hackingmaterials/atomate | train | 217 |
4396fd8004105cab2e1345b010778c2b13abeb1b | [
"self._validate_arr_or_dict_val_type(arr_or_dict=arr_or_dict)\nif locals_ is None:\n locals_ = {}\nif globals_ is None:\n globals_ = {}\nself._arr_or_dict = arr_or_dict\nself._locals = locals_\nself._globals = globals_\nself._indent = Indent()",
"if isinstance(arr_or_dict, (Array, Dictionary)):\n return\... | <|body_start_0|>
self._validate_arr_or_dict_val_type(arr_or_dict=arr_or_dict)
if locals_ is None:
locals_ = {}
if globals_ is None:
globals_ = {}
self._arr_or_dict = arr_or_dict
self._locals = locals_
self._globals = globals_
self._indent =... | For | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class For:
def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None:
"""A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to ite... | stack_v2_sparse_classes_36k_train_031949 | 5,769 | permissive | [
{
"docstring": "A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to iterate. locals_ : dict or None, default None Current scope's local variables. Set locals() value to this argument. If specified, all local scope VariableNameInterface... | 6 | stack_v2_sparse_classes_30k_train_000625 | Implement the Python class `For` described below.
Class description:
Implement the For class.
Method signatures and docstrings:
- def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None: A class to append for (loop) expression.... | Implement the Python class `For` described below.
Class description:
Implement the For class.
Method signatures and docstrings:
- def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None: A class to append for (loop) expression.... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class For:
def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None:
"""A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to ite... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class For:
def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None:
"""A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to iterate. locals_ ... | the_stack_v2_python_sparse | apysc/loop/_for.py | TrendingTechnology/apysc | train | 0 | |
72e525837567bda15ca358a6bd363a9da5b1f597 | [
"super().__init__(out_embed_dims, vocab_size, vocab_reduction_module)\nif fixed_weights is None:\n self.fixed_weights = None\n self.gating_network = nn.Sequential(Linear(sum(out_embed_dims), hidden_layer_size, bias=True), activation_fn(), Linear(hidden_layer_size, len(out_embed_dims), bias=True))\n self.lo... | <|body_start_0|>
super().__init__(out_embed_dims, vocab_size, vocab_reduction_module)
if fixed_weights is None:
self.fixed_weights = None
self.gating_network = nn.Sequential(Linear(sum(out_embed_dims), hidden_layer_size, bias=True), activation_fn(), Linear(hidden_layer_size, len(... | Base class for strategies with explicitly learned weights. | BaseWeightedStrategy | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseWeightedStrategy:
"""Base class for strategies with explicitly learned weights."""
def __init__(self, out_embed_dims, vocab_size, vocab_reduction_module=None, fixed_weights=None, hidden_layer_size=32, activation_fn=torch.nn.ReLU, logit_fn=torch.exp):
"""Initializes a combination ... | stack_v2_sparse_classes_36k_train_031950 | 32,193 | permissive | [
{
"docstring": "Initializes a combination strategy with explicit weights. Args: out_embed_dims (list): List of output dimensionalities of the decoders. vocab_size (int): Size of the output projection. vocab_reduction_module: For vocabulary reduction fixed_weights (list): If not None, use these fixed weights rat... | 2 | stack_v2_sparse_classes_30k_train_003535 | Implement the Python class `BaseWeightedStrategy` described below.
Class description:
Base class for strategies with explicitly learned weights.
Method signatures and docstrings:
- def __init__(self, out_embed_dims, vocab_size, vocab_reduction_module=None, fixed_weights=None, hidden_layer_size=32, activation_fn=torch... | Implement the Python class `BaseWeightedStrategy` described below.
Class description:
Base class for strategies with explicitly learned weights.
Method signatures and docstrings:
- def __init__(self, out_embed_dims, vocab_size, vocab_reduction_module=None, fixed_weights=None, hidden_layer_size=32, activation_fn=torch... | 01985e0e82ee22e5d1edb909485f156608046c3e | <|skeleton|>
class BaseWeightedStrategy:
"""Base class for strategies with explicitly learned weights."""
def __init__(self, out_embed_dims, vocab_size, vocab_reduction_module=None, fixed_weights=None, hidden_layer_size=32, activation_fn=torch.nn.ReLU, logit_fn=torch.exp):
"""Initializes a combination ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseWeightedStrategy:
"""Base class for strategies with explicitly learned weights."""
def __init__(self, out_embed_dims, vocab_size, vocab_reduction_module=None, fixed_weights=None, hidden_layer_size=32, activation_fn=torch.nn.ReLU, logit_fn=torch.exp):
"""Initializes a combination strategy with... | the_stack_v2_python_sparse | pytorch_translate/multi_model.py | dwraft/translate | train | 1 |
fb0db1158596d67d48e243b098d9cb6f22020dbb | [
"data = {}\nfor key, value in entry.items():\n converter = self.convert.get(key, str)\n data[key] = converter(value)\nreturn data",
"with open(os.path.join(directory, self.filename)) as raw:\n reader = csv.DictReader(raw, fieldnames=self.header)\n seen = False\n for row in reader:\n converte... | <|body_start_0|>
data = {}
for key, value in entry.items():
converter = self.convert.get(key, str)
data[key] = converter(value)
return data
<|end_body_0|>
<|body_start_1|>
with open(os.path.join(directory, self.filename)) as raw:
reader = csv.DictRead... | A base parser for all motif csv files. This is callable and will produce a generator of dictonaries. If the row has a 'name' property we will yield the name and dictonary, otherwise we just yield the dictonary. This will also convert the field values specified by convert property. | BaseParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseParser:
"""A base parser for all motif csv files. This is callable and will produce a generator of dictonaries. If the row has a 'name' property we will yield the name and dictonary, otherwise we just yield the dictonary. This will also convert the field values specified by convert property."... | stack_v2_sparse_classes_36k_train_031951 | 12,261 | no_license | [
{
"docstring": "Converts the values as requested. :param dict entry: The dictonary to convert.",
"name": "__convert__",
"signature": "def __convert__(self, entry)"
},
{
"docstring": "Parse the file in the given directory. :param str directory: The directory to get the file in. :yields: Each row ... | 2 | null | Implement the Python class `BaseParser` described below.
Class description:
A base parser for all motif csv files. This is callable and will produce a generator of dictonaries. If the row has a 'name' property we will yield the name and dictonary, otherwise we just yield the dictonary. This will also convert the field... | Implement the Python class `BaseParser` described below.
Class description:
A base parser for all motif csv files. This is callable and will produce a generator of dictonaries. If the row has a 'name' property we will yield the name and dictonary, otherwise we just yield the dictonary. This will also convert the field... | 1982e10a56885e56d79aac69365b9ff78c0e3d92 | <|skeleton|>
class BaseParser:
"""A base parser for all motif csv files. This is callable and will produce a generator of dictonaries. If the row has a 'name' property we will yield the name and dictonary, otherwise we just yield the dictonary. This will also convert the field values specified by convert property."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseParser:
"""A base parser for all motif csv files. This is callable and will produce a generator of dictonaries. If the row has a 'name' property we will yield the name and dictonary, otherwise we just yield the dictonary. This will also convert the field values specified by convert property."""
def _... | the_stack_v2_python_sparse | pymotifs/motifs/builder.py | BGSU-RNA/RNA-3D-Hub-core | train | 3 |
9950e1b66b76d8c0050628f88eff259315cf3609 | [
"super(WideDeep, self).__init__()\nself.cate_fea_size = len(cate_fea_uniques)\nself.num_fea_size = num_fea_size\nself.n_layers = 3\nself.n_filters = 12\nself.k = emb_size\nself.sparse_emb = nn.ModuleList([nn.Embedding(voc_size, emb_size) for voc_size in cate_fea_uniques])\nself.linear = nn.Linear(self.num_fea_size,... | <|body_start_0|>
super(WideDeep, self).__init__()
self.cate_fea_size = len(cate_fea_uniques)
self.num_fea_size = num_fea_size
self.n_layers = 3
self.n_filters = 12
self.k = emb_size
self.sparse_emb = nn.ModuleList([nn.Embedding(voc_size, emb_size) for voc_size in ... | WideDeep | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WideDeep:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
<|body_... | stack_v2_sparse_classes_36k_train_031952 | 5,176 | permissive | [
{
"docstring": ":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:",
"name": "__init__",
"signature": "def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.... | 2 | stack_v2_sparse_classes_30k_train_011803 | Implement the Python class `WideDeep` described below.
Class description:
Implement the WideDeep class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就... | Implement the Python class `WideDeep` described below.
Class description:
Implement the WideDeep class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class WideDeep:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WideDeep:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
super(WideDeep, self)... | the_stack_v2_python_sparse | PyTorch/dev/others/Widedeep_ID2866_for_PyTorch/WideDeep/model.py | Ascend/ModelZoo-PyTorch | train | 23 | |
7aa4b96b3329bd11f1c5608a23e2053117e09e8a | [
"logger.debug('Starting iam wrapper')\nself.s3_client = session.client(service_name='s3')\nself.s3_resource = session.resource(service_name='s3')",
"if dryrun:\n logger.warning('Dryrun requested for creating bucket %s' % (name,))\n return None\nif location and location != 'us-east-1':\n resp = self.s3_cl... | <|body_start_0|>
logger.debug('Starting iam wrapper')
self.s3_client = session.client(service_name='s3')
self.s3_resource = session.resource(service_name='s3')
<|end_body_0|>
<|body_start_1|>
if dryrun:
logger.warning('Dryrun requested for creating bucket %s' % (name,))
... | S3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3:
def __init__(self, session):
"""This function creates the initial client and resource objects :param session: a boto3 session object for connecting to aws :return: a wrapper.S3 object for running wrapper commands"""
<|body_0|>
def create_bucket(self, name, location=None,... | stack_v2_sparse_classes_36k_train_031953 | 1,393 | no_license | [
{
"docstring": "This function creates the initial client and resource objects :param session: a boto3 session object for connecting to aws :return: a wrapper.S3 object for running wrapper commands",
"name": "__init__",
"signature": "def __init__(self, session)"
},
{
"docstring": "This function c... | 2 | stack_v2_sparse_classes_30k_train_021630 | Implement the Python class `S3` described below.
Class description:
Implement the S3 class.
Method signatures and docstrings:
- def __init__(self, session): This function creates the initial client and resource objects :param session: a boto3 session object for connecting to aws :return: a wrapper.S3 object for runni... | Implement the Python class `S3` described below.
Class description:
Implement the S3 class.
Method signatures and docstrings:
- def __init__(self, session): This function creates the initial client and resource objects :param session: a boto3 session object for connecting to aws :return: a wrapper.S3 object for runni... | a0ec72024a22b6cfc683512c9e26003a01a47b59 | <|skeleton|>
class S3:
def __init__(self, session):
"""This function creates the initial client and resource objects :param session: a boto3 session object for connecting to aws :return: a wrapper.S3 object for running wrapper commands"""
<|body_0|>
def create_bucket(self, name, location=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3:
def __init__(self, session):
"""This function creates the initial client and resource objects :param session: a boto3 session object for connecting to aws :return: a wrapper.S3 object for running wrapper commands"""
logger.debug('Starting iam wrapper')
self.s3_client = session.clie... | the_stack_v2_python_sparse | wrapper/s3.py | s4mur4i/char-libv2 | train | 0 | |
ef2ea55617d96aa3deb6a8661432e3249a20aeda | [
"super(EncoderMix, self).__init__(idim=idim, selfattention_layer_type='selfattn', attention_dim=attention_dim, attention_heads=attention_heads, linear_units=linear_units, num_blocks=num_blocks_rec, dropout_rate=dropout_rate, positional_dropout_rate=positional_dropout_rate, attention_dropout_rate=attention_dropout_r... | <|body_start_0|>
super(EncoderMix, self).__init__(idim=idim, selfattention_layer_type='selfattn', attention_dim=attention_dim, attention_heads=attention_heads, linear_units=linear_units, num_blocks=num_blocks_rec, dropout_rate=dropout_rate, positional_dropout_rate=positional_dropout_rate, attention_dropout_rate... | Transformer encoder module. :param int idim: input dim :param int attention_dim: dimension of attention :param int attention_heads: the number of heads of multi head attention :param int linear_units: the number of units of position-wise feed forward :param int num_blocks: the number of decoder blocks :param float drop... | EncoderMix | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderMix:
"""Transformer encoder module. :param int idim: input dim :param int attention_dim: dimension of attention :param int attention_heads: the number of heads of multi head attention :param int linear_units: the number of units of position-wise feed forward :param int num_blocks: the numb... | stack_v2_sparse_classes_36k_train_031954 | 6,407 | permissive | [
{
"docstring": "Construct an Encoder object.",
"name": "__init__",
"signature": "def __init__(self, idim, attention_dim=256, attention_heads=4, linear_units=2048, num_blocks_sd=4, num_blocks_rec=8, dropout_rate=0.1, positional_dropout_rate=0.1, attention_dropout_rate=0.0, input_layer='conv2d', pos_enc_c... | 3 | null | Implement the Python class `EncoderMix` described below.
Class description:
Transformer encoder module. :param int idim: input dim :param int attention_dim: dimension of attention :param int attention_heads: the number of heads of multi head attention :param int linear_units: the number of units of position-wise feed ... | Implement the Python class `EncoderMix` described below.
Class description:
Transformer encoder module. :param int idim: input dim :param int attention_dim: dimension of attention :param int attention_heads: the number of heads of multi head attention :param int linear_units: the number of units of position-wise feed ... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class EncoderMix:
"""Transformer encoder module. :param int idim: input dim :param int attention_dim: dimension of attention :param int attention_heads: the number of heads of multi head attention :param int linear_units: the number of units of position-wise feed forward :param int num_blocks: the numb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderMix:
"""Transformer encoder module. :param int idim: input dim :param int attention_dim: dimension of attention :param int attention_heads: the number of heads of multi head attention :param int linear_units: the number of units of position-wise feed forward :param int num_blocks: the number of decoder... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/encoder_mix.py | espnet/espnet | train | 7,242 |
6539695e02bcfec9e32c10f20497b9717b0ee485 | [
"self.destination_s3_uri = destination_s3_uri\nself.kms_key_id = kms_key_id\nself.generate_inference_id = generate_inference_id",
"batch_data_capture_config = {'DestinationS3Uri': self.destination_s3_uri}\nif self.kms_key_id is not None:\n batch_data_capture_config['KmsKeyId'] = self.kms_key_id\nif self.genera... | <|body_start_0|>
self.destination_s3_uri = destination_s3_uri
self.kms_key_id = kms_key_id
self.generate_inference_id = generate_inference_id
<|end_body_0|>
<|body_start_1|>
batch_data_capture_config = {'DestinationS3Uri': self.destination_s3_uri}
if self.kms_key_id is not None:... | Configuration object passed in when create a batch transform job. Specifies configuration related to batch transform job data capture for use with Amazon SageMaker Model Monitoring | BatchDataCaptureConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchDataCaptureConfig:
"""Configuration object passed in when create a batch transform job. Specifies configuration related to batch transform job data capture for use with Amazon SageMaker Model Monitoring"""
def __init__(self, destination_s3_uri: str, kms_key_id: str=None, generate_infere... | stack_v2_sparse_classes_36k_train_031955 | 16,412 | permissive | [
{
"docstring": "Create new BatchDataCaptureConfig Args: destination_s3_uri (str): S3 Location to store the captured data kms_key_id (str): The KMS key to use when writing to S3. KmsKeyId can be an ID of a KMS key, ARN of a KMS key, alias of a KMS key, or alias of a KMS key. The KmsKeyId is applied to all output... | 2 | null | Implement the Python class `BatchDataCaptureConfig` described below.
Class description:
Configuration object passed in when create a batch transform job. Specifies configuration related to batch transform job data capture for use with Amazon SageMaker Model Monitoring
Method signatures and docstrings:
- def __init__(... | Implement the Python class `BatchDataCaptureConfig` described below.
Class description:
Configuration object passed in when create a batch transform job. Specifies configuration related to batch transform job data capture for use with Amazon SageMaker Model Monitoring
Method signatures and docstrings:
- def __init__(... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class BatchDataCaptureConfig:
"""Configuration object passed in when create a batch transform job. Specifies configuration related to batch transform job data capture for use with Amazon SageMaker Model Monitoring"""
def __init__(self, destination_s3_uri: str, kms_key_id: str=None, generate_infere... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchDataCaptureConfig:
"""Configuration object passed in when create a batch transform job. Specifies configuration related to batch transform job data capture for use with Amazon SageMaker Model Monitoring"""
def __init__(self, destination_s3_uri: str, kms_key_id: str=None, generate_inference_id: bool=... | the_stack_v2_python_sparse | src/sagemaker/inputs.py | aws/sagemaker-python-sdk | train | 2,050 |
396ea4c1da477abeef83272f049b43b9c2305edb | [
"if not root:\n return 0\nreturn max(self.max_depth(root.left), self.max_depth(root.right)) + 1",
"if not root:\n return True\nelif abs(self.max_depth(root.left) - self.max_depth(root.right)) > 1:\n return False\nreturn self.isBalanced(root.left) and self.isBalanced(root.right)",
"is_balanced = True\n\... | <|body_start_0|>
if not root:
return 0
return max(self.max_depth(root.left), self.max_depth(root.right)) + 1
<|end_body_0|>
<|body_start_1|>
if not root:
return True
elif abs(self.max_depth(root.left) - self.max_depth(root.right)) > 1:
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_depth(self, root: TreeNode) -> int:
"""二叉树的最大深度"""
<|body_0|>
def isBalancedTop2Bottom(self, root: TreeNode) -> bool:
"""从顶到底"""
<|body_1|>
def isBalanced(self, root: TreeNode) -> bool:
"""从底到顶部,需掌握"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k_train_031956 | 1,592 | no_license | [
{
"docstring": "二叉树的最大深度",
"name": "max_depth",
"signature": "def max_depth(self, root: TreeNode) -> int"
},
{
"docstring": "从顶到底",
"name": "isBalancedTop2Bottom",
"signature": "def isBalancedTop2Bottom(self, root: TreeNode) -> bool"
},
{
"docstring": "从底到顶部,需掌握",
"name": "is... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_depth(self, root: TreeNode) -> int: 二叉树的最大深度
- def isBalancedTop2Bottom(self, root: TreeNode) -> bool: 从顶到底
- def isBalanced(self, root: TreeNode) -> bool: 从底到顶部,需掌握 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_depth(self, root: TreeNode) -> int: 二叉树的最大深度
- def isBalancedTop2Bottom(self, root: TreeNode) -> bool: 从顶到底
- def isBalanced(self, root: TreeNode) -> bool: 从底到顶部,需掌握
<|s... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def max_depth(self, root: TreeNode) -> int:
"""二叉树的最大深度"""
<|body_0|>
def isBalancedTop2Bottom(self, root: TreeNode) -> bool:
"""从顶到底"""
<|body_1|>
def isBalanced(self, root: TreeNode) -> bool:
"""从底到顶部,需掌握"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def max_depth(self, root: TreeNode) -> int:
"""二叉树的最大深度"""
if not root:
return 0
return max(self.max_depth(root.left), self.max_depth(root.right)) + 1
def isBalancedTop2Bottom(self, root: TreeNode) -> bool:
"""从顶到底"""
if not root:
... | the_stack_v2_python_sparse | 110.平衡二叉树/solution.py | QtTao/daily_leetcode | train | 0 | |
057807310c3dcf027a2c3f41e04b0ad1a290aae2 | [
"elementName = None\nif ifcIdx is not None:\n elementName = 'e%d' % ifcIdx\nelse:\n elementName = ifcObj.name\nNamedXmlElement.__init__(self, scenPlan, parent, 'interface', elementName)\nself.ifcObj = ifcObj\nself.addChannelReference()",
"try:\n cm = self.scenPlan.allChannelMembers[self.id]\n if cm is... | <|body_start_0|>
elementName = None
if ifcIdx is not None:
elementName = 'e%d' % ifcIdx
else:
elementName = ifcObj.name
NamedXmlElement.__init__(self, scenPlan, parent, 'interface', elementName)
self.ifcObj = ifcObj
self.addChannelReference()
<|end... | A network interface element | InterfaceElement | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceElement:
"""A network interface element"""
def __init__(self, scenPlan, parent, devObj, ifcObj, ifcIdx=None):
"""Create a network interface element with references to channel that this interface is used."""
<|body_0|>
def addChannelReference(self):
"""Ad... | stack_v2_sparse_classes_36k_train_031957 | 37,675 | permissive | [
{
"docstring": "Create a network interface element with references to channel that this interface is used.",
"name": "__init__",
"signature": "def __init__(self, scenPlan, parent, devObj, ifcObj, ifcIdx=None)"
},
{
"docstring": "Add a reference to the channel that uses this interface",
"name... | 4 | null | Implement the Python class `InterfaceElement` described below.
Class description:
A network interface element
Method signatures and docstrings:
- def __init__(self, scenPlan, parent, devObj, ifcObj, ifcIdx=None): Create a network interface element with references to channel that this interface is used.
- def addChann... | Implement the Python class `InterfaceElement` described below.
Class description:
A network interface element
Method signatures and docstrings:
- def __init__(self, scenPlan, parent, devObj, ifcObj, ifcIdx=None): Create a network interface element with references to channel that this interface is used.
- def addChann... | 9c246b0ae0e9182dcf61acc4faee41841d5cbd51 | <|skeleton|>
class InterfaceElement:
"""A network interface element"""
def __init__(self, scenPlan, parent, devObj, ifcObj, ifcIdx=None):
"""Create a network interface element with references to channel that this interface is used."""
<|body_0|>
def addChannelReference(self):
"""Ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterfaceElement:
"""A network interface element"""
def __init__(self, scenPlan, parent, devObj, ifcObj, ifcIdx=None):
"""Create a network interface element with references to channel that this interface is used."""
elementName = None
if ifcIdx is not None:
elementName... | the_stack_v2_python_sparse | coreemu-read-only/daemon/core/misc/xmlwriter1.py | ermin-sakic/common-open-research-emulator-CORE | train | 3 |
87e4bcf8dc95312fe7c8dee6a9f6ba459c6a1ca8 | [
"super().__init__(hyper_parameters)\nself.atrous_rates = hyper_parameters['graph'].get('atrous_rates', [2, 1, 2])\nself.crf_lr_multiplier = hyper_parameters.get('train', {}).get('crf_lr_multiplier', 1 if self.embed_type in ['WARD', 'RANDOM'] else 3200)",
"conv_pools = []\nfor i in range(len(self.filters_size)):\n... | <|body_start_0|>
super().__init__(hyper_parameters)
self.atrous_rates = hyper_parameters['graph'].get('atrous_rates', [2, 1, 2])
self.crf_lr_multiplier = hyper_parameters.get('train', {}).get('crf_lr_multiplier', 1 if self.embed_type in ['WARD', 'RANDOM'] else 3200)
<|end_body_0|>
<|body_start_... | DGCNNGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DGCNNGraph:
def __init__(self, hyper_parameters):
"""Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None"""
<|body_0|>
def build_model(self, inputs, o... | stack_v2_sparse_classes_36k_train_031958 | 3,746 | permissive | [
{
"docstring": "Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains \"sharing\", \"embed\", \"graph\", \"train\", \"save\" and \"data\". Returns: None",
"name": "__init__",
"signature": "def __init__(self, hyper_parameters)"
},
{
"docstring":... | 2 | null | Implement the Python class `DGCNNGraph` described below.
Class description:
Implement the DGCNNGraph class.
Method signatures and docstrings:
- def __init__(self, hyper_parameters): Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "... | Implement the Python class `DGCNNGraph` described below.
Class description:
Implement the DGCNNGraph class.
Method signatures and docstrings:
- def __init__(self, hyper_parameters): Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "... | 5237381459db5909f392737e33618a16c1e0452a | <|skeleton|>
class DGCNNGraph:
def __init__(self, hyper_parameters):
"""Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None"""
<|body_0|>
def build_model(self, inputs, o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DGCNNGraph:
def __init__(self, hyper_parameters):
"""Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None"""
super().__init__(hyper_parameters)
self.atrous_rates ... | the_stack_v2_python_sparse | macadam/sl/s04_dgcnn.py | payiz-asj/Macadam | train | 1 | |
3242e86cd04a55217f66cadf08afa36006f96dca | [
"self.__minbiasspectrum = minbiasspectrum\nscaler = TriggeredSpectrumScaler(minbiasspectrum, triggeredspectrum)\nself.__triggeredspectrum = scaler.GetScaledTriggeredSpectrum()",
"result = deepcopy(self.__minbiasspectrum)\nresult.Sumw2()\nfor mybin in range(1, result.GetXaxis().GetNbins() + 1):\n inputspectrum ... | <|body_start_0|>
self.__minbiasspectrum = minbiasspectrum
scaler = TriggeredSpectrumScaler(minbiasspectrum, triggeredspectrum)
self.__triggeredspectrum = scaler.GetScaledTriggeredSpectrum()
<|end_body_0|>
<|body_start_1|>
result = deepcopy(self.__minbiasspectrum)
result.Sumw2()
... | Class combining the min. bias spectrum and the scaled-down triggered spectrum | SpectrumCombiner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrumCombiner:
"""Class combining the min. bias spectrum and the scaled-down triggered spectrum"""
def __init__(self, minbiasspectrum, triggeredspectrum):
"""Constructor"""
<|body_0|>
def MakeCombinedSpectrum(self, swappt):
"""Create a combined spectrum from t... | stack_v2_sparse_classes_36k_train_031959 | 2,466 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, minbiasspectrum, triggeredspectrum)"
},
{
"docstring": "Create a combined spectrum from the min bias spectrum and the triggered spectrum, using the points from the min bias spectrum up to a given pt, and the point... | 2 | null | Implement the Python class `SpectrumCombiner` described below.
Class description:
Class combining the min. bias spectrum and the scaled-down triggered spectrum
Method signatures and docstrings:
- def __init__(self, minbiasspectrum, triggeredspectrum): Constructor
- def MakeCombinedSpectrum(self, swappt): Create a com... | Implement the Python class `SpectrumCombiner` described below.
Class description:
Class combining the min. bias spectrum and the scaled-down triggered spectrum
Method signatures and docstrings:
- def __init__(self, minbiasspectrum, triggeredspectrum): Constructor
- def MakeCombinedSpectrum(self, swappt): Create a com... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class SpectrumCombiner:
"""Class combining the min. bias spectrum and the scaled-down triggered spectrum"""
def __init__(self, minbiasspectrum, triggeredspectrum):
"""Constructor"""
<|body_0|>
def MakeCombinedSpectrum(self, swappt):
"""Create a combined spectrum from t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpectrumCombiner:
"""Class combining the min. bias spectrum and the scaled-down triggered spectrum"""
def __init__(self, minbiasspectrum, triggeredspectrum):
"""Constructor"""
self.__minbiasspectrum = minbiasspectrum
scaler = TriggeredSpectrumScaler(minbiasspectrum, triggeredspect... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/correction/SpectrumCombiner.py | alisw/AliPhysics | train | 129 |
f0e3694e7884b3770b1288a4f144d2266e4d602c | [
"model = _build_model()\n_train_model(model)\nnr_of_unique_weights = _get_number_of_unique_weights(model, -1, 'kernel')\nself.assertGreater(nr_of_unique_weights, NUMBER_OF_CLUSTERS)\nnr_of_unique_weights = _get_number_of_unique_weights(model, -1, 'bias')\nself.assertGreater(nr_of_unique_weights, NUMBER_OF_CLUSTERS)... | <|body_start_0|>
model = _build_model()
_train_model(model)
nr_of_unique_weights = _get_number_of_unique_weights(model, -1, 'kernel')
self.assertGreater(nr_of_unique_weights, NUMBER_OF_CLUSTERS)
nr_of_unique_weights = _get_number_of_unique_weights(model, -1, 'bias')
self.... | FunctionalTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionalTest:
def testMnistMyDenseLayer(self):
"""Test model with a custom clusterable layer derived from Dense. This customerable layer (see MyDenseLayer definition above) provides the function get_clusterable_weights() so that both 'kernel' weights as well as 'bias' weights are clust... | stack_v2_sparse_classes_36k_train_031960 | 8,905 | permissive | [
{
"docstring": "Test model with a custom clusterable layer derived from Dense. This customerable layer (see MyDenseLayer definition above) provides the function get_clusterable_weights() so that both 'kernel' weights as well as 'bias' weights are clustered.",
"name": "testMnistMyDenseLayer",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_002182 | Implement the Python class `FunctionalTest` described below.
Class description:
Implement the FunctionalTest class.
Method signatures and docstrings:
- def testMnistMyDenseLayer(self): Test model with a custom clusterable layer derived from Dense. This customerable layer (see MyDenseLayer definition above) provides t... | Implement the Python class `FunctionalTest` described below.
Class description:
Implement the FunctionalTest class.
Method signatures and docstrings:
- def testMnistMyDenseLayer(self): Test model with a custom clusterable layer derived from Dense. This customerable layer (see MyDenseLayer definition above) provides t... | 4733c85f21d1eb570fd575ea201cb211a485bfb0 | <|skeleton|>
class FunctionalTest:
def testMnistMyDenseLayer(self):
"""Test model with a custom clusterable layer derived from Dense. This customerable layer (see MyDenseLayer definition above) provides the function get_clusterable_weights() so that both 'kernel' weights as well as 'bias' weights are clust... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionalTest:
def testMnistMyDenseLayer(self):
"""Test model with a custom clusterable layer derived from Dense. This customerable layer (see MyDenseLayer definition above) provides the function get_clusterable_weights() so that both 'kernel' weights as well as 'bias' weights are clustered."""
... | the_stack_v2_python_sparse | tensorflow_model_optimization/python/core/clustering/keras/mnist_clusterable_layer_test.py | tensorflow/model-optimization | train | 1,550 | |
9bea97f082fa6abee64e2d9cc400ac36880a3655 | [
"list_c = []\nfor index, item in enumerate(S):\n if C == item:\n list_c.append(index)\nlist_return = []\nfor index, item in enumerate(S):\n list_dif = []\n for dif in list_c:\n list_dif.append(abs(index - dif))\n list_return.append(min(list_dif))\nreturn list_return",
"list_c = []\nfor i... | <|body_start_0|>
list_c = []
for index, item in enumerate(S):
if C == item:
list_c.append(index)
list_return = []
for index, item in enumerate(S):
list_dif = []
for dif in list_c:
list_dif.append(abs(index - dif))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_0|>
def shortestToChar2(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
list_c = []
... | stack_v2_sparse_classes_36k_train_031961 | 1,081 | no_license | [
{
"docstring": ":type S: str :type C: str :rtype: List[int]",
"name": "shortestToChar",
"signature": "def shortestToChar(self, S, C)"
},
{
"docstring": ":type S: str :type C: str :rtype: List[int]",
"name": "shortestToChar2",
"signature": "def shortestToChar2(self, S, C)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000273 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestToChar(self, S, C): :type S: str :type C: str :rtype: List[int]
- def shortestToChar2(self, S, C): :type S: str :type C: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestToChar(self, S, C): :type S: str :type C: str :rtype: List[int]
- def shortestToChar2(self, S, C): :type S: str :type C: str :rtype: List[int]
<|skeleton|>
class Sol... | f777f0224f188a787457c418fa3331c1e92d13e5 | <|skeleton|>
class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_0|>
def shortestToChar2(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
list_c = []
for index, item in enumerate(S):
if C == item:
list_c.append(index)
list_return = []
for index, item in enumerate(S):
list_dif... | the_stack_v2_python_sparse | let821.py | fredfeng0326/LeetCode | train | 3 | |
53bb256c7a103a37a3425c7143ff2715d3936639 | [
"content_type = ContentType.objects.get_for_model(model_admin.model)\ntags = TaggedItem.objects.filter(content_type=content_type).values('tag__name').distinct().order_by('tag__name')\ntags_list = []\nfor tag in tags:\n tags_list.append((tag['tag__name'], tag['tag__name']))\nreturn tuple(tags_list)",
"if self.v... | <|body_start_0|>
content_type = ContentType.objects.get_for_model(model_admin.model)
tags = TaggedItem.objects.filter(content_type=content_type).values('tag__name').distinct().order_by('tag__name')
tags_list = []
for tag in tags:
tags_list.append((tag['tag__name'], tag['tag__... | TagsFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagsFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
... | stack_v2_sparse_classes_36k_train_031962 | 9,844 | no_license | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | null | Implement the Python class `TagsFilter` described below.
Class description:
Implement the TagsFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The se... | Implement the Python class `TagsFilter` described below.
Class description:
Implement the TagsFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The se... | f2ac4ecc076b223c262f2cde4fa3b35b4a5cd54e | <|skeleton|>
class TagsFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagsFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
content_... | the_stack_v2_python_sparse | tendenci/apps/perms/admin.py | chendong0444/ams | train | 0 | |
d042c44879da2872351b391b6858ebae47dd4d66 | [
"super(EncoderCNN, self).__init__()\nresnet = models.resnet152(pretrained=True)\nmodules = list(resnet.children())[:-1]\nself.resnet = nn.Sequential(*modules)\nself.outdim = resnet.fc.in_features",
"with torch.no_grad():\n features = self.resnet(images)\n features = features.reshape(features.size(0), -1)\nr... | <|body_start_0|>
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.outdim = resnet.fc.in_features
<|end_body_0|>
<|body_start_1|>
with torch.no_grad():
... | EncoderCNN | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderCNN:
def __init__(self):
"""Load the pretrained ResNet-152 and replace top fc layer."""
<|body_0|>
def forward(self, images):
"""Extract feature vectors from input images."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(EncoderCNN, self... | stack_v2_sparse_classes_36k_train_031963 | 2,581 | permissive | [
{
"docstring": "Load the pretrained ResNet-152 and replace top fc layer.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Extract feature vectors from input images.",
"name": "forward",
"signature": "def forward(self, images)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021455 | Implement the Python class `EncoderCNN` described below.
Class description:
Implement the EncoderCNN class.
Method signatures and docstrings:
- def __init__(self): Load the pretrained ResNet-152 and replace top fc layer.
- def forward(self, images): Extract feature vectors from input images. | Implement the Python class `EncoderCNN` described below.
Class description:
Implement the EncoderCNN class.
Method signatures and docstrings:
- def __init__(self): Load the pretrained ResNet-152 and replace top fc layer.
- def forward(self, images): Extract feature vectors from input images.
<|skeleton|>
class Encod... | 6d3aa9a752c30719ce80ce126fcbedd4c40cdc54 | <|skeleton|>
class EncoderCNN:
def __init__(self):
"""Load the pretrained ResNet-152 and replace top fc layer."""
<|body_0|>
def forward(self, images):
"""Extract feature vectors from input images."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderCNN:
def __init__(self):
"""Load the pretrained ResNet-152 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.outdim ... | the_stack_v2_python_sparse | caption_model.py | wwt17/soft-BLEU-loss | train | 1 | |
1e67c6c738895f204c72fae2b3852ba91e94cc8c | [
"words.sort(key=len)\n\ndef is_predecessor(s1, s2):\n if len(s1) + 1 != len(s2):\n return False\n i = j = 0\n diff = 0\n while i < len(s1) and j < len(s2):\n if s1[i] != s2[j]:\n diff += 1\n j += 1\n if diff > 1:\n return False\n else:... | <|body_start_0|>
words.sort(key=len)
def is_predecessor(s1, s2):
if len(s1) + 1 != len(s2):
return False
i = j = 0
diff = 0
while i < len(s1) and j < len(s2):
if s1[i] != s2[j]:
diff += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestStrChain(self, words: List[str]) -> int:
"""Time complexity: O(N^2) space: O(N) runtime: 1864 ms Args: words (List[str]): [description] Returns: int: [description]"""
<|body_0|>
def longestStrChain2(self, words: List[str]) -> int:
"""Faster imple... | stack_v2_sparse_classes_36k_train_031964 | 1,518 | no_license | [
{
"docstring": "Time complexity: O(N^2) space: O(N) runtime: 1864 ms Args: words (List[str]): [description] Returns: int: [description]",
"name": "longestStrChain",
"signature": "def longestStrChain(self, words: List[str]) -> int"
},
{
"docstring": "Faster implementation Args: words (List[str]):... | 2 | stack_v2_sparse_classes_30k_train_015235 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestStrChain(self, words: List[str]) -> int: Time complexity: O(N^2) space: O(N) runtime: 1864 ms Args: words (List[str]): [description] Returns: int: [description]
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestStrChain(self, words: List[str]) -> int: Time complexity: O(N^2) space: O(N) runtime: 1864 ms Args: words (List[str]): [description] Returns: int: [description]
- def ... | 89b6c180bb772978b6646131f9734b122e745f9c | <|skeleton|>
class Solution:
def longestStrChain(self, words: List[str]) -> int:
"""Time complexity: O(N^2) space: O(N) runtime: 1864 ms Args: words (List[str]): [description] Returns: int: [description]"""
<|body_0|>
def longestStrChain2(self, words: List[str]) -> int:
"""Faster imple... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestStrChain(self, words: List[str]) -> int:
"""Time complexity: O(N^2) space: O(N) runtime: 1864 ms Args: words (List[str]): [description] Returns: int: [description]"""
words.sort(key=len)
def is_predecessor(s1, s2):
if len(s1) + 1 != len(s2):
... | the_stack_v2_python_sparse | dp/python/minimum-area-rectangle.py | dyf102/LC-daily | train | 2 | |
656659b354982941df6cdd5e7eb01d753e654e07 | [
"try:\n response = requests.post(url=BASE_URI + 'OVCCallejero.asmx/Consulta_DNPRC', data={'Provincia': '', 'Municipio': '', 'RC': rc.upper()}, timeout=TIMEOUT)\n response.raise_for_status()\n xml = response.text\n return CadastreXml(xml)\nexcept HTTPError as http_err:\n logger.exception(f'HTTPError o... | <|body_start_0|>
try:
response = requests.post(url=BASE_URI + 'OVCCallejero.asmx/Consulta_DNPRC', data={'Provincia': '', 'Municipio': '', 'RC': rc.upper()}, timeout=TIMEOUT)
response.raise_for_status()
xml = response.text
return CadastreXml(xml)
except HTT... | CadastreApi is a raw connection for the Spain Cadastre API. Use CadastreService for get models associated to cadastre info | CadastreApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CadastreApi:
"""CadastreApi is a raw connection for the Spain Cadastre API. Use CadastreService for get models associated to cadastre info"""
def get_info_by_rc(self, rc: str):
"""Get cadastre information from RC"""
<|body_0|>
def get_info_by_address(self, province: str,... | stack_v2_sparse_classes_36k_train_031965 | 4,210 | permissive | [
{
"docstring": "Get cadastre information from RC",
"name": "get_info_by_rc",
"signature": "def get_info_by_rc(self, rc: str)"
},
{
"docstring": "Get cadastre information from RC",
"name": "get_info_by_address",
"signature": "def get_info_by_address(self, province: str, municipality: str,... | 4 | null | Implement the Python class `CadastreApi` described below.
Class description:
CadastreApi is a raw connection for the Spain Cadastre API. Use CadastreService for get models associated to cadastre info
Method signatures and docstrings:
- def get_info_by_rc(self, rc: str): Get cadastre information from RC
- def get_info... | Implement the Python class `CadastreApi` described below.
Class description:
CadastreApi is a raw connection for the Spain Cadastre API. Use CadastreService for get models associated to cadastre info
Method signatures and docstrings:
- def get_info_by_rc(self, rc: str): Get cadastre information from RC
- def get_info... | 125e3e54060b342a473480f8cb1a913fc54f55ed | <|skeleton|>
class CadastreApi:
"""CadastreApi is a raw connection for the Spain Cadastre API. Use CadastreService for get models associated to cadastre info"""
def get_info_by_rc(self, rc: str):
"""Get cadastre information from RC"""
<|body_0|>
def get_info_by_address(self, province: str,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CadastreApi:
"""CadastreApi is a raw connection for the Spain Cadastre API. Use CadastreService for get models associated to cadastre info"""
def get_info_by_rc(self, rc: str):
"""Get cadastre information from RC"""
try:
response = requests.post(url=BASE_URI + 'OVCCallejero.as... | the_stack_v2_python_sparse | 5. WEB/app/external_sources/cadastres/services/cadastre_api.py | doyaguillo1997/Data2Gether | train | 1 |
3a28c0c499c81243595795c3da776ddb869878b9 | [
"i = 0\ncontainer = []\nwhile i < len(height):\n j = i + 1\n while j < len(height):\n tmp_container = (j - i) * min(height[i], height[j])\n container.append(tmp_container)\n j += 1\n i += 1\nreturn max(container)",
"max_container = 0\ni = 0\nj = len(height) - 1\nwhile i < j:\n tmp... | <|body_start_0|>
i = 0
container = []
while i < len(height):
j = i + 1
while j < len(height):
tmp_container = (j - i) * min(height[i], height[j])
container.append(tmp_container)
j += 1
i += 1
return max(c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height):
"""This method is rejected because of TLE(Time Limited Error). :type height: List[int] :rtype: int"""
<|body_0|>
def maxArea2(self, height):
"""Accepted. :type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031966 | 1,737 | no_license | [
{
"docstring": "This method is rejected because of TLE(Time Limited Error). :type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": "Accepted. :type height: List[int] :rtype: int",
"name": "maxArea2",
"signature": "def maxArea2(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): This method is rejected because of TLE(Time Limited Error). :type height: List[int] :rtype: int
- def maxArea2(self, height): Accepted. :type height: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): This method is rejected because of TLE(Time Limited Error). :type height: List[int] :rtype: int
- def maxArea2(self, height): Accepted. :type height: L... | ecbb8fb7f96f644c16dbb0cf7ffb69bc959a5647 | <|skeleton|>
class Solution:
def maxArea(self, height):
"""This method is rejected because of TLE(Time Limited Error). :type height: List[int] :rtype: int"""
<|body_0|>
def maxArea2(self, height):
"""Accepted. :type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height):
"""This method is rejected because of TLE(Time Limited Error). :type height: List[int] :rtype: int"""
i = 0
container = []
while i < len(height):
j = i + 1
while j < len(height):
tmp_container = (j - i... | the_stack_v2_python_sparse | source_code/11_ContainerWithMostWater.py | CircleZ3791117/CodingPractice | train | 14 | |
b63f040109ebc0a77f7cd0fd6c2a330601983155 | [
"log.info('Start dynamic topology creation...')\nbuilder.create_Controller('ESCAPE')\nagt1, nc_sw1 = builder.create_NETCONF_EE(name='NC1')\nagt2, nc_sw2 = builder.create_NETCONF_EE(name='NC2')\nsw3 = builder.create_Switch(name='SW3')\nsw4 = builder.create_Switch(name='SW4')\nsap1 = builder.create_SAP(name='SAP1')\n... | <|body_start_0|>
log.info('Start dynamic topology creation...')
builder.create_Controller('ESCAPE')
agt1, nc_sw1 = builder.create_NETCONF_EE(name='NC1')
agt2, nc_sw2 = builder.create_NETCONF_EE(name='NC2')
sw3 = builder.create_Switch(name='SW3')
sw4 = builder.create_Switc... | Topology class for testing purposes and serve as a fallback topology. Use the dynamic way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | EE1 | | EE2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | S3 +-----------+ S4 | | | | | +----------+ +----------+... | FallbackDynamicTopology | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FallbackDynamicTopology:
"""Topology class for testing purposes and serve as a fallback topology. Use the dynamic way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | EE1 | | EE2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | S3 +... | stack_v2_sparse_classes_36k_train_031967 | 40,815 | permissive | [
{
"docstring": "Set a topology with NETCONF capability for mostly testing. :param builder: builder object :return: None",
"name": "construct",
"signature": "def construct(self, builder=None)"
},
{
"docstring": "Return the topology description. :return: topo description :rtype: :class:`NFFG`",
... | 2 | null | Implement the Python class `FallbackDynamicTopology` described below.
Class description:
Topology class for testing purposes and serve as a fallback topology. Use the dynamic way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | EE1 | | EE2 | | | | | +----------+ +----------+ |1 |1 1| 1| +--... | Implement the Python class `FallbackDynamicTopology` described below.
Class description:
Topology class for testing purposes and serve as a fallback topology. Use the dynamic way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | EE1 | | EE2 | | | | | +----------+ +----------+ |1 |1 1| 1| +--... | 21b95843aa9308a5d3689bc2d30b2752b7121117 | <|skeleton|>
class FallbackDynamicTopology:
"""Topology class for testing purposes and serve as a fallback topology. Use the dynamic way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | EE1 | | EE2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | S3 +... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FallbackDynamicTopology:
"""Topology class for testing purposes and serve as a fallback topology. Use the dynamic way for topology compilation. .. raw:: ascii +----------+ +----------+ | | | | | EE1 | | EE2 | | | | | +----------+ +----------+ |1 |1 1| 1| +----------+ +----------+ | |2 2| | | S3 +-----------+ ... | the_stack_v2_python_sparse | escape/escape/infr/topology.py | JerryLX/escape | train | 0 |
92b9ccbcaabb711107ca5e2f24b766791607611f | [
"self.board = board\nself.board_cell_lst = board.cell_list()\nself.__target_location = board.target_location()",
"user_input = input('please write down the color of the car you wish to move, and the direction: ')\nif len(user_input) != 3 or user_input[1] != ',':\n print('Bad input length or no \",\" between ca... | <|body_start_0|>
self.board = board
self.board_cell_lst = board.cell_list()
self.__target_location = board.target_location()
<|end_body_0|>
<|body_start_1|>
user_input = input('please write down the color of the car you wish to move, and the direction: ')
if len(user_input) != 3... | a class that runs the rush hour game, using the classes Car and Board, the game finishes when a car arrive to the target location according to the board. | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""a class that runs the rush hour game, using the classes Car and Board, the game finishes when a car arrive to the target location according to the board."""
def __init__(self, board):
"""Initialize a new Game object. :param board: An object of type board :param dict_of_cars:... | stack_v2_sparse_classes_36k_train_031968 | 6,085 | no_license | [
{
"docstring": "Initialize a new Game object. :param board: An object of type board :param dict_of_cars: dict of cars on the given board, with a car type and his name.",
"name": "__init__",
"signature": "def __init__(self, board)"
},
{
"docstring": "a function that checks if the user's input is ... | 4 | stack_v2_sparse_classes_30k_val_001134 | Implement the Python class `Game` described below.
Class description:
a class that runs the rush hour game, using the classes Car and Board, the game finishes when a car arrive to the target location according to the board.
Method signatures and docstrings:
- def __init__(self, board): Initialize a new Game object. :... | Implement the Python class `Game` described below.
Class description:
a class that runs the rush hour game, using the classes Car and Board, the game finishes when a car arrive to the target location according to the board.
Method signatures and docstrings:
- def __init__(self, board): Initialize a new Game object. :... | f691dff94e1014cde6a8596c853b42184f2295fb | <|skeleton|>
class Game:
"""a class that runs the rush hour game, using the classes Car and Board, the game finishes when a car arrive to the target location according to the board."""
def __init__(self, board):
"""Initialize a new Game object. :param board: An object of type board :param dict_of_cars:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""a class that runs the rush hour game, using the classes Car and Board, the game finishes when a car arrive to the target location according to the board."""
def __init__(self, board):
"""Initialize a new Game object. :param board: An object of type board :param dict_of_cars: dict of cars... | the_stack_v2_python_sparse | ex9/game.py | alonShevach/introduction-to-CS | train | 0 |
5404941c9dab8dd0907b8e6545a46a1e0013c3a6 | [
"self.source_type = source_type.lower()\nself.source = self._set_source()\nif not self.source:\n raise AccountsAccessorError('Invalid source type specified.')",
"if self.source_type == 'db':\n return CURAccountsDB()\nreturn None",
"if utils.ingest_method_for_provider(account.get('provider_type')) == POLL_... | <|body_start_0|>
self.source_type = source_type.lower()
self.source = self._set_source()
if not self.source:
raise AccountsAccessorError('Invalid source type specified.')
<|end_body_0|>
<|body_start_1|>
if self.source_type == 'db':
return CURAccountsDB()
... | Interface for masu to use to get CUR accounts. | AccountsAccessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountsAccessor:
"""Interface for masu to use to get CUR accounts."""
def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE):
"""Set the CUR accounts external source."""
<|body_0|>
def _set_source(self):
"""Create the provider service object. Set what source... | stack_v2_sparse_classes_36k_train_031969 | 3,451 | permissive | [
{
"docstring": "Set the CUR accounts external source.",
"name": "__init__",
"signature": "def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE)"
},
{
"docstring": "Create the provider service object. Set what source should be used to get CUR accounts. Args: None Returns: (Object) : Some obj... | 4 | null | Implement the Python class `AccountsAccessor` described below.
Class description:
Interface for masu to use to get CUR accounts.
Method signatures and docstrings:
- def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE): Set the CUR accounts external source.
- def _set_source(self): Create the provider service ob... | Implement the Python class `AccountsAccessor` described below.
Class description:
Interface for masu to use to get CUR accounts.
Method signatures and docstrings:
- def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE): Set the CUR accounts external source.
- def _set_source(self): Create the provider service ob... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AccountsAccessor:
"""Interface for masu to use to get CUR accounts."""
def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE):
"""Set the CUR accounts external source."""
<|body_0|>
def _set_source(self):
"""Create the provider service object. Set what source... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountsAccessor:
"""Interface for masu to use to get CUR accounts."""
def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE):
"""Set the CUR accounts external source."""
self.source_type = source_type.lower()
self.source = self._set_source()
if not self.source:
... | the_stack_v2_python_sparse | koku/masu/external/accounts_accessor.py | project-koku/koku | train | 225 |
07867f5e8bc62545a415561576f013fa76a13089 | [
"test_model = SketchupModel()\ntest_model.google_id = 'test1'\ntest_model.tags = ['tag1', 'tag2']\ntest_model.title = 'title1'\ntest_model.text = \"Description of 'title1' SketchupModel.\"\ntest_model.mesh = file('sketchup_models/fixtures/mesh_can.tri').read()\ntest_model.save()\nself.test_model = SketchupModel.fin... | <|body_start_0|>
test_model = SketchupModel()
test_model.google_id = 'test1'
test_model.tags = ['tag1', 'tag2']
test_model.title = 'title1'
test_model.text = "Description of 'title1' SketchupModel."
test_model.mesh = file('sketchup_models/fixtures/mesh_can.tri').read()
... | Test case for the model ShapeDistribution. | TestShapeDistribution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestShapeDistribution:
"""Test case for the model ShapeDistribution."""
def setUp(self):
"""Run before starting testing."""
<|body_0|>
def test_write_and_read(self):
"""Test writing/reading a ShapeDistribution."""
<|body_1|>
def test_data_as_numpy_ar... | stack_v2_sparse_classes_36k_train_031970 | 1,526 | no_license | [
{
"docstring": "Run before starting testing.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test writing/reading a ShapeDistribution.",
"name": "test_write_and_read",
"signature": "def test_write_and_read(self)"
},
{
"docstring": "Test that we can use the da... | 3 | stack_v2_sparse_classes_30k_train_006576 | Implement the Python class `TestShapeDistribution` described below.
Class description:
Test case for the model ShapeDistribution.
Method signatures and docstrings:
- def setUp(self): Run before starting testing.
- def test_write_and_read(self): Test writing/reading a ShapeDistribution.
- def test_data_as_numpy_array(... | Implement the Python class `TestShapeDistribution` described below.
Class description:
Test case for the model ShapeDistribution.
Method signatures and docstrings:
- def setUp(self): Run before starting testing.
- def test_write_and_read(self): Test writing/reading a ShapeDistribution.
- def test_data_as_numpy_array(... | 13d58da77ceef6282948e56e83ff7f5fbe22d57f | <|skeleton|>
class TestShapeDistribution:
"""Test case for the model ShapeDistribution."""
def setUp(self):
"""Run before starting testing."""
<|body_0|>
def test_write_and_read(self):
"""Test writing/reading a ShapeDistribution."""
<|body_1|>
def test_data_as_numpy_ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestShapeDistribution:
"""Test case for the model ShapeDistribution."""
def setUp(self):
"""Run before starting testing."""
test_model = SketchupModel()
test_model.google_id = 'test1'
test_model.tags = ['tag1', 'tag2']
test_model.title = 'title1'
test_model... | the_stack_v2_python_sparse | django_server/shape_distribution/tests.py | julfla/master_project | train | 0 |
fd1d88191e7a8b559ef093b7c12a44b4bd85bf7c | [
"cmd = 'esxcfg-vmknic -l'\nheader_keys = ['Interface', 'Port Group/DVPort', 'IP Family', 'IP Address', 'Netmask', 'Broadcast', 'MAC Address', 'MTU', 'TSO MSS', 'Enabled', 'Type']\nraw_data = client_object.connection.request(cmd).response_data\nhorizontal_data = horizontal_parser.get_parsed_data(raw_data, expect_emp... | <|body_start_0|>
cmd = 'esxcfg-vmknic -l'
header_keys = ['Interface', 'Port Group/DVPort', 'IP Family', 'IP Address', 'Netmask', 'Broadcast', 'MAC Address', 'MTU', 'TSO MSS', 'Enabled', 'Type']
raw_data = client_object.connection.request(cmd).response_data
horizontal_data = horizontal_pa... | ESX55AdapterImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESX55AdapterImpl:
def get_adapter_info(cls, client_object):
"""Returns parsed data as dictionary for all vmknic that exists on the host."""
<|body_0|>
def get_vtep_detail(cls, client_object, **kwargs):
"""Returns parsed data as dictionary for all vtep(vxlan vmknic) i... | stack_v2_sparse_classes_36k_train_031971 | 3,531 | no_license | [
{
"docstring": "Returns parsed data as dictionary for all vmknic that exists on the host.",
"name": "get_adapter_info",
"signature": "def get_adapter_info(cls, client_object)"
},
{
"docstring": "Returns parsed data as dictionary for all vtep(vxlan vmknic) information that exists on the host.",
... | 2 | stack_v2_sparse_classes_30k_train_009306 | Implement the Python class `ESX55AdapterImpl` described below.
Class description:
Implement the ESX55AdapterImpl class.
Method signatures and docstrings:
- def get_adapter_info(cls, client_object): Returns parsed data as dictionary for all vmknic that exists on the host.
- def get_vtep_detail(cls, client_object, **kw... | Implement the Python class `ESX55AdapterImpl` described below.
Class description:
Implement the ESX55AdapterImpl class.
Method signatures and docstrings:
- def get_adapter_info(cls, client_object): Returns parsed data as dictionary for all vmknic that exists on the host.
- def get_vtep_detail(cls, client_object, **kw... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class ESX55AdapterImpl:
def get_adapter_info(cls, client_object):
"""Returns parsed data as dictionary for all vmknic that exists on the host."""
<|body_0|>
def get_vtep_detail(cls, client_object, **kwargs):
"""Returns parsed data as dictionary for all vtep(vxlan vmknic) i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESX55AdapterImpl:
def get_adapter_info(cls, client_object):
"""Returns parsed data as dictionary for all vmknic that exists on the host."""
cmd = 'esxcfg-vmknic -l'
header_keys = ['Interface', 'Port Group/DVPort', 'IP Family', 'IP Address', 'Netmask', 'Broadcast', 'MAC Address', 'MTU',... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/vsphere/esx/cli/esx55_adapter_impl.py | Cloudxtreme/MyProject | train | 0 | |
b60734479f1c0cb2ccbcb23571f67dd1c408a627 | [
"rights = access.GSoCChecker(params)\nrights['any_access'] = ['allow']\nrights['show'] = [('checkIsSurveyReadable', grading_survey_logic)]\nrights['create'] = ['checkIsUser']\nrights['edit'] = [('checkIsSurveyWritable', grading_survey_logic)]\nrights['delete'] = ['checkIsDeveloper']\nrights['list'] = ['checkDocumen... | <|body_start_0|>
rights = access.GSoCChecker(params)
rights['any_access'] = ['allow']
rights['show'] = [('checkIsSurveyReadable', grading_survey_logic)]
rights['create'] = ['checkIsUser']
rights['edit'] = [('checkIsSurveyWritable', grading_survey_logic)]
rights['delete'] ... | View methods for the GradingProjectSurvey model. | View | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the GradingProjectSurvey model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
... | stack_v2_sparse_classes_36k_train_031972 | 9,757 | permissive | [
{
"docstring": "Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Returns t... | 3 | stack_v2_sparse_classes_30k_train_001969 | Implement the Python class `View` described below.
Class description:
View methods for the GradingProjectSurvey model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete vie... | Implement the Python class `View` described below.
Class description:
View methods for the GradingProjectSurvey model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete vie... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class View:
"""View methods for the GradingProjectSurvey model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the GradingProjectSurvey model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
rights... | the_stack_v2_python_sparse | app/soc/modules/gsoc/views/models/grading_project_survey.py | pombredanne/Melange-1 | train | 0 |
7fb4b03bf6fae47f0b4c0a4b05c4f4484aa4930d | [
"super().__init__()\nself.app = app\nself.executors = self.db.query(ExecutorEntity).filter(ExecutorEntity.app_id == app.app_id, ExecutorEntity.id != 'driver', ExecutorEntity.id is not None).all()\nself.driver = self.db.query(ExecutorEntity).filter(ExecutorEntity.app_id == app.app_id, ExecutorEntity.id == 'driver').... | <|body_start_0|>
super().__init__()
self.app = app
self.executors = self.db.query(ExecutorEntity).filter(ExecutorEntity.app_id == app.app_id, ExecutorEntity.id != 'driver', ExecutorEntity.id is not None).all()
self.driver = self.db.query(ExecutorEntity).filter(ExecutorEntity.app_id == ap... | Class for analyzing executors. | ExecutorAnalyzer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutorAnalyzer:
"""Class for analyzing executors."""
def __init__(self, app):
"""Create the ExecutorAnalyzer object :param app: Application object"""
<|body_0|>
def analyze_executor_memory_wastage(self):
"""!!! At the moment, this analysis does not work correct... | stack_v2_sparse_classes_36k_train_031973 | 6,003 | permissive | [
{
"docstring": "Create the ExecutorAnalyzer object :param app: Application object",
"name": "__init__",
"signature": "def __init__(self, app)"
},
{
"docstring": "!!! At the moment, this analysis does not work correctly and should not be used !!! Analyze if executors have reasonable amount of mem... | 4 | stack_v2_sparse_classes_30k_train_005581 | Implement the Python class `ExecutorAnalyzer` described below.
Class description:
Class for analyzing executors.
Method signatures and docstrings:
- def __init__(self, app): Create the ExecutorAnalyzer object :param app: Application object
- def analyze_executor_memory_wastage(self): !!! At the moment, this analysis ... | Implement the Python class `ExecutorAnalyzer` described below.
Class description:
Class for analyzing executors.
Method signatures and docstrings:
- def __init__(self, app): Create the ExecutorAnalyzer object :param app: Application object
- def analyze_executor_memory_wastage(self): !!! At the moment, this analysis ... | 53c33d1a889258a624645c5e9cb2343495f018a2 | <|skeleton|>
class ExecutorAnalyzer:
"""Class for analyzing executors."""
def __init__(self, app):
"""Create the ExecutorAnalyzer object :param app: Application object"""
<|body_0|>
def analyze_executor_memory_wastage(self):
"""!!! At the moment, this analysis does not work correct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecutorAnalyzer:
"""Class for analyzing executors."""
def __init__(self, app):
"""Create the ExecutorAnalyzer object :param app: Application object"""
super().__init__()
self.app = app
self.executors = self.db.query(ExecutorEntity).filter(ExecutorEntity.app_id == app.app_... | the_stack_v2_python_sparse | sparkscope_web/analyzers/executor_analyzer.py | stovicekjan/sparkscope | train | 1 |
ae85aaa67aac6a3b37f741463d2c69857f90aba7 | [
"if root is None:\n return True\nreturn self.isValidBSTMinMax(root)[0]",
"if root.left and root.right:\n left, left_min, left_max = self.isValidBSTMinMax(root.left)\n right, right_min, right_max = self.isValidBSTMinMax(root.right)\n return (left and right and (left_max < root.val) and (root.val < righ... | <|body_start_0|>
if root is None:
return True
return self.isValidBSTMinMax(root)[0]
<|end_body_0|>
<|body_start_1|>
if root.left and root.right:
left, left_min, left_max = self.isValidBSTMinMax(root.left)
right, right_min, right_max = self.isValidBSTMinMax(ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBSTMinMax(self, root):
"""Returns if the tree rooted at `root` is a valid BST, and the min and max value of the tree -- min value always <= max value"""
<|body... | stack_v2_sparse_classes_36k_train_031974 | 4,457 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": "Returns if the tree rooted at `root` is a valid BST, and the min and max value of the tree -- min value always <= max value",
"name": "isValidBSTMinMax",
... | 2 | stack_v2_sparse_classes_30k_train_008370 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def isValidBSTMinMax(self, root): Returns if the tree rooted at `root` is a valid BST, and the min and max value o... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def isValidBSTMinMax(self, root): Returns if the tree rooted at `root` is a valid BST, and the min and max value o... | 69a960dd8f39e9c8435a3678852071e1085fcb72 | <|skeleton|>
class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBSTMinMax(self, root):
"""Returns if the tree rooted at `root` is a valid BST, and the min and max value of the tree -- min value always <= max value"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
return self.isValidBSTMinMax(root)[0]
def isValidBSTMinMax(self, root):
"""Returns if the tree rooted at `root` is a valid BST, and the min and max value ... | the_stack_v2_python_sparse | python/tree/lc98.py | chao-ji/LeetCode | train | 1 | |
eb08abec96daac681ede59cf9fcf636442028f63 | [
"self.has_joined_match(match, user_id)\nif match.can_leave():\n return True\nraise ApiException(422, '不满足赛事退塞条件, 无法退出')",
"try:\n return MatchMember.get(user_id=user_id, match_id=match.id)\nexcept MatchMember.DoesNotExist:\n raise ApiException(422, '未加入赛事, 无须退出')",
"form = self.validated_arguments\nins... | <|body_start_0|>
self.has_joined_match(match, user_id)
if match.can_leave():
return True
raise ApiException(422, '不满足赛事退塞条件, 无法退出')
<|end_body_0|>
<|body_start_1|>
try:
return MatchMember.get(user_id=user_id, match_id=match.id)
except MatchMember.DoesNotE... | 退出赛事 | LeaveMatchHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeaveMatchHandler:
"""退出赛事"""
def can_leave(self, match: Match, user_id: int) -> bool:
"""赛事是否可以退出 :param match: :param user_id: :return:"""
<|body_0|>
def has_joined_match(self, match, user_id) -> MatchMember:
"""用户是否加入赛事 :param match: :param user_id: :return:""... | stack_v2_sparse_classes_36k_train_031975 | 39,331 | no_license | [
{
"docstring": "赛事是否可以退出 :param match: :param user_id: :return:",
"name": "can_leave",
"signature": "def can_leave(self, match: Match, user_id: int) -> bool"
},
{
"docstring": "用户是否加入赛事 :param match: :param user_id: :return:",
"name": "has_joined_match",
"signature": "def has_joined_matc... | 3 | stack_v2_sparse_classes_30k_train_001424 | Implement the Python class `LeaveMatchHandler` described below.
Class description:
退出赛事
Method signatures and docstrings:
- def can_leave(self, match: Match, user_id: int) -> bool: 赛事是否可以退出 :param match: :param user_id: :return:
- def has_joined_match(self, match, user_id) -> MatchMember: 用户是否加入赛事 :param match: :para... | Implement the Python class `LeaveMatchHandler` described below.
Class description:
退出赛事
Method signatures and docstrings:
- def can_leave(self, match: Match, user_id: int) -> bool: 赛事是否可以退出 :param match: :param user_id: :return:
- def has_joined_match(self, match, user_id) -> MatchMember: 用户是否加入赛事 :param match: :para... | 49c31d9cce6ca451ff069697913b33fe55028a46 | <|skeleton|>
class LeaveMatchHandler:
"""退出赛事"""
def can_leave(self, match: Match, user_id: int) -> bool:
"""赛事是否可以退出 :param match: :param user_id: :return:"""
<|body_0|>
def has_joined_match(self, match, user_id) -> MatchMember:
"""用户是否加入赛事 :param match: :param user_id: :return:""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeaveMatchHandler:
"""退出赛事"""
def can_leave(self, match: Match, user_id: int) -> bool:
"""赛事是否可以退出 :param match: :param user_id: :return:"""
self.has_joined_match(match, user_id)
if match.can_leave():
return True
raise ApiException(422, '不满足赛事退塞条件, 无法退出')
... | the_stack_v2_python_sparse | PaiDuiGuanJia/yiyun/handlers/rest/match.py | haoweiking/image_tesseract_private | train | 0 |
d38d650fd33c384c1fd42951a980b1380a86ec26 | [
"q = self.db.query(Account)\navailable_filters = set(['status', 'id'])\nfilters = dict(((k, v) for k, v in request.params.items() if k in available_filters))\nif filters:\n q = q.filter_by(**filters)\nreturn Response([dict(r) for r in q.all()])",
"id_ = request.params.get('id')\na = Account(id=id_)\nself.db.ad... | <|body_start_0|>
q = self.db.query(Account)
available_filters = set(['status', 'id'])
filters = dict(((k, v) for k, v in request.params.items() if k in available_filters))
if filters:
q = q.filter_by(**filters)
return Response([dict(r) for r in q.all()])
<|end_body_0|... | AccountController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountController:
def index(self, request):
"""GET /v1.0/admin/accounts List accounts"""
<|body_0|>
def create(self, request):
"""POST /v1.0/admin/accounts Create account"""
<|body_1|>
def delete(self, request):
"""DELETE /v1.0/admin/accounts/{i... | stack_v2_sparse_classes_36k_train_031976 | 2,942 | permissive | [
{
"docstring": "GET /v1.0/admin/accounts List accounts",
"name": "index",
"signature": "def index(self, request)"
},
{
"docstring": "POST /v1.0/admin/accounts Create account",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "DELETE /v1.0/admin/account... | 5 | null | Implement the Python class `AccountController` described below.
Class description:
Implement the AccountController class.
Method signatures and docstrings:
- def index(self, request): GET /v1.0/admin/accounts List accounts
- def create(self, request): POST /v1.0/admin/accounts Create account
- def delete(self, reques... | Implement the Python class `AccountController` described below.
Class description:
Implement the AccountController class.
Method signatures and docstrings:
- def index(self, request): GET /v1.0/admin/accounts List accounts
- def create(self, request): POST /v1.0/admin/accounts Create account
- def delete(self, reques... | d6ea6428662f6d2a24742044041739bf2af1e366 | <|skeleton|>
class AccountController:
def index(self, request):
"""GET /v1.0/admin/accounts List accounts"""
<|body_0|>
def create(self, request):
"""POST /v1.0/admin/accounts Create account"""
<|body_1|>
def delete(self, request):
"""DELETE /v1.0/admin/accounts/{i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountController:
def index(self, request):
"""GET /v1.0/admin/accounts List accounts"""
q = self.db.query(Account)
available_filters = set(['status', 'id'])
filters = dict(((k, v) for k, v in request.params.items() if k in available_filters))
if filters:
q... | the_stack_v2_python_sparse | lunr/api/controller/account.py | mona-nanda/lunr | train | 0 | |
8aeff0b9ef4ccbf9a8a6c374cb3566705965f099 | [
"self.num_filter = num_filter\nself.window_size = window_size\nself.activation = activation\nself.dropout = dropout\nself.regularizer = regularizer\nself.random_seed = random_seed\nself.trainable = trainable\nself.scope = scope\nself.device_spec = get_device_spec(default_gpu_id, num_gpus)\nwith tf.variable_scope(se... | <|body_start_0|>
self.num_filter = num_filter
self.window_size = window_size
self.activation = activation
self.dropout = dropout
self.regularizer = regularizer
self.random_seed = random_seed
self.trainable = trainable
self.scope = scope
self.device... | convolutional highway layer | ConvHighway | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvHighway:
"""convolutional highway layer"""
def __init__(self, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='conv_highway'):
"""initialize convolutional highway layer"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_031977 | 9,944 | permissive | [
{
"docstring": "initialize convolutional highway layer",
"name": "__init__",
"signature": "def __init__(self, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='conv_highway')"
},
{
"docstring": "call convolutional ... | 2 | stack_v2_sparse_classes_30k_val_000053 | Implement the Python class `ConvHighway` described below.
Class description:
convolutional highway layer
Method signatures and docstrings:
- def __init__(self, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='conv_highway'): initialize... | Implement the Python class `ConvHighway` described below.
Class description:
convolutional highway layer
Method signatures and docstrings:
- def __init__(self, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='conv_highway'): initialize... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class ConvHighway:
"""convolutional highway layer"""
def __init__(self, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='conv_highway'):
"""initialize convolutional highway layer"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvHighway:
"""convolutional highway layer"""
def __init__(self, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='conv_highway'):
"""initialize convolutional highway layer"""
self.num_filter = num_filter
... | the_stack_v2_python_sparse | sequence_labeling/layer/highway.py | stevezheng23/sequence_labeling_tf | train | 18 |
f15d712d95469f57e465be721289eee78c36deea | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.accessPackageMultipleChoiceQuestion'.casefo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | AccessPackageQuestion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessPackageQuestion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageQuestion:
"""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 th... | stack_v2_sparse_classes_36k_train_031978 | 4,732 | 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: AccessPackageQuestion",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `AccessPackageQuestion` described below.
Class description:
Implement the AccessPackageQuestion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageQuestion: Creates a new instance of the appropriate class base... | Implement the Python class `AccessPackageQuestion` described below.
Class description:
Implement the AccessPackageQuestion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageQuestion: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessPackageQuestion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageQuestion:
"""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 th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessPackageQuestion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageQuestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | the_stack_v2_python_sparse | msgraph/generated/models/access_package_question.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
58aa135f37a9b90f70fb2d90d898f2be8fc419fd | [
"self.count = k\nself.myhq = hq()\nfor i in range(len(nums)):\n self.myhq.push(nums[i])\nfor i in range(k, len(nums)):\n self.myhq.pop()",
"self.myhq.push(val)\nif len(self.myhq.heap) > self.count:\n self.myhq.pop()\nreturn self.myhq.heap[0]"
] | <|body_start_0|>
self.count = k
self.myhq = hq()
for i in range(len(nums)):
self.myhq.push(nums[i])
for i in range(k, len(nums)):
self.myhq.pop()
<|end_body_0|>
<|body_start_1|>
self.myhq.push(val)
if len(self.myhq.heap) > self.count:
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.count = k
self.myhq = hq()
for i in r... | stack_v2_sparse_classes_36k_train_031979 | 1,895 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019103 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | a9ad5b5bc912a4ce5613000fbc47905510cde5ea | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.count = k
self.myhq = hq()
for i in range(len(nums)):
self.myhq.push(nums[i])
for i in range(k, len(nums)):
self.myhq.pop()
def add(self, val):
""... | the_stack_v2_python_sparse | 2.11 KthLargest.py | ANh0r/LeetCode-Daily | train | 2 | |
43bc742e88650eb5c8cbe3c29336985cf2a8c8c7 | [
"super(L2ChamferDist, self).__init__()\nself.num_add = num_add\nself.chamfer_dist = ChamferDist(method=chamfer_method)\nself.cd_w = chamfer_weight\nself.l2_dist = L2Dist()",
"B = adv_pc.shape[0]\nchamfer_loss = self.chamfer_dist(adv_pc, ori_pc, weights=weights, batch_avg=batch_avg)\nl2_loss = self.l2_dist(adv_obj... | <|body_start_0|>
super(L2ChamferDist, self).__init__()
self.num_add = num_add
self.chamfer_dist = ChamferDist(method=chamfer_method)
self.cd_w = chamfer_weight
self.l2_dist = L2Dist()
<|end_body_0|>
<|body_start_1|>
B = adv_pc.shape[0]
chamfer_loss = self.chamfer... | L2ChamferDist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2ChamferDist:
def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.2):
"""Distance function used in generating adv objects. Consisting of a L2 dist and a chamfer dist. Args: num_add (int): number of added objects. chamfer_method (str, optional): chamfer. Defaults to 'a... | stack_v2_sparse_classes_36k_train_031980 | 11,583 | permissive | [
{
"docstring": "Distance function used in generating adv objects. Consisting of a L2 dist and a chamfer dist. Args: num_add (int): number of added objects. chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. chamfer_weight (float, optional): weight factor. Defaults to 0.2.",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_012340 | Implement the Python class `L2ChamferDist` described below.
Class description:
Implement the L2ChamferDist class.
Method signatures and docstrings:
- def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.2): Distance function used in generating adv objects. Consisting of a L2 dist and a chamfer dist.... | Implement the Python class `L2ChamferDist` described below.
Class description:
Implement the L2ChamferDist class.
Method signatures and docstrings:
- def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.2): Distance function used in generating adv objects. Consisting of a L2 dist and a chamfer dist.... | 4e2462b66fa1eac90cfbf61fa0dc635d223fdf2f | <|skeleton|>
class L2ChamferDist:
def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.2):
"""Distance function used in generating adv objects. Consisting of a L2 dist and a chamfer dist. Args: num_add (int): number of added objects. chamfer_method (str, optional): chamfer. Defaults to 'a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class L2ChamferDist:
def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.2):
"""Distance function used in generating adv objects. Consisting of a L2 dist and a chamfer dist. Args: num_add (int): number of added objects. chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. chamf... | the_stack_v2_python_sparse | baselines/attack/util/dist_utils.py | code-roamer/IF-Defense | train | 0 | |
e27694d038a5e61a9d74293065ec3460b49fd0d1 | [
"assert exists in (True, False, None)\nassert type in ('file', 'dir', 'symlink', 'socket', None) or hasattr(type, '__call__')\nself._exists = exists\nself._type = type\nself._dash_ok = dash_ok",
"if string == '-':\n if self._type == 'dir':\n raise err('standard input/output (-) not allowed as directory ... | <|body_start_0|>
assert exists in (True, False, None)
assert type in ('file', 'dir', 'symlink', 'socket', None) or hasattr(type, '__call__')
self._exists = exists
self._type = type
self._dash_ok = dash_ok
<|end_body_0|>
<|body_start_1|>
if string == '-':
if s... | Custom argument type for path validation. Adapted from: https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse | PathType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PathType:
"""Custom argument type for path validation. Adapted from: https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse"""
def __init__(self, exists=True, type='file', dash_ok=True):
"""Initialize Path. Parameters ---------- exists : bool True: a path tha... | stack_v2_sparse_classes_36k_train_031981 | 2,544 | permissive | [
{
"docstring": "Initialize Path. Parameters ---------- exists : bool True: a path that does exist False: a path that does not exist, in a valid parent directory None: don't care type : str file, dir, symlink, socket, None, or a function returning True for valid paths None: don't care dash_ok: bool whether to al... | 2 | stack_v2_sparse_classes_30k_train_000602 | Implement the Python class `PathType` described below.
Class description:
Custom argument type for path validation. Adapted from: https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse
Method signatures and docstrings:
- def __init__(self, exists=True, type='file', dash_ok=True): Initialize P... | Implement the Python class `PathType` described below.
Class description:
Custom argument type for path validation. Adapted from: https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse
Method signatures and docstrings:
- def __init__(self, exists=True, type='file', dash_ok=True): Initialize P... | d99b21ec844a46d6e18e729ab299f8e9051a68e8 | <|skeleton|>
class PathType:
"""Custom argument type for path validation. Adapted from: https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse"""
def __init__(self, exists=True, type='file', dash_ok=True):
"""Initialize Path. Parameters ---------- exists : bool True: a path tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PathType:
"""Custom argument type for path validation. Adapted from: https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse"""
def __init__(self, exists=True, type='file', dash_ok=True):
"""Initialize Path. Parameters ---------- exists : bool True: a path that does exist ... | the_stack_v2_python_sparse | dacbench/argument_parsing.py | automl/DACBench | train | 19 |
76fd0f95bb57487e9e4e61a13e929363395056cd | [
"self.tab_entrada = tabuleiro.copy()\nself.tab_final = [self.tab_entrada.copy()]\nself.game_rounds = game_rounds\nself.largura = len(tabuleiro[0])\nself.altura = len(tabuleiro)",
"cells = {}\nfor y_pos in range(self.altura):\n for x_pos in range(self.largura):\n elmt = self.tab_final[game_round][y_pos][... | <|body_start_0|>
self.tab_entrada = tabuleiro.copy()
self.tab_final = [self.tab_entrada.copy()]
self.game_rounds = game_rounds
self.largura = len(tabuleiro[0])
self.altura = len(tabuleiro)
<|end_body_0|>
<|body_start_1|>
cells = {}
for y_pos in range(self.altura)... | Classe para execução do Jogo da Vida | Jogo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Jogo:
"""Classe para execução do Jogo da Vida"""
def __init__(self, tabuleiro, game_rounds):
"""Função para preparar atributos necessários ao jogo, como tabuleiro inicial e numero de game_rounds. Tambem são iniciados o tabuleiro final, de 3 dimensões, sendo a primeira delas o quadro ... | stack_v2_sparse_classes_36k_train_031982 | 5,159 | no_license | [
{
"docstring": "Função para preparar atributos necessários ao jogo, como tabuleiro inicial e numero de game_rounds. Tambem são iniciados o tabuleiro final, de 3 dimensões, sendo a primeira delas o quadro dado, a altura e largura de um determinado tabuleiro.",
"name": "__init__",
"signature": "def __init... | 6 | stack_v2_sparse_classes_30k_val_000208 | Implement the Python class `Jogo` described below.
Class description:
Classe para execução do Jogo da Vida
Method signatures and docstrings:
- def __init__(self, tabuleiro, game_rounds): Função para preparar atributos necessários ao jogo, como tabuleiro inicial e numero de game_rounds. Tambem são iniciados o tabuleir... | Implement the Python class `Jogo` described below.
Class description:
Classe para execução do Jogo da Vida
Method signatures and docstrings:
- def __init__(self, tabuleiro, game_rounds): Função para preparar atributos necessários ao jogo, como tabuleiro inicial e numero de game_rounds. Tambem são iniciados o tabuleir... | b61f63d2396f8fa6e90b7d9c74830306988c6f64 | <|skeleton|>
class Jogo:
"""Classe para execução do Jogo da Vida"""
def __init__(self, tabuleiro, game_rounds):
"""Função para preparar atributos necessários ao jogo, como tabuleiro inicial e numero de game_rounds. Tambem são iniciados o tabuleiro final, de 3 dimensões, sendo a primeira delas o quadro ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Jogo:
"""Classe para execução do Jogo da Vida"""
def __init__(self, tabuleiro, game_rounds):
"""Função para preparar atributos necessários ao jogo, como tabuleiro inicial e numero de game_rounds. Tambem são iniciados o tabuleiro final, de 3 dimensões, sendo a primeira delas o quadro dado, a altur... | the_stack_v2_python_sparse | lab09/main.py | kinderferraz/mc102 | train | 0 |
90ad29834c1f722d7f44461fe6f4b57ae9dd8490 | [
"self.text = text\nself.channel_id = channel_id or ''\nself.search_type = search_type\nreturn super().__new__(self)",
"self.raise_for_non_200(self, response, 'Search for \"{}\" failed.'.format(self.text))\nresults = response.json()\nreturn [DoSearchResult(item) for item in results]",
"data = {'brandid': '341', ... | <|body_start_0|>
self.text = text
self.channel_id = channel_id or ''
self.search_type = search_type
return super().__new__(self)
<|end_body_0|>
<|body_start_1|>
self.raise_for_non_200(self, response, 'Search for "{}" failed.'.format(self.text))
results = response.json()
... | DoSearch request. | DoSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoSearch:
"""DoSearch request."""
def __new__(self, text, channel_id=None, search_type=RANGE):
"""Create Do Search request. Args: text: Text string to search Kwargs: channel_id: The ID of the sales channel search_type: The type of search to do Returns: list(DoSearchResult)"""
... | stack_v2_sparse_classes_36k_train_031983 | 1,708 | permissive | [
{
"docstring": "Create Do Search request. Args: text: Text string to search Kwargs: channel_id: The ID of the sales channel search_type: The type of search to do Returns: list(DoSearchResult)",
"name": "__new__",
"signature": "def __new__(self, text, channel_id=None, search_type=RANGE)"
},
{
"do... | 3 | null | Implement the Python class `DoSearch` described below.
Class description:
DoSearch request.
Method signatures and docstrings:
- def __new__(self, text, channel_id=None, search_type=RANGE): Create Do Search request. Args: text: Text string to search Kwargs: channel_id: The ID of the sales channel search_type: The type... | Implement the Python class `DoSearch` described below.
Class description:
DoSearch request.
Method signatures and docstrings:
- def __new__(self, text, channel_id=None, search_type=RANGE): Create Do Search request. Args: text: Text string to search Kwargs: channel_id: The ID of the sales channel search_type: The type... | 2df4ac6e350a7eacb377cfecea25bacdb9b73975 | <|skeleton|>
class DoSearch:
"""DoSearch request."""
def __new__(self, text, channel_id=None, search_type=RANGE):
"""Create Do Search request. Args: text: Text string to search Kwargs: channel_id: The ID of the sales channel search_type: The type of search to do Returns: list(DoSearchResult)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoSearch:
"""DoSearch request."""
def __new__(self, text, channel_id=None, search_type=RANGE):
"""Create Do Search request. Args: text: Text string to search Kwargs: channel_id: The ID of the sales channel search_type: The type of search to do Returns: list(DoSearchResult)"""
self.text = ... | the_stack_v2_python_sparse | ccapi/requests/products/dosearch.py | stcstores/ccapi | train | 1 |
062e3840ed3be135188b65eecd5a1ca05de0ac15 | [
"self.preset = preset\nself.tags = []\nself.keys = []",
"f = open(self.preset)\nxml = f.read()\ntree = etree.parse(StringIO(xml))\nitems = tree.xpath('//ns:item', namespaces=self.namespaces)\nfor item in items:\n self.process_item_and_children(item)\nreturn self.tags",
"geometrytypes = None\nif item.get('typ... | <|body_start_0|>
self.preset = preset
self.tags = []
self.keys = []
<|end_body_0|>
<|body_start_1|>
f = open(self.preset)
xml = f.read()
tree = etree.parse(StringIO(xml))
items = tree.xpath('//ns:item', namespaces=self.namespaces)
for item in items:
... | Parses uploaded JOSM Presets and creates Tag model instances based on the contents of the preset file. See jobs.models.Tag for the instance fields. Looks for the 'key', 'text', 'combo', 'multiselect' and 'check' child elements of all 'item' elements in the preset. Pulls out the 'key' attribute of these elements. | UnfilteredPresetParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnfilteredPresetParser:
"""Parses uploaded JOSM Presets and creates Tag model instances based on the contents of the preset file. See jobs.models.Tag for the instance fields. Looks for the 'key', 'text', 'combo', 'multiselect' and 'check' child elements of all 'item' elements in the preset. Pulls... | stack_v2_sparse_classes_36k_train_031984 | 15,693 | no_license | [
{
"docstring": "Initialize the parser with the preset.",
"name": "__init__",
"signature": "def __init__(self, preset=None, *args, **kwargs)"
},
{
"docstring": "Read in the JOSM Preset and processes the 'item' elements.",
"name": "parse",
"signature": "def parse(self)"
},
{
"docst... | 6 | stack_v2_sparse_classes_30k_val_001087 | Implement the Python class `UnfilteredPresetParser` described below.
Class description:
Parses uploaded JOSM Presets and creates Tag model instances based on the contents of the preset file. See jobs.models.Tag for the instance fields. Looks for the 'key', 'text', 'combo', 'multiselect' and 'check' child elements of a... | Implement the Python class `UnfilteredPresetParser` described below.
Class description:
Parses uploaded JOSM Presets and creates Tag model instances based on the contents of the preset file. See jobs.models.Tag for the instance fields. Looks for the 'key', 'text', 'combo', 'multiselect' and 'check' child elements of a... | f90b2ba55fa82d6c0dc35f0aeb28dc3d35159bf3 | <|skeleton|>
class UnfilteredPresetParser:
"""Parses uploaded JOSM Presets and creates Tag model instances based on the contents of the preset file. See jobs.models.Tag for the instance fields. Looks for the 'key', 'text', 'combo', 'multiselect' and 'check' child elements of all 'item' elements in the preset. Pulls... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnfilteredPresetParser:
"""Parses uploaded JOSM Presets and creates Tag model instances based on the contents of the preset file. See jobs.models.Tag for the instance fields. Looks for the 'key', 'text', 'combo', 'multiselect' and 'check' child elements of all 'item' elements in the preset. Pulls out the 'key... | the_stack_v2_python_sparse | jobs/presets.py | posm/osm-export-tool2 | train | 2 |
ae4fa59e747cddcf424b369d43b99c781e7ee744 | [
"url = f'{self._url}/department/create?access_token={self.token}'\nr = self.request('post', url, data)\nreturn r.json()",
"url = f'{self._url}/department/update?access_token={self.token}'\nr = self.request('post', url, data)\nreturn r.json()",
"url = f'{self._url}/department/delete?access_token={self.token}&id=... | <|body_start_0|>
url = f'{self._url}/department/create?access_token={self.token}'
r = self.request('post', url, data)
return r.json()
<|end_body_0|>
<|body_start_1|>
url = f'{self._url}/department/update?access_token={self.token}'
r = self.request('post', url, data)
retu... | Department | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Department:
def create_department(self, data):
"""创建部门 :param data: 上送信息 :return: response"""
<|body_0|>
def update_department(self, data):
"""更新部门 :param data: 上送信息 :return: response"""
<|body_1|>
def delete_department(self, ID=None):
"""删除部门 :p... | stack_v2_sparse_classes_36k_train_031985 | 1,560 | no_license | [
{
"docstring": "创建部门 :param data: 上送信息 :return: response",
"name": "create_department",
"signature": "def create_department(self, data)"
},
{
"docstring": "更新部门 :param data: 上送信息 :return: response",
"name": "update_department",
"signature": "def update_department(self, data)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_004631 | Implement the Python class `Department` described below.
Class description:
Implement the Department class.
Method signatures and docstrings:
- def create_department(self, data): 创建部门 :param data: 上送信息 :return: response
- def update_department(self, data): 更新部门 :param data: 上送信息 :return: response
- def delete_departm... | Implement the Python class `Department` described below.
Class description:
Implement the Department class.
Method signatures and docstrings:
- def create_department(self, data): 创建部门 :param data: 上送信息 :return: response
- def update_department(self, data): 更新部门 :param data: 上送信息 :return: response
- def delete_departm... | 63afcd40ee036d7238409ca7226ccf4cb15e5cd6 | <|skeleton|>
class Department:
def create_department(self, data):
"""创建部门 :param data: 上送信息 :return: response"""
<|body_0|>
def update_department(self, data):
"""更新部门 :param data: 上送信息 :return: response"""
<|body_1|>
def delete_department(self, ID=None):
"""删除部门 :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Department:
def create_department(self, data):
"""创建部门 :param data: 上送信息 :return: response"""
url = f'{self._url}/department/create?access_token={self.token}'
r = self.request('post', url, data)
return r.json()
def update_department(self, data):
"""更新部门 :param data... | the_stack_v2_python_sparse | pages/API/department_api.py | Lusilucy/TestWeWork | train | 1 | |
f12695213c7e209d254cd8ae1da70e4ed61bc69a | [
"self.N_start = N_start\nself.ROI = ROI\nself.N_files = N_finish - N_start\nself.im_shape = (ROI[3] - ROI[1], ROI[2] - ROI[0])\nself.Npad = init_Npad(ROI, compression=compNpad)",
"data_names, ff_names = init_names(data_name, N_distances, first_distance=first_distance)\nimlist = var.im_folder(path)\nimages = np.ze... | <|body_start_0|>
self.N_start = N_start
self.ROI = ROI
self.N_files = N_finish - N_start
self.im_shape = (ROI[3] - ROI[1], ROI[2] - ROI[0])
self.Npad = init_Npad(ROI, compression=compNpad)
<|end_body_0|>
<|body_start_1|>
data_names, ff_names = init_names(data_name, N_dis... | Processor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processor:
def __init__(self, ROI, folder, N_start, N_finish, compNpad=8):
"""Initialize parameters. Normally should contain ROI, N_distances, etc"""
<|body_0|>
def init_paths(self, data_name, path, N_distances, first_distance=1):
"""Generate paths images & flatfield... | stack_v2_sparse_classes_36k_train_031986 | 8,317 | permissive | [
{
"docstring": "Initialize parameters. Normally should contain ROI, N_distances, etc",
"name": "__init__",
"signature": "def __init__(self, ROI, folder, N_start, N_finish, compNpad=8)"
},
{
"docstring": "Generate paths images & flatfields",
"name": "init_paths",
"signature": "def init_pa... | 2 | stack_v2_sparse_classes_30k_test_001024 | Implement the Python class `Processor` described below.
Class description:
Implement the Processor class.
Method signatures and docstrings:
- def __init__(self, ROI, folder, N_start, N_finish, compNpad=8): Initialize parameters. Normally should contain ROI, N_distances, etc
- def init_paths(self, data_name, path, N_d... | Implement the Python class `Processor` described below.
Class description:
Implement the Processor class.
Method signatures and docstrings:
- def __init__(self, ROI, folder, N_start, N_finish, compNpad=8): Initialize parameters. Normally should contain ROI, N_distances, etc
- def init_paths(self, data_name, path, N_d... | 0178822dfbf4b1a249d510030b21fca28d51d2c0 | <|skeleton|>
class Processor:
def __init__(self, ROI, folder, N_start, N_finish, compNpad=8):
"""Initialize parameters. Normally should contain ROI, N_distances, etc"""
<|body_0|>
def init_paths(self, data_name, path, N_distances, first_distance=1):
"""Generate paths images & flatfield... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Processor:
def __init__(self, ROI, folder, N_start, N_finish, compNpad=8):
"""Initialize parameters. Normally should contain ROI, N_distances, etc"""
self.N_start = N_start
self.ROI = ROI
self.N_files = N_finish - N_start
self.im_shape = (ROI[3] - ROI[1], ROI[2] - ROI[0... | the_stack_v2_python_sparse | maximus48/deprecated/tomo_proc2.py | maximka48/XIMG-EMBL | train | 2 | |
912af52f26b5206d827aa4aae976a3d2b908a8c2 | [
"if learn_rate_decay_mode not in self.VALID_DECAY_MODES:\n raise ValueError('Invalid decay mode: {}'.format(learn_rate_decay_mode))\nself.initial_learn_rate = initial_learn_rate\nself.learn_rate = initial_learn_rate\nself.learn_rate_decay_mode = learn_rate_decay_mode.lower()\nself.boyan_N0 = boyan_N0\nif self.le... | <|body_start_0|>
if learn_rate_decay_mode not in self.VALID_DECAY_MODES:
raise ValueError('Invalid decay mode: {}'.format(learn_rate_decay_mode))
self.initial_learn_rate = initial_learn_rate
self.learn_rate = initial_learn_rate
self.learn_rate_decay_mode = learn_rate_decay_mo... | Abstract base class that contains step-size control methods for (stochastic) descent algorithms such as TD Learning, Greedy-GQ etc. | DescentAlgorithm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DescentAlgorithm:
"""Abstract base class that contains step-size control methods for (stochastic) descent algorithms such as TD Learning, Greedy-GQ etc."""
def __init__(self, initial_learn_rate=0.1, learn_rate_decay_mode='dabney', boyan_N0=1000):
""":param initial_learn_rate: Initial... | stack_v2_sparse_classes_36k_train_031987 | 8,683 | permissive | [
{
"docstring": ":param initial_learn_rate: Initial learning rate to use (where applicable). .. warning:: ``initial_learn_rate`` should be set to 1 for automatic learning rate; otherwise, initial_learn_rate will act as a permanent upper-bound on learn_rate. :param learn_rate_decay_mode: The learning rate decay m... | 2 | stack_v2_sparse_classes_30k_train_020415 | Implement the Python class `DescentAlgorithm` described below.
Class description:
Abstract base class that contains step-size control methods for (stochastic) descent algorithms such as TD Learning, Greedy-GQ etc.
Method signatures and docstrings:
- def __init__(self, initial_learn_rate=0.1, learn_rate_decay_mode='da... | Implement the Python class `DescentAlgorithm` described below.
Class description:
Abstract base class that contains step-size control methods for (stochastic) descent algorithms such as TD Learning, Greedy-GQ etc.
Method signatures and docstrings:
- def __init__(self, initial_learn_rate=0.1, learn_rate_decay_mode='da... | 329166de28d311d8f87358a62c38f40a7318fe07 | <|skeleton|>
class DescentAlgorithm:
"""Abstract base class that contains step-size control methods for (stochastic) descent algorithms such as TD Learning, Greedy-GQ etc."""
def __init__(self, initial_learn_rate=0.1, learn_rate_decay_mode='dabney', boyan_N0=1000):
""":param initial_learn_rate: Initial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DescentAlgorithm:
"""Abstract base class that contains step-size control methods for (stochastic) descent algorithms such as TD Learning, Greedy-GQ etc."""
def __init__(self, initial_learn_rate=0.1, learn_rate_decay_mode='dabney', boyan_N0=1000):
""":param initial_learn_rate: Initial learning rat... | the_stack_v2_python_sparse | rlpy/agents/agent.py | kngwyu/rlpy3 | train | 4 |
5ec46dec409619b85f0edb0e36b746f38b106f4b | [
"CtrlDev.__init__(self, parent)\nself._name = 'DVD/CD'\nself._category = 'Armazenamento'\nself._diag = DiagDVDCD(self)\nself._compat = CompatDVDCD(self)\nself._guiClass = GUIDVDCD",
"self._callInfo()\nself._callCompat()\nself._callDiag()"
] | <|body_start_0|>
CtrlDev.__init__(self, parent)
self._name = 'DVD/CD'
self._category = 'Armazenamento'
self._diag = DiagDVDCD(self)
self._compat = CompatDVDCD(self)
self._guiClass = GUIDVDCD
<|end_body_0|>
<|body_start_1|>
self._callInfo()
self._callCompa... | Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificacao, compatibilidade, diagnostico e cria a tela de exibicao. | CtrlDvdcd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtrlDvdcd:
"""Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificacao, compatibilidade, diagnostico e cria a tela de exibicao."""
def __init__(self, parent):
"""Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe bas... | stack_v2_sparse_classes_36k_train_031988 | 1,186 | no_license | [
{
"docstring": "Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe base 'CtrlDev'.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Executa o info, compat e diag (dependendo do resultado do compatibilidade) e cria as tela... | 2 | stack_v2_sparse_classes_30k_train_015827 | Implement the Python class `CtrlDvdcd` described below.
Class description:
Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificacao, compatibilidade, diagnostico e cria a tela de exibicao.
Method signatures and docstrings:
- def __init__(self, parent): Construtor que inicializa os atributos... | Implement the Python class `CtrlDvdcd` described below.
Class description:
Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificacao, compatibilidade, diagnostico e cria a tela de exibicao.
Method signatures and docstrings:
- def __init__(self, parent): Construtor que inicializa os atributos... | bda0c2c8977dd1246339f1f0f4718d29e8795f21 | <|skeleton|>
class CtrlDvdcd:
"""Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificacao, compatibilidade, diagnostico e cria a tela de exibicao."""
def __init__(self, parent):
"""Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe bas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtrlDvdcd:
"""Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificacao, compatibilidade, diagnostico e cria a tela de exibicao."""
def __init__(self, parent):
"""Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe base 'CtrlDev'."... | the_stack_v2_python_sparse | src/libs/dvdcd/ctrl_dvdcd.py | adrianomelo/ldc-desktop | train | 1 |
199d4f7cb29c2c903341f6de229d16da916473d1 | [
"super(LocateDatabaseParser, self).__init__()\nself._cstring_map = self._GetDataTypeMap('cstring')\nself._directory_entry_header_map = self._GetDataTypeMap('directory_entry_header')\nself._directory_header_map = self._GetDataTypeMap('directory_header')",
"sub_entry_names = []\ntotal_data_size = 0\ndirectory_entry... | <|body_start_0|>
super(LocateDatabaseParser, self).__init__()
self._cstring_map = self._GetDataTypeMap('cstring')
self._directory_entry_header_map = self._GetDataTypeMap('directory_entry_header')
self._directory_header_map = self._GetDataTypeMap('directory_header')
<|end_body_0|>
<|body... | Parser for locate database (updatedb) files. | LocateDatabaseParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocateDatabaseParser:
"""Parser for locate database (updatedb) files."""
def __init__(self):
"""Initializes a locate database (updatedb) file parser."""
<|body_0|>
def _ParseDirectoryEntry(self, file_object, file_offset):
"""Parses a locate database (updatedb) di... | stack_v2_sparse_classes_36k_train_031989 | 5,609 | permissive | [
{
"docstring": "Initializes a locate database (updatedb) file parser.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parses a locate database (updatedb) directory entry. Args: file_object (dfvfs.FileIO): file-like object to be parsed. file_offset (int): offset of the ... | 4 | stack_v2_sparse_classes_30k_train_017983 | Implement the Python class `LocateDatabaseParser` described below.
Class description:
Parser for locate database (updatedb) files.
Method signatures and docstrings:
- def __init__(self): Initializes a locate database (updatedb) file parser.
- def _ParseDirectoryEntry(self, file_object, file_offset): Parses a locate d... | Implement the Python class `LocateDatabaseParser` described below.
Class description:
Parser for locate database (updatedb) files.
Method signatures and docstrings:
- def __init__(self): Initializes a locate database (updatedb) file parser.
- def _ParseDirectoryEntry(self, file_object, file_offset): Parses a locate d... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class LocateDatabaseParser:
"""Parser for locate database (updatedb) files."""
def __init__(self):
"""Initializes a locate database (updatedb) file parser."""
<|body_0|>
def _ParseDirectoryEntry(self, file_object, file_offset):
"""Parses a locate database (updatedb) di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocateDatabaseParser:
"""Parser for locate database (updatedb) files."""
def __init__(self):
"""Initializes a locate database (updatedb) file parser."""
super(LocateDatabaseParser, self).__init__()
self._cstring_map = self._GetDataTypeMap('cstring')
self._directory_entry_h... | the_stack_v2_python_sparse | plaso/parsers/locate.py | log2timeline/plaso | train | 1,506 |
282540f63bcd69eccd0196b7f7b32c22fa28d7dd | [
"self.dictionary = {}\nfor val in dictionary:\n self.dictionary[self._calculate_abbr(val)] = True",
"if self._calculate_abbr(word) in self.dictionary:\n return False\nreturn True",
"length = len(val)\nif length > 2:\n return '{0}{1}{2}'.format(val[0], length, val[-1])\nelse:\n return val"
] | <|body_start_0|>
self.dictionary = {}
for val in dictionary:
self.dictionary[self._calculate_abbr(val)] = True
<|end_body_0|>
<|body_start_1|>
if self._calculate_abbr(word) in self.dictionary:
return False
return True
<|end_body_1|>
<|body_start_2|>
leng... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool NOTES: we need a function to calculate the abbrs of a... | stack_v2_sparse_classes_36k_train_031990 | 1,153 | no_license | [
{
"docstring": "initialize your data structure here. :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": "check if a word is unique. :type word: str :rtype: bool NOTES: we need a function to calculate the abbrs of all of the dictionar... | 3 | stack_v2_sparse_classes_30k_train_008475 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | 94a35dc3e25ee55530920fd57d7484d24d4abbfb | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool NOTES: we need a function to calculate the abbrs of a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
self.dictionary = {}
for val in dictionary:
self.dictionary[self._calculate_abbr(val)] = True
def isUnique(self, word):
"""check if a word is u... | the_stack_v2_python_sparse | leetcode/problems/unique_word_abbr.py | DanielHabib/practice_makes_perfect | train | 4 | |
38f962ae6a2cbf8c400bcb8a54ade41a46fcf0d3 | [
"if template_path:\n self.template = self.get_template(template_path)\nelif template_content is not None:\n self.template = template_content\nelse:\n self.template = ''",
"template_message = self.template\nfor renderer in self.Renderers:\n template_message = renderer.render(template_message, context)\... | <|body_start_0|>
if template_path:
self.template = self.get_template(template_path)
elif template_content is not None:
self.template = template_content
else:
self.template = ''
<|end_body_0|>
<|body_start_1|>
template_message = self.template
f... | 通知模板 | AlarmNoticeTemplate | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlarmNoticeTemplate:
"""通知模板"""
def __init__(self, template_path=None, template_content=None):
""":param template_path: 模板路径 :type template_path: str or unicode"""
<|body_0|>
def render(self, context):
"""模板渲染 :param context: 上下文 :return: 渲染后内容 :rtype: str"""
... | stack_v2_sparse_classes_36k_train_031991 | 3,015 | permissive | [
{
"docstring": ":param template_path: 模板路径 :type template_path: str or unicode",
"name": "__init__",
"signature": "def __init__(self, template_path=None, template_content=None)"
},
{
"docstring": "模板渲染 :param context: 上下文 :return: 渲染后内容 :rtype: str",
"name": "render",
"signature": "def r... | 5 | null | Implement the Python class `AlarmNoticeTemplate` described below.
Class description:
通知模板
Method signatures and docstrings:
- def __init__(self, template_path=None, template_content=None): :param template_path: 模板路径 :type template_path: str or unicode
- def render(self, context): 模板渲染 :param context: 上下文 :return: 渲染后... | Implement the Python class `AlarmNoticeTemplate` described below.
Class description:
通知模板
Method signatures and docstrings:
- def __init__(self, template_path=None, template_content=None): :param template_path: 模板路径 :type template_path: str or unicode
- def render(self, context): 模板渲染 :param context: 上下文 :return: 渲染后... | 57d745ce6be531c000a3b477c38bfdd4c2ac74e3 | <|skeleton|>
class AlarmNoticeTemplate:
"""通知模板"""
def __init__(self, template_path=None, template_content=None):
""":param template_path: 模板路径 :type template_path: str or unicode"""
<|body_0|>
def render(self, context):
"""模板渲染 :param context: 上下文 :return: 渲染后内容 :rtype: str"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlarmNoticeTemplate:
"""通知模板"""
def __init__(self, template_path=None, template_content=None):
""":param template_path: 模板路径 :type template_path: str or unicode"""
if template_path:
self.template = self.get_template(template_path)
elif template_content is not None:
... | the_stack_v2_python_sparse | apps/core/notice/template.py | fengzhongzhu1621/xTool | train | 3 |
39245499ad5a59d1cd55b4d9d86f61a82df8071a | [
"dp = [1] * n\ns = set([1])\nfor i in range(1, n):\n dp[i] = float('inf')\n for factor in [2, 3, 5]:\n r = dp[i - 1] // factor\n for k in range(r + 1, dp[i - 1] + 1):\n if k in s:\n dp[i] = min(dp[i], k * factor)\n break\n s.add(dp[i])\nreturn dp[-1]",... | <|body_start_0|>
dp = [1] * n
s = set([1])
for i in range(1, n):
dp[i] = float('inf')
for factor in [2, 3, 5]:
r = dp[i - 1] // factor
for k in range(r + 1, dp[i - 1] + 1):
if k in s:
dp[i] = min(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthUglyNumber_1(self, n: int) -> int:
"""FIXME:超时 求 n=15 n=14 时为 20 20//2 = 10 --> 11 不是丑数 --> 12 是 --> 12*2=24 20//3 = 6 --> 7 不是丑数 --> 8 是 --> 8*3=24 20//5= 4 --> 5 是丑数 --> 5*5=25"""
<|body_0|>
def nthUglyNumber(self, n: int) -> int:
"""动态规划"""
... | stack_v2_sparse_classes_36k_train_031992 | 1,802 | no_license | [
{
"docstring": "FIXME:超时 求 n=15 n=14 时为 20 20//2 = 10 --> 11 不是丑数 --> 12 是 --> 12*2=24 20//3 = 6 --> 7 不是丑数 --> 8 是 --> 8*3=24 20//5= 4 --> 5 是丑数 --> 5*5=25",
"name": "nthUglyNumber_1",
"signature": "def nthUglyNumber_1(self, n: int) -> int"
},
{
"docstring": "动态规划",
"name": "nthUglyNumber",... | 2 | stack_v2_sparse_classes_30k_train_017146 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber_1(self, n: int) -> int: FIXME:超时 求 n=15 n=14 时为 20 20//2 = 10 --> 11 不是丑数 --> 12 是 --> 12*2=24 20//3 = 6 --> 7 不是丑数 --> 8 是 --> 8*3=24 20//5= 4 --> 5 是丑数 --> 5*... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber_1(self, n: int) -> int: FIXME:超时 求 n=15 n=14 时为 20 20//2 = 10 --> 11 不是丑数 --> 12 是 --> 12*2=24 20//3 = 6 --> 7 不是丑数 --> 8 是 --> 8*3=24 20//5= 4 --> 5 是丑数 --> 5*... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def nthUglyNumber_1(self, n: int) -> int:
"""FIXME:超时 求 n=15 n=14 时为 20 20//2 = 10 --> 11 不是丑数 --> 12 是 --> 12*2=24 20//3 = 6 --> 7 不是丑数 --> 8 是 --> 8*3=24 20//5= 4 --> 5 是丑数 --> 5*5=25"""
<|body_0|>
def nthUglyNumber(self, n: int) -> int:
"""动态规划"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nthUglyNumber_1(self, n: int) -> int:
"""FIXME:超时 求 n=15 n=14 时为 20 20//2 = 10 --> 11 不是丑数 --> 12 是 --> 12*2=24 20//3 = 6 --> 7 不是丑数 --> 8 是 --> 8*3=24 20//5= 4 --> 5 是丑数 --> 5*5=25"""
dp = [1] * n
s = set([1])
for i in range(1, n):
dp[i] = float('inf'... | the_stack_v2_python_sparse | .leetcode/264.丑数-ii.py | xiaoruijiang/algorithm | train | 0 | |
0571382fe6c5a2d313a6f6b0c3355dff657764ec | [
"result = ''\nfor string in strs:\n result += '{' + str(len(string)) + '}' + string\nreturn result",
"i = 1\nstrs = []\nwhile i < len(s):\n endBracket = s.find('}', i)\n lengthCount = int(s[i:endBracket])\n strs.append(s[endBracket + 1:endBracket + 1 + lengthCount])\n i = endBracket + 2 + lengthCou... | <|body_start_0|>
result = ''
for string in strs:
result += '{' + str(len(string)) + '}' + string
return result
<|end_body_0|>
<|body_start_1|>
i = 1
strs = []
while i < len(s):
endBracket = s.find('}', i)
lengthCount = int(s[i:endBrack... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_031993 | 855 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | c348fe6b30c59294bdfa39d1daf175288acf0f20 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
result = ''
for string in strs:
result += '{' + str(len(string)) + '}' + string
return result
def decode(self, s):
"""Decodes a single s... | the_stack_v2_python_sparse | P1-300/P271.py | LydiaZhou/LeetCode | train | 0 | |
6db6eb6589d901e8853e0bb9867c8b4d1773c50e | [
"cnt = 0\nif i:\n cnt += board[i - 1][j]\n if j:\n cnt += board[i - 1][j - 1]\n if j != ncol - 1:\n cnt += board[i - 1][j + 1]\nif j:\n cnt += board[i][j - 1]\nif j != ncol - 1:\n cnt += board[i][j + 1]\nif i != nrow - 1:\n cnt += board[i + 1][j]\n if j:\n cnt += board[i + ... | <|body_start_0|>
cnt = 0
if i:
cnt += board[i - 1][j]
if j:
cnt += board[i - 1][j - 1]
if j != ncol - 1:
cnt += board[i - 1][j + 1]
if j:
cnt += board[i][j - 1]
if j != ncol - 1:
cnt += board[i][j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countlive(self, i, j, board, nrow, ncol):
""":param i: int position :param j: int position :return: int number of live cell around"""
<|body_0|>
def gameOfLife(self, board):
""":type board: List[List[int]] :rtype: void Do not return anything, modify boa... | stack_v2_sparse_classes_36k_train_031994 | 1,499 | no_license | [
{
"docstring": ":param i: int position :param j: int position :return: int number of live cell around",
"name": "countlive",
"signature": "def countlive(self, i, j, board, nrow, ncol)"
},
{
"docstring": ":type board: List[List[int]] :rtype: void Do not return anything, modify board in-place inst... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countlive(self, i, j, board, nrow, ncol): :param i: int position :param j: int position :return: int number of live cell around
- def gameOfLife(self, board): :type board: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countlive(self, i, j, board, nrow, ncol): :param i: int position :param j: int position :return: int number of live cell around
- def gameOfLife(self, board): :type board: Li... | 9752533bc76ce5ecb881f61e33a3bc4b20dcf666 | <|skeleton|>
class Solution:
def countlive(self, i, j, board, nrow, ncol):
""":param i: int position :param j: int position :return: int number of live cell around"""
<|body_0|>
def gameOfLife(self, board):
""":type board: List[List[int]] :rtype: void Do not return anything, modify boa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countlive(self, i, j, board, nrow, ncol):
""":param i: int position :param j: int position :return: int number of live cell around"""
cnt = 0
if i:
cnt += board[i - 1][j]
if j:
cnt += board[i - 1][j - 1]
if j != ncol - 1... | the_stack_v2_python_sparse | 289. Game of Life/289. Game of Life.py | 603lzy/LeetCode | train | 3 | |
e9a2ab8dcfb00a61b737708957a26afc3d59c1c1 | [
"if not hasattr(self, 'get_custom_fields'):\n return dict()\nreturn {field.name: value for field, value in self.get_custom_fields().items()}",
"content_type = ContentType.objects.get_for_model(self)\nfields = CustomField.objects.filter(obj_type=content_type)\nif hasattr(self, 'pk'):\n values = CustomFieldVa... | <|body_start_0|>
if not hasattr(self, 'get_custom_fields'):
return dict()
return {field.name: value for field, value in self.get_custom_fields().items()}
<|end_body_0|>
<|body_start_1|>
content_type = ContentType.objects.get_for_model(self)
fields = CustomField.objects.filte... | CustomFieldModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomFieldModel:
def cf(self):
"""Name-based CustomFieldValue accessor for use in templates"""
<|body_0|>
def get_custom_fields(self):
"""Return a dictionary of custom fields for a single object in the form {<field>: value}."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031995 | 7,182 | no_license | [
{
"docstring": "Name-based CustomFieldValue accessor for use in templates",
"name": "cf",
"signature": "def cf(self)"
},
{
"docstring": "Return a dictionary of custom fields for a single object in the form {<field>: value}.",
"name": "get_custom_fields",
"signature": "def get_custom_fiel... | 2 | stack_v2_sparse_classes_30k_train_006942 | Implement the Python class `CustomFieldModel` described below.
Class description:
Implement the CustomFieldModel class.
Method signatures and docstrings:
- def cf(self): Name-based CustomFieldValue accessor for use in templates
- def get_custom_fields(self): Return a dictionary of custom fields for a single object in... | Implement the Python class `CustomFieldModel` described below.
Class description:
Implement the CustomFieldModel class.
Method signatures and docstrings:
- def cf(self): Name-based CustomFieldValue accessor for use in templates
- def get_custom_fields(self): Return a dictionary of custom fields for a single object in... | 61b14507749cd512ba2c8e73cc3c16d35b129a28 | <|skeleton|>
class CustomFieldModel:
def cf(self):
"""Name-based CustomFieldValue accessor for use in templates"""
<|body_0|>
def get_custom_fields(self):
"""Return a dictionary of custom fields for a single object in the form {<field>: value}."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomFieldModel:
def cf(self):
"""Name-based CustomFieldValue accessor for use in templates"""
if not hasattr(self, 'get_custom_fields'):
return dict()
return {field.name: value for field, value in self.get_custom_fields().items()}
def get_custom_fields(self):
... | the_stack_v2_python_sparse | extras/models.py | huzichunjohn/just_some_tests | train | 0 | |
774a2a03ed0ab64fc7423695c9375c0210c5c73b | [
"s = list(str(num))\nlastIndexes = {c: i for i, c in enumerate(s)}\nfor i, c in enumerate(s):\n for swap in range(9, int(c), -1):\n swapIdx = lastIndexes.get(str(swap), -1)\n if swapIdx > i:\n s[i], s[swapIdx] = (s[swapIdx], s[i])\n return int(''.join(s))\nreturn num",
"s = ... | <|body_start_0|>
s = list(str(num))
lastIndexes = {c: i for i, c in enumerate(s)}
for i, c in enumerate(s):
for swap in range(9, int(c), -1):
swapIdx = lastIndexes.get(str(swap), -1)
if swapIdx > i:
s[i], s[swapIdx] = (s[swapIdx], s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumSwap(self, num: int) -> int:
"""1. Store each number's last occurred position to the lastIndexes list. 2. Scan the number from left to right. When the current digit has a larger digit in the remaining part, swap them."""
<|body_0|>
def maximumSwap2(self,... | stack_v2_sparse_classes_36k_train_031996 | 1,509 | no_license | [
{
"docstring": "1. Store each number's last occurred position to the lastIndexes list. 2. Scan the number from left to right. When the current digit has a larger digit in the remaining part, swap them.",
"name": "maximumSwap",
"signature": "def maximumSwap(self, num: int) -> int"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_017629 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumSwap(self, num: int) -> int: 1. Store each number's last occurred position to the lastIndexes list. 2. Scan the number from left to right. When the current digit has a... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumSwap(self, num: int) -> int: 1. Store each number's last occurred position to the lastIndexes list. 2. Scan the number from left to right. When the current digit has a... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def maximumSwap(self, num: int) -> int:
"""1. Store each number's last occurred position to the lastIndexes list. 2. Scan the number from left to right. When the current digit has a larger digit in the remaining part, swap them."""
<|body_0|>
def maximumSwap2(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximumSwap(self, num: int) -> int:
"""1. Store each number's last occurred position to the lastIndexes list. 2. Scan the number from left to right. When the current digit has a larger digit in the remaining part, swap them."""
s = list(str(num))
lastIndexes = {c: i for i... | the_stack_v2_python_sparse | 2020/maximum_swap.py | eronekogin/leetcode | train | 0 | |
62cd61bfa3959fc8f1aa859460607a59ba2dbd90 | [
"res = 0\ncounter = Counter()\nfor num1 in A:\n num2 = int(str(num1)[::-1])\n res += counter[num1 - num2]\n counter[num1 - num2] += 1\nreturn res % MOD",
"res = 0\nC = Counter((num - int(str(num)[::-1]) for num in A))\nfor count in C.values():\n res += count * (count - 1) // 2\nreturn res % MOD"
] | <|body_start_0|>
res = 0
counter = Counter()
for num1 in A:
num2 = int(str(num1)[::-1])
res += counter[num1 - num2]
counter[num1 - num2] += 1
return res % MOD
<|end_body_0|>
<|body_start_1|>
res = 0
C = Counter((num - int(str(num)[::-1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNicePairs(self, A: List[int]) -> int:
"""一遍遍历 前不看后"""
<|body_0|>
def countNicePairs2(self, A: List[int]) -> int:
"""先全部存起来再统计"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
counter = Counter()
for num1 in ... | stack_v2_sparse_classes_36k_train_031997 | 1,195 | no_license | [
{
"docstring": "一遍遍历 前不看后",
"name": "countNicePairs",
"signature": "def countNicePairs(self, A: List[int]) -> int"
},
{
"docstring": "先全部存起来再统计",
"name": "countNicePairs2",
"signature": "def countNicePairs2(self, A: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNicePairs(self, A: List[int]) -> int: 一遍遍历 前不看后
- def countNicePairs2(self, A: List[int]) -> int: 先全部存起来再统计 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNicePairs(self, A: List[int]) -> int: 一遍遍历 前不看后
- def countNicePairs2(self, A: List[int]) -> int: 先全部存起来再统计
<|skeleton|>
class Solution:
def countNicePairs(self, A... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def countNicePairs(self, A: List[int]) -> int:
"""一遍遍历 前不看后"""
<|body_0|>
def countNicePairs2(self, A: List[int]) -> int:
"""先全部存起来再统计"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countNicePairs(self, A: List[int]) -> int:
"""一遍遍历 前不看后"""
res = 0
counter = Counter()
for num1 in A:
num2 = int(str(num1)[::-1])
res += counter[num1 - num2]
counter[num1 - num2] += 1
return res % MOD
def countNiceP... | the_stack_v2_python_sparse | 19_数学/组合/组合配对/1814. 统计一个数组中好对子的数目.py | 981377660LMT/algorithm-study | train | 225 | |
7bc98c65cd4f92bcb51fedc01b5885c2f508f15f | [
"def switch(root):\n if root:\n root.left, root.right = (root.right, root.left)\n switch(root.left)\n switch(root.right)\nt = copy.deepcopy(root)\nswitch(t)\nreturn self.isSameTree(t, root)",
"if not p and (not q):\n return True\nif not p or not q:\n return False\nreturn p.val == q.v... | <|body_start_0|>
def switch(root):
if root:
root.left, root.right = (root.right, root.left)
switch(root.left)
switch(root.right)
t = copy.deepcopy(root)
switch(t)
return self.isSameTree(t, root)
<|end_body_0|>
<|body_start_1|>
... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def switch(root):
... | stack_v2_sparse_classes_36k_train_031998 | 1,390 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006848 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
class Solution1:
... | 24a52fb090868b7525cab05aef6d49c25d91e6b2 | <|skeleton|>
class Solution1:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
def switch(root):
if root:
root.left, root.right = (root.right, root.left)
switch(root.left)
switch(root.right)
t = copy.deepcopy(root)
sw... | the_stack_v2_python_sparse | part4/101.py | Ressull250/code_practice | train | 0 | |
5ade448680a5844bf13a1889693214afefa8fdf9 | [
"self.name = name\nself.w_name = name + '_w'\nself.b_name = name + '_b'\nself.input_dim = input_dim\nself.output_dim = output_dim\nself.params = {}\nself.grads = {}\nself.params[self.w_name] = init_scale * np.random.randn(input_dim, output_dim)\nself.params[self.b_name] = np.zeros(output_dim)\nself.grads[self.w_nam... | <|body_start_0|>
self.name = name
self.w_name = name + '_w'
self.b_name = name + '_b'
self.input_dim = input_dim
self.output_dim = output_dim
self.params = {}
self.grads = {}
self.params[self.w_name] = init_scale * np.random.randn(input_dim, output_dim)
... | temporal_fc | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class temporal_fc:
def __init__(self, input_dim, output_dim, init_scale=0.02, name='t_fc'):
"""In forward pass, please use self.params for the weights and biases for this layer In backward pass, store the computed gradients to self.grads name: the name of current layer input_dim: input dimensi... | stack_v2_sparse_classes_36k_train_031999 | 28,090 | permissive | [
{
"docstring": "In forward pass, please use self.params for the weights and biases for this layer In backward pass, store the computed gradients to self.grads name: the name of current layer input_dim: input dimension output_dim: output dimension self.meta: variables needed for the backward pass",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_010874 | Implement the Python class `temporal_fc` described below.
Class description:
Implement the temporal_fc class.
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, init_scale=0.02, name='t_fc'): In forward pass, please use self.params for the weights and biases for this layer In backward pass,... | Implement the Python class `temporal_fc` described below.
Class description:
Implement the temporal_fc class.
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, init_scale=0.02, name='t_fc'): In forward pass, please use self.params for the weights and biases for this layer In backward pass,... | c5cfa2410d47c7e43a476a8c8a9795182fe8f836 | <|skeleton|>
class temporal_fc:
def __init__(self, input_dim, output_dim, init_scale=0.02, name='t_fc'):
"""In forward pass, please use self.params for the weights and biases for this layer In backward pass, store the computed gradients to self.grads name: the name of current layer input_dim: input dimensi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class temporal_fc:
def __init__(self, input_dim, output_dim, init_scale=0.02, name='t_fc'):
"""In forward pass, please use self.params for the weights and biases for this layer In backward pass, store the computed gradients to self.grads name: the name of current layer input_dim: input dimension output_dim:... | the_stack_v2_python_sparse | 2017_Fall/CSCI-599/Assignment02/lib/layer_utils.py | saketkc/hatex | train | 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.